duke@1: /*
jjg@1492: * Copyright (c) 1999, 2013, Oracle and/or its affiliates. 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
ohair@554: * published by the Free Software Foundation. Oracle designates this
duke@1: * particular file as subject to the "Classpath" exception as provided
ohair@554: * by Oracle 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: *
ohair@554: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@554: * or visit www.oracle.com if you need additional information or have any
ohair@554: * questions.
duke@1: */
duke@1:
duke@1: package com.sun.tools.javac.comp;
duke@1:
duke@1: import java.util.*;
jjg@1521:
ohrstrom@1384: import javax.tools.JavaFileManager;
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.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.*;
mcimadamore@1347: import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
mcimadamore@1337: import com.sun.tools.javac.comp.Infer.InferenceContext;
mcimadamore@1337: import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
mcimadamore@1510: import com.sun.tools.javac.tree.JCTree.*;
mcimadamore@1510: import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
duke@1:
duke@1: import static com.sun.tools.javac.code.Flags.*;
jjg@1127: import static com.sun.tools.javac.code.Flags.ANNOTATION;
jjg@1127: import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
duke@1: import static com.sun.tools.javac.code.Kinds.*;
jjg@1374: import static com.sun.tools.javac.code.TypeTag.*;
jjg@1374: import static com.sun.tools.javac.code.TypeTag.WILDCARD;
duke@1:
jjg@1127: import static com.sun.tools.javac.tree.JCTree.Tag.*;
jjg@700:
duke@1: /** Type checking helper class for the attribution phase.
duke@1: *
jjg@581: *
This is NOT part of any supported API.
jjg@581: * If 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:
jjg@113: private final Names names;
duke@1: private final Log log;
mcimadamore@1219: private final Resolve rs;
duke@1: private final Symtab syms;
mcimadamore@690: private final Enter enter;
mcimadamore@1347: private final DeferredAttr deferredAttr;
duke@1: private final Infer infer;
duke@1: private final Types types;
mcimadamore@89: private final JCDiagnostic.Factory diags;
mcimadamore@359: private boolean warnOnSyntheticConflicts;
jjg@576: private boolean suppressAbortOnBadClassFile;
mcimadamore@852: private boolean enableSunApiLintControl;
duke@1: private final TreeInfo treeinfo;
ohrstrom@1384: private final JavaFileManager fileManager;
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:
mcimadamore@795: // The method being analyzed in Attr - it is set/reset as needed by
mcimadamore@795: // Attr as it visits new method declarations.
mcimadamore@795: private MethodSymbol method;
mcimadamore@795:
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:
jjg@113: names = Names.instance(context);
jjg@1521: dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
jjg@1521: names.FIELD, names.METHOD, names.CONSTRUCTOR,
jjg@1521: names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
duke@1: log = Log.instance(context);
mcimadamore@1219: rs = Resolve.instance(context);
duke@1: syms = Symtab.instance(context);
mcimadamore@690: enter = Enter.instance(context);
mcimadamore@1347: deferredAttr = DeferredAttr.instance(context);
duke@1: infer = Infer.instance(context);
duke@1: this.types = Types.instance(context);
mcimadamore@89: diags = JCDiagnostic.Factory.instance(context);
duke@1: Options options = Options.instance(context);
duke@1: lint = Lint.instance(context);
duke@1: treeinfo = TreeInfo.instance(context);
ohrstrom@1384: fileManager = context.get(JavaFileManager.class);
duke@1:
duke@1: Source source = Source.instance(context);
duke@1: allowGenerics = source.allowGenerics();
mcimadamore@1219: allowVarargs = source.allowVarargs();
duke@1: allowAnnotations = source.allowAnnotations();
jjg@398: allowCovariantReturns = source.allowCovariantReturns();
mcimadamore@795: allowSimplifiedVarargs = source.allowSimplifiedVarargs();
mcimadamore@1393: allowDefaultMethods = source.allowDefaultMethods();
mcimadamore@1415: allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
jjg@1157: complexInference = options.isSet("complexinference");
jjg@700: warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
jjg@700: suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
mcimadamore@852: enableSunApiLintControl = options.isSet("enableSunApiLintControl");
duke@1:
jjg@398: Target target = Target.instance(context);
jjg@398: syntheticNameChar = target.syntheticNameChar();
jjg@398:
duke@1: boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
duke@1: boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
jjg@377: boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
jjg@60: boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
duke@1:
jjg@60: deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
jjg@612: enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
jjg@60: uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
jjg@612: enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
jjg@377: sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
jjg@612: enforceMandatoryWarnings, "sunapi", null);
mcimadamore@852:
mcimadamore@852: deferredLintHandler = DeferredLintHandler.immediateHandler;
duke@1: }
duke@1:
duke@1: /** Switch: generics enabled?
duke@1: */
duke@1: boolean allowGenerics;
duke@1:
mcimadamore@1219: /** Switch: varargs enabled?
mcimadamore@1219: */
mcimadamore@1219: boolean allowVarargs;
mcimadamore@1219:
duke@1: /** Switch: annotations enabled?
duke@1: */
duke@1: boolean allowAnnotations;
duke@1:
jjg@398: /** Switch: covariant returns enabled?
jjg@398: */
jjg@398: boolean allowCovariantReturns;
jjg@398:
mcimadamore@795: /** Switch: simplified varargs enabled?
mcimadamore@795: */
mcimadamore@795: boolean allowSimplifiedVarargs;
mcimadamore@795:
mcimadamore@1393: /** Switch: default methods enabled?
mcimadamore@1393: */
mcimadamore@1393: boolean allowDefaultMethods;
mcimadamore@1393:
mcimadamore@1393: /** Switch: should unrelated return types trigger a method clash?
mcimadamore@1393: */
mcimadamore@1393: boolean allowStrictMethodClashCheck;
mcimadamore@1393:
duke@1: /** Switch: -complexinference option set?
duke@1: */
duke@1: boolean complexInference;
duke@1:
jjg@398: /** Character for synthetic names
jjg@398: */
jjg@398: char syntheticNameChar;
jjg@398:
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:
jjg@582: /** A handler for messages about using proprietary API.
jjg@377: */
jjg@377: private MandatoryWarningHandler sunApiHandler;
duke@1:
mcimadamore@852: /** A handler for deferred lint warnings.
mcimadamore@852: */
mcimadamore@852: private DeferredLintHandler deferredLintHandler;
mcimadamore@852:
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:
mcimadamore@852: DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
mcimadamore@852: DeferredLintHandler prev = deferredLintHandler;
mcimadamore@852: deferredLintHandler = newDeferredLintHandler;
mcimadamore@852: return prev;
mcimadamore@852: }
mcimadamore@852:
mcimadamore@795: MethodSymbol setMethod(MethodSymbol newMethod) {
mcimadamore@795: MethodSymbol prev = method;
mcimadamore@795: method = newMethod;
mcimadamore@795: return prev;
mcimadamore@795: }
mcimadamore@795:
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:
mcimadamore@580: /** Warn about unsafe vararg method decl.
mcimadamore@580: * @param pos Position to be used for error reporting.
mcimadamore@580: */
mcimadamore@795: void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
mcimadamore@795: if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
mcimadamore@795: log.warning(LintCategory.VARARGS, pos, key, args);
mcimadamore@580: }
mcimadamore@580:
jjg@582: /** Warn about using proprietary API.
jjg@377: * @param pos Position to be used for error reporting.
jjg@377: * @param msg A string describing the problem.
jjg@377: */
jjg@377: public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
jjg@377: if (!lint.isSuppressed(LintCategory.SUNAPI))
jjg@377: sunApiHandler.report(pos, msg, args);
jjg@377: }
jjg@377:
jjg@505: public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
jjg@505: if (lint.isEnabled(LintCategory.STATIC))
jjg@612: log.warning(LintCategory.STATIC, pos, msg, args);
jjg@505: }
jjg@505:
duke@1: /**
duke@1: * Report any deferred diagnostics.
duke@1: */
duke@1: public void reportDeferredDiagnostics() {
duke@1: deprecationHandler.reportDeferredDiagnostic();
duke@1: uncheckedHandler.reportDeferredDiagnostic();
jjg@377: sunApiHandler.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) {
jjg@12: log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
jjg@576: if (ex instanceof ClassReader.BadClassFile
jjg@576: && !suppressAbortOnBadClassFile) throw new Abort();
duke@1: else 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) {
jrose@267: // this error used to be raised by the parser,
jrose@267: // but has been delayed to this point:
jjg@1374: if (found instanceof Type && ((Type)found).hasTag(VOID)) {
jrose@267: log.error(pos, "illegal.start.of.type");
jrose@267: return syms.errType;
jrose@267: }
duke@1: log.error(pos, "type.found.req", found, required);
jjg@110: return types.createErrorType(found instanceof Type ? (Type)found : 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()) {
mcimadamore@1085: Symbol location = sym.location();
mcimadamore@1085: if (location.kind == MTH &&
mcimadamore@1085: ((MethodSymbol)location).isStaticOrInstanceInit()) {
mcimadamore@1085: log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
mcimadamore@1085: kindName(sym.location()), kindName(sym.location().enclClass()),
mcimadamore@1085: sym.location().enclClass());
mcimadamore@1085: } else {
mcimadamore@1085: log.error(pos, "already.defined", kindName(sym), sym,
mcimadamore@1085: kindName(sym.location()), sym.location());
mcimadamore@1085: }
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()) {
jjg@1374: if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
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.
jjg@1358: * This is of the form {@code $ 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 +
jjg@398: 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:
mcimadamore@1238: /**
mcimadamore@1238: * A check context is an object that can be used to perform compatibility
mcimadamore@1238: * checks - depending on the check context, meaning of 'compatibility' might
mcimadamore@1238: * vary significantly.
mcimadamore@1238: */
mcimadamore@1348: public interface CheckContext {
mcimadamore@1238: /**
mcimadamore@1238: * Is type 'found' compatible with type 'req' in given context
mcimadamore@1238: */
mcimadamore@1238: boolean compatible(Type found, Type req, Warner warn);
mcimadamore@1238: /**
mcimadamore@1238: * Report a check error
mcimadamore@1238: */
mcimadamore@1296: void report(DiagnosticPosition pos, JCDiagnostic details);
mcimadamore@1238: /**
mcimadamore@1238: * Obtain a warner for this check context
mcimadamore@1238: */
mcimadamore@1238: public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
mcimadamore@1337:
mcimadamore@1337: public Infer.InferenceContext inferenceContext();
mcimadamore@1347:
mcimadamore@1347: public DeferredAttr.DeferredAttrContext deferredAttrContext();
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1238: /**
mcimadamore@1238: * This class represent a check context that is nested within another check
mcimadamore@1238: * context - useful to check sub-expressions. The default behavior simply
mcimadamore@1238: * redirects all method calls to the enclosing check context leveraging
mcimadamore@1238: * the forwarding pattern.
mcimadamore@1238: */
mcimadamore@1238: static class NestedCheckContext implements CheckContext {
mcimadamore@1238: CheckContext enclosingContext;
mcimadamore@1238:
mcimadamore@1238: NestedCheckContext(CheckContext enclosingContext) {
mcimadamore@1238: this.enclosingContext = enclosingContext;
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1238: public boolean compatible(Type found, Type req, Warner warn) {
mcimadamore@1238: return enclosingContext.compatible(found, req, warn);
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1296: public void report(DiagnosticPosition pos, JCDiagnostic details) {
mcimadamore@1296: enclosingContext.report(pos, details);
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1238: public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
mcimadamore@1238: return enclosingContext.checkWarner(pos, found, req);
mcimadamore@1238: }
mcimadamore@1337:
mcimadamore@1337: public Infer.InferenceContext inferenceContext() {
mcimadamore@1337: return enclosingContext.inferenceContext();
mcimadamore@1337: }
mcimadamore@1347:
mcimadamore@1347: public DeferredAttrContext deferredAttrContext() {
mcimadamore@1347: return enclosingContext.deferredAttrContext();
mcimadamore@1347: }
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1238: /**
mcimadamore@1238: * Check context to be used when evaluating assignment/return statements
mcimadamore@1238: */
mcimadamore@1238: CheckContext basicHandler = new CheckContext() {
mcimadamore@1296: public void report(DiagnosticPosition pos, JCDiagnostic details) {
mcimadamore@1296: log.error(pos, "prob.found.req", details);
mcimadamore@1238: }
mcimadamore@1238: public boolean compatible(Type found, Type req, Warner warn) {
mcimadamore@1238: return types.isAssignable(found, req, warn);
mcimadamore@1238: }
mcimadamore@1238:
mcimadamore@1238: public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
mcimadamore@1238: return convertWarner(pos, found, req);
mcimadamore@1238: }
mcimadamore@1337:
mcimadamore@1337: public InferenceContext inferenceContext() {
mcimadamore@1337: return infer.emptyContext;
mcimadamore@1337: }
mcimadamore@1347:
mcimadamore@1347: public DeferredAttrContext deferredAttrContext() {
mcimadamore@1347: return deferredAttr.emptyDeferredAttrContext;
mcimadamore@1347: }
mcimadamore@1238: };
mcimadamore@1238:
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) {
mcimadamore@1238: return checkType(pos, found, req, basicHandler);
darcy@609: }
darcy@609:
mcimadamore@1337: Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
mcimadamore@1337: final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
mcimadamore@1337: if (inferenceContext.free(req)) {
mcimadamore@1337: inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
mcimadamore@1337: @Override
mcimadamore@1337: public void typesInferred(InferenceContext inferenceContext) {
mcimadamore@1337: checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
mcimadamore@1337: }
mcimadamore@1337: });
mcimadamore@1337: }
jjg@1374: if (req.hasTag(ERROR))
duke@1: return req;
jjg@1374: if (req.hasTag(NONE))
duke@1: return found;
mcimadamore@1238: if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
duke@1: return found;
mcimadamore@1238: } else {
jjg@1374: if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
mcimadamore@1296: checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
mcimadamore@1238: return types.createErrorType(found);
mcimadamore@1238: }
mcimadamore@1296: checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
jjg@110: return types.createErrorType(found);
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) {
mcimadamore@1238: return checkCastable(pos, found, req, basicHandler);
mcimadamore@1238: }
mcimadamore@1238: Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
mcimadamore@1268: if (types.isCastable(found, req, castWarner(pos, found, req))) {
duke@1: return req;
duke@1: } else {
mcimadamore@1296: checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
mcimadamore@1238: return types.createErrorType(found);
duke@1: }
duke@1: }
mcimadamore@1237:
mcimadamore@1237: /** Check for redundant casts (i.e. where source type is a subtype of target type)
mcimadamore@1237: * The problem should only be reported for non-292 cast
mcimadamore@1237: */
mcimadamore@1237: public void checkRedundantCast(Env env, JCTypeCast tree) {
mcimadamore@1237: if (!tree.type.isErroneous() &&
mcimadamore@1348: (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
mcimadamore@1348: && types.isSameType(tree.expr.type, tree.clazz.type)
jjg@1521: && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
mcimadamore@1348: && !is292targetTypeCast(tree)) {
mcimadamore@1237: log.warning(Lint.LintCategory.CAST,
mcimadamore@1237: tree.pos(), "redundant.cast", tree.expr.type);
mcimadamore@1237: }
mcimadamore@1237: }
mcimadamore@1237: //where
jjg@1521: private boolean is292targetTypeCast(JCTypeCast tree) {
jjg@1521: boolean is292targetTypeCast = false;
jjg@1521: JCExpression expr = TreeInfo.skipParens(tree.expr);
jjg@1521: if (expr.hasTag(APPLY)) {
jjg@1521: JCMethodInvocation apply = (JCMethodInvocation)expr;
jjg@1521: Symbol sym = TreeInfo.symbol(apply.meth);
jjg@1521: is292targetTypeCast = sym != null &&
jjg@1521: sym.kind == MTH &&
jjg@1521: (sym.flags() & HYPOTHETICAL) != 0;
mcimadamore@1237: }
jjg@1521: return is292targetTypeCast;
jjg@1521: }
mcimadamore@1237:
jjg@1521: private static final boolean ignoreAnnotatedCasts = true;
duke@1:
duke@1: /** Check that a type is within some bounds.
duke@1: *
jjg@1358: * Used in TypeApply to verify that, e.g., X in {@code V} is a valid
duke@1: * type argument.
duke@1: * @param a The type that should be bounded by bs.
jjg@1358: * @param bound The bound.
duke@1: */
mcimadamore@1216: private boolean checkExtends(Type a, Type bound) {
mcimadamore@154: if (a.isUnbound()) {
mcimadamore@821: return true;
jjg@1374: } else if (!a.hasTag(WILDCARD)) {
mcimadamore@154: a = types.upperBound(a);
mcimadamore@1216: return types.isSubtype(a, bound);
mcimadamore@154: } else if (a.isExtendsBound()) {
mcimadamore@1415: return types.isCastable(bound, types.upperBound(a), types.noWarnings);
mcimadamore@154: } else if (a.isSuperBound()) {
mcimadamore@1216: return !types.notSoftSubtype(types.lowerBound(a), bound);
mcimadamore@154: }
mcimadamore@821: return true;
mcimadamore@154: }
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) {
jjg@1374: if (t.hasTag(VOID)) {
duke@1: log.error(pos, "void.not.allowed.here");
jjg@110: return types.createErrorType(t);
duke@1: } else {
duke@1: return t;
duke@1: }
duke@1: }
duke@1:
mcimadamore@1496: Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
mcimadamore@1496: if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
mcimadamore@1496: return typeTagError(pos,
mcimadamore@1496: diags.fragment("type.req.class.array"),
mcimadamore@1496: asTypeParam(t));
mcimadamore@1496: } else {
mcimadamore@1496: return t;
mcimadamore@1496: }
mcimadamore@1496: }
mcimadamore@1496:
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) {
mcimadamore@1496: if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
duke@1: return typeTagError(pos,
mcimadamore@89: diags.fragment("type.req.class"),
mcimadamore@1496: asTypeParam(t));
mcimadamore@1496: } else {
duke@1: return t;
mcimadamore@1496: }
duke@1: }
mcimadamore@1496: //where
mcimadamore@1496: private Object asTypeParam(Type t) {
mcimadamore@1496: return (t.hasTag(TYPEVAR))
mcimadamore@1496: ? diags.fragment("type.parameter", t)
mcimadamore@1496: : t;
mcimadamore@1496: }
duke@1:
mcimadamore@1352: /** Check that type is a valid qualifier for a constructor reference expression
mcimadamore@1352: */
mcimadamore@1352: Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
mcimadamore@1496: t = checkClassOrArrayType(pos, t);
jjg@1374: if (t.hasTag(CLASS)) {
mcimadamore@1352: if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
mcimadamore@1352: log.error(pos, "abstract.cant.be.instantiated");
mcimadamore@1352: t = types.createErrorType(t);
mcimadamore@1352: } else if ((t.tsym.flags() & ENUM) != 0) {
mcimadamore@1352: log.error(pos, "enum.cant.be.instantiated");
mcimadamore@1352: t = types.createErrorType(t);
mcimadamore@1352: }
mcimadamore@1352: }
mcimadamore@1352: return t;
mcimadamore@1352: }
mcimadamore@1352:
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()) {
jjg@1374: if (args.head.hasTag(WILDCARD))
duke@1: return typeTagError(pos,
jjg@598: diags.fragment("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) {
mcimadamore@1496: t = checkClassOrArrayType(pos, t);
mcimadamore@1496: if (!t.isErroneous() && !types.isReifiable(t)) {
duke@1: log.error(pos, "illegal.generic.type.for.instof");
jjg@110: return types.createErrorType(t);
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) {
jjg@1374: if (t.isReference())
duke@1: return t;
jjg@1374: else
duke@1: return typeTagError(pos,
mcimadamore@89: diags.fragment("type.req.ref"),
duke@1: t);
duke@1: }
duke@1:
jrose@267: /** Check that each type is a reference type, i.e. a class, interface or array type
jrose@267: * or a type variable.
jrose@267: * @param trees Original trees, used for error reporting.
jrose@267: * @param types The types to be checked.
jrose@267: */
jrose@267: List checkRefTypes(List trees, List types) {
jrose@267: List tl = trees;
jrose@267: for (List l = types; l.nonEmpty(); l = l.tail) {
jrose@267: l.head = checkRefType(tl.head.pos(), l.head);
jrose@267: tl = tl.tail;
jrose@267: }
jrose@267: return types;
jrose@267: }
jrose@267:
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) {
jjg@1374: if (t.isNullOrReference())
duke@1: return t;
jjg@1374: else
duke@1: return typeTagError(pos,
mcimadamore@89: diags.fragment("type.req.ref"),
duke@1: t);
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",
mcimadamore@80: asFlagSet(TreeInfo.firstFlag(flags & set1)),
mcimadamore@80: asFlagSet(TreeInfo.firstFlag(flags & set2)));
duke@1: return false;
duke@1: } else
duke@1: return true;
duke@1: }
duke@1:
mcimadamore@914: /** Check that usage of diamond operator is correct (i.e. diamond should not
mcimadamore@914: * be used with non-generic classes or in anonymous class creation expressions)
mcimadamore@537: */
mcimadamore@914: Type checkDiamond(JCNewClass tree, Type t) {
mcimadamore@914: if (!TreeInfo.isDiamond(tree) ||
mcimadamore@914: t.isErroneous()) {
mcimadamore@914: return checkClassType(tree.clazz.pos(), t, true);
mcimadamore@914: } else if (tree.def != null) {
mcimadamore@914: log.error(tree.clazz.pos(),
mcimadamore@914: "cant.apply.diamond.1",
mcimadamore@914: t, diags.fragment("diamond.and.anon.class", t));
mcimadamore@914: return types.createErrorType(t);
mcimadamore@948: } else if (t.tsym.type.getTypeArguments().isEmpty()) {
mcimadamore@914: log.error(tree.clazz.pos(),
mcimadamore@914: "cant.apply.diamond.1",
mcimadamore@914: t, diags.fragment("diamond.non.generic", t));
mcimadamore@914: return types.createErrorType(t);
mcimadamore@993: } else if (tree.typeargs != null &&
mcimadamore@993: tree.typeargs.nonEmpty()) {
mcimadamore@993: log.error(tree.clazz.pos(),
mcimadamore@993: "cant.apply.diamond.1",
mcimadamore@993: t, diags.fragment("diamond.and.explicit.params", t));
mcimadamore@993: return types.createErrorType(t);
mcimadamore@914: } else {
mcimadamore@914: return t;
mcimadamore@537: }
mcimadamore@537: }
mcimadamore@537:
mcimadamore@795: void checkVarargsMethodDecl(Env env, JCMethodDecl tree) {
mcimadamore@580: MethodSymbol m = tree.sym;
mcimadamore@795: if (!allowSimplifiedVarargs) return;
mcimadamore@795: boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
mcimadamore@795: Type varargElemType = null;
mcimadamore@580: if (m.isVarArgs()) {
mcimadamore@795: varargElemType = types.elemtype(tree.params.last().type);
mcimadamore@795: }
mcimadamore@795: if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
mcimadamore@795: if (varargElemType != null) {
mcimadamore@795: log.error(tree,
mcimadamore@795: "varargs.invalid.trustme.anno",
mcimadamore@795: syms.trustMeType.tsym,
mcimadamore@795: diags.fragment("varargs.trustme.on.virtual.varargs", m));
mcimadamore@795: } else {
mcimadamore@795: log.error(tree,
mcimadamore@795: "varargs.invalid.trustme.anno",
mcimadamore@795: syms.trustMeType.tsym,
mcimadamore@795: diags.fragment("varargs.trustme.on.non.varargs.meth", m));
mcimadamore@580: }
mcimadamore@795: } else if (hasTrustMeAnno && varargElemType != null &&
mcimadamore@795: types.isReifiable(varargElemType)) {
mcimadamore@795: warnUnsafeVararg(tree,
mcimadamore@795: "varargs.redundant.trustme.anno",
mcimadamore@795: syms.trustMeType.tsym,
mcimadamore@795: diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
mcimadamore@795: }
mcimadamore@795: else if (!hasTrustMeAnno && varargElemType != null &&
mcimadamore@795: !types.isReifiable(varargElemType)) {
mcimadamore@795: warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
mcimadamore@580: }
mcimadamore@580: }
mcimadamore@795: //where
mcimadamore@795: private boolean isTrustMeAllowedOnMethod(Symbol s) {
mcimadamore@795: return (s.flags() & VARARGS) != 0 &&
mcimadamore@795: (s.isConstructor() ||
mcimadamore@795: (s.flags() & (STATIC | FINAL)) != 0);
mcimadamore@795: }
mcimadamore@580:
mcimadamore@1219: Type checkMethod(Type owntype,
mcimadamore@1219: Symbol sym,
mcimadamore@1219: Env env,
mcimadamore@1219: final List argtrees,
mcimadamore@1219: List argtypes,
mcimadamore@1226: boolean useVarargs,
mcimadamore@1226: boolean unchecked) {
mcimadamore@1219: // System.out.println("call : " + env.tree);
mcimadamore@1219: // System.out.println("method : " + owntype);
mcimadamore@1219: // System.out.println("actuals: " + argtypes);
mcimadamore@1219: List formals = owntype.getParameterTypes();
mcimadamore@1219: Type last = useVarargs ? formals.last() : null;
jjg@1521: if (sym.name == names.init &&
mcimadamore@1219: sym.owner == syms.enumSym)
mcimadamore@1219: formals = formals.tail.tail;
mcimadamore@1219: List args = argtrees;
mcimadamore@1347: DeferredAttr.DeferredTypeMap checkDeferredMap =
mcimadamore@1347: deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
mcimadamore@1352: if (args != null) {
mcimadamore@1352: //this is null when type-checking a method reference
mcimadamore@1352: while (formals.head != last) {
mcimadamore@1219: JCTree arg = args.head;
mcimadamore@1352: Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
mcimadamore@1352: assertConvertible(arg, arg.type, formals.head, warn);
mcimadamore@1219: args = args.tail;
mcimadamore@1352: formals = formals.tail;
mcimadamore@1219: }
mcimadamore@1352: if (useVarargs) {
mcimadamore@1352: Type varArg = types.elemtype(last);
mcimadamore@1352: while (args.tail != null) {
mcimadamore@1352: JCTree arg = args.head;
mcimadamore@1352: Warner warn = convertWarner(arg.pos(), arg.type, varArg);
mcimadamore@1352: assertConvertible(arg, arg.type, varArg, warn);
mcimadamore@1352: args = args.tail;
mcimadamore@1352: }
mcimadamore@1352: } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
mcimadamore@1352: // non-varargs call to varargs method
mcimadamore@1352: Type varParam = owntype.getParameterTypes().last();
mcimadamore@1352: Type lastArg = checkDeferredMap.apply(argtypes.last());
mcimadamore@1352: if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
mcimadamore@1352: !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
mcimadamore@1352: log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
mcimadamore@1352: types.elemtype(varParam), varParam);
mcimadamore@1352: }
mcimadamore@1219: }
mcimadamore@1226: if (unchecked) {
mcimadamore@1219: warnUnchecked(env.tree.pos(),
mcimadamore@1219: "unchecked.meth.invocation.applied",
mcimadamore@1219: kindName(sym),
mcimadamore@1219: sym.name,
mcimadamore@1219: rs.methodArguments(sym.type.getParameterTypes()),
mcimadamore@1347: rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
mcimadamore@1219: kindName(sym.location()),
mcimadamore@1219: sym.location());
mcimadamore@1219: owntype = new MethodType(owntype.getParameterTypes(),
mcimadamore@1219: types.erasure(owntype.getReturnType()),
mcimadamore@1219: types.erasure(owntype.getThrownTypes()),
mcimadamore@1219: syms.methodClass);
mcimadamore@1219: }
mcimadamore@1219: if (useVarargs) {
mcimadamore@1219: Type argtype = owntype.getParameterTypes().last();
mcimadamore@1219: if (!types.isReifiable(argtype) &&
mcimadamore@1219: (!allowSimplifiedVarargs ||
mcimadamore@1219: sym.attribute(syms.trustMeType.tsym) == null ||
mcimadamore@1219: !isTrustMeAllowedOnMethod(sym))) {
mcimadamore@1219: warnUnchecked(env.tree.pos(),
mcimadamore@1219: "unchecked.generic.array.creation",
mcimadamore@1219: argtype);
mcimadamore@1219: }
mcimadamore@1415: if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
mcimadamore@1510: TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
mcimadamore@1219: }
mcimadamore@1219: }
mcimadamore@1510: PolyKind pkind = (sym.type.hasTag(FORALL) &&
mcimadamore@1510: sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
mcimadamore@1510: PolyKind.POLY : PolyKind.STANDALONE;
mcimadamore@1510: TreeInfo.setPolyKind(env.tree, pkind);
mcimadamore@1219: return owntype;
mcimadamore@547: }
mcimadamore@1219: //where
mcimadamore@1219: private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
mcimadamore@1219: if (types.isConvertible(actual, formal, warn))
mcimadamore@1219: return;
mcimadamore@1219:
mcimadamore@1219: if (formal.isCompound()
mcimadamore@1219: && types.isSubtype(actual, types.supertype(formal))
mcimadamore@1219: && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
mcimadamore@1219: return;
mcimadamore@1219: }
mcimadamore@547:
mcimadamore@821: /**
mcimadamore@821: * Check that type 't' is a valid instantiation of a generic class
mcimadamore@821: * (see JLS 4.5)
mcimadamore@821: *
mcimadamore@821: * @param t class type to be checked
mcimadamore@821: * @return true if 't' is well-formed
mcimadamore@821: */
mcimadamore@821: public boolean checkValidGenericType(Type t) {
mcimadamore@821: return firstIncompatibleTypeArg(t) == null;
mcimadamore@821: }
mcimadamore@821: //WHERE
mcimadamore@821: private Type firstIncompatibleTypeArg(Type type) {
mcimadamore@821: List formals = type.tsym.type.allparams();
mcimadamore@821: List actuals = type.allparams();
mcimadamore@821: List args = type.getTypeArguments();
mcimadamore@821: List forms = type.tsym.type.getTypeArguments();
mcimadamore@1216: ListBuffer bounds_buf = new ListBuffer();
mcimadamore@821:
mcimadamore@821: // For matching pairs of actual argument types `a' and
mcimadamore@821: // formal type parameters with declared bound `b' ...
mcimadamore@821: while (args.nonEmpty() && forms.nonEmpty()) {
mcimadamore@821: // exact type arguments needs to know their
mcimadamore@821: // bounds (for upper and lower bound
mcimadamore@1216: // calculations). So we create new bounds where
mcimadamore@1216: // type-parameters are replaced with actuals argument types.
mcimadamore@1216: bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
mcimadamore@821: args = args.tail;
mcimadamore@821: forms = forms.tail;
mcimadamore@821: }
mcimadamore@821:
mcimadamore@821: args = type.getTypeArguments();
mcimadamore@821: List tvars_cap = types.substBounds(formals,
mcimadamore@821: formals,
mcimadamore@821: types.capture(type).allparams());
mcimadamore@821: while (args.nonEmpty() && tvars_cap.nonEmpty()) {
mcimadamore@821: // Let the actual arguments know their bound
mcimadamore@821: args.head.withTypeVar((TypeVar)tvars_cap.head);
mcimadamore@821: args = args.tail;
mcimadamore@821: tvars_cap = tvars_cap.tail;
mcimadamore@821: }
mcimadamore@821:
mcimadamore@821: args = type.getTypeArguments();
mcimadamore@1216: List bounds = bounds_buf.toList();
mcimadamore@821:
mcimadamore@1216: while (args.nonEmpty() && bounds.nonEmpty()) {
mcimadamore@1216: Type actual = args.head;
mcimadamore@854: if (!isTypeArgErroneous(actual) &&
mcimadamore@1216: !bounds.head.isErroneous() &&
mcimadamore@1216: !checkExtends(actual, bounds.head)) {
mcimadamore@821: return args.head;
mcimadamore@821: }
mcimadamore@821: args = args.tail;
mcimadamore@1216: bounds = bounds.tail;
mcimadamore@821: }
mcimadamore@821:
mcimadamore@821: args = type.getTypeArguments();
mcimadamore@1216: bounds = bounds_buf.toList();
mcimadamore@821:
mcimadamore@821: for (Type arg : types.capture(type).getTypeArguments()) {
jjg@1374: if (arg.hasTag(TYPEVAR) &&
mcimadamore@828: arg.getUpperBound().isErroneous() &&
mcimadamore@1216: !bounds.head.isErroneous() &&
mcimadamore@854: !isTypeArgErroneous(args.head)) {
mcimadamore@821: return args.head;
mcimadamore@821: }
mcimadamore@1216: bounds = bounds.tail;
mcimadamore@854: args = args.tail;
mcimadamore@821: }
mcimadamore@821:
mcimadamore@821: return null;
mcimadamore@821: }
mcimadamore@854: //where
mcimadamore@854: boolean isTypeArgErroneous(Type t) {
mcimadamore@854: return isTypeArgErroneous.visit(t);
mcimadamore@854: }
mcimadamore@854:
mcimadamore@854: Types.UnaryVisitor isTypeArgErroneous = new Types.UnaryVisitor() {
mcimadamore@854: public Boolean visitType(Type t, Void s) {
mcimadamore@854: return t.isErroneous();
mcimadamore@854: }
mcimadamore@854: @Override
mcimadamore@854: public Boolean visitTypeVar(TypeVar t, Void s) {
mcimadamore@854: return visit(t.getUpperBound());
mcimadamore@854: }
mcimadamore@854: @Override
mcimadamore@854: public Boolean visitCapturedType(CapturedType t, Void s) {
mcimadamore@854: return visit(t.getUpperBound()) ||
mcimadamore@854: visit(t.getLowerBound());
mcimadamore@854: }
mcimadamore@854: @Override
mcimadamore@854: public Boolean visitWildcardType(WildcardType t, Void s) {
mcimadamore@854: return visit(t.type);
mcimadamore@854: }
mcimadamore@854: };
mcimadamore@821:
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;
mcimadamore@1366: } else if ((sym.owner.flags_field & INTERFACE) != 0) {
mcimadamore@1513: if ((flags & (DEFAULT | STATIC)) != 0) {
mcimadamore@1513: mask = InterfaceMethodMask;
mcimadamore@1513: implicit = PUBLIC;
mcimadamore@1513: if ((flags & DEFAULT) != 0) {
mcimadamore@1513: implicit |= ABSTRACT;
mcimadamore@1513: }
mcimadamore@1366: } else {
mcimadamore@1366: mask = implicit = InterfaceMethodFlags;
mcimadamore@1366: }
mcimadamore@1366: }
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;
jjg@113: if (sym.name.isEmpty()) { // 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: }
mcimadamore@1366: long illegal = flags & ExtendedStandardFlags & ~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,
mcimadamore@80: "mod.not.allowed.here", asFlagSet(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,
mcimadamore@1366: PRIVATE | STATIC | DEFAULT))
duke@1: &&
duke@1: checkDisjoint(pos, flags,
mcimadamore@1513: STATIC,
mcimadamore@1513: DEFAULT)
mcimadamore@1513: &&
mcimadamore@1513: 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: }
mcimadamore@1366: return flags & (mask | ~ExtendedStandardFlags) | 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) {
jjg@1127: if (!tree.hasTag(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:
jjg@398: @Override
duke@1: public void visitTree(JCTree tree) { /* no-op */ }
duke@1:
jjg@398: @Override
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: *
jjg@1358: * {@code
duke@1: * class B { ... }
duke@1: * class C extends B { ... }
jjg@1358: * }
duke@1: *
duke@1: * and we can't make sure that the bound is already attributed because
duke@1: * of possible cycles.
mcimadamore@638: *
mcimadamore@638: * Visitor method: Validate a type expression, if it is not null, catching
duke@1: * and reporting any completion failures.
duke@1: */
mcimadamore@122: void validate(JCTree tree, Env env) {
mcimadamore@638: validate(tree, env, true);
duke@1: }
mcimadamore@638: void validate(JCTree tree, Env env, boolean checkRaw) {
mcimadamore@638: new Validator(env).validateTree(tree, checkRaw, true);
mcimadamore@122: }
duke@1:
duke@1: /** Visitor method: Validate a list of type expressions.
duke@1: */
mcimadamore@122: void validate(List extends JCTree> trees, Env env) {
duke@1: for (List extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
mcimadamore@122: validate(l.head, env);
duke@1: }
duke@1:
duke@1: /** A visitor class for type validation.
duke@1: */
duke@1: class Validator extends JCTree.Visitor {
duke@1:
mcimadamore@638: boolean isOuter;
mcimadamore@638: Env env;
mcimadamore@638:
mcimadamore@638: Validator(Env env) {
mcimadamore@638: this.env = env;
mcimadamore@638: }
mcimadamore@638:
jjg@398: @Override
duke@1: public void visitTypeArray(JCArrayTypeTree tree) {
mcimadamore@638: tree.elemtype.accept(this);
duke@1: }
duke@1:
jjg@398: @Override
duke@1: public void visitTypeApply(JCTypeApply tree) {
jjg@1374: if (tree.type.hasTag(CLASS)) {
duke@1: List args = tree.arguments;
mcimadamore@158: List forms = tree.type.tsym.type.getTypeArguments();
mcimadamore@821:
mcimadamore@821: Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
mcimadamore@821: if (incompatibleArg != null) {
mcimadamore@821: for (JCTree arg : tree.arguments) {
mcimadamore@821: if (arg.type == incompatibleArg) {
mcimadamore@829: log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
mcimadamore@821: }
mcimadamore@829: forms = forms.tail;
mcimadamore@829: }
mcimadamore@829: }
mcimadamore@829:
mcimadamore@829: forms = tree.type.tsym.type.getTypeArguments();
duke@1:
mcimadamore@638: boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
mcimadamore@638:
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()) {
mcimadamore@638: validateTree(args.head,
mcimadamore@638: !(isOuter && is_java_lang_Class),
mcimadamore@638: false);
duke@1: args = args.tail;
duke@1: forms = forms.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");
jjg@1127: if (tree.clazz.hasTag(SELECT))
duke@1: visitSelectInternal((JCFieldAccess)tree.clazz);
duke@1: }
duke@1: }
duke@1:
jjg@398: @Override
duke@1: public void visitTypeParameter(JCTypeParameter tree) {
mcimadamore@638: validateTrees(tree.bounds, true, isOuter);
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)
mcimadamore@638: validateTree(tree.inner, true, isOuter);
duke@1: }
duke@1:
jjg@398: @Override
duke@1: public void visitSelect(JCFieldAccess tree) {
jjg@1374: if (tree.type.hasTag(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: }
mcimadamore@852:
duke@1: public void visitSelectInternal(JCFieldAccess tree) {
mcimadamore@122: if (tree.type.tsym.isStatic() &&
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
mcimadamore@122: tree.selected.accept(this);
duke@1: }
duke@1: }
duke@1:
jjg@1521: @Override
jjg@1521: public void visitAnnotatedType(JCAnnotatedType tree) {
jjg@1521: tree.underlyingType.accept(this);
jjg@1521: }
jjg@1521:
duke@1: /** Default visitor method: do nothing.
duke@1: */
jjg@398: @Override
duke@1: public void visitTree(JCTree tree) {
duke@1: }
mcimadamore@122:
mcimadamore@638: public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
mcimadamore@638: try {
mcimadamore@638: if (tree != null) {
mcimadamore@638: this.isOuter = isOuter;
mcimadamore@638: tree.accept(this);
mcimadamore@638: if (checkRaw)
mcimadamore@638: checkRaw(tree, env);
mcimadamore@638: }
mcimadamore@638: } catch (CompletionFailure ex) {
mcimadamore@638: completionError(tree.pos(), ex);
mcimadamore@638: }
mcimadamore@638: }
mcimadamore@638:
mcimadamore@638: public void validateTrees(List extends JCTree> trees, boolean checkRaw, boolean isOuter) {
mcimadamore@638: for (List extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
mcimadamore@638: validateTree(l.head, checkRaw, isOuter);
mcimadamore@638: }
mcimadamore@638:
mcimadamore@638: void checkRaw(JCTree tree, Env env) {
mcimadamore@795: if (lint.isEnabled(LintCategory.RAW) &&
jjg@1374: tree.type.hasTag(CLASS) &&
mcimadamore@638: !TreeInfo.isDiamond(tree) &&
mcimadamore@1103: !withinAnonConstr(env) &&
mcimadamore@638: tree.type.isRaw()) {
mcimadamore@795: log.warning(LintCategory.RAW,
mcimadamore@638: tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
mcimadamore@638: }
mcimadamore@638: }
mcimadamore@1103:
mcimadamore@1103: boolean withinAnonConstr(Env env) {
mcimadamore@1103: return env.enclClass.name.isEmpty() &&
mcimadamore@1103: env.enclMethod != null && env.enclMethod.name == names.init;
mcimadamore@1103: }
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
jjg@1374: (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
jjg@1374: (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
jjg@1374: exc.hasTag(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: */
mcimadamore@362: 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 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: */
mcimadamore@89: 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";
mcimadamore@89: return diags.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: */
mcimadamore@89: 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";
mcimadamore@89: return diags.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: */
mcimadamore@89: 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";
mcimadamore@89: return diags.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),
mcimadamore@80: asFlagSet(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),
mcimadamore@80: other.flags() == 0 ?
mcimadamore@80: Flag.PACKAGE :
mcimadamore@80: asFlagSet(other.flags() & AccessFlags));
duke@1: return;
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:
mcimadamore@795: overrideWarner.clear();
duke@1: boolean resultTypesOK =
tbell@202: types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
duke@1: if (!resultTypesOK) {
jjg@398: if (!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 {
mcimadamore@362: log.error(TreeInfo.diagnosticPositionFor(m, tree),
mcimadamore@362: "override.incompatible.ret",
mcimadamore@362: cannotOverride(m, other),
duke@1: mtres, otres);
duke@1: return;
duke@1: }
mcimadamore@795: } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
duke@1: warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
mcimadamore@362: "override.unchecked.ret",
mcimadamore@362: uncheckedOverrides(m, other),
mcimadamore@362: 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);
mcimadamore@362: List unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
mcimadamore@362: List unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
mcimadamore@362: if (unhandledErased.nonEmpty()) {
duke@1: log.error(TreeInfo.diagnosticPositionFor(m, tree),
duke@1: "override.meth.doesnt.throw",
duke@1: cannotOverride(m, other),
mcimadamore@362: unhandledUnerased.head);
mcimadamore@362: return;
mcimadamore@362: }
mcimadamore@362: else if (unhandledUnerased.nonEmpty()) {
mcimadamore@362: warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
mcimadamore@362: "override.unchecked.thrown",
mcimadamore@362: cannotOverride(m, other),
mcimadamore@362: unhandledUnerased.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)
mcimadamore@795: && lint.isEnabled(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.
mcimadamore@852: if (!isDeprecatedOverrideIgnorable(other, origin)) {
mcimadamore@852: checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, 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);
jjg@1374: if (!st.hasTag(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);
jjg@1374: if (!sup.hasTag(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;
jjg@1374: t2.hasTag(CLASS);
duke@1: t2 = types.supertype(t2)) {
mcimadamore@24: for (Scope.Entry e2 = t2.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) {
mcimadamore@746: return firstIncompatibility(pos, t1, t2, site) == null;
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: */
mcimadamore@746: private Symbol firstIncompatibility(DiagnosticPosition pos, 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()) {
mcimadamore@746: Symbol s = firstDirectIncompatibility(pos, 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) {
jjg@1374: if (!t.hasTag(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) {
jjg@1374: if (!t.hasTag(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. */
mcimadamore@746: private Symbol firstDirectIncompatibility(DiagnosticPosition pos, 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;
mcimadamore@1441: if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
mcimadamore@1441: (s1.flags() & SYNTHETIC) != 0) 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;
mcimadamore@1441: if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
mcimadamore@1441: (s2.flags() & SYNTHETIC) != 0) 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) ||
jjg@1374: !rt1.isPrimitiveOrVoid() &&
jjg@1374: !rt2.isPrimitiveOrVoid() &&
mcimadamore@1415: (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
mcimadamore@1415: types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
mcimadamore@59: checkCommonOverriderIn(s1,s2,site);
mcimadamore@746: if (!compat) {
mcimadamore@746: log.error(pos, "types.incompatible.diff.ret",
mcimadamore@746: t1, t2, s2.name +
mcimadamore@746: "(" + types.memberType(t2, s2).getParameterTypes() + ")");
mcimadamore@746: return s2;
mcimadamore@746: }
mcimadamore@889: } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
mcimadamore@889: !checkCommonOverriderIn(s1, s2, site)) {
mcimadamore@746: log.error(pos,
mcimadamore@746: "name.clash.same.erasure.no.override",
mcimadamore@746: s1, s1.location(),
mcimadamore@746: s2, s2.location());
mcimadamore@746: return s2;
duke@1: }
duke@1: }
duke@1: }
duke@1: return null;
duke@1: }
mcimadamore@59: //WHERE
mcimadamore@59: boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
mcimadamore@59: Map supertypes = new HashMap();
mcimadamore@59: Type st1 = types.memberType(site, s1);
mcimadamore@59: Type st2 = types.memberType(site, s2);
mcimadamore@59: closure(site, supertypes);
mcimadamore@59: for (Type t : supertypes.values()) {
mcimadamore@59: for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
mcimadamore@59: Symbol s3 = e.sym;
mcimadamore@59: if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
mcimadamore@59: Type st3 = types.memberType(site,s3);
mcimadamore@59: if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
mcimadamore@59: if (s3.owner == site.tsym) {
mcimadamore@59: return true;
mcimadamore@59: }
mcimadamore@59: List tvars1 = st1.getTypeArguments();
mcimadamore@59: List tvars2 = st2.getTypeArguments();
mcimadamore@59: List tvars3 = st3.getTypeArguments();
mcimadamore@59: Type rt1 = st1.getReturnType();
mcimadamore@59: Type rt2 = st2.getReturnType();
mcimadamore@59: Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
mcimadamore@59: Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
mcimadamore@59: boolean compat =
jjg@1374: !rt13.isPrimitiveOrVoid() &&
jjg@1374: !rt23.isPrimitiveOrVoid() &&
mcimadamore@1415: (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
mcimadamore@1415: types.covariantReturnType(rt23, rt2, types.noWarnings));
mcimadamore@59: if (compat)
mcimadamore@59: return true;
mcimadamore@59: }
mcimadamore@59: }
mcimadamore@59: }
mcimadamore@59: return false;
mcimadamore@59: }
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: }
jjg@1374: for (Type t = origin.type; t.hasTag(CLASS);
duke@1: t = types.supertype(t)) {
mcimadamore@746: if (t != origin.type) {
mcimadamore@746: checkOverride(tree, t, origin, m);
mcimadamore@746: }
mcimadamore@746: for (Type t2 : types.interfaces(t)) {
mcimadamore@746: checkOverride(tree, t2, origin, m);
duke@1: }
duke@1: }
duke@1: }
duke@1:
mcimadamore@746: void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
mcimadamore@746: TypeSymbol c = site.tsym;
mcimadamore@746: Scope.Entry e = c.members().lookup(m.name);
mcimadamore@746: while (e.scope != null) {
mcimadamore@746: if (m.overrides(e.sym, origin, types, false)) {
mcimadamore@746: if ((e.sym.flags() & ABSTRACT) == 0) {
mcimadamore@746: checkOverride(tree, m, (MethodSymbol)e.sym, origin);
mcimadamore@746: }
mcimadamore@746: }
mcimadamore@746: e = e.next();
mcimadamore@746: }
mcimadamore@746: }
mcimadamore@746:
mcimadamore@746: private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
mcimadamore@858: ClashFilter cf = new ClashFilter(origin.type);
mcimadamore@858: return (cf.accepts(s1) &&
mcimadamore@858: cf.accepts(s2) &&
mcimadamore@858: types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
mcimadamore@746: }
mcimadamore@746:
mcimadamore@746:
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 &&
mcimadamore@1393: (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
duke@1: MethodSymbol absmeth = (MethodSymbol)e.sym;
duke@1: MethodSymbol implmeth = absmeth.implementation(impl, types, true);
mcimadamore@1393: if (implmeth == null || implmeth == absmeth) {
mcimadamore@1393: //look for default implementations
mcimadamore@1393: if (allowDefaultMethods) {
mcimadamore@1393: MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
mcimadamore@1393: if (prov != null && prov.overrides(absmeth, impl, types, true)) {
mcimadamore@1393: implmeth = prov;
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: if (implmeth == null || implmeth == absmeth) {
duke@1: undef = absmeth;
mcimadamore@1393: }
duke@1: }
duke@1: }
duke@1: if (undef == null) {
duke@1: Type st = types.supertype(c.type);
jjg@1374: if (st.hasTag(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:
mcimadamore@690: void checkNonCyclicDecl(JCClassDecl tree) {
mcimadamore@690: CycleChecker cc = new CycleChecker();
mcimadamore@690: cc.scan(tree);
mcimadamore@690: if (!cc.errorFound && !cc.partialCheck) {
mcimadamore@690: tree.sym.flags_field |= ACYCLIC;
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: class CycleChecker extends TreeScanner {
mcimadamore@690:
mcimadamore@690: List seenClasses = List.nil();
mcimadamore@690: boolean errorFound = false;
mcimadamore@690: boolean partialCheck = false;
mcimadamore@690:
mcimadamore@690: private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
mcimadamore@690: if (sym != null && sym.kind == TYP) {
mcimadamore@690: Env classEnv = enter.getEnv((TypeSymbol)sym);
mcimadamore@690: if (classEnv != null) {
mcimadamore@690: DiagnosticSource prevSource = log.currentSource();
mcimadamore@690: try {
mcimadamore@690: log.useSource(classEnv.toplevel.sourcefile);
mcimadamore@690: scan(classEnv.tree);
mcimadamore@690: }
mcimadamore@690: finally {
mcimadamore@690: log.useSource(prevSource.getFile());
mcimadamore@690: }
mcimadamore@690: } else if (sym.kind == TYP) {
mcimadamore@690: checkClass(pos, sym, List.nil());
mcimadamore@690: }
mcimadamore@690: } else {
mcimadamore@690: //not completed yet
mcimadamore@690: partialCheck = true;
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: @Override
mcimadamore@690: public void visitSelect(JCFieldAccess tree) {
mcimadamore@690: super.visitSelect(tree);
mcimadamore@690: checkSymbol(tree.pos(), tree.sym);
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: @Override
mcimadamore@690: public void visitIdent(JCIdent tree) {
mcimadamore@690: checkSymbol(tree.pos(), tree.sym);
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: @Override
mcimadamore@690: public void visitTypeApply(JCTypeApply tree) {
mcimadamore@690: scan(tree.clazz);
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: @Override
mcimadamore@690: public void visitTypeArray(JCArrayTypeTree tree) {
mcimadamore@690: scan(tree.elemtype);
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: @Override
mcimadamore@690: public void visitClassDef(JCClassDecl tree) {
mcimadamore@690: List supertypes = List.nil();
mcimadamore@690: if (tree.getExtendsClause() != null) {
mcimadamore@690: supertypes = supertypes.prepend(tree.getExtendsClause());
mcimadamore@690: }
mcimadamore@690: if (tree.getImplementsClause() != null) {
mcimadamore@690: for (JCTree intf : tree.getImplementsClause()) {
mcimadamore@690: supertypes = supertypes.prepend(intf);
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690: checkClass(tree.pos(), tree.sym, supertypes);
mcimadamore@690: }
mcimadamore@690:
mcimadamore@690: void checkClass(DiagnosticPosition pos, Symbol c, List supertypes) {
mcimadamore@690: if ((c.flags_field & ACYCLIC) != 0)
mcimadamore@690: return;
mcimadamore@690: if (seenClasses.contains(c)) {
mcimadamore@690: errorFound = true;
mcimadamore@690: noteCyclic(pos, (ClassSymbol)c);
mcimadamore@690: } else if (!c.type.isErroneous()) {
mcimadamore@690: try {
mcimadamore@690: seenClasses = seenClasses.prepend(c);
jjg@1374: if (c.type.hasTag(CLASS)) {
mcimadamore@690: if (supertypes.nonEmpty()) {
mcimadamore@690: scan(supertypes);
mcimadamore@690: }
mcimadamore@690: else {
mcimadamore@690: ClassType ct = (ClassType)c.type;
mcimadamore@690: if (ct.supertype_field == null ||
mcimadamore@690: ct.interfaces_field == null) {
mcimadamore@690: //not completed yet
mcimadamore@690: partialCheck = true;
mcimadamore@690: return;
mcimadamore@690: }
mcimadamore@690: checkSymbol(pos, ct.supertype_field.tsym);
mcimadamore@690: for (Type intf : ct.interfaces_field) {
mcimadamore@690: checkSymbol(pos, intf.tsym);
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690: if (c.owner.kind == TYP) {
mcimadamore@690: checkSymbol(pos, c.owner);
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690: } finally {
mcimadamore@690: seenClasses = seenClasses.tail;
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690: }
mcimadamore@690:
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) {
mcimadamore@236: checkNonCyclic1(pos, t, List.nil());
duke@1: }
duke@1:
mcimadamore@236: private void checkNonCyclic1(DiagnosticPosition pos, Type t, List seen) {
duke@1: final TypeVar tv;
jjg@1374: if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
mcimadamore@42: return;
duke@1: if (seen.contains(t)) {
duke@1: tv = (TypeVar)t;
jjg@110: tv.bound = types.createErrorType(t);
duke@1: log.error(pos, "cyclic.inheritance", t);
jjg@1374: } else if (t.hasTag(TYPEVAR)) {
duke@1: tv = (TypeVar)t;
mcimadamore@236: seen = seen.prepend(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;
jjg@1374: if (c.type.hasTag(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;
jjg@1374: if (st != null && st.hasTag(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)
jjg@110: l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
duke@1: Type st = types.supertype(c.type);
jjg@1374: if (st.hasTag(CLASS))
jjg@110: ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
jjg@110: c.type = types.createErrorType(c, c.type);
duke@1: c.flags_field |= ACYCLIC;
duke@1: }
duke@1:
mcimadamore@1415: /**
mcimadamore@1415: * Check that functional interface methods would make sense when seen
mcimadamore@1415: * from the perspective of the implementing class
mcimadamore@1415: */
mcimadamore@1415: void checkFunctionalInterface(JCTree tree, Type funcInterface) {
mcimadamore@1415: ClassType c = new ClassType(Type.noType, List.nil(), null);
mcimadamore@1415: ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
mcimadamore@1415: c.interfaces_field = List.of(funcInterface);
mcimadamore@1415: c.supertype_field = syms.objectType;
mcimadamore@1415: c.tsym = csym;
mcimadamore@1415: csym.members_field = new Scope(csym);
mcimadamore@1415: csym.completer = null;
mcimadamore@1415: checkImplementations(tree, csym, csym);
mcimadamore@1415: }
mcimadamore@1415:
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) {
mcimadamore@1415: checkImplementations(tree, tree.sym, tree.sym);
duke@1: }
jjg@1521: //where
duke@1: /** Check that all methods which implement some
duke@1: * method in `ic' conform to the method they implement.
duke@1: */
mcimadamore@1415: void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
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);
jjg@1374: if (supertype.hasTag(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:
mcimadamore@359: void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
mcimadamore@359: for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
mcimadamore@359: for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
mcimadamore@359: // VM allows methods and variables with differing types
mcimadamore@359: if (sym.kind == e.sym.kind &&
mcimadamore@359: types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
mcimadamore@359: sym != e.sym &&
mcimadamore@359: (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
mcimadamore@608: (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
mcimadamore@359: (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
mcimadamore@359: syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
mcimadamore@359: return;
mcimadamore@359: }
mcimadamore@359: }
mcimadamore@359: }
mcimadamore@359: }
mcimadamore@359:
mcimadamore@780: /** Check that all non-override equivalent methods accessible from 'site'
mcimadamore@780: * are mutually compatible (JLS 8.4.8/9.4.1).
mcimadamore@780: *
mcimadamore@780: * @param pos Position to be used for error reporting.
mcimadamore@780: * @param site The class whose methods are checked.
mcimadamore@780: * @param sym The method symbol to be checked.
mcimadamore@780: */
mcimadamore@858: void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
mcimadamore@858: ClashFilter cf = new ClashFilter(site);
mcimadamore@1198: //for each method m1 that is overridden (directly or indirectly)
mcimadamore@1198: //by method 'sym' in 'site'...
mcimadamore@1198: for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
mcimadamore@1198: if (!sym.overrides(m1, site.tsym, types, false)) continue;
mcimadamore@1198: //...check each method m2 that is a member of 'site'
mcimadamore@1198: for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
mcimadamore@1198: if (m2 == m1) continue;
mcimadamore@858: //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
mcimadamore@858: //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
mcimadamore@1393: if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
mcimadamore@1198: types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
mcimadamore@858: sym.flags_field |= CLASH;
mcimadamore@1198: String key = m1 == sym ?
mcimadamore@858: "name.clash.same.erasure.no.override" :
mcimadamore@858: "name.clash.same.erasure.no.override.1";
mcimadamore@858: log.error(pos,
mcimadamore@858: key,
mcimadamore@858: sym, sym.location(),
mcimadamore@1198: m2, m2.location(),
mcimadamore@1198: m1, m1.location());
mcimadamore@858: return;
mcimadamore@858: }
mcimadamore@780: }
mcimadamore@780: }
mcimadamore@780: }
mcimadamore@780:
mcimadamore@877:
mcimadamore@877:
mcimadamore@858: /** Check that all static methods accessible from 'site' are
mcimadamore@858: * mutually compatible (JLS 8.4.8).
mcimadamore@858: *
mcimadamore@858: * @param pos Position to be used for error reporting.
mcimadamore@858: * @param site The class whose methods are checked.
mcimadamore@858: * @param sym The method symbol to be checked.
mcimadamore@780: */
mcimadamore@858: void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
mcimadamore@780: ClashFilter cf = new ClashFilter(site);
mcimadamore@858: //for each method m1 that is a member of 'site'...
mcimadamore@1015: for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
mcimadamore@858: //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
mcimadamore@858: //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
mcimadamore@1393: if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
mcimadamore@877: types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
mcimadamore@780: log.error(pos,
mcimadamore@858: "name.clash.same.erasure.no.hide",
mcimadamore@858: sym, sym.location(),
mcimadamore@877: s, s.location());
mcimadamore@858: return;
mcimadamore@858: }
mcimadamore@858: }
mcimadamore@858: }
mcimadamore@780:
mcimadamore@858: //where
mcimadamore@858: private class ClashFilter implements Filter {
mcimadamore@780:
mcimadamore@858: Type site;
mcimadamore@780:
mcimadamore@858: ClashFilter(Type site) {
mcimadamore@858: this.site = site;
mcimadamore@858: }
mcimadamore@858:
mcimadamore@858: boolean shouldSkip(Symbol s) {
mcimadamore@858: return (s.flags() & CLASH) != 0 &&
mcimadamore@858: s.owner == site.tsym;
mcimadamore@858: }
mcimadamore@858:
mcimadamore@858: public boolean accepts(Symbol s) {
mcimadamore@858: return s.kind == MTH &&
mcimadamore@858: (s.flags() & SYNTHETIC) == 0 &&
mcimadamore@858: !shouldSkip(s) &&
mcimadamore@858: s.isInheritedIn(site.tsym, types) &&
mcimadamore@858: !s.isConstructor();
mcimadamore@858: }
mcimadamore@858: }
mcimadamore@780:
mcimadamore@1393: void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
mcimadamore@1393: DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
mcimadamore@1393: for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
mcimadamore@1393: Assert.check(m.kind == MTH);
mcimadamore@1393: List prov = types.interfaceCandidates(site, (MethodSymbol)m);
mcimadamore@1393: if (prov.size() > 1) {
mcimadamore@1393: ListBuffer abstracts = ListBuffer.lb();
mcimadamore@1393: ListBuffer defaults = ListBuffer.lb();
mcimadamore@1393: for (MethodSymbol provSym : prov) {
mcimadamore@1393: if ((provSym.flags() & DEFAULT) != 0) {
mcimadamore@1393: defaults = defaults.append(provSym);
mcimadamore@1393: } else if ((provSym.flags() & ABSTRACT) != 0) {
mcimadamore@1393: abstracts = abstracts.append(provSym);
mcimadamore@1393: }
mcimadamore@1393: if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
mcimadamore@1393: //strong semantics - issue an error if two sibling interfaces
mcimadamore@1393: //have two override-equivalent defaults - or if one is abstract
mcimadamore@1393: //and the other is default
mcimadamore@1393: String errKey;
mcimadamore@1393: Symbol s1 = defaults.first();
mcimadamore@1393: Symbol s2;
mcimadamore@1393: if (defaults.size() > 1) {
mcimadamore@1393: errKey = "types.incompatible.unrelated.defaults";
mcimadamore@1393: s2 = defaults.toList().tail.head;
mcimadamore@1393: } else {
mcimadamore@1393: errKey = "types.incompatible.abstract.default";
mcimadamore@1393: s2 = abstracts.first();
mcimadamore@1393: }
mcimadamore@1393: log.error(pos, errKey,
mcimadamore@1393: Kinds.kindName(site.tsym), site,
mcimadamore@1393: m.name, types.memberType(site, m).getParameterTypes(),
mcimadamore@1393: s1.location(), s2.location());
mcimadamore@1393: break;
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393:
mcimadamore@1393: //where
mcimadamore@1393: private class DefaultMethodClashFilter implements Filter {
mcimadamore@1393:
mcimadamore@1393: Type site;
mcimadamore@1393:
mcimadamore@1393: DefaultMethodClashFilter(Type site) {
mcimadamore@1393: this.site = site;
mcimadamore@1393: }
mcimadamore@1393:
mcimadamore@1393: public boolean accepts(Symbol s) {
mcimadamore@1393: return s.kind == MTH &&
mcimadamore@1393: (s.flags() & DEFAULT) != 0 &&
mcimadamore@1393: s.isInheritedIn(site.tsym, types) &&
mcimadamore@1393: !s.isConstructor();
mcimadamore@1393: }
mcimadamore@1393: }
mcimadamore@1393:
mcimadamore@359: /** Report a conflict between a user symbol and a synthetic symbol.
mcimadamore@359: */
mcimadamore@359: private void syntheticError(DiagnosticPosition pos, Symbol sym) {
mcimadamore@359: if (!sym.type.isErroneous()) {
mcimadamore@359: if (warnOnSyntheticConflicts) {
mcimadamore@359: log.warning(pos, "synthetic.name.conflict", sym, sym.location());
mcimadamore@359: }
mcimadamore@359: else {
mcimadamore@359: log.error(pos, "synthetic.name.conflict", sym, sym.location());
mcimadamore@359: }
mcimadamore@359: }
mcimadamore@359: }
mcimadamore@359:
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:
mcimadamore@629: /**
mcimadamore@634: * Recursively validate annotations values
mcimadamore@629: */
mcimadamore@634: void validateAnnotationTree(JCTree tree) {
mcimadamore@634: class AnnotationValidator extends TreeScanner {
mcimadamore@629: @Override
mcimadamore@629: public void visitAnnotation(JCAnnotation tree) {
jjg@1017: if (!tree.type.isErroneous()) {
jjg@1017: super.visitAnnotation(tree);
jjg@1017: validateAnnotation(tree);
jjg@1017: }
mcimadamore@629: }
mcimadamore@629: }
mcimadamore@634: tree.accept(new AnnotationValidator());
mcimadamore@629: }
mcimadamore@629:
jjg@1326: /**
jjg@1326: * {@literal
jjg@1326: * Annotation types are restricted to primitives, String, an
duke@1: * enum, an annotation, Class, Class>, Class extends
duke@1: * Anything>, arrays of the preceding.
jjg@1326: * }
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: *
jjh@972: * @jls 9.6 Annotation Types
duke@1: */
duke@1: void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
jjg@1374: for (Type sup = syms.annotationType; sup.hasTag(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: for (JCAnnotation a : annotations)
duke@1: validateAnnotation(a, s);
duke@1: }
duke@1:
jjg@1521: /** Check the type annotations.
jjg@1521: */
jjg@1521: public void validateTypeAnnotations(List annotations, boolean isTypeParameter) {
jjg@1521: for (JCAnnotation a : annotations)
jjg@1521: validateTypeAnnotation(a, isTypeParameter);
jjg@1521: }
jjg@1521:
duke@1: /** Check an annotation of a symbol.
duke@1: */
jfranck@1313: private void validateAnnotation(JCAnnotation a, Symbol s) {
mcimadamore@634: validateAnnotationTree(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: }
mcimadamore@1497:
mcimadamore@1497: if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
mcimadamore@1497: if (s.kind != TYP) {
mcimadamore@1497: log.error(a.pos(), "bad.functional.intf.anno");
mcimadamore@1497: } else {
mcimadamore@1497: try {
mcimadamore@1497: types.findDescriptorSymbol((TypeSymbol)s);
mcimadamore@1497: } catch (Types.FunctionDescriptorLookupError ex) {
mcimadamore@1497: log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
mcimadamore@1497: }
mcimadamore@1497: }
mcimadamore@1497: }
duke@1: }
duke@1:
jjg@1521: public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
jjg@1521: Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
jjg@1521: validateAnnotationTree(a);
jjg@1521:
jjg@1521: if (!isTypeAnnotation(a, isTypeParameter))
jjg@1521: log.error(a.pos(), "annotation.type.not.applicable");
jjg@1521: }
jjg@1521:
jfranck@1313: /**
jjg@1492: * Validate the proposed container 'repeatable' on the
jfranck@1313: * annotation type symbol 's'. Report errors at position
jfranck@1313: * 'pos'.
jfranck@1313: *
jjg@1492: * @param s The (annotation)type declaration annotated with a @Repeatable
jjg@1492: * @param repeatable the @Repeatable on 's'
jfranck@1313: * @param pos where to report errors
jfranck@1313: */
jjg@1492: public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
jjg@1492: Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
jfranck@1313:
jfranck@1313: Type t = null;
jjg@1492: List> l = repeatable.values;
jfranck@1313: if (!l.isEmpty()) {
jfranck@1313: Assert.check(l.head.fst.name == names.value);
jfranck@1313: t = ((Attribute.Class)l.head.snd).getValue();
jfranck@1313: }
jfranck@1313:
jfranck@1313: if (t == null) {
jjg@1492: // errors should already have been reported during Annotate
jfranck@1313: return;
jfranck@1313: }
jfranck@1313:
jjg@1492: validateValue(t.tsym, s, pos);
jfranck@1313: validateRetention(t.tsym, s, pos);
jfranck@1313: validateDocumented(t.tsym, s, pos);
jfranck@1313: validateInherited(t.tsym, s, pos);
jfranck@1313: validateTarget(t.tsym, s, pos);
jfranck@1344: validateDefault(t.tsym, s, pos);
jfranck@1313: }
jfranck@1313:
jjg@1492: private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
jjg@1492: Scope.Entry e = container.members().lookup(names.value);
jjg@1492: if (e.scope != null && e.sym.kind == MTH) {
jjg@1492: MethodSymbol m = (MethodSymbol) e.sym;
jjg@1492: Type ret = m.getReturnType();
jjg@1492: if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.value.return",
jjg@1492: container, ret, types.makeArrayType(contained.type));
jjg@1492: }
jjg@1492: } else {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.no.value", container);
jfranck@1313: }
jfranck@1313: }
jfranck@1313:
jfranck@1313: private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
jfranck@1313: Attribute.RetentionPolicy containerRetention = types.getRetention(container);
jfranck@1313: Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
jfranck@1313:
jfranck@1313: boolean error = false;
jfranck@1313: switch (containedRetention) {
jfranck@1313: case RUNTIME:
jfranck@1313: if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
jfranck@1313: error = true;
jfranck@1313: }
jfranck@1313: break;
jfranck@1313: case CLASS:
jfranck@1313: if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
jfranck@1313: error = true;
jfranck@1313: }
jfranck@1313: }
jfranck@1313: if (error ) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.retention",
jfranck@1313: container, containerRetention,
jfranck@1313: contained, containedRetention);
jfranck@1313: }
jfranck@1313: }
jfranck@1313:
jfranck@1313: private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
jfranck@1313: if (contained.attribute(syms.documentedType.tsym) != null) {
jfranck@1313: if (container.attribute(syms.documentedType.tsym) == null) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
jfranck@1313: }
jfranck@1313: }
jfranck@1313: }
jfranck@1313:
jfranck@1313: private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
jfranck@1313: if (contained.attribute(syms.inheritedType.tsym) != null) {
jfranck@1313: if (container.attribute(syms.inheritedType.tsym) == null) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
jfranck@1313: }
jfranck@1313: }
jfranck@1313: }
jfranck@1313:
jfranck@1313: private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
jfranck@1313: Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
jfranck@1313:
jfranck@1313: // If contained has no Target, we are done
jfranck@1313: if (containedTarget == null) {
jfranck@1313: return;
jfranck@1313: }
jfranck@1313:
jfranck@1313: // If contained has Target m1, container must have a Target
jfranck@1313: // annotation, m2, and m2 must be a subset of m1. (This is
jfranck@1313: // trivially true if contained has no target as per above).
jfranck@1313:
jfranck@1313: // contained has target, but container has not, error
jfranck@1313: Attribute.Array containerTarget = getAttributeTargetAttribute(container);
jfranck@1313: if (containerTarget == null) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
jfranck@1313: return;
jfranck@1313: }
jfranck@1313:
jfranck@1313: Set containerTargets = new HashSet();
jfranck@1313: for (Attribute app : containerTarget.values) {
jfranck@1313: if (!(app instanceof Attribute.Enum)) {
jfranck@1313: continue; // recovery
jfranck@1313: }
jfranck@1313: Attribute.Enum e = (Attribute.Enum)app;
jfranck@1313: containerTargets.add(e.value.name);
jfranck@1313: }
jfranck@1313:
jfranck@1313: Set containedTargets = new HashSet();
jfranck@1313: for (Attribute app : containedTarget.values) {
jfranck@1313: if (!(app instanceof Attribute.Enum)) {
jfranck@1313: continue; // recovery
jfranck@1313: }
jfranck@1313: Attribute.Enum e = (Attribute.Enum)app;
jfranck@1313: containedTargets.add(e.value.name);
jfranck@1313: }
jfranck@1313:
jfranck@1313: if (!isTargetSubset(containedTargets, containerTargets)) {
jjg@1492: log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
jfranck@1313: }
jfranck@1313: }
jfranck@1313:
jfranck@1313: /** Checks that t is a subset of s, with respect to ElementType
jfranck@1313: * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
jfranck@1313: */
jfranck@1313: private boolean isTargetSubset(Set s, Set t) {
jfranck@1313: // Check that all elements in t are present in s
jfranck@1313: for (Name n2 : t) {
jfranck@1313: boolean currentElementOk = false;
jfranck@1313: for (Name n1 : s) {
jfranck@1313: if (n1 == n2) {
jfranck@1313: currentElementOk = true;
jfranck@1313: break;
jfranck@1313: } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
jfranck@1313: currentElementOk = true;
jfranck@1313: break;
jfranck@1313: }
jfranck@1313: }
jfranck@1313: if (!currentElementOk)
jfranck@1313: return false;
jfranck@1313: }
jfranck@1313: return true;
jfranck@1313: }
jfranck@1313:
jfranck@1344: private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
jfranck@1344: // validate that all other elements of containing type has defaults
jfranck@1344: Scope scope = container.members();
jfranck@1344: for(Symbol elm : scope.getElements()) {
jfranck@1344: if (elm.name != names.value &&
jfranck@1344: elm.kind == Kinds.MTH &&
jfranck@1344: ((MethodSymbol)elm).defaultValue == null) {
jfranck@1344: log.error(pos,
jjg@1492: "invalid.repeatable.annotation.elem.nondefault",
jfranck@1344: container,
jfranck@1344: elm);
jfranck@1344: }
jfranck@1344: }
jfranck@1344: }
jfranck@1344:
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:
jjg@1521: /** Is the annotation applicable to type annotations? */
jjg@1521: protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
jjg@1521: Attribute.Compound atTarget =
jjg@1521: a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
jjg@1521: if (atTarget == null) {
jjg@1521: // An annotation without @Target is not a type annotation.
jjg@1521: return false;
jjg@1521: }
jjg@1521:
jjg@1521: Attribute atValue = atTarget.member(names.value);
jjg@1521: if (!(atValue instanceof Attribute.Array)) {
jjg@1521: return false; // error recovery
jjg@1521: }
jjg@1521:
jjg@1521: Attribute.Array arr = (Attribute.Array) atValue;
jjg@1521: for (Attribute app : arr.values) {
jjg@1521: if (!(app instanceof Attribute.Enum)) {
jjg@1521: return false; // recovery
jjg@1521: }
jjg@1521: Attribute.Enum e = (Attribute.Enum) app;
jjg@1521:
jjg@1521: if (e.value.name == names.TYPE_USE)
jjg@1521: return true;
jjg@1521: else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
jjg@1521: return true;
jjg@1521: }
jjg@1521: return false;
jjg@1521: }
jjg@1521:
duke@1: /** Is the annotation applicable to the symbol? */
duke@1: boolean annotationApplicable(JCAnnotation a, Symbol s) {
jfranck@1313: Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
jjg@1521: Name[] targets;
jjg@1521:
jfranck@1313: if (arr == null) {
jjg@1521: targets = defaultTargetMetaInfo(a, s);
jjg@1521: } else {
jjg@1521: // TODO: can we optimize this?
jjg@1521: targets = new Name[arr.values.length];
jjg@1521: for (int i=0; i members = new LinkedHashSet();
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:
jfranck@1445: // remove the ones that are assigned values
duke@1: for (JCTree arg : a.args) {
jjg@1127: if (!arg.hasTag(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;
jfranck@1445: if (!members.remove(m)) {
jfranck@1445: isValid = false;
jjg@479: log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
duke@1: m.name, a.type);
jfranck@1445: }
duke@1: }
duke@1:
duke@1: // all the remaining ones better have default values
jfranck@1445: List missingDefaults = List.nil();
mcimadamore@632: for (MethodSymbol m : members) {
mcimadamore@632: if (m.defaultValue == null && !m.type.isErroneous()) {
jfranck@1445: missingDefaults = missingDefaults.append(m.name);
mcimadamore@632: }
mcimadamore@632: }
jfranck@1445: missingDefaults = missingDefaults.reverse();
mcimadamore@632: if (missingDefaults.nonEmpty()) {
jfranck@1445: isValid = false;
mcimadamore@632: String key = (missingDefaults.size() > 1)
mcimadamore@632: ? "annotation.missing.default.value.1"
mcimadamore@632: : "annotation.missing.default.value";
mcimadamore@632: log.error(a.pos(), key, a.type, missingDefaults);
mcimadamore@632: }
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)
jfranck@1445: return isValid;
duke@1:
jfranck@1445: if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
duke@1: JCAssign assign = (JCAssign) a.args.head;
duke@1: Symbol m = TreeInfo.symbol(assign.lhs);
jfranck@1445: if (m.name != names.value) return false;
duke@1: JCTree rhs = assign.rhs;
jfranck@1445: if (!rhs.hasTag(NEWARRAY)) return false;
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))) {
jfranck@1445: isValid = false;
duke@1: log.error(elem.pos(), "repeated.annotation.target");
duke@1: }
duke@1: }
jfranck@1445: return isValid;
duke@1: }
duke@1:
duke@1: void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
duke@1: if (allowAnnotations &&
mcimadamore@795: lint.isEnabled(LintCategory.DEP_ANN) &&
duke@1: (s.flags() & DEPRECATED) != 0 &&
duke@1: !syms.deprecatedType.isErroneous() &&
duke@1: s.attribute(syms.deprecatedType.tsym) == null) {
mcimadamore@795: log.warning(LintCategory.DEP_ANN,
jjg@612: pos, "missing.deprecated.annotation");
duke@1: }
duke@1: }
duke@1:
mcimadamore@852: void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
mcimadamore@852: if ((s.flags() & DEPRECATED) != 0 &&
mcimadamore@852: (other.flags() & DEPRECATED) == 0 &&
mcimadamore@852: s.outermostClass() != other.outermostClass()) {
mcimadamore@852: deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
mcimadamore@852: @Override
mcimadamore@852: public void report() {
mcimadamore@852: warnDeprecated(pos, s);
mcimadamore@852: }
mcimadamore@852: });
jjg@1157: }
mcimadamore@852: }
mcimadamore@852:
mcimadamore@852: void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
mcimadamore@852: if ((s.flags() & PROPRIETARY) != 0) {
mcimadamore@852: deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
mcimadamore@852: public void report() {
mcimadamore@852: if (enableSunApiLintControl)
mcimadamore@852: warnSunApi(pos, "sun.proprietary", s);
mcimadamore@852: else
mcimadamore@1218: log.mandatoryWarning(pos, "sun.proprietary", s);
mcimadamore@852: }
mcimadamore@852: });
mcimadamore@852: }
mcimadamore@852: }
mcimadamore@852:
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;
jjg@816: Assert.check((tree.sym.flags_field & LOCKED) == 0);
duke@1: try {
duke@1: tree.sym.flags_field |= LOCKED;
duke@1: for (JCTree def : tree.defs) {
jjg@1127: if (!def.hasTag(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) {
jjg@1374: switch (type.getTag()) {
jjg@1374: case CLASS:
duke@1: if ((type.tsym.flags() & ANNOTATION) != 0)
duke@1: checkNonCyclicElementsInternal(pos, type.tsym);
duke@1: break;
jjg@1374: case 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,
jjg@1127: JCTree.Tag tag,
duke@1: Type left,
duke@1: Type right) {
duke@1: if (operator.opcode == ByteCodes.error) {
duke@1: log.error(pos,
mcimadamore@853: "operator.cant.be.applied.1",
duke@1: treeinfo.operatorName(tag),
mcimadamore@853: 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
mcimadamore@795: && lint.isEnabled(LintCategory.DIVZERO)
jjg@1374: && (operand.getTag().isSubRangeOf(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) {
mcimadamore@795: log.warning(LintCategory.DIVZERO, 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) {
jjg@1127: if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
jjg@1127: lint.isEnabled(LintCategory.EMPTY))
mcimadamore@795: log.warning(LintCategory.EMPTY, 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 &&
mcimadamore@858: (e.sym.flags() & CLASH) == 0 &&
mcimadamore@858: sym.kind == e.sym.kind &&
mcimadamore@858: sym.name != names.error &&
mcimadamore@858: (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
mcimadamore@844: if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
duke@1: varargsDuplicateError(pos, sym, e.sym);
mcimadamore@844: return true;
mcimadamore@907: } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
mcimadamore@252: duplicateErasureError(pos, sym, e.sym);
mcimadamore@844: sym.flags_field |= CLASH;
mcimadamore@844: return true;
mcimadamore@844: } else {
duke@1: duplicateError(pos, e.sym);
mcimadamore@844: return false;
mcimadamore@844: }
duke@1: }
duke@1: }
duke@1: return true;
duke@1: }
mcimadamore@844:
mcimadamore@858: /** Report duplicate declaration error.
mcimadamore@858: */
mcimadamore@858: void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
mcimadamore@858: if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
mcimadamore@858: log.error(pos, "name.clash.same.erasure", sym1, sym2);
mcimadamore@844: }
mcimadamore@858: }
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: */
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) {
jjg@1127: while (tree.hasTag(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:
ohrstrom@1384: /** Check that an auxiliary class is not accessed from any other file than its own.
ohrstrom@1384: */
ohrstrom@1384: void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env env, ClassSymbol c) {
ohrstrom@1384: if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
ohrstrom@1384: (c.flags() & AUXILIARY) != 0 &&
ohrstrom@1384: rs.isAccessible(env, c) &&
ohrstrom@1384: !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
ohrstrom@1384: {
ohrstrom@1384: log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
ohrstrom@1384: c, c.sourcefile);
ohrstrom@1384: }
ohrstrom@1384: }
ohrstrom@1384:
duke@1: private class ConversionWarner extends Warner {
mcimadamore@795: final String uncheckedKey;
duke@1: final Type found;
duke@1: final Type expected;
mcimadamore@795: public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
duke@1: super(pos);
mcimadamore@795: this.uncheckedKey = uncheckedKey;
duke@1: this.found = found;
duke@1: this.expected = expected;
duke@1: }
duke@1:
jjg@398: @Override
mcimadamore@795: public void warn(LintCategory lint) {
duke@1: boolean warned = this.warned;
mcimadamore@795: super.warn(lint);
duke@1: if (warned) return; // suppress redundant diagnostics
mcimadamore@795: switch (lint) {
mcimadamore@795: case UNCHECKED:
mcimadamore@795: Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
mcimadamore@795: break;
mcimadamore@795: case VARARGS:
mcimadamore@795: if (method != null &&
mcimadamore@795: method.attribute(syms.trustMeType.tsym) != null &&
mcimadamore@795: isTrustMeAllowedOnMethod(method) &&
mcimadamore@795: !types.isReifiable(method.type.getParameterTypes().last())) {
mcimadamore@795: Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
mcimadamore@795: }
mcimadamore@795: break;
mcimadamore@795: default:
mcimadamore@795: throw new AssertionError("Unexpected lint: " + lint);
mcimadamore@795: }
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: }