duke@1: /*
duke@1: * Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved.
duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@1: *
duke@1: * This code is free software; you can redistribute it and/or modify it
duke@1: * under the terms of the GNU General Public License version 2 only, as
duke@1: * published by the Free Software Foundation. Sun designates this
duke@1: * particular file as subject to the "Classpath" exception as provided
duke@1: * by Sun in the LICENSE file that accompanied this code.
duke@1: *
duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT
duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@1: * version 2 for more details (a copy is included in the LICENSE file that
duke@1: * accompanied this code).
duke@1: *
duke@1: * You should have received a copy of the GNU General Public License version
duke@1: * 2 along with this work; if not, write to the Free Software Foundation,
duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@1: *
duke@1: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
duke@1: * CA 95054 USA or visit www.sun.com if you need additional information or
duke@1: * have any questions.
duke@1: */
duke@1:
duke@1: package com.sun.tools.javac.comp;
duke@1:
duke@1: import java.util.*;
duke@1: import java.util.Set;
duke@1:
duke@1: import com.sun.tools.javac.code.*;
duke@1: import com.sun.tools.javac.jvm.*;
duke@1: import com.sun.tools.javac.tree.*;
duke@1: import com.sun.tools.javac.util.*;
duke@1: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
duke@1: import com.sun.tools.javac.util.List;
duke@1:
duke@1: import com.sun.tools.javac.tree.JCTree.*;
duke@1: import com.sun.tools.javac.code.Lint;
duke@1: import com.sun.tools.javac.code.Lint.LintCategory;
duke@1: import com.sun.tools.javac.code.Type.*;
duke@1: import com.sun.tools.javac.code.Symbol.*;
duke@1:
duke@1: import static com.sun.tools.javac.code.Flags.*;
duke@1: import static com.sun.tools.javac.code.Kinds.*;
duke@1: import static com.sun.tools.javac.code.TypeTags.*;
duke@1:
duke@1: /** Type checking helper class for the attribution phase.
duke@1: *
duke@1: *
This is NOT part of any API supported by Sun Microsystems. If
duke@1: * you write code that depends on this, you do so at your own risk.
duke@1: * This code and its internal interfaces are subject to change or
duke@1: * deletion without notice.
duke@1: */
duke@1: public class Check {
duke@1: protected static final Context.Key checkKey =
duke@1: new Context.Key();
duke@1:
duke@1: private final Name.Table names;
duke@1: private final Log log;
duke@1: private final Symtab syms;
duke@1: private final Infer infer;
duke@1: private final Target target;
duke@1: private final Source source;
duke@1: private final Types types;
duke@1: private final boolean skipAnnotations;
duke@1: private final TreeInfo treeinfo;
duke@1:
duke@1: // The set of lint options currently in effect. It is initialized
duke@1: // from the context, and then is set/reset as needed by Attr as it
duke@1: // visits all the various parts of the trees during attribution.
duke@1: private Lint lint;
duke@1:
duke@1: public static Check instance(Context context) {
duke@1: Check instance = context.get(checkKey);
duke@1: if (instance == null)
duke@1: instance = new Check(context);
duke@1: return instance;
duke@1: }
duke@1:
duke@1: protected Check(Context context) {
duke@1: context.put(checkKey, this);
duke@1:
duke@1: names = Name.Table.instance(context);
duke@1: log = Log.instance(context);
duke@1: syms = Symtab.instance(context);
duke@1: infer = Infer.instance(context);
duke@1: this.types = Types.instance(context);
duke@1: Options options = Options.instance(context);
duke@1: target = Target.instance(context);
duke@1: source = Source.instance(context);
duke@1: lint = Lint.instance(context);
duke@1: treeinfo = TreeInfo.instance(context);
duke@1:
duke@1: Source source = Source.instance(context);
duke@1: allowGenerics = source.allowGenerics();
duke@1: allowAnnotations = source.allowAnnotations();
duke@1: complexInference = options.get("-complexinference") != null;
duke@1: skipAnnotations = options.get("skipAnnotations") != null;
duke@1:
duke@1: boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
duke@1: boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
duke@1:
duke@1: deprecationHandler = new MandatoryWarningHandler(log,verboseDeprecated, "deprecated");
duke@1: uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked, "unchecked");
duke@1: }
duke@1:
duke@1: /** Switch: generics enabled?
duke@1: */
duke@1: boolean allowGenerics;
duke@1:
duke@1: /** Switch: annotations enabled?
duke@1: */
duke@1: boolean allowAnnotations;
duke@1:
duke@1: /** Switch: -complexinference option set?
duke@1: */
duke@1: boolean complexInference;
duke@1:
duke@1: /** A table mapping flat names of all compiled classes in this run to their
duke@1: * symbols; maintained from outside.
duke@1: */
duke@1: public Map compiled = new HashMap();
duke@1:
duke@1: /** A handler for messages about deprecated usage.
duke@1: */
duke@1: private MandatoryWarningHandler deprecationHandler;
duke@1:
duke@1: /** A handler for messages about unchecked or unsafe usage.
duke@1: */
duke@1: private MandatoryWarningHandler uncheckedHandler;
duke@1:
duke@1:
duke@1: /* *************************************************************************
duke@1: * Errors and Warnings
duke@1: **************************************************************************/
duke@1:
duke@1: Lint setLint(Lint newLint) {
duke@1: Lint prev = lint;
duke@1: lint = newLint;
duke@1: return prev;
duke@1: }
duke@1:
duke@1: /** Warn about deprecated symbol.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param sym The deprecated symbol.
duke@1: */
duke@1: void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
duke@1: if (!lint.isSuppressed(LintCategory.DEPRECATION))
duke@1: deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
duke@1: }
duke@1:
duke@1: /** Warn about unchecked operation.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param msg A string describing the problem.
duke@1: */
duke@1: public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
duke@1: if (!lint.isSuppressed(LintCategory.UNCHECKED))
duke@1: uncheckedHandler.report(pos, msg, args);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Report any deferred diagnostics.
duke@1: */
duke@1: public void reportDeferredDiagnostics() {
duke@1: deprecationHandler.reportDeferredDiagnostic();
duke@1: uncheckedHandler.reportDeferredDiagnostic();
duke@1: }
duke@1:
duke@1:
duke@1: /** Report a failure to complete a class.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param ex The failure to report.
duke@1: */
duke@1: public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
duke@1: log.error(pos, "cant.access", ex.sym, ex.errmsg);
duke@1: if (ex instanceof ClassReader.BadClassFile) throw new Abort();
duke@1: else return syms.errType;
duke@1: }
duke@1:
duke@1: /** Report a type error.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param problem A string describing the error.
duke@1: * @param found The type that was found.
duke@1: * @param req The type that was required.
duke@1: */
duke@1: Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
duke@1: log.error(pos, "prob.found.req",
duke@1: problem, found, req);
duke@1: return syms.errType;
duke@1: }
duke@1:
duke@1: Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
duke@1: log.error(pos, "prob.found.req.1", problem, found, req, explanation);
duke@1: return syms.errType;
duke@1: }
duke@1:
duke@1: /** Report an error that wrong type tag was found.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param required An internationalized string describing the type tag
duke@1: * required.
duke@1: * @param found The type that was found.
duke@1: */
duke@1: Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
duke@1: log.error(pos, "type.found.req", found, required);
duke@1: return syms.errType;
duke@1: }
duke@1:
duke@1: /** Report an error that symbol cannot be referenced before super
duke@1: * has been called.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param sym The referenced symbol.
duke@1: */
duke@1: void earlyRefError(DiagnosticPosition pos, Symbol sym) {
duke@1: log.error(pos, "cant.ref.before.ctor.called", sym);
duke@1: }
duke@1:
duke@1: /** Report duplicate declaration error.
duke@1: */
duke@1: void duplicateError(DiagnosticPosition pos, Symbol sym) {
duke@1: if (!sym.type.isErroneous()) {
duke@1: log.error(pos, "already.defined", sym, sym.location());
duke@1: }
duke@1: }
duke@1:
duke@1: /** Report array/varargs duplicate declaration
duke@1: */
duke@1: void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
duke@1: if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
duke@1: log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
duke@1: }
duke@1: }
duke@1:
duke@1: /* ************************************************************************
duke@1: * duplicate declaration checking
duke@1: *************************************************************************/
duke@1:
duke@1: /** Check that variable does not hide variable with same name in
duke@1: * immediately enclosing local scope.
duke@1: * @param pos Position for error reporting.
duke@1: * @param v The symbol.
duke@1: * @param s The scope.
duke@1: */
duke@1: void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
duke@1: if (s.next != null) {
duke@1: for (Scope.Entry e = s.next.lookup(v.name);
duke@1: e.scope != null && e.sym.owner == v.owner;
duke@1: e = e.next()) {
duke@1: if (e.sym.kind == VAR &&
duke@1: (e.sym.owner.kind & (VAR | MTH)) != 0 &&
duke@1: v.name != names.error) {
duke@1: duplicateError(pos, e.sym);
duke@1: return;
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that a class or interface does not hide a class or
duke@1: * interface with same name in immediately enclosing local scope.
duke@1: * @param pos Position for error reporting.
duke@1: * @param c The symbol.
duke@1: * @param s The scope.
duke@1: */
duke@1: void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
duke@1: if (s.next != null) {
duke@1: for (Scope.Entry e = s.next.lookup(c.name);
duke@1: e.scope != null && e.sym.owner == c.owner;
duke@1: e = e.next()) {
duke@1: if (e.sym.kind == TYP &&
duke@1: (e.sym.owner.kind & (VAR | MTH)) != 0 &&
duke@1: c.name != names.error) {
duke@1: duplicateError(pos, e.sym);
duke@1: return;
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that class does not have the same name as one of
duke@1: * its enclosing classes, or as a class defined in its enclosing scope.
duke@1: * return true if class is unique in its enclosing scope.
duke@1: * @param pos Position for error reporting.
duke@1: * @param name The class name.
duke@1: * @param s The enclosing scope.
duke@1: */
duke@1: boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
duke@1: for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
duke@1: if (e.sym.kind == TYP && e.sym.name != names.error) {
duke@1: duplicateError(pos, e.sym);
duke@1: return false;
duke@1: }
duke@1: }
duke@1: for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
duke@1: if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
duke@1: duplicateError(pos, sym);
duke@1: return true;
duke@1: }
duke@1: }
duke@1: return true;
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Class name generation
duke@1: **************************************************************************/
duke@1:
duke@1: /** Return name of local class.
duke@1: * This is of the form $ n
duke@1: * where
duke@1: * enclClass is the flat name of the enclosing class,
duke@1: * classname is the simple name of the local class
duke@1: */
duke@1: Name localClassName(ClassSymbol c) {
duke@1: for (int i=1; ; i++) {
duke@1: Name flatname = names.
duke@1: fromString("" + c.owner.enclClass().flatname +
duke@1: target.syntheticNameChar() + i +
duke@1: c.name);
duke@1: if (compiled.get(flatname) == null) return flatname;
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Type Checking
duke@1: **************************************************************************/
duke@1:
duke@1: /** Check that a given type is assignable to a given proto-type.
duke@1: * If it is, return the type, otherwise return errType.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param found The type that was found.
duke@1: * @param req The type that was required.
duke@1: */
duke@1: Type checkType(DiagnosticPosition pos, Type found, Type req) {
duke@1: if (req.tag == ERROR)
duke@1: return req;
duke@1: if (found.tag == FORALL)
duke@1: return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
duke@1: if (req.tag == NONE)
duke@1: return found;
duke@1: if (types.isAssignable(found, req, convertWarner(pos, found, req)))
duke@1: return found;
duke@1: if (found.tag <= DOUBLE && req.tag <= DOUBLE)
duke@1: return typeError(pos, JCDiagnostic.fragment("possible.loss.of.precision"), found, req);
duke@1: if (found.isSuperBound()) {
duke@1: log.error(pos, "assignment.from.super-bound", found);
duke@1: return syms.errType;
duke@1: }
duke@1: if (req.isExtendsBound()) {
duke@1: log.error(pos, "assignment.to.extends-bound", req);
duke@1: return syms.errType;
duke@1: }
duke@1: return typeError(pos, JCDiagnostic.fragment("incompatible.types"), found, req);
duke@1: }
duke@1:
duke@1: /** Instantiate polymorphic type to some prototype, unless
duke@1: * prototype is `anyPoly' in which case polymorphic type
duke@1: * is returned unchanged.
duke@1: */
duke@1: Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) {
duke@1: if (pt == Infer.anyPoly && complexInference) {
duke@1: return t;
duke@1: } else if (pt == Infer.anyPoly || pt.tag == NONE) {
duke@1: Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
duke@1: return instantiatePoly(pos, t, newpt, warn);
duke@1: } else if (pt.tag == ERROR) {
duke@1: return pt;
duke@1: } else {
duke@1: try {
duke@1: return infer.instantiateExpr(t, pt, warn);
duke@1: } catch (Infer.NoInstanceException ex) {
duke@1: if (ex.isAmbiguous) {
duke@1: JCDiagnostic d = ex.getDiagnostic();
duke@1: log.error(pos,
duke@1: "undetermined.type" + (d!=null ? ".1" : ""),
duke@1: t, d);
duke@1: return syms.errType;
duke@1: } else {
duke@1: JCDiagnostic d = ex.getDiagnostic();
duke@1: return typeError(pos,
duke@1: JCDiagnostic.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
duke@1: t, pt);
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that a given type can be cast to a given target type.
duke@1: * Return the result of the cast.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param found The type that is being cast.
duke@1: * @param req The target type of the cast.
duke@1: */
duke@1: Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
duke@1: if (found.tag == FORALL) {
duke@1: instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
duke@1: return req;
duke@1: } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
duke@1: return req;
duke@1: } else {
duke@1: return typeError(pos,
duke@1: JCDiagnostic.fragment("inconvertible.types"),
duke@1: found, req);
duke@1: }
duke@1: }
duke@1: //where
duke@1: /** Is type a type variable, or a (possibly multi-dimensional) array of
duke@1: * type variables?
duke@1: */
duke@1: boolean isTypeVar(Type t) {
duke@1: return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
duke@1: }
duke@1:
duke@1: /** Check that a type is within some bounds.
duke@1: *
duke@1: * Used in TypeApply to verify that, e.g., X in V is a valid
duke@1: * type argument.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param a The type that should be bounded by bs.
duke@1: * @param bs The bound.
duke@1: */
duke@1: private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
duke@1: if (a.isUnbound()) {
duke@1: return;
duke@1: } else if (a.tag != WILDCARD) {
duke@1: a = types.upperBound(a);
duke@1: for (List l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
duke@1: if (!types.isSubtype(a, l.head)) {
duke@1: log.error(pos, "not.within.bounds", a);
duke@1: return;
duke@1: }
duke@1: }
duke@1: } else if (a.isExtendsBound()) {
duke@1: if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
duke@1: log.error(pos, "not.within.bounds", a);
duke@1: } else if (a.isSuperBound()) {
duke@1: if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
duke@1: log.error(pos, "not.within.bounds", a);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that type is different from 'void'.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: */
duke@1: Type checkNonVoid(DiagnosticPosition pos, Type t) {
duke@1: if (t.tag == VOID) {
duke@1: log.error(pos, "void.not.allowed.here");
duke@1: return syms.errType;
duke@1: } else {
duke@1: return t;
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that type is a class or interface type.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: */
duke@1: Type checkClassType(DiagnosticPosition pos, Type t) {
duke@1: if (t.tag != CLASS && t.tag != ERROR)
duke@1: return typeTagError(pos,
duke@1: JCDiagnostic.fragment("type.req.class"),
duke@1: (t.tag == TYPEVAR)
duke@1: ? JCDiagnostic.fragment("type.parameter", t)
duke@1: : t);
duke@1: else
duke@1: return t;
duke@1: }
duke@1:
duke@1: /** Check that type is a class or interface type.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: * @param noBounds True if type bounds are illegal here.
duke@1: */
duke@1: Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
duke@1: t = checkClassType(pos, t);
duke@1: if (noBounds && t.isParameterized()) {
duke@1: List args = t.getTypeArguments();
duke@1: while (args.nonEmpty()) {
duke@1: if (args.head.tag == WILDCARD)
duke@1: return typeTagError(pos,
duke@1: log.getLocalizedString("type.req.exact"),
duke@1: args.head);
duke@1: args = args.tail;
duke@1: }
duke@1: }
duke@1: return t;
duke@1: }
duke@1:
duke@1: /** Check that type is a reifiable class, interface or array type.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: */
duke@1: Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
duke@1: if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
duke@1: return typeTagError(pos,
duke@1: JCDiagnostic.fragment("type.req.class.array"),
duke@1: t);
duke@1: } else if (!types.isReifiable(t)) {
duke@1: log.error(pos, "illegal.generic.type.for.instof");
duke@1: return syms.errType;
duke@1: } else {
duke@1: return t;
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that type is a reference type, i.e. a class, interface or array type
duke@1: * or a type variable.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: */
duke@1: Type checkRefType(DiagnosticPosition pos, Type t) {
duke@1: switch (t.tag) {
duke@1: case CLASS:
duke@1: case ARRAY:
duke@1: case TYPEVAR:
duke@1: case WILDCARD:
duke@1: case ERROR:
duke@1: return t;
duke@1: default:
duke@1: return typeTagError(pos,
duke@1: JCDiagnostic.fragment("type.req.ref"),
duke@1: t);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that type is a null or reference type.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type to be checked.
duke@1: */
duke@1: Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
duke@1: switch (t.tag) {
duke@1: case CLASS:
duke@1: case ARRAY:
duke@1: case TYPEVAR:
duke@1: case WILDCARD:
duke@1: case BOT:
duke@1: case ERROR:
duke@1: return t;
duke@1: default:
duke@1: return typeTagError(pos,
duke@1: JCDiagnostic.fragment("type.req.ref"),
duke@1: t);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that flag set does not contain elements of two conflicting sets. s
duke@1: * Return true if it doesn't.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param flags The set of flags to be checked.
duke@1: * @param set1 Conflicting flags set #1.
duke@1: * @param set2 Conflicting flags set #2.
duke@1: */
duke@1: boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
duke@1: if ((flags & set1) != 0 && (flags & set2) != 0) {
duke@1: log.error(pos,
duke@1: "illegal.combination.of.modifiers",
duke@1: TreeInfo.flagNames(TreeInfo.firstFlag(flags & set1)),
duke@1: TreeInfo.flagNames(TreeInfo.firstFlag(flags & set2)));
duke@1: return false;
duke@1: } else
duke@1: return true;
duke@1: }
duke@1:
duke@1: /** Check that given modifiers are legal for given symbol and
duke@1: * return modifiers together with any implicit modififiers for that symbol.
duke@1: * Warning: we can't use flags() here since this method
duke@1: * is called during class enter, when flags() would cause a premature
duke@1: * completion.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param flags The set of modifiers given in a definition.
duke@1: * @param sym The defined symbol.
duke@1: */
duke@1: long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
duke@1: long mask;
duke@1: long implicit = 0;
duke@1: switch (sym.kind) {
duke@1: case VAR:
duke@1: if (sym.owner.kind != TYP)
duke@1: mask = LocalVarFlags;
duke@1: else if ((sym.owner.flags_field & INTERFACE) != 0)
duke@1: mask = implicit = InterfaceVarFlags;
duke@1: else
duke@1: mask = VarFlags;
duke@1: break;
duke@1: case MTH:
duke@1: if (sym.name == names.init) {
duke@1: if ((sym.owner.flags_field & ENUM) != 0) {
duke@1: // enum constructors cannot be declared public or
duke@1: // protected and must be implicitly or explicitly
duke@1: // private
duke@1: implicit = PRIVATE;
duke@1: mask = PRIVATE;
duke@1: } else
duke@1: mask = ConstructorFlags;
duke@1: } else if ((sym.owner.flags_field & INTERFACE) != 0)
duke@1: mask = implicit = InterfaceMethodFlags;
duke@1: else {
duke@1: mask = MethodFlags;
duke@1: }
duke@1: // Imply STRICTFP if owner has STRICTFP set.
duke@1: if (((flags|implicit) & Flags.ABSTRACT) == 0)
duke@1: implicit |= sym.owner.flags_field & STRICTFP;
duke@1: break;
duke@1: case TYP:
duke@1: if (sym.isLocal()) {
duke@1: mask = LocalClassFlags;
duke@1: if (sym.name.len == 0) { // Anonymous class
duke@1: // Anonymous classes in static methods are themselves static;
duke@1: // that's why we admit STATIC here.
duke@1: mask |= STATIC;
duke@1: // JLS: Anonymous classes are final.
duke@1: implicit |= FINAL;
duke@1: }
duke@1: if ((sym.owner.flags_field & STATIC) == 0 &&
duke@1: (flags & ENUM) != 0)
duke@1: log.error(pos, "enums.must.be.static");
duke@1: } else if (sym.owner.kind == TYP) {
duke@1: mask = MemberClassFlags;
duke@1: if (sym.owner.owner.kind == PCK ||
duke@1: (sym.owner.flags_field & STATIC) != 0)
duke@1: mask |= STATIC;
duke@1: else if ((flags & ENUM) != 0)
duke@1: log.error(pos, "enums.must.be.static");
duke@1: // Nested interfaces and enums are always STATIC (Spec ???)
duke@1: if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
duke@1: } else {
duke@1: mask = ClassFlags;
duke@1: }
duke@1: // Interfaces are always ABSTRACT
duke@1: if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
duke@1:
duke@1: if ((flags & ENUM) != 0) {
duke@1: // enums can't be declared abstract or final
duke@1: mask &= ~(ABSTRACT | FINAL);
duke@1: implicit |= implicitEnumFinalFlag(tree);
duke@1: }
duke@1: // Imply STRICTFP if owner has STRICTFP set.
duke@1: implicit |= sym.owner.flags_field & STRICTFP;
duke@1: break;
duke@1: default:
duke@1: throw new AssertionError();
duke@1: }
duke@1: long illegal = flags & StandardFlags & ~mask;
duke@1: if (illegal != 0) {
duke@1: if ((illegal & INTERFACE) != 0) {
duke@1: log.error(pos, "intf.not.allowed.here");
duke@1: mask |= INTERFACE;
duke@1: }
duke@1: else {
duke@1: log.error(pos,
duke@1: "mod.not.allowed.here", TreeInfo.flagNames(illegal));
duke@1: }
duke@1: }
duke@1: else if ((sym.kind == TYP ||
duke@1: // ISSUE: Disallowing abstract&private is no longer appropriate
duke@1: // in the presence of inner classes. Should it be deleted here?
duke@1: checkDisjoint(pos, flags,
duke@1: ABSTRACT,
duke@1: PRIVATE | STATIC))
duke@1: &&
duke@1: checkDisjoint(pos, flags,
duke@1: ABSTRACT | INTERFACE,
duke@1: FINAL | NATIVE | SYNCHRONIZED)
duke@1: &&
duke@1: checkDisjoint(pos, flags,
duke@1: PUBLIC,
duke@1: PRIVATE | PROTECTED)
duke@1: &&
duke@1: checkDisjoint(pos, flags,
duke@1: PRIVATE,
duke@1: PUBLIC | PROTECTED)
duke@1: &&
duke@1: checkDisjoint(pos, flags,
duke@1: FINAL,
duke@1: VOLATILE)
duke@1: &&
duke@1: (sym.kind == TYP ||
duke@1: checkDisjoint(pos, flags,
duke@1: ABSTRACT | NATIVE,
duke@1: STRICTFP))) {
duke@1: // skip
duke@1: }
duke@1: return flags & (mask | ~StandardFlags) | implicit;
duke@1: }
duke@1:
duke@1:
duke@1: /** Determine if this enum should be implicitly final.
duke@1: *
duke@1: * If the enum has no specialized enum contants, it is final.
duke@1: *
duke@1: * If the enum does have specialized enum contants, it is
duke@1: * not final.
duke@1: */
duke@1: private long implicitEnumFinalFlag(JCTree tree) {
duke@1: if (tree.getTag() != JCTree.CLASSDEF) return 0;
duke@1: class SpecialTreeVisitor extends JCTree.Visitor {
duke@1: boolean specialized;
duke@1: SpecialTreeVisitor() {
duke@1: this.specialized = false;
duke@1: };
duke@1:
duke@1: public void visitTree(JCTree tree) { /* no-op */ }
duke@1:
duke@1: public void visitVarDef(JCVariableDecl tree) {
duke@1: if ((tree.mods.flags & ENUM) != 0) {
duke@1: if (tree.init instanceof JCNewClass &&
duke@1: ((JCNewClass) tree.init).def != null) {
duke@1: specialized = true;
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: SpecialTreeVisitor sts = new SpecialTreeVisitor();
duke@1: JCClassDecl cdef = (JCClassDecl) tree;
duke@1: for (JCTree defs: cdef.defs) {
duke@1: defs.accept(sts);
duke@1: if (sts.specialized) return 0;
duke@1: }
duke@1: return FINAL;
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Type Validation
duke@1: **************************************************************************/
duke@1:
duke@1: /** Validate a type expression. That is,
duke@1: * check that all type arguments of a parametric type are within
duke@1: * their bounds. This must be done in a second phase after type attributon
duke@1: * since a class might have a subclass as type parameter bound. E.g:
duke@1: *
duke@1: * class B { ... }
duke@1: * class C extends B { ... }
duke@1: *
duke@1: * and we can't make sure that the bound is already attributed because
duke@1: * of possible cycles.
duke@1: */
duke@1: private Validator validator = new Validator();
duke@1:
duke@1: /** Visitor method: Validate a type expression, if it is not null, catching
duke@1: * and reporting any completion failures.
duke@1: */
duke@1: void validate(JCTree tree) {
duke@1: try {
duke@1: if (tree != null) tree.accept(validator);
duke@1: } catch (CompletionFailure ex) {
duke@1: completionError(tree.pos(), ex);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Visitor method: Validate a list of type expressions.
duke@1: */
duke@1: void validate(List extends JCTree> trees) {
duke@1: for (List extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
duke@1: validate(l.head);
duke@1: }
duke@1:
duke@1: /** Visitor method: Validate a list of type parameters.
duke@1: */
duke@1: void validateTypeParams(List trees) {
duke@1: for (List l = trees; l.nonEmpty(); l = l.tail)
duke@1: validate(l.head);
duke@1: }
duke@1:
duke@1: /** A visitor class for type validation.
duke@1: */
duke@1: class Validator extends JCTree.Visitor {
duke@1:
duke@1: public void visitTypeArray(JCArrayTypeTree tree) {
duke@1: validate(tree.elemtype);
duke@1: }
duke@1:
duke@1: public void visitTypeApply(JCTypeApply tree) {
duke@1: if (tree.type.tag == CLASS) {
duke@1: List formals = tree.type.tsym.type.getTypeArguments();
duke@1: List actuals = tree.type.getTypeArguments();
duke@1: List args = tree.arguments;
duke@1: List forms = formals;
duke@1: ListBuffer tvars_buf = new ListBuffer();
duke@1:
duke@1: // For matching pairs of actual argument types `a' and
duke@1: // formal type parameters with declared bound `b' ...
duke@1: while (args.nonEmpty() && forms.nonEmpty()) {
duke@1: validate(args.head);
duke@1:
duke@1: // exact type arguments needs to know their
duke@1: // bounds (for upper and lower bound
duke@1: // calculations). So we create new TypeVars with
duke@1: // bounds substed with actuals.
duke@1: tvars_buf.append(types.substBound(((TypeVar)forms.head),
duke@1: formals,
duke@1: Type.removeBounds(actuals)));
duke@1:
duke@1: args = args.tail;
duke@1: forms = forms.tail;
duke@1: }
duke@1:
duke@1: args = tree.arguments;
duke@1: List tvars = tvars_buf.toList();
duke@1: while (args.nonEmpty() && tvars.nonEmpty()) {
duke@1: // Let the actual arguments know their bound
duke@1: args.head.type.withTypeVar(tvars.head);
duke@1: args = args.tail;
duke@1: tvars = tvars.tail;
duke@1: }
duke@1:
duke@1: args = tree.arguments;
duke@1: tvars = tvars_buf.toList();
duke@1: while (args.nonEmpty() && tvars.nonEmpty()) {
duke@1: checkExtends(args.head.pos(),
duke@1: args.head.type,
duke@1: tvars.head);
duke@1: args = args.tail;
duke@1: tvars = tvars.tail;
duke@1: }
duke@1:
duke@1: // Check that this type is either fully parameterized, or
duke@1: // not parameterized at all.
duke@1: if (tree.type.getEnclosingType().isRaw())
duke@1: log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
duke@1: if (tree.clazz.getTag() == JCTree.SELECT)
duke@1: visitSelectInternal((JCFieldAccess)tree.clazz);
duke@1: }
duke@1: }
duke@1:
duke@1: public void visitTypeParameter(JCTypeParameter tree) {
duke@1: validate(tree.bounds);
duke@1: checkClassBounds(tree.pos(), tree.type);
duke@1: }
duke@1:
duke@1: @Override
duke@1: public void visitWildcard(JCWildcard tree) {
duke@1: if (tree.inner != null)
duke@1: validate(tree.inner);
duke@1: }
duke@1:
duke@1: public void visitSelect(JCFieldAccess tree) {
duke@1: if (tree.type.tag == CLASS) {
duke@1: visitSelectInternal(tree);
duke@1:
duke@1: // Check that this type is either fully parameterized, or
duke@1: // not parameterized at all.
duke@1: if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
duke@1: log.error(tree.pos(), "improperly.formed.type.param.missing");
duke@1: }
duke@1: }
duke@1: public void visitSelectInternal(JCFieldAccess tree) {
duke@1: if (tree.type.getEnclosingType().tag != CLASS &&
duke@1: tree.selected.type.isParameterized()) {
duke@1: // The enclosing type is not a class, so we are
duke@1: // looking at a static member type. However, the
duke@1: // qualifying expression is parameterized.
duke@1: log.error(tree.pos(), "cant.select.static.class.from.param.type");
duke@1: } else {
duke@1: // otherwise validate the rest of the expression
duke@1: validate(tree.selected);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Default visitor method: do nothing.
duke@1: */
duke@1: public void visitTree(JCTree tree) {
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Exception checking
duke@1: **************************************************************************/
duke@1:
duke@1: /* The following methods treat classes as sets that contain
duke@1: * the class itself and all their subclasses
duke@1: */
duke@1:
duke@1: /** Is given type a subtype of some of the types in given list?
duke@1: */
duke@1: boolean subset(Type t, List ts) {
duke@1: for (List l = ts; l.nonEmpty(); l = l.tail)
duke@1: if (types.isSubtype(t, l.head)) return true;
duke@1: return false;
duke@1: }
duke@1:
duke@1: /** Is given type a subtype or supertype of
duke@1: * some of the types in given list?
duke@1: */
duke@1: boolean intersects(Type t, List ts) {
duke@1: for (List l = ts; l.nonEmpty(); l = l.tail)
duke@1: if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
duke@1: return false;
duke@1: }
duke@1:
duke@1: /** Add type set to given type list, unless it is a subclass of some class
duke@1: * in the list.
duke@1: */
duke@1: List incl(Type t, List ts) {
duke@1: return subset(t, ts) ? ts : excl(t, ts).prepend(t);
duke@1: }
duke@1:
duke@1: /** Remove type set from type set list.
duke@1: */
duke@1: List excl(Type t, List ts) {
duke@1: if (ts.isEmpty()) {
duke@1: return ts;
duke@1: } else {
duke@1: List ts1 = excl(t, ts.tail);
duke@1: if (types.isSubtype(ts.head, t)) return ts1;
duke@1: else if (ts1 == ts.tail) return ts;
duke@1: else return ts1.prepend(ts.head);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Form the union of two type set lists.
duke@1: */
duke@1: List union(List ts1, List ts2) {
duke@1: List ts = ts1;
duke@1: for (List l = ts2; l.nonEmpty(); l = l.tail)
duke@1: ts = incl(l.head, ts);
duke@1: return ts;
duke@1: }
duke@1:
duke@1: /** Form the difference of two type lists.
duke@1: */
duke@1: List diff(List ts1, List ts2) {
duke@1: List ts = ts1;
duke@1: for (List l = ts2; l.nonEmpty(); l = l.tail)
duke@1: ts = excl(l.head, ts);
duke@1: return ts;
duke@1: }
duke@1:
duke@1: /** Form the intersection of two type lists.
duke@1: */
duke@1: public List intersect(List ts1, List ts2) {
duke@1: List ts = List.nil();
duke@1: for (List l = ts1; l.nonEmpty(); l = l.tail)
duke@1: if (subset(l.head, ts2)) ts = incl(l.head, ts);
duke@1: for (List l = ts2; l.nonEmpty(); l = l.tail)
duke@1: if (subset(l.head, ts1)) ts = incl(l.head, ts);
duke@1: return ts;
duke@1: }
duke@1:
duke@1: /** Is exc an exception symbol that need not be declared?
duke@1: */
duke@1: boolean isUnchecked(ClassSymbol exc) {
duke@1: return
duke@1: exc.kind == ERR ||
duke@1: exc.isSubClass(syms.errorType.tsym, types) ||
duke@1: exc.isSubClass(syms.runtimeExceptionType.tsym, types);
duke@1: }
duke@1:
duke@1: /** Is exc an exception type that need not be declared?
duke@1: */
duke@1: boolean isUnchecked(Type exc) {
duke@1: return
duke@1: (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
duke@1: (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
duke@1: exc.tag == BOT;
duke@1: }
duke@1:
duke@1: /** Same, but handling completion failures.
duke@1: */
duke@1: boolean isUnchecked(DiagnosticPosition pos, Type exc) {
duke@1: try {
duke@1: return isUnchecked(exc);
duke@1: } catch (CompletionFailure ex) {
duke@1: completionError(pos, ex);
duke@1: return true;
duke@1: }
duke@1: }
duke@1:
duke@1: /** Is exc handled by given exception list?
duke@1: */
duke@1: boolean isHandled(Type exc, List handled) {
duke@1: return isUnchecked(exc) || subset(exc, handled);
duke@1: }
duke@1:
duke@1: /** Return all exceptions in thrown list that are not in handled list.
duke@1: * @param thrown The list of thrown exceptions.
duke@1: * @param handled The list of handled exceptions.
duke@1: */
duke@1: List unHandled(List thrown, List handled) {
duke@1: List unhandled = List.nil();
duke@1: for (List l = thrown; l.nonEmpty(); l = l.tail)
duke@1: if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
duke@1: return unhandled;
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Overriding/Implementation checking
duke@1: **************************************************************************/
duke@1:
duke@1: /** The level of access protection given by a flag set,
duke@1: * where PRIVATE is highest and PUBLIC is lowest.
duke@1: */
duke@1: static int protection(long flags) {
duke@1: switch ((short)(flags & AccessFlags)) {
duke@1: case PRIVATE: return 3;
duke@1: case PROTECTED: return 1;
duke@1: default:
duke@1: case PUBLIC: return 0;
duke@1: case 0: return 2;
duke@1: }
duke@1: }
duke@1:
duke@1: /** A string describing the access permission given by a flag set.
duke@1: * This always returns a space-separated list of Java Keywords.
duke@1: */
duke@1: private static String protectionString(long flags) {
duke@1: long flags1 = flags & AccessFlags;
duke@1: return (flags1 == 0) ? "package" : TreeInfo.flagNames(flags1);
duke@1: }
duke@1:
duke@1: /** A customized "cannot override" error message.
duke@1: * @param m The overriding method.
duke@1: * @param other The overridden method.
duke@1: * @return An internationalized string.
duke@1: */
duke@1: static Object cannotOverride(MethodSymbol m, MethodSymbol other) {
duke@1: String key;
duke@1: if ((other.owner.flags() & INTERFACE) == 0)
duke@1: key = "cant.override";
duke@1: else if ((m.owner.flags() & INTERFACE) == 0)
duke@1: key = "cant.implement";
duke@1: else
duke@1: key = "clashes.with";
duke@1: return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
duke@1: }
duke@1:
duke@1: /** A customized "override" warning message.
duke@1: * @param m The overriding method.
duke@1: * @param other The overridden method.
duke@1: * @return An internationalized string.
duke@1: */
duke@1: static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
duke@1: String key;
duke@1: if ((other.owner.flags() & INTERFACE) == 0)
duke@1: key = "unchecked.override";
duke@1: else if ((m.owner.flags() & INTERFACE) == 0)
duke@1: key = "unchecked.implement";
duke@1: else
duke@1: key = "unchecked.clash.with";
duke@1: return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
duke@1: }
duke@1:
duke@1: /** A customized "override" warning message.
duke@1: * @param m The overriding method.
duke@1: * @param other The overridden method.
duke@1: * @return An internationalized string.
duke@1: */
duke@1: static Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
duke@1: String key;
duke@1: if ((other.owner.flags() & INTERFACE) == 0)
duke@1: key = "varargs.override";
duke@1: else if ((m.owner.flags() & INTERFACE) == 0)
duke@1: key = "varargs.implement";
duke@1: else
duke@1: key = "varargs.clash.with";
duke@1: return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
duke@1: }
duke@1:
duke@1: /** Check that this method conforms with overridden method 'other'.
duke@1: * where `origin' is the class where checking started.
duke@1: * Complications:
duke@1: * (1) Do not check overriding of synthetic methods
duke@1: * (reason: they might be final).
duke@1: * todo: check whether this is still necessary.
duke@1: * (2) Admit the case where an interface proxy throws fewer exceptions
duke@1: * than the method it implements. Augment the proxy methods with the
duke@1: * undeclared exceptions in this case.
duke@1: * (3) When generics are enabled, admit the case where an interface proxy
duke@1: * has a result type
duke@1: * extended by the result type of the method it implements.
duke@1: * Change the proxies result type to the smaller type in this case.
duke@1: *
duke@1: * @param tree The tree from which positions
duke@1: * are extracted for errors.
duke@1: * @param m The overriding method.
duke@1: * @param other The overridden method.
duke@1: * @param origin The class of which the overriding method
duke@1: * is a member.
duke@1: */
duke@1: void checkOverride(JCTree tree,
duke@1: MethodSymbol m,
duke@1: MethodSymbol other,
duke@1: ClassSymbol origin) {
duke@1: // Don't check overriding of synthetic methods or by bridge methods.
duke@1: if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
duke@1: return;
duke@1: }
duke@1:
duke@1: // Error if static method overrides instance method (JLS 8.4.6.2).
duke@1: if ((m.flags() & STATIC) != 0 &&
duke@1: (other.flags() & STATIC) == 0) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
duke@1: cannotOverride(m, other));
duke@1: return;
duke@1: }
duke@1:
duke@1: // Error if instance method overrides static or final
duke@1: // method (JLS 8.4.6.1).
duke@1: if ((other.flags() & FINAL) != 0 ||
duke@1: (m.flags() & STATIC) == 0 &&
duke@1: (other.flags() & STATIC) != 0) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
duke@1: cannotOverride(m, other),
duke@1: TreeInfo.flagNames(other.flags() & (FINAL | STATIC)));
duke@1: return;
duke@1: }
duke@1:
duke@1: if ((m.owner.flags() & ANNOTATION) != 0) {
duke@1: // handled in validateAnnotationMethod
duke@1: return;
duke@1: }
duke@1:
duke@1: // Error if overriding method has weaker access (JLS 8.4.6.3).
duke@1: if ((origin.flags() & INTERFACE) == 0 &&
duke@1: protection(m.flags()) > protection(other.flags())) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
duke@1: cannotOverride(m, other),
duke@1: protectionString(other.flags()));
duke@1: return;
duke@1:
duke@1: }
duke@1:
duke@1: Type mt = types.memberType(origin.type, m);
duke@1: Type ot = types.memberType(origin.type, other);
duke@1: // Error if overriding result type is different
duke@1: // (or, in the case of generics mode, not a subtype) of
duke@1: // overridden result type. We have to rename any type parameters
duke@1: // before comparing types.
duke@1: List mtvars = mt.getTypeArguments();
duke@1: List otvars = ot.getTypeArguments();
duke@1: Type mtres = mt.getReturnType();
duke@1: Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
duke@1:
duke@1: overrideWarner.warned = false;
duke@1: boolean resultTypesOK =
duke@1: types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
duke@1: if (!resultTypesOK) {
duke@1: if (!source.allowCovariantReturns() &&
duke@1: m.owner != origin &&
duke@1: m.owner.isSubClass(other.owner, types)) {
duke@1: // allow limited interoperability with covariant returns
duke@1: } else {
duke@1: typeError(TreeInfo.diagnosticPositionFor(m, tree),
duke@1: JCDiagnostic.fragment("override.incompatible.ret",
duke@1: cannotOverride(m, other)),
duke@1: mtres, otres);
duke@1: return;
duke@1: }
duke@1: } else if (overrideWarner.warned) {
duke@1: warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
duke@1: "prob.found.req",
duke@1: JCDiagnostic.fragment("override.unchecked.ret",
duke@1: uncheckedOverrides(m, other)),
duke@1: mtres, otres);
duke@1: }
duke@1:
duke@1: // Error if overriding method throws an exception not reported
duke@1: // by overridden method.
duke@1: List otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
duke@1: List unhandled = unHandled(mt.getThrownTypes(), otthrown);
duke@1: if (unhandled.nonEmpty()) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(m, tree),
duke@1: "override.meth.doesnt.throw",
duke@1: cannotOverride(m, other),
duke@1: unhandled.head);
duke@1: return;
duke@1: }
duke@1:
duke@1: // Optional warning if varargs don't agree
duke@1: if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
duke@1: && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
duke@1: log.warning(TreeInfo.diagnosticPositionFor(m, tree),
duke@1: ((m.flags() & Flags.VARARGS) != 0)
duke@1: ? "override.varargs.missing"
duke@1: : "override.varargs.extra",
duke@1: varargsOverrides(m, other));
duke@1: }
duke@1:
duke@1: // Warn if instance method overrides bridge method (compiler spec ??)
duke@1: if ((other.flags() & BRIDGE) != 0) {
duke@1: log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
duke@1: uncheckedOverrides(m, other));
duke@1: }
duke@1:
duke@1: // Warn if a deprecated method overridden by a non-deprecated one.
duke@1: if ((other.flags() & DEPRECATED) != 0
duke@1: && (m.flags() & DEPRECATED) == 0
duke@1: && m.outermostClass() != other.outermostClass()
duke@1: && !isDeprecatedOverrideIgnorable(other, origin)) {
duke@1: warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
duke@1: }
duke@1: }
duke@1: // where
duke@1: private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
duke@1: // If the method, m, is defined in an interface, then ignore the issue if the method
duke@1: // is only inherited via a supertype and also implemented in the supertype,
duke@1: // because in that case, we will rediscover the issue when examining the method
duke@1: // in the supertype.
duke@1: // If the method, m, is not defined in an interface, then the only time we need to
duke@1: // address the issue is when the method is the supertype implemementation: any other
duke@1: // case, we will have dealt with when examining the supertype classes
duke@1: ClassSymbol mc = m.enclClass();
duke@1: Type st = types.supertype(origin.type);
duke@1: if (st.tag != CLASS)
duke@1: return true;
duke@1: MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
duke@1:
duke@1: if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
duke@1: List intfs = types.interfaces(origin.type);
duke@1: return (intfs.contains(mc.type) ? false : (stimpl != null));
duke@1: }
duke@1: else
duke@1: return (stimpl != m);
duke@1: }
duke@1:
duke@1:
duke@1: // used to check if there were any unchecked conversions
duke@1: Warner overrideWarner = new Warner();
duke@1:
duke@1: /** Check that a class does not inherit two concrete methods
duke@1: * with the same signature.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param site The class type to be checked.
duke@1: */
duke@1: public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
duke@1: Type sup = types.supertype(site);
duke@1: if (sup.tag != CLASS) return;
duke@1:
duke@1: for (Type t1 = sup;
duke@1: t1.tsym.type.isParameterized();
duke@1: t1 = types.supertype(t1)) {
duke@1: for (Scope.Entry e1 = t1.tsym.members().elems;
duke@1: e1 != null;
duke@1: e1 = e1.sibling) {
duke@1: Symbol s1 = e1.sym;
duke@1: if (s1.kind != MTH ||
duke@1: (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
duke@1: !s1.isInheritedIn(site.tsym, types) ||
duke@1: ((MethodSymbol)s1).implementation(site.tsym,
duke@1: types,
duke@1: true) != s1)
duke@1: continue;
duke@1: Type st1 = types.memberType(t1, s1);
duke@1: int s1ArgsLength = st1.getParameterTypes().length();
duke@1: if (st1 == s1.type) continue;
duke@1:
duke@1: for (Type t2 = sup;
duke@1: t2.tag == CLASS;
duke@1: t2 = types.supertype(t2)) {
duke@1: for (Scope.Entry e2 = t1.tsym.members().lookup(s1.name);
duke@1: e2.scope != null;
duke@1: e2 = e2.next()) {
duke@1: Symbol s2 = e2.sym;
duke@1: if (s2 == s1 ||
duke@1: s2.kind != MTH ||
duke@1: (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
duke@1: s2.type.getParameterTypes().length() != s1ArgsLength ||
duke@1: !s2.isInheritedIn(site.tsym, types) ||
duke@1: ((MethodSymbol)s2).implementation(site.tsym,
duke@1: types,
duke@1: true) != s2)
duke@1: continue;
duke@1: Type st2 = types.memberType(t2, s2);
duke@1: if (types.overrideEquivalent(st1, st2))
duke@1: log.error(pos, "concrete.inheritance.conflict",
duke@1: s1, t1, s2, t2, sup);
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that classes (or interfaces) do not each define an abstract
duke@1: * method with same name and arguments but incompatible return types.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t1 The first argument type.
duke@1: * @param t2 The second argument type.
duke@1: */
duke@1: public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
duke@1: Type t1,
duke@1: Type t2) {
duke@1: return checkCompatibleAbstracts(pos, t1, t2,
duke@1: types.makeCompoundType(t1, t2));
duke@1: }
duke@1:
duke@1: public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
duke@1: Type t1,
duke@1: Type t2,
duke@1: Type site) {
duke@1: Symbol sym = firstIncompatibility(t1, t2, site);
duke@1: if (sym != null) {
duke@1: log.error(pos, "types.incompatible.diff.ret",
duke@1: t1, t2, sym.name +
duke@1: "(" + types.memberType(t2, sym).getParameterTypes() + ")");
duke@1: return false;
duke@1: }
duke@1: return true;
duke@1: }
duke@1:
duke@1: /** Return the first method which is defined with same args
duke@1: * but different return types in two given interfaces, or null if none
duke@1: * exists.
duke@1: * @param t1 The first type.
duke@1: * @param t2 The second type.
duke@1: * @param site The most derived type.
duke@1: * @returns symbol from t2 that conflicts with one in t1.
duke@1: */
duke@1: private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
duke@1: Map interfaces1 = new HashMap();
duke@1: closure(t1, interfaces1);
duke@1: Map interfaces2;
duke@1: if (t1 == t2)
duke@1: interfaces2 = interfaces1;
duke@1: else
duke@1: closure(t2, interfaces1, interfaces2 = new HashMap());
duke@1:
duke@1: for (Type t3 : interfaces1.values()) {
duke@1: for (Type t4 : interfaces2.values()) {
duke@1: Symbol s = firstDirectIncompatibility(t3, t4, site);
duke@1: if (s != null) return s;
duke@1: }
duke@1: }
duke@1: return null;
duke@1: }
duke@1:
duke@1: /** Compute all the supertypes of t, indexed by type symbol. */
duke@1: private void closure(Type t, Map typeMap) {
duke@1: if (t.tag != CLASS) return;
duke@1: if (typeMap.put(t.tsym, t) == null) {
duke@1: closure(types.supertype(t), typeMap);
duke@1: for (Type i : types.interfaces(t))
duke@1: closure(i, typeMap);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
duke@1: private void closure(Type t, Map typesSkip, Map typeMap) {
duke@1: if (t.tag != CLASS) return;
duke@1: if (typesSkip.get(t.tsym) != null) return;
duke@1: if (typeMap.put(t.tsym, t) == null) {
duke@1: closure(types.supertype(t), typesSkip, typeMap);
duke@1: for (Type i : types.interfaces(t))
duke@1: closure(i, typesSkip, typeMap);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Return the first method in t2 that conflicts with a method from t1. */
duke@1: private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
duke@1: for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
duke@1: Symbol s1 = e1.sym;
duke@1: Type st1 = null;
duke@1: if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
duke@1: Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
duke@1: if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
duke@1: for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
duke@1: Symbol s2 = e2.sym;
duke@1: if (s1 == s2) continue;
duke@1: if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
duke@1: if (st1 == null) st1 = types.memberType(t1, s1);
duke@1: Type st2 = types.memberType(t2, s2);
duke@1: if (types.overrideEquivalent(st1, st2)) {
duke@1: List tvars1 = st1.getTypeArguments();
duke@1: List tvars2 = st2.getTypeArguments();
duke@1: Type rt1 = st1.getReturnType();
duke@1: Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
duke@1: boolean compat =
duke@1: types.isSameType(rt1, rt2) ||
duke@1: rt1.tag >= CLASS && rt2.tag >= CLASS &&
duke@1: (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
duke@1: types.covariantReturnType(rt2, rt1, Warner.noWarnings));
duke@1: if (!compat) return s2;
duke@1: }
duke@1: }
duke@1: }
duke@1: return null;
duke@1: }
duke@1:
duke@1: /** Check that a given method conforms with any method it overrides.
duke@1: * @param tree The tree from which positions are extracted
duke@1: * for errors.
duke@1: * @param m The overriding method.
duke@1: */
duke@1: void checkOverride(JCTree tree, MethodSymbol m) {
duke@1: ClassSymbol origin = (ClassSymbol)m.owner;
duke@1: if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
duke@1: if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
duke@1: log.error(tree.pos(), "enum.no.finalize");
duke@1: return;
duke@1: }
duke@1: for (Type t = types.supertype(origin.type); t.tag == CLASS;
duke@1: t = types.supertype(t)) {
duke@1: TypeSymbol c = t.tsym;
duke@1: Scope.Entry e = c.members().lookup(m.name);
duke@1: while (e.scope != null) {
duke@1: if (m.overrides(e.sym, origin, types, false))
duke@1: checkOverride(tree, m, (MethodSymbol)e.sym, origin);
duke@1: e = e.next();
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that all abstract members of given class have definitions.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param c The class.
duke@1: */
duke@1: void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
duke@1: try {
duke@1: MethodSymbol undef = firstUndef(c, c);
duke@1: if (undef != null) {
duke@1: if ((c.flags() & ENUM) != 0 &&
duke@1: types.supertype(c.type).tsym == syms.enumSym &&
duke@1: (c.flags() & FINAL) == 0) {
duke@1: // add the ABSTRACT flag to an enum
duke@1: c.flags_field |= ABSTRACT;
duke@1: } else {
duke@1: MethodSymbol undef1 =
duke@1: new MethodSymbol(undef.flags(), undef.name,
duke@1: types.memberType(c.type, undef), undef.owner);
duke@1: log.error(pos, "does.not.override.abstract",
duke@1: c, undef1, undef1.location());
duke@1: }
duke@1: }
duke@1: } catch (CompletionFailure ex) {
duke@1: completionError(pos, ex);
duke@1: }
duke@1: }
duke@1: //where
duke@1: /** Return first abstract member of class `c' that is not defined
duke@1: * in `impl', null if there is none.
duke@1: */
duke@1: private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
duke@1: MethodSymbol undef = null;
duke@1: // Do not bother to search in classes that are not abstract,
duke@1: // since they cannot have abstract members.
duke@1: if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
duke@1: Scope s = c.members();
duke@1: for (Scope.Entry e = s.elems;
duke@1: undef == null && e != null;
duke@1: e = e.sibling) {
duke@1: if (e.sym.kind == MTH &&
duke@1: (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
duke@1: MethodSymbol absmeth = (MethodSymbol)e.sym;
duke@1: MethodSymbol implmeth = absmeth.implementation(impl, types, true);
duke@1: if (implmeth == null || implmeth == absmeth)
duke@1: undef = absmeth;
duke@1: }
duke@1: }
duke@1: if (undef == null) {
duke@1: Type st = types.supertype(c.type);
duke@1: if (st.tag == CLASS)
duke@1: undef = firstUndef(impl, (ClassSymbol)st.tsym);
duke@1: }
duke@1: for (List l = types.interfaces(c.type);
duke@1: undef == null && l.nonEmpty();
duke@1: l = l.tail) {
duke@1: undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
duke@1: }
duke@1: }
duke@1: return undef;
duke@1: }
duke@1:
duke@1: /** Check for cyclic references. Issue an error if the
duke@1: * symbol of the type referred to has a LOCKED flag set.
duke@1: *
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type referred to.
duke@1: */
duke@1: void checkNonCyclic(DiagnosticPosition pos, Type t) {
duke@1: checkNonCyclicInternal(pos, t);
duke@1: }
duke@1:
duke@1:
duke@1: void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
duke@1: checkNonCyclic1(pos, t, new HashSet());
duke@1: }
duke@1:
duke@1: private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set seen) {
duke@1: final TypeVar tv;
duke@1: if (seen.contains(t)) {
duke@1: tv = (TypeVar)t;
duke@1: tv.bound = new ErrorType();
duke@1: log.error(pos, "cyclic.inheritance", t);
duke@1: } else if (t.tag == TYPEVAR) {
duke@1: tv = (TypeVar)t;
duke@1: seen.add(tv);
duke@1: for (Type b : types.getBounds(tv))
duke@1: checkNonCyclic1(pos, b, seen);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check for cyclic references. Issue an error if the
duke@1: * symbol of the type referred to has a LOCKED flag set.
duke@1: *
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param t The type referred to.
duke@1: * @returns True if the check completed on all attributed classes
duke@1: */
duke@1: private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
duke@1: boolean complete = true; // was the check complete?
duke@1: //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
duke@1: Symbol c = t.tsym;
duke@1: if ((c.flags_field & ACYCLIC) != 0) return true;
duke@1:
duke@1: if ((c.flags_field & LOCKED) != 0) {
duke@1: noteCyclic(pos, (ClassSymbol)c);
duke@1: } else if (!c.type.isErroneous()) {
duke@1: try {
duke@1: c.flags_field |= LOCKED;
duke@1: if (c.type.tag == CLASS) {
duke@1: ClassType clazz = (ClassType)c.type;
duke@1: if (clazz.interfaces_field != null)
duke@1: for (List l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
duke@1: complete &= checkNonCyclicInternal(pos, l.head);
duke@1: if (clazz.supertype_field != null) {
duke@1: Type st = clazz.supertype_field;
duke@1: if (st != null && st.tag == CLASS)
duke@1: complete &= checkNonCyclicInternal(pos, st);
duke@1: }
duke@1: if (c.owner.kind == TYP)
duke@1: complete &= checkNonCyclicInternal(pos, c.owner.type);
duke@1: }
duke@1: } finally {
duke@1: c.flags_field &= ~LOCKED;
duke@1: }
duke@1: }
duke@1: if (complete)
duke@1: complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
duke@1: if (complete) c.flags_field |= ACYCLIC;
duke@1: return complete;
duke@1: }
duke@1:
duke@1: /** Note that we found an inheritance cycle. */
duke@1: private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
duke@1: log.error(pos, "cyclic.inheritance", c);
duke@1: for (List l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
duke@1: l.head = new ErrorType((ClassSymbol)l.head.tsym);
duke@1: Type st = types.supertype(c.type);
duke@1: if (st.tag == CLASS)
duke@1: ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
duke@1: c.type = new ErrorType(c);
duke@1: c.flags_field |= ACYCLIC;
duke@1: }
duke@1:
duke@1: /** Check that all methods which implement some
duke@1: * method conform to the method they implement.
duke@1: * @param tree The class definition whose members are checked.
duke@1: */
duke@1: void checkImplementations(JCClassDecl tree) {
duke@1: checkImplementations(tree, tree.sym);
duke@1: }
duke@1: //where
duke@1: /** Check that all methods which implement some
duke@1: * method in `ic' conform to the method they implement.
duke@1: */
duke@1: void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
duke@1: ClassSymbol origin = tree.sym;
duke@1: for (List l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
duke@1: ClassSymbol lc = (ClassSymbol)l.head.tsym;
duke@1: if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
duke@1: for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
duke@1: if (e.sym.kind == MTH &&
duke@1: (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
duke@1: MethodSymbol absmeth = (MethodSymbol)e.sym;
duke@1: MethodSymbol implmeth = absmeth.implementation(origin, types, false);
duke@1: if (implmeth != null && implmeth != absmeth &&
duke@1: (implmeth.owner.flags() & INTERFACE) ==
duke@1: (origin.flags() & INTERFACE)) {
duke@1: // don't check if implmeth is in a class, yet
duke@1: // origin is an interface. This case arises only
duke@1: // if implmeth is declared in Object. The reason is
duke@1: // that interfaces really don't inherit from
duke@1: // Object it's just that the compiler represents
duke@1: // things that way.
duke@1: checkOverride(tree, implmeth, absmeth, origin);
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check that all abstract methods implemented by a class are
duke@1: * mutually compatible.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param c The class whose interfaces are checked.
duke@1: */
duke@1: void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
duke@1: List supertypes = types.interfaces(c);
duke@1: Type supertype = types.supertype(c);
duke@1: if (supertype.tag == CLASS &&
duke@1: (supertype.tsym.flags() & ABSTRACT) != 0)
duke@1: supertypes = supertypes.prepend(supertype);
duke@1: for (List l = supertypes; l.nonEmpty(); l = l.tail) {
duke@1: if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
duke@1: !checkCompatibleAbstracts(pos, l.head, l.head, c))
duke@1: return;
duke@1: for (List m = supertypes; m != l; m = m.tail)
duke@1: if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
duke@1: return;
duke@1: }
duke@1: checkCompatibleConcretes(pos, c);
duke@1: }
duke@1:
duke@1: /** Check that class c does not implement directly or indirectly
duke@1: * the same parameterized interface with two different argument lists.
duke@1: * @param pos Position to be used for error reporting.
duke@1: * @param type The type whose interfaces are checked.
duke@1: */
duke@1: void checkClassBounds(DiagnosticPosition pos, Type type) {
duke@1: checkClassBounds(pos, new HashMap(), type);
duke@1: }
duke@1: //where
duke@1: /** Enter all interfaces of type `type' into the hash table `seensofar'
duke@1: * with their class symbol as key and their type as value. Make
duke@1: * sure no class is entered with two different types.
duke@1: */
duke@1: void checkClassBounds(DiagnosticPosition pos,
duke@1: Map seensofar,
duke@1: Type type) {
duke@1: if (type.isErroneous()) return;
duke@1: for (List l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
duke@1: Type it = l.head;
duke@1: Type oldit = seensofar.put(it.tsym, it);
duke@1: if (oldit != null) {
duke@1: List oldparams = oldit.allparams();
duke@1: List newparams = it.allparams();
duke@1: if (!types.containsTypeEquivalent(oldparams, newparams))
duke@1: log.error(pos, "cant.inherit.diff.arg",
duke@1: it.tsym, Type.toString(oldparams),
duke@1: Type.toString(newparams));
duke@1: }
duke@1: checkClassBounds(pos, seensofar, it);
duke@1: }
duke@1: Type st = types.supertype(type);
duke@1: if (st != null) checkClassBounds(pos, seensofar, st);
duke@1: }
duke@1:
duke@1: /** Enter interface into into set.
duke@1: * If it existed already, issue a "repeated interface" error.
duke@1: */
duke@1: void checkNotRepeated(DiagnosticPosition pos, Type it, Set its) {
duke@1: if (its.contains(it))
duke@1: log.error(pos, "repeated.interface");
duke@1: else {
duke@1: its.add(it);
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Check annotations
duke@1: **************************************************************************/
duke@1:
duke@1: /** Annotation types are restricted to primitives, String, an
duke@1: * enum, an annotation, Class, Class>, Class extends
duke@1: * Anything>, arrays of the preceding.
duke@1: */
duke@1: void validateAnnotationType(JCTree restype) {
duke@1: // restype may be null if an error occurred, so don't bother validating it
duke@1: if (restype != null) {
duke@1: validateAnnotationType(restype.pos(), restype.type);
duke@1: }
duke@1: }
duke@1:
duke@1: void validateAnnotationType(DiagnosticPosition pos, Type type) {
duke@1: if (type.isPrimitive()) return;
duke@1: if (types.isSameType(type, syms.stringType)) return;
duke@1: if ((type.tsym.flags() & Flags.ENUM) != 0) return;
duke@1: if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
duke@1: if (types.lowerBound(type).tsym == syms.classType.tsym) return;
duke@1: if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
duke@1: validateAnnotationType(pos, types.elemtype(type));
duke@1: return;
duke@1: }
duke@1: log.error(pos, "invalid.annotation.member.type");
duke@1: }
duke@1:
duke@1: /**
duke@1: * "It is also a compile-time error if any method declared in an
duke@1: * annotation type has a signature that is override-equivalent to
duke@1: * that of any public or protected method declared in class Object
duke@1: * or in the interface annotation.Annotation."
duke@1: *
duke@1: * @jls3 9.6 Annotation Types
duke@1: */
duke@1: void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
duke@1: for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
duke@1: Scope s = sup.tsym.members();
duke@1: for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
duke@1: if (e.sym.kind == MTH &&
duke@1: (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
duke@1: types.overrideEquivalent(m.type, e.sym.type))
duke@1: log.error(pos, "intf.annotation.member.clash", e.sym, sup);
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /** Check the annotations of a symbol.
duke@1: */
duke@1: public void validateAnnotations(List annotations, Symbol s) {
duke@1: if (skipAnnotations) return;
duke@1: for (JCAnnotation a : annotations)
duke@1: validateAnnotation(a, s);
duke@1: }
duke@1:
duke@1: /** Check an annotation of a symbol.
duke@1: */
duke@1: public void validateAnnotation(JCAnnotation a, Symbol s) {
duke@1: validateAnnotation(a);
duke@1:
duke@1: if (!annotationApplicable(a, s))
duke@1: log.error(a.pos(), "annotation.type.not.applicable");
duke@1:
duke@1: if (a.annotationType.type.tsym == syms.overrideType.tsym) {
duke@1: if (!isOverrider(s))
duke@1: log.error(a.pos(), "method.does.not.override.superclass");
duke@1: }
duke@1: }
duke@1:
duke@1: /** Is s a method symbol that overrides a method in a superclass? */
duke@1: boolean isOverrider(Symbol s) {
duke@1: if (s.kind != MTH || s.isStatic())
duke@1: return false;
duke@1: MethodSymbol m = (MethodSymbol)s;
duke@1: TypeSymbol owner = (TypeSymbol)m.owner;
duke@1: for (Type sup : types.closure(owner.type)) {
duke@1: if (sup == owner.type)
duke@1: continue; // skip "this"
duke@1: Scope scope = sup.tsym.members();
duke@1: for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
duke@1: if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
duke@1: return true;
duke@1: }
duke@1: }
duke@1: return false;
duke@1: }
duke@1:
duke@1: /** Is the annotation applicable to the symbol? */
duke@1: boolean annotationApplicable(JCAnnotation a, Symbol s) {
duke@1: Attribute.Compound atTarget =
duke@1: a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
duke@1: if (atTarget == null) return true;
duke@1: Attribute atValue = atTarget.member(names.value);
duke@1: if (!(atValue instanceof Attribute.Array)) return true; // error recovery
duke@1: Attribute.Array arr = (Attribute.Array) atValue;
duke@1: for (Attribute app : arr.values) {
duke@1: if (!(app instanceof Attribute.Enum)) return true; // recovery
duke@1: Attribute.Enum e = (Attribute.Enum) app;
duke@1: if (e.value.name == names.TYPE)
duke@1: { if (s.kind == TYP) return true; }
duke@1: else if (e.value.name == names.FIELD)
duke@1: { if (s.kind == VAR && s.owner.kind != MTH) return true; }
duke@1: else if (e.value.name == names.METHOD)
duke@1: { if (s.kind == MTH && !s.isConstructor()) return true; }
duke@1: else if (e.value.name == names.PARAMETER)
duke@1: { if (s.kind == VAR &&
duke@1: s.owner.kind == MTH &&
duke@1: (s.flags() & PARAMETER) != 0)
duke@1: return true;
duke@1: }
duke@1: else if (e.value.name == names.CONSTRUCTOR)
duke@1: { if (s.kind == MTH && s.isConstructor()) return true; }
duke@1: else if (e.value.name == names.LOCAL_VARIABLE)
duke@1: { if (s.kind == VAR && s.owner.kind == MTH &&
duke@1: (s.flags() & PARAMETER) == 0)
duke@1: return true;
duke@1: }
duke@1: else if (e.value.name == names.ANNOTATION_TYPE)
duke@1: { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
duke@1: return true;
duke@1: }
duke@1: else if (e.value.name == names.PACKAGE)
duke@1: { if (s.kind == PCK) return true; }
duke@1: else
duke@1: return true; // recovery
duke@1: }
duke@1: return false;
duke@1: }
duke@1:
duke@1: /** Check an annotation value.
duke@1: */
duke@1: public void validateAnnotation(JCAnnotation a) {
duke@1: if (a.type.isErroneous()) return;
duke@1:
duke@1: // collect an inventory of the members
duke@1: Set members = new HashSet();
duke@1: for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
duke@1: e != null;
duke@1: e = e.sibling)
duke@1: if (e.sym.kind == MTH)
duke@1: members.add((MethodSymbol) e.sym);
duke@1:
duke@1: // count them off as they're annotated
duke@1: for (JCTree arg : a.args) {
duke@1: if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
duke@1: JCAssign assign = (JCAssign) arg;
duke@1: Symbol m = TreeInfo.symbol(assign.lhs);
duke@1: if (m == null || m.type.isErroneous()) continue;
duke@1: if (!members.remove(m))
duke@1: log.error(arg.pos(), "duplicate.annotation.member.value",
duke@1: m.name, a.type);
duke@1: if (assign.rhs.getTag() == ANNOTATION)
duke@1: validateAnnotation((JCAnnotation)assign.rhs);
duke@1: }
duke@1:
duke@1: // all the remaining ones better have default values
duke@1: for (MethodSymbol m : members)
duke@1: if (m.defaultValue == null && !m.type.isErroneous())
duke@1: log.error(a.pos(), "annotation.missing.default.value",
duke@1: a.type, m.name);
duke@1:
duke@1: // special case: java.lang.annotation.Target must not have
duke@1: // repeated values in its value member
duke@1: if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
duke@1: a.args.tail == null)
duke@1: return;
duke@1:
duke@1: if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
duke@1: JCAssign assign = (JCAssign) a.args.head;
duke@1: Symbol m = TreeInfo.symbol(assign.lhs);
duke@1: if (m.name != names.value) return;
duke@1: JCTree rhs = assign.rhs;
duke@1: if (rhs.getTag() != JCTree.NEWARRAY) return;
duke@1: JCNewArray na = (JCNewArray) rhs;
duke@1: Set targets = new HashSet();
duke@1: for (JCTree elem : na.elems) {
duke@1: if (!targets.add(TreeInfo.symbol(elem))) {
duke@1: log.error(elem.pos(), "repeated.annotation.target");
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
duke@1: if (allowAnnotations &&
duke@1: lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
duke@1: (s.flags() & DEPRECATED) != 0 &&
duke@1: !syms.deprecatedType.isErroneous() &&
duke@1: s.attribute(syms.deprecatedType.tsym) == null) {
duke@1: log.warning(pos, "missing.deprecated.annotation");
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Check for recursive annotation elements.
duke@1: **************************************************************************/
duke@1:
duke@1: /** Check for cycles in the graph of annotation elements.
duke@1: */
duke@1: void checkNonCyclicElements(JCClassDecl tree) {
duke@1: if ((tree.sym.flags_field & ANNOTATION) == 0) return;
duke@1: assert (tree.sym.flags_field & LOCKED) == 0;
duke@1: try {
duke@1: tree.sym.flags_field |= LOCKED;
duke@1: for (JCTree def : tree.defs) {
duke@1: if (def.getTag() != JCTree.METHODDEF) continue;
duke@1: JCMethodDecl meth = (JCMethodDecl)def;
duke@1: checkAnnotationResType(meth.pos(), meth.restype.type);
duke@1: }
duke@1: } finally {
duke@1: tree.sym.flags_field &= ~LOCKED;
duke@1: tree.sym.flags_field |= ACYCLIC_ANN;
duke@1: }
duke@1: }
duke@1:
duke@1: void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
duke@1: if ((tsym.flags_field & ACYCLIC_ANN) != 0)
duke@1: return;
duke@1: if ((tsym.flags_field & LOCKED) != 0) {
duke@1: log.error(pos, "cyclic.annotation.element");
duke@1: return;
duke@1: }
duke@1: try {
duke@1: tsym.flags_field |= LOCKED;
duke@1: for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
duke@1: Symbol s = e.sym;
duke@1: if (s.kind != Kinds.MTH)
duke@1: continue;
duke@1: checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
duke@1: }
duke@1: } finally {
duke@1: tsym.flags_field &= ~LOCKED;
duke@1: tsym.flags_field |= ACYCLIC_ANN;
duke@1: }
duke@1: }
duke@1:
duke@1: void checkAnnotationResType(DiagnosticPosition pos, Type type) {
duke@1: switch (type.tag) {
duke@1: case TypeTags.CLASS:
duke@1: if ((type.tsym.flags() & ANNOTATION) != 0)
duke@1: checkNonCyclicElementsInternal(pos, type.tsym);
duke@1: break;
duke@1: case TypeTags.ARRAY:
duke@1: checkAnnotationResType(pos, types.elemtype(type));
duke@1: break;
duke@1: default:
duke@1: break; // int etc
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Check for cycles in the constructor call graph.
duke@1: **************************************************************************/
duke@1:
duke@1: /** Check for cycles in the graph of constructors calling other
duke@1: * constructors.
duke@1: */
duke@1: void checkCyclicConstructors(JCClassDecl tree) {
duke@1: Map callMap = new HashMap();
duke@1:
duke@1: // enter each constructor this-call into the map
duke@1: for (List l = tree.defs; l.nonEmpty(); l = l.tail) {
duke@1: JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
duke@1: if (app == null) continue;
duke@1: JCMethodDecl meth = (JCMethodDecl) l.head;
duke@1: if (TreeInfo.name(app.meth) == names._this) {
duke@1: callMap.put(meth.sym, TreeInfo.symbol(app.meth));
duke@1: } else {
duke@1: meth.sym.flags_field |= ACYCLIC;
duke@1: }
duke@1: }
duke@1:
duke@1: // Check for cycles in the map
duke@1: Symbol[] ctors = new Symbol[0];
duke@1: ctors = callMap.keySet().toArray(ctors);
duke@1: for (Symbol caller : ctors) {
duke@1: checkCyclicConstructor(tree, caller, callMap);
duke@1: }
duke@1: }
duke@1:
duke@1: /** Look in the map to see if the given constructor is part of a
duke@1: * call cycle.
duke@1: */
duke@1: private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
duke@1: Map callMap) {
duke@1: if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
duke@1: if ((ctor.flags_field & LOCKED) != 0) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
duke@1: "recursive.ctor.invocation");
duke@1: } else {
duke@1: ctor.flags_field |= LOCKED;
duke@1: checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
duke@1: ctor.flags_field &= ~LOCKED;
duke@1: }
duke@1: ctor.flags_field |= ACYCLIC;
duke@1: }
duke@1: }
duke@1:
duke@1: /* *************************************************************************
duke@1: * Miscellaneous
duke@1: **************************************************************************/
duke@1:
duke@1: /**
duke@1: * Return the opcode of the operator but emit an error if it is an
duke@1: * error.
duke@1: * @param pos position for error reporting.
duke@1: * @param operator an operator
duke@1: * @param tag a tree tag
duke@1: * @param left type of left hand side
duke@1: * @param right type of right hand side
duke@1: */
duke@1: int checkOperator(DiagnosticPosition pos,
duke@1: OperatorSymbol operator,
duke@1: int tag,
duke@1: Type left,
duke@1: Type right) {
duke@1: if (operator.opcode == ByteCodes.error) {
duke@1: log.error(pos,
duke@1: "operator.cant.be.applied",
duke@1: treeinfo.operatorName(tag),
duke@1: left + "," + right);
duke@1: }
duke@1: return operator.opcode;
duke@1: }
duke@1:
duke@1:
duke@1: /**
duke@1: * Check for division by integer constant zero
duke@1: * @param pos Position for error reporting.
duke@1: * @param operator The operator for the expression
duke@1: * @param operand The right hand operand for the expression
duke@1: */
duke@1: void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
duke@1: if (operand.constValue() != null
duke@1: && lint.isEnabled(Lint.LintCategory.DIVZERO)
duke@1: && operand.tag <= LONG
duke@1: && ((Number) (operand.constValue())).longValue() == 0) {
duke@1: int opc = ((OperatorSymbol)operator).opcode;
duke@1: if (opc == ByteCodes.idiv || opc == ByteCodes.imod
duke@1: || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
duke@1: log.warning(pos, "div.zero");
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Check for empty statements after if
duke@1: */
duke@1: void checkEmptyIf(JCIf tree) {
duke@1: if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
duke@1: log.warning(tree.thenpart.pos(), "empty.if");
duke@1: }
duke@1:
duke@1: /** Check that symbol is unique in given scope.
duke@1: * @param pos Position for error reporting.
duke@1: * @param sym The symbol.
duke@1: * @param s The scope.
duke@1: */
duke@1: boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
duke@1: if (sym.type.isErroneous())
duke@1: return true;
duke@1: if (sym.owner.name == names.any) return false;
duke@1: for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
duke@1: if (sym != e.sym &&
duke@1: sym.kind == e.sym.kind &&
duke@1: sym.name != names.error &&
duke@1: (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
duke@1: if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
duke@1: varargsDuplicateError(pos, sym, e.sym);
duke@1: else
duke@1: duplicateError(pos, e.sym);
duke@1: return false;
duke@1: }
duke@1: }
duke@1: return true;
duke@1: }
duke@1:
duke@1: /** Check that single-type import is not already imported or top-level defined,
duke@1: * but make an exception for two single-type imports which denote the same type.
duke@1: * @param pos Position for error reporting.
duke@1: * @param sym The symbol.
duke@1: * @param s The scope
duke@1: */
duke@1: boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
duke@1: return checkUniqueImport(pos, sym, s, false);
duke@1: }
duke@1:
duke@1: /** Check that static single-type import is not already imported or top-level defined,
duke@1: * but make an exception for two single-type imports which denote the same type.
duke@1: * @param pos Position for error reporting.
duke@1: * @param sym The symbol.
duke@1: * @param s The scope
duke@1: * @param staticImport Whether or not this was a static import
duke@1: */
duke@1: boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
duke@1: return checkUniqueImport(pos, sym, s, true);
duke@1: }
duke@1:
duke@1: /** Check that single-type import is not already imported or top-level defined,
duke@1: * but make an exception for two single-type imports which denote the same type.
duke@1: * @param pos Position for error reporting.
duke@1: * @param sym The symbol.
duke@1: * @param s The scope.
duke@1: * @param staticImport Whether or not this was a static import
duke@1: */
duke@1: private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
duke@1: for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
duke@1: // is encountered class entered via a class declaration?
duke@1: boolean isClassDecl = e.scope == s;
duke@1: if ((isClassDecl || sym != e.sym) &&
duke@1: sym.kind == e.sym.kind &&
duke@1: sym.name != names.error) {
duke@1: if (!e.sym.type.isErroneous()) {
duke@1: String what = e.sym.toString();
duke@1: if (!isClassDecl) {
duke@1: if (staticImport)
duke@1: log.error(pos, "already.defined.static.single.import", what);
duke@1: else
duke@1: log.error(pos, "already.defined.single.import", what);
duke@1: }
duke@1: else if (sym != e.sym)
duke@1: log.error(pos, "already.defined.this.unit", what);
duke@1: }
duke@1: return false;
duke@1: }
duke@1: }
duke@1: return true;
duke@1: }
duke@1:
duke@1: /** Check that a qualified name is in canonical form (for import decls).
duke@1: */
duke@1: public void checkCanonical(JCTree tree) {
duke@1: if (!isCanonical(tree))
duke@1: log.error(tree.pos(), "import.requires.canonical",
duke@1: TreeInfo.symbol(tree));
duke@1: }
duke@1: // where
duke@1: private boolean isCanonical(JCTree tree) {
duke@1: while (tree.getTag() == JCTree.SELECT) {
duke@1: JCFieldAccess s = (JCFieldAccess) tree;
duke@1: if (s.sym.owner != TreeInfo.symbol(s.selected))
duke@1: return false;
duke@1: tree = s.selected;
duke@1: }
duke@1: return true;
duke@1: }
duke@1:
duke@1: private class ConversionWarner extends Warner {
duke@1: final String key;
duke@1: final Type found;
duke@1: final Type expected;
duke@1: public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
duke@1: super(pos);
duke@1: this.key = key;
duke@1: this.found = found;
duke@1: this.expected = expected;
duke@1: }
duke@1:
duke@1: public void warnUnchecked() {
duke@1: boolean warned = this.warned;
duke@1: super.warnUnchecked();
duke@1: if (warned) return; // suppress redundant diagnostics
duke@1: Object problem = JCDiagnostic.fragment(key);
duke@1: Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
duke@1: }
duke@1: }
duke@1:
duke@1: public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
duke@1: return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
duke@1: }
duke@1:
duke@1: public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
duke@1: return new ConversionWarner(pos, "unchecked.assign", found, expected);
duke@1: }
duke@1: }