Issue #271017 - AssertionError: isSubtype PACKAGE - fixed.
2 * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
26 package com.sun.tools.javac.comp;
30 import javax.tools.JavaFileManager;
31 import javax.lang.model.element.ElementKind;
33 import com.sun.tools.javac.code.*;
34 import com.sun.tools.javac.code.Attribute.Compound;
35 import com.sun.tools.javac.code.Directive.ExportsDirective;
36 import com.sun.tools.javac.code.Directive.RequiresDirective;
37 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
38 import com.sun.tools.javac.jvm.*;
39 import com.sun.tools.javac.resources.CompilerProperties.Errors;
40 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
41 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
42 import com.sun.tools.javac.tree.*;
43 import com.sun.tools.javac.util.*;
44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
46 import com.sun.tools.javac.util.List;
48 import com.sun.tools.javac.code.Lint;
49 import com.sun.tools.javac.code.Lint.LintCategory;
50 import com.sun.tools.javac.code.Scope.WriteableScope;
51 import com.sun.tools.javac.code.Type.*;
52 import com.sun.tools.javac.code.Symbol.*;
53 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
54 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
55 import com.sun.tools.javac.tree.JCTree.*;
57 import static com.sun.tools.javac.code.Flags.*;
58 import static com.sun.tools.javac.code.Flags.ANNOTATION;
59 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
60 import static com.sun.tools.javac.code.Kinds.*;
61 import static com.sun.tools.javac.code.Kinds.Kind.*;
62 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
63 import static com.sun.tools.javac.code.TypeTag.*;
64 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
66 import static com.sun.tools.javac.tree.JCTree.Tag.*;
68 /** Type checking helper class for the attribution phase.
70 * <p><b>This is NOT part of any supported API.
71 * If you write code that depends on this, you do so at your own risk.
72 * This code and its internal interfaces are subject to change or
73 * deletion without notice.</b>
76 protected static final Context.Key<Check> checkKey = new Context.Key<>();
78 private final Names names;
79 private final Log log;
80 private final Resolve rs;
81 private final Symtab syms;
82 private final Enter enter;
83 private final DeferredAttr deferredAttr;
84 private final Infer infer;
85 private final Types types;
86 private final TypeAnnotations typeAnnotations;
87 private final JCDiagnostic.Factory diags;
88 private final JavaFileManager fileManager;
89 private final Source source;
90 private final Profile profile;
91 private final boolean warnOnAnyAccessToMembers;
93 // The set of lint options currently in effect. It is initialized
94 // from the context, and then is set/reset as needed by Attr as it
95 // visits all the various parts of the trees during attribution.
98 // The method being analyzed in Attr - it is set/reset as needed by
99 // Attr as it visits new method declarations.
100 private MethodSymbol method;
102 public static Check instance(Context context) {
103 Check instance = context.get(checkKey);
104 if (instance == null)
105 instance = new Check(context);
109 protected Check(Context context) {
110 context.put(checkKey, this);
112 names = Names.instance(context);
113 dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
114 names.FIELD, names.METHOD, names.CONSTRUCTOR,
115 names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
116 log = Log.instance(context);
117 rs = Resolve.instance(context);
118 syms = Symtab.instance(context);
119 enter = Enter.instance(context);
120 deferredAttr = DeferredAttr.instance(context);
121 infer = Infer.instance(context);
122 types = Types.instance(context);
123 typeAnnotations = TypeAnnotations.instance(context);
124 diags = JCDiagnostic.Factory.instance(context);
125 Options options = Options.instance(context);
126 lint = Lint.instance(context);
127 fileManager = context.get(JavaFileManager.class);
129 source = Source.instance(context);
130 allowSimplifiedVarargs = source.allowSimplifiedVarargs();
131 allowDefaultMethods = source.allowDefaultMethods();
132 allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
133 allowPrivateSafeVarargs = source.allowPrivateSafeVarargs();
134 allowDiamondWithAnonymousClassCreation = source.allowDiamondWithAnonymousClassCreation();
135 warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
137 Target target = Target.instance(context);
138 syntheticNameChar = target.syntheticNameChar();
140 profile = Profile.instance(context);
142 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
143 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
144 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
145 boolean enforceMandatoryWarnings = true;
147 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
148 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
149 removalHandler = new MandatoryWarningHandler(log, verboseRemoval,
150 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
151 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
152 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
153 sunApiHandler = new MandatoryWarningHandler(log, false,
154 enforceMandatoryWarnings, "sunapi", null);
156 deferredLintHandler = DeferredLintHandler.instance(context);
159 /** Switch: simplified varargs enabled?
161 boolean allowSimplifiedVarargs;
163 /** Switch: default methods enabled?
165 boolean allowDefaultMethods;
167 /** Switch: should unrelated return types trigger a method clash?
169 boolean allowStrictMethodClashCheck;
171 /** Switch: can the @SafeVarargs annotation be applied to private methods?
173 boolean allowPrivateSafeVarargs;
175 /** Switch: can diamond inference be used in anonymous instance creation ?
177 boolean allowDiamondWithAnonymousClassCreation;
179 /** Character for synthetic names
181 char syntheticNameChar;
183 /** A table mapping flat names of all compiled classes for each module in this run
184 * to their symbols; maintained from outside.
186 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
188 /** A handler for messages about deprecated usage.
190 private MandatoryWarningHandler deprecationHandler;
192 /** A handler for messages about deprecated-for-removal usage.
194 private MandatoryWarningHandler removalHandler;
196 /** A handler for messages about unchecked or unsafe usage.
198 private MandatoryWarningHandler uncheckedHandler;
200 /** A handler for messages about using proprietary API.
202 private MandatoryWarningHandler sunApiHandler;
204 /** A handler for deferred lint warnings.
206 private DeferredLintHandler deferredLintHandler;
208 /* *************************************************************************
209 * Errors and Warnings
210 **************************************************************************/
212 Lint setLint(Lint newLint) {
218 MethodSymbol setMethod(MethodSymbol newMethod) {
219 MethodSymbol prev = method;
224 /** Warn about deprecated symbol.
225 * @param pos Position to be used for error reporting.
226 * @param sym The deprecated symbol.
228 void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
229 if (sym.isDeprecatedForRemoval()) {
230 if (!lint.isSuppressed(LintCategory.REMOVAL)) {
231 if (sym.kind == MDL) {
232 removalHandler.report(pos, "has.been.deprecated.for.removal.module", sym);
234 removalHandler.report(pos, "has.been.deprecated.for.removal", sym, sym.location());
237 } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
238 if (sym.kind == MDL) {
239 deprecationHandler.report(pos, "has.been.deprecated.module", sym);
241 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
246 /** Warn about unchecked operation.
247 * @param pos Position to be used for error reporting.
248 * @param msg A string describing the problem.
250 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
251 if (!lint.isSuppressed(LintCategory.UNCHECKED))
252 uncheckedHandler.report(pos, msg, args);
255 /** Warn about unsafe vararg method decl.
256 * @param pos Position to be used for error reporting.
258 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
259 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
260 log.warning(LintCategory.VARARGS, pos, key, args);
263 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
264 if (lint.isEnabled(LintCategory.STATIC))
265 log.warning(LintCategory.STATIC, pos, msg, args);
268 /** Warn about division by integer constant zero.
269 * @param pos Position to be used for error reporting.
271 void warnDivZero(DiagnosticPosition pos) {
272 if (lint.isEnabled(LintCategory.DIVZERO))
273 log.warning(LintCategory.DIVZERO, pos, "div.zero");
277 * Report any deferred diagnostics.
279 public void reportDeferredDiagnostics() {
280 deprecationHandler.reportDeferredDiagnostic();
281 removalHandler.reportDeferredDiagnostic();
282 uncheckedHandler.reportDeferredDiagnostic();
283 sunApiHandler.reportDeferredDiagnostic();
287 /** Report a failure to complete a class.
288 * @param pos Position to be used for error reporting.
289 * @param ex The failure to report.
291 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
292 log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue());
296 /** Report an error that wrong type tag was found.
297 * @param pos Position to be used for error reporting.
298 * @param required An internationalized string describing the type tag
300 * @param found The type that was found.
302 Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
303 // this error used to be raised by the parser,
304 // but has been delayed to this point:
305 if (found instanceof Type && ((Type)found).hasTag(VOID)) {
306 log.error(pos, "illegal.start.of.type");
309 log.error(pos, "type.found.req", found, required);
310 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
313 /** Report an error that symbol cannot be referenced before super
315 * @param pos Position to be used for error reporting.
316 * @param sym The referenced symbol.
318 void earlyRefError(DiagnosticPosition pos, Symbol sym) {
319 log.error(pos, "cant.ref.before.ctor.called", sym);
322 /** Report duplicate declaration error.
324 void duplicateError(DiagnosticPosition pos, Symbol sym) {
325 if (!sym.type.isErroneous()) {
326 Symbol location = sym.location();
327 if (location.kind == MTH &&
328 ((MethodSymbol)location).isStaticOrInstanceInit()) {
329 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
330 kindName(sym.location()), kindName(sym.location().enclClass()),
331 sym.location().enclClass());
333 log.error(pos, "already.defined", kindName(sym), sym,
334 kindName(sym.location()), sym.location());
339 /** Report array/varargs duplicate declaration
341 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
342 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
343 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
347 /* ************************************************************************
348 * duplicate declaration checking
349 *************************************************************************/
351 /** Check that variable does not hide variable with same name in
352 * immediately enclosing local scope.
353 * @param pos Position for error reporting.
354 * @param v The symbol.
355 * @param s The scope.
357 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
358 for (Symbol sym : s.getSymbolsByName(v.name)) {
359 if (sym.owner != v.owner) break;
360 if (sym.kind == VAR &&
361 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
362 v.name != names.error) {
363 duplicateError(pos, sym);
369 /** Check that a class or interface does not hide a class or
370 * interface with same name in immediately enclosing local scope.
371 * @param pos Position for error reporting.
372 * @param c The symbol.
373 * @param s The scope.
375 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
376 for (Symbol sym : s.getSymbolsByName(c.name)) {
377 if (sym.owner != c.owner) break;
378 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
379 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
380 c.name != names.error) {
381 duplicateError(pos, sym);
387 /** Check that class does not have the same name as one of
388 * its enclosing classes, or as a class defined in its enclosing scope.
389 * return true if class is unique in its enclosing scope.
390 * @param pos Position for error reporting.
391 * @param name The class name.
392 * @param s The enclosing scope.
394 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
395 for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
396 if (sym.kind == TYP) {
397 if (sym.name != names.error)
398 duplicateError(pos, sym);
402 for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
403 if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
404 duplicateError(pos, sym);
411 /* *************************************************************************
412 * Class name generation
413 **************************************************************************/
416 private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
418 /** Return name of local class.
419 * This is of the form {@code <enclClass> $ n <classname> }
421 * enclClass is the flat name of the enclosing class,
422 * classname is the simple name of the local class
424 Name localClassName(ClassSymbol c) {
425 Name enclFlatname = c.owner.enclClass().flatname;
426 String enclFlatnameStr = enclFlatname.toString();
427 Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
428 Integer index = localClassNameIndexes.get(key);
429 for (int i = (index == null) ? 1 : index; ; i++) {
430 Name flatname = names.fromString(enclFlatnameStr
431 + syntheticNameChar + i + c.name);
432 if (getCompiled(c.packge().modle, flatname) == null) {
433 localClassNameIndexes.put(key, i + 1);
439 Name localClassName (final ClassSymbol enclClass, final Name name, final int index) {
440 Name flatname = names.
441 fromString("" + enclClass.flatname +
442 syntheticNameChar + index +
447 void clearLocalClassNameIndexes(ClassSymbol c) {
448 if (c.owner != null && c.owner.kind != NIL) {
449 localClassNameIndexes.remove(new Pair<>(
450 c.owner.enclClass().flatname, c.name));
454 public void newRound() {
456 localClassNameIndexes.clear();
459 public void putCompiled(ClassSymbol csym) {
460 compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
463 public ClassSymbol getCompiled(ClassSymbol csym) {
464 return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
467 public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
468 return compiled.get(Pair.of(msym, flatname));
471 public void removeCompiled(ClassSymbol csym) {
472 compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
475 /* *************************************************************************
477 **************************************************************************/
480 * A check context is an object that can be used to perform compatibility
481 * checks - depending on the check context, meaning of 'compatibility' might
482 * vary significantly.
484 public interface CheckContext {
486 * Is type 'found' compatible with type 'req' in given context
488 boolean compatible(Type found, Type req, Warner warn);
490 * Report a check error
492 void report(DiagnosticPosition pos, JCDiagnostic details);
494 * Obtain a warner for this check context
496 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
498 public InferenceContext inferenceContext();
500 public DeferredAttr.DeferredAttrContext deferredAttrContext();
504 * This class represent a check context that is nested within another check
505 * context - useful to check sub-expressions. The default behavior simply
506 * redirects all method calls to the enclosing check context leveraging
507 * the forwarding pattern.
509 static class NestedCheckContext implements CheckContext {
510 CheckContext enclosingContext;
512 NestedCheckContext(CheckContext enclosingContext) {
513 this.enclosingContext = enclosingContext;
516 public boolean compatible(Type found, Type req, Warner warn) {
517 return enclosingContext.compatible(found, req, warn);
520 public void report(DiagnosticPosition pos, JCDiagnostic details) {
521 enclosingContext.report(pos, details);
524 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
525 return enclosingContext.checkWarner(pos, found, req);
528 public InferenceContext inferenceContext() {
529 return enclosingContext.inferenceContext();
532 public DeferredAttrContext deferredAttrContext() {
533 return enclosingContext.deferredAttrContext();
538 * Check context to be used when evaluating assignment/return statements
540 CheckContext basicHandler = new CheckContext() {
541 public void report(DiagnosticPosition pos, JCDiagnostic details) {
542 log.error(pos, "prob.found.req", details);
544 public boolean compatible(Type found, Type req, Warner warn) {
545 return types.isAssignable(found, req, warn);
548 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
549 return convertWarner(pos, found, req);
552 public InferenceContext inferenceContext() {
553 return infer.emptyContext;
556 public DeferredAttrContext deferredAttrContext() {
557 return deferredAttr.emptyDeferredAttrContext;
561 public String toString() {
562 return "CheckContext: basicHandler";
566 /** Check that a given type is assignable to a given proto-type.
567 * If it is, return the type, otherwise return errType.
568 * @param pos Position to be used for error reporting.
569 * @param found The type that was found.
570 * @param req The type that was required.
572 public Type checkType(DiagnosticPosition pos, Type found, Type req) {
573 return checkType(pos, found, req, basicHandler);
576 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
577 final InferenceContext inferenceContext = checkContext.inferenceContext();
578 if (inferenceContext.free(req) || inferenceContext.free(found)) {
579 inferenceContext.addFreeTypeListener(List.of(req, found),
580 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
582 if (req.hasTag(ERROR))
584 if (req.hasTag(NONE))
586 if (found == null || checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
589 if (found.isNumeric() && req.isNumeric()) {
590 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
591 return types.createErrorType(found);
593 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
594 return types.createErrorType(found);
598 /** Check that a given type can be cast to a given target type.
599 * Return the result of the cast.
600 * @param pos Position to be used for error reporting.
601 * @param found The type that is being cast.
602 * @param req The target type of the cast.
604 Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
605 return checkCastable(pos, found, req, basicHandler);
607 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
608 if (types.isCastable(found, req, castWarner(pos, found, req))) {
611 checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
612 return types.createErrorType(found);
616 /** Check for redundant casts (i.e. where source type is a subtype of target type)
617 * The problem should only be reported for non-292 cast
619 public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
620 if (!tree.type.isErroneous()
621 && types.isSameType(tree.expr.type, tree.clazz.type)
622 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
623 && !is292targetTypeCast(tree)) {
624 deferredLintHandler.report(() -> {
625 if (lint.isEnabled(LintCategory.CAST))
626 log.warning(LintCategory.CAST,
627 tree.pos(), "redundant.cast", tree.clazz.type);
632 private boolean is292targetTypeCast(JCTypeCast tree) {
633 boolean is292targetTypeCast = false;
634 JCExpression expr = TreeInfo.skipParens(tree.expr);
635 if (expr.hasTag(APPLY)) {
636 JCMethodInvocation apply = (JCMethodInvocation)expr;
637 Symbol sym = TreeInfo.symbol(apply.meth);
638 is292targetTypeCast = sym != null &&
640 (sym.flags() & HYPOTHETICAL) != 0;
642 return is292targetTypeCast;
645 private static final boolean ignoreAnnotatedCasts = true;
647 /** Check that a type is within some bounds.
649 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
651 * @param a The type that should be bounded by bs.
652 * @param bound The bound.
654 private boolean checkExtends(Type a, Type bound) {
657 } else if (!a.hasTag(WILDCARD)) {
658 a = types.cvarUpperBound(a);
659 return types.isSubtype(a, bound);
660 } else if (a.isExtendsBound()) {
661 return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
662 } else if (a.isSuperBound()) {
663 return !types.notSoftSubtype(types.wildLowerBound(a), bound);
668 /** Check that type is different from 'void'.
669 * @param pos Position to be used for error reporting.
670 * @param t The type to be checked.
672 Type checkNonVoid(DiagnosticPosition pos, Type t) {
673 if (t.hasTag(VOID)) {
674 log.error(pos, "void.not.allowed.here");
675 return types.createErrorType(t);
681 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
682 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
683 return typeTagError(pos,
684 diags.fragment("type.req.class.array"),
691 /** Check that type is a class or interface type.
692 * @param pos Position to be used for error reporting.
693 * @param t The type to be checked.
695 Type checkClassType(DiagnosticPosition pos, Type t) {
696 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
697 return typeTagError(pos,
698 diags.fragment("type.req.class"),
705 private Object asTypeParam(Type t) {
706 return (t.hasTag(TYPEVAR))
707 ? diags.fragment("type.parameter", t)
711 /** Check that type is a valid qualifier for a constructor reference expression
713 Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
714 t = checkClassOrArrayType(pos, t);
715 if (t.hasTag(CLASS)) {
716 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
717 log.error(pos, "abstract.cant.be.instantiated", t.tsym);
718 t = types.createErrorType(t);
719 } else if ((t.tsym.flags() & ENUM) != 0) {
720 log.error(pos, "enum.cant.be.instantiated");
721 t = types.createErrorType(t);
723 t = checkClassType(pos, t, true);
725 } else if (t.hasTag(ARRAY)) {
726 if (!types.isReifiable(((ArrayType)t).elemtype)) {
727 log.error(pos, "generic.array.creation");
728 t = types.createErrorType(t);
734 /** Check that type is a class or interface type.
735 * @param pos Position to be used for error reporting.
736 * @param t The type to be checked.
737 * @param noBounds True if type bounds are illegal here.
739 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
740 t = checkClassType(pos, t);
741 if (noBounds && t.isParameterized()) {
742 List<Type> args = t.getTypeArguments();
743 while (args.nonEmpty()) {
744 if (args.head.hasTag(WILDCARD))
745 return typeTagError(pos,
746 diags.fragment("type.req.exact"),
754 /** Check that type is a reference type, i.e. a class, interface or array type
755 * or a type variable.
756 * @param pos Position to be used for error reporting.
757 * @param t The type to be checked.
759 Type checkRefType(DiagnosticPosition pos, Type t) {
763 return typeTagError(pos,
764 diags.fragment("type.req.ref"),
768 /** Check that each type is a reference type, i.e. a class, interface or array type
769 * or a type variable.
770 * @param trees Original trees, used for error reporting.
771 * @param types The types to be checked.
773 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
774 List<JCExpression> tl = trees;
775 for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
776 l.head = checkRefType(tl.head.pos(), l.head);
782 /** Check that type is a null or reference type.
783 * @param pos Position to be used for error reporting.
784 * @param t The type to be checked.
786 Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
787 if (t.isReference() || t.hasTag(BOT))
790 return typeTagError(pos,
791 diags.fragment("type.req.ref"),
795 /** Check that flag set does not contain elements of two conflicting sets. s
796 * Return true if it doesn't.
797 * @param pos Position to be used for error reporting.
798 * @param flags The set of flags to be checked.
799 * @param set1 Conflicting flags set #1.
800 * @param set2 Conflicting flags set #2.
802 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
803 if ((flags & set1) != 0 && (flags & set2) != 0) {
805 "illegal.combination.of.modifiers",
806 asFlagSet(TreeInfo.firstFlag(flags & set1)),
807 asFlagSet(TreeInfo.firstFlag(flags & set2)));
813 /** Check that usage of diamond operator is correct (i.e. diamond should not
814 * be used with non-generic classes or in anonymous class creation expressions)
816 Type checkDiamond(JCNewClass tree, Type t) {
817 if (!TreeInfo.isDiamond(tree) ||
819 return checkClassType(tree.clazz.pos(), t, true);
821 if (tree.def != null && !allowDiamondWithAnonymousClassCreation) {
822 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
823 Errors.CantApplyDiamond1(t, Fragments.DiamondAndAnonClassNotSupportedInSource(source.name)));
825 if (t.tsym.type.getTypeArguments().isEmpty()) {
826 log.error(tree.clazz.pos(),
827 "cant.apply.diamond.1",
828 t, diags.fragment("diamond.non.generic", t));
829 return types.createErrorType(t);
830 } else if (tree.typeargs != null &&
831 tree.typeargs.nonEmpty()) {
832 log.error(tree.clazz.pos(),
833 "cant.apply.diamond.1",
834 t, diags.fragment("diamond.and.explicit.params", t));
835 return types.createErrorType(t);
842 /** Check that the type inferred using the diamond operator does not contain
843 * non-denotable types such as captured types or intersection types.
844 * @param t the type inferred using the diamond operator
845 * @return the (possibly empty) list of non-denotable types.
847 List<Type> checkDiamondDenotable(ClassType t) {
848 ListBuffer<Type> buf = new ListBuffer<>();
849 for (Type arg : t.allparams()) {
850 if (!diamondTypeChecker.visit(arg, null)) {
858 /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
859 * types. The visit methods return false as soon as a non-denotable type is encountered and true
862 private static final Types.SimpleVisitor<Boolean, Void> diamondTypeChecker = new Types.SimpleVisitor<Boolean, Void>() {
864 public Boolean visitType(Type t, Void s) {
868 public Boolean visitClassType(ClassType t, Void s) {
869 if (t.isCompound()) {
872 for (Type targ : t.allparams()) {
873 if (!visit(targ, s)) {
881 public Boolean visitTypeVar(TypeVar t, Void s) {
882 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
883 (i.e cannot have been produced by inference (18.4))
885 return t.tsym.owner.type.getTypeArguments().contains(t);
889 public Boolean visitCapturedType(CapturedType t, Void s) {
890 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
891 (i.e cannot have been produced by capture conversion (5.1.10))
897 public Boolean visitArrayType(ArrayType t, Void s) {
898 return visit(t.elemtype, s);
902 public Boolean visitWildcardType(WildcardType t, Void s) {
903 return visit(t.type, s);
907 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
908 MethodSymbol m = tree.sym;
909 if (!allowSimplifiedVarargs) return;
910 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
911 Type varargElemType = null;
913 varargElemType = types.elemtype(tree.params.last().type);
915 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
916 if (varargElemType != null) {
918 "varargs.invalid.trustme.anno",
919 syms.trustMeType.tsym,
920 allowPrivateSafeVarargs ?
921 diags.fragment("varargs.trustme.on.virtual.varargs", m) :
922 diags.fragment("varargs.trustme.on.virtual.varargs.final.only", m));
925 "varargs.invalid.trustme.anno",
926 syms.trustMeType.tsym,
927 diags.fragment("varargs.trustme.on.non.varargs.meth", m));
929 } else if (hasTrustMeAnno && varargElemType != null &&
930 types.isReifiable(varargElemType)) {
931 warnUnsafeVararg(tree,
932 "varargs.redundant.trustme.anno",
933 syms.trustMeType.tsym,
934 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
936 else if (!hasTrustMeAnno && varargElemType != null &&
937 !types.isReifiable(varargElemType)) {
938 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
942 private boolean isTrustMeAllowedOnMethod(Symbol s) {
943 return (s.flags() & VARARGS) != 0 &&
944 (s.isConstructor() ||
945 (s.flags() & (STATIC | FINAL |
946 (allowPrivateSafeVarargs ? PRIVATE : 0) )) != 0);
949 Type checkMethod(final Type mtype,
951 final Env<AttrContext> env,
952 final List<JCExpression> argtrees,
953 final List<Type> argtypes,
954 final boolean useVarargs,
955 InferenceContext inferenceContext) {
956 // System.out.println("call : " + env.tree);
957 // System.out.println("method : " + owntype);
958 // System.out.println("actuals: " + argtypes);
959 if (inferenceContext.free(mtype)) {
960 inferenceContext.addFreeTypeListener(List.of(mtype),
961 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
964 Type owntype = mtype;
965 List<Type> formals = owntype.getParameterTypes();
966 List<Type> nonInferred = sym.type.getParameterTypes();
967 if (nonInferred.length() != formals.length()) nonInferred = formals;
968 Type last = useVarargs ? formals.last() : null;
969 if (sym.name == names.init && sym.owner == syms.enumSym) {
970 formals = formals.tail.tail;
971 nonInferred = nonInferred.tail.tail;
973 List<JCExpression> args = argtrees;
975 //this is null when type-checking a method reference
976 while (formals.head != last && args.head != null) {
977 JCTree arg = args.head;
978 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
979 assertConvertible(arg, arg.type, formals.head, warn);
981 formals = formals.tail;
982 nonInferred = nonInferred.tail;
985 Type varArg = types.elemtype(last);
986 while (args.tail != null) {
987 JCTree arg = args.head;
988 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
989 assertConvertible(arg, arg.type, varArg, warn);
992 } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
993 // non-varargs call to varargs method
994 Type varParam = owntype.getParameterTypes().last();
995 Type lastArg = argtypes.last();
996 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
997 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
998 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
999 types.elemtype(varParam), varParam);
1003 Type argtype = owntype.getParameterTypes().last();
1004 if (!types.isReifiable(argtype) &&
1005 (!allowSimplifiedVarargs ||
1006 sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
1007 !isTrustMeAllowedOnMethod(sym))) {
1008 warnUnchecked(env.tree.pos(),
1009 "unchecked.generic.array.creation",
1012 if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) {
1013 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
1019 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
1020 if (actual == null || formal == null)
1023 if (types.isConvertible(actual, formal, warn))
1026 if (formal.isCompound()
1027 && types.isSubtype(actual, types.supertype(formal))
1028 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1033 * Check that type 't' is a valid instantiation of a generic class
1036 * @param t class type to be checked
1037 * @return true if 't' is well-formed
1039 public boolean checkValidGenericType(Type t) {
1040 return firstIncompatibleTypeArg(t) == null;
1043 private Type firstIncompatibleTypeArg(Type type) {
1044 List<Type> formals = type.tsym.type.allparams();
1045 List<Type> actuals = type.allparams();
1046 List<Type> args = type.getTypeArguments();
1047 List<Type> forms = type.tsym.type.getTypeArguments();
1048 ListBuffer<Type> bounds_buf = new ListBuffer<>();
1050 // For matching pairs of actual argument types `a' and
1051 // formal type parameters with declared bound `b' ...
1052 while (args.nonEmpty() && forms.nonEmpty()) {
1053 // exact type arguments needs to know their
1054 // bounds (for upper and lower bound
1055 // calculations). So we create new bounds where
1056 // type-parameters are replaced with actuals argument types.
1057 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1062 args = type.getTypeArguments();
1063 List<Type> tvars_cap = types.substBounds(formals,
1065 types.capture(type).allparams());
1066 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1067 // Let the actual arguments know their bound
1068 args.head.withTypeVar((TypeVar)tvars_cap.head);
1070 tvars_cap = tvars_cap.tail;
1073 args = type.getTypeArguments();
1074 List<Type> bounds = bounds_buf.toList();
1076 while (args.nonEmpty() && bounds.nonEmpty()) {
1077 Type actual = args.head;
1078 if (!isTypeArgErroneous(actual) &&
1079 !bounds.head.isErroneous() &&
1080 !checkExtends(actual, bounds.head)) {
1084 bounds = bounds.tail;
1087 args = type.getTypeArguments();
1088 bounds = bounds_buf.toList();
1090 for (Type arg : types.capture(type).getTypeArguments()) {
1091 if (arg.hasTag(TYPEVAR) &&
1092 arg.getUpperBound().isErroneous() &&
1093 !bounds.head.isErroneous() &&
1094 !isTypeArgErroneous(args.head)) {
1097 bounds = bounds.tail;
1104 boolean isTypeArgErroneous(Type t) {
1105 return isTypeArgErroneous.visit(t);
1108 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1109 public Boolean visitType(Type t, Void s) {
1110 return t.isErroneous();
1113 public Boolean visitTypeVar(TypeVar t, Void s) {
1114 return visit(t.getUpperBound());
1117 public Boolean visitCapturedType(CapturedType t, Void s) {
1118 return visit(t.getUpperBound()) ||
1119 visit(t.getLowerBound());
1122 public Boolean visitWildcardType(WildcardType t, Void s) {
1123 return visit(t.type);
1127 /** Check that given modifiers are legal for given symbol and
1128 * return modifiers together with any implicit modifiers for that symbol.
1129 * Warning: we can't use flags() here since this method
1130 * is called during class enter, when flags() would cause a premature
1132 * @param pos Position to be used for error reporting.
1133 * @param flags The set of modifiers given in a definition.
1134 * @param sym The defined symbol.
1136 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1142 if (TreeInfo.isReceiverParam(tree))
1143 mask = ReceiverParamFlags;
1144 else if (sym.owner.kind != TYP && sym.owner.kind != ERR)
1145 mask = LocalVarFlags;
1146 else if ((sym.owner.flags_field & INTERFACE) != 0)
1147 mask = implicit = InterfaceVarFlags;
1152 if (sym.name == names.init) {
1153 if ((sym.owner.flags_field & ENUM) != 0) {
1154 // enum constructors cannot be declared public or
1155 // protected and must be implicitly or explicitly
1160 mask = ConstructorFlags;
1161 } else if ((sym.owner.flags_field & INTERFACE) != 0) {
1162 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1163 mask = AnnotationTypeElementMask;
1164 implicit = PUBLIC | ABSTRACT;
1165 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1166 mask = InterfaceMethodMask;
1167 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1168 if ((flags & DEFAULT) != 0) {
1169 implicit |= ABSTRACT;
1172 mask = implicit = InterfaceMethodFlags;
1177 // Imply STRICTFP if owner has STRICTFP set.
1178 if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1179 ((flags) & Flags.DEFAULT) != 0)
1180 implicit |= sym.owner.flags_field & STRICTFP;
1184 if (sym.isLocal()) {
1185 mask = LocalClassFlags;
1186 if ((sym.owner.flags_field & STATIC) == 0 &&
1187 (flags & ENUM) != 0)
1188 log.error(pos, "enums.must.be.static");
1189 } else if (sym.owner.kind == TYP || sym.owner.kind == ERR) {
1190 mask = MemberClassFlags;
1191 if (sym.owner.owner.kind == PCK ||
1192 (sym.owner.flags_field & STATIC) != 0)
1194 else if ((flags & ENUM) != 0)
1195 log.error(pos, "enums.must.be.static");
1196 // Nested interfaces and enums are always STATIC (Spec ???)
1197 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
1201 // Interfaces are always ABSTRACT
1202 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1204 if ((flags & ENUM) != 0) {
1205 // enums can't be declared abstract or final
1206 mask &= ~(ABSTRACT | FINAL);
1207 implicit |= implicitEnumFinalFlag(tree);
1209 // Imply STRICTFP if owner has STRICTFP set.
1210 implicit |= sym.owner.flags_field & STRICTFP;
1213 throw new AssertionError();
1215 long illegal = flags & ExtendedStandardFlags & ~mask;
1217 if ((illegal & INTERFACE) != 0) {
1218 log.error(pos, "intf.not.allowed.here");
1223 "mod.not.allowed.here", asFlagSet(illegal));
1226 else if ((sym.kind == TYP ||
1227 // ISSUE: Disallowing abstract&private is no longer appropriate
1228 // in the presence of inner classes. Should it be deleted here?
1229 checkDisjoint(pos, flags,
1231 PRIVATE | STATIC | DEFAULT))) {
1232 if (checkDisjoint(pos, flags,
1235 if (checkDisjoint(pos, flags,
1236 ABSTRACT | INTERFACE,
1237 FINAL | NATIVE | SYNCHRONIZED)) {
1238 if (checkDisjoint(pos, flags,
1240 PRIVATE | PROTECTED)) {
1241 if (checkDisjoint(pos, flags,
1243 PUBLIC | PROTECTED)) {
1244 if (checkDisjoint(pos, flags,
1247 if ((sym.kind == TYP ||
1248 checkDisjoint(pos, flags,
1258 flags &= ~(PUBLIC | PROTECTED);
1261 flags &= ~(PRIVATE | PROTECTED);
1264 flags &= ~(FINAL | NATIVE | SYNCHRONIZED);
1270 flags &= ~(PRIVATE | STATIC | DEFAULT);
1272 return flags & (mask | ~ExtendedStandardFlags) | implicit;
1276 /** Determine if this enum should be implicitly final.
1278 * If the enum has no specialized enum contants, it is final.
1280 * If the enum does have specialized enum contants, it is
1283 private long implicitEnumFinalFlag(JCTree tree) {
1284 if (!tree.hasTag(CLASSDEF)) return 0;
1285 class SpecialTreeVisitor extends JCTree.Visitor {
1286 boolean specialized;
1287 SpecialTreeVisitor() {
1288 this.specialized = false;
1292 public void visitTree(JCTree tree) { /* no-op */ }
1295 public void visitVarDef(JCVariableDecl tree) {
1296 if ((tree.mods.flags & ENUM) != 0) {
1297 if (tree.init instanceof JCNewClass &&
1298 ((JCNewClass) tree.init).def != null) {
1305 SpecialTreeVisitor sts = new SpecialTreeVisitor();
1306 JCClassDecl cdef = (JCClassDecl) tree;
1307 for (JCTree defs: cdef.defs) {
1309 if (sts.specialized) return 0;
1314 /* *************************************************************************
1316 **************************************************************************/
1318 /** Validate a type expression. That is,
1319 * check that all type arguments of a parametric type are within
1320 * their bounds. This must be done in a second phase after type attribution
1321 * since a class might have a subclass as type parameter bound. E.g:
1324 * class B<A extends C> { ... }
1325 * class C extends B<C> { ... }
1328 * and we can't make sure that the bound is already attributed because
1329 * of possible cycles.
1331 * Visitor method: Validate a type expression, if it is not null, catching
1332 * and reporting any completion failures.
1334 void validate(JCTree tree, Env<AttrContext> env) {
1335 validate(tree, env, true);
1337 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1338 new Validator(env).validateTree(tree, checkRaw, true);
1341 /** Visitor method: Validate a list of type expressions.
1343 void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1344 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1345 validate(l.head, env);
1348 /** A visitor class for type validation.
1350 class Validator extends JCTree.Visitor {
1354 Env<AttrContext> env;
1356 Validator(Env<AttrContext> env) {
1361 public void visitTypeArray(JCArrayTypeTree tree) {
1362 validateTree(tree.elemtype, checkRaw, isOuter);
1366 public void visitTypeApply(JCTypeApply tree) {
1367 if (tree.type != null && tree.type.hasTag(CLASS)) {
1368 List<JCExpression> args = tree.arguments;
1369 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1371 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1372 if (incompatibleArg != null) {
1373 for (JCTree arg : tree.arguments) {
1374 if (arg.type == incompatibleArg) {
1375 log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
1381 forms = tree.type.tsym.type.getTypeArguments();
1383 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1385 // For matching pairs of actual argument types `a' and
1386 // formal type parameters with declared bound `b' ...
1387 while (args.nonEmpty() && forms.nonEmpty()) {
1388 validateTree(args.head,
1389 !(isOuter && is_java_lang_Class),
1395 // Check that this type is either fully parameterized, or
1396 // not parameterized at all.
1397 if (tree.type.getEnclosingType().isRaw())
1398 log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
1399 if (tree.clazz.hasTag(SELECT))
1400 visitSelectInternal((JCFieldAccess)tree.clazz);
1405 public void visitTypeParameter(JCTypeParameter tree) {
1406 validateTrees(tree.bounds, true, isOuter);
1407 checkClassBounds(tree.pos(), tree.type);
1411 public void visitWildcard(JCWildcard tree) {
1412 if (tree.inner != null)
1413 validateTree(tree.inner, true, isOuter);
1417 public void visitSelect(JCFieldAccess tree) {
1418 if (tree.type.hasTag(CLASS)) {
1419 visitSelectInternal(tree);
1421 // Check that this type is either fully parameterized, or
1422 // not parameterized at all.
1423 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1424 log.error(tree.pos(), "improperly.formed.type.param.missing");
1428 public void visitSelectInternal(JCFieldAccess tree) {
1429 if (tree.type.tsym.isStatic() &&
1430 tree.selected.type.isParameterized()) {
1431 // The enclosing type is not a class, so we are
1432 // looking at a static member type. However, the
1433 // qualifying expression is parameterized.
1434 log.error(tree.pos(), "cant.select.static.class.from.param.type");
1436 // otherwise validate the rest of the expression
1437 tree.selected.accept(this);
1442 public void visitAnnotatedType(JCAnnotatedType tree) {
1443 tree.underlyingType.accept(this);
1447 public void visitTypeIdent(JCPrimitiveTypeTree that) {
1448 if (that.type.hasTag(TypeTag.VOID)) {
1449 log.error(that.pos(), "void.not.allowed.here");
1451 super.visitTypeIdent(that);
1454 /** Default visitor method: do nothing.
1457 public void visitTree(JCTree tree) {
1460 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1462 boolean prevCheckRaw = this.checkRaw;
1463 this.checkRaw = checkRaw;
1464 this.isOuter = isOuter;
1469 checkRaw(tree, env);
1470 } catch (CompletionFailure ex) {
1471 completionError(tree.pos(), ex);
1473 this.checkRaw = prevCheckRaw;
1478 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1479 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1480 validateTree(l.head, checkRaw, isOuter);
1484 void checkRaw(JCTree tree, Env<AttrContext> env) {
1485 if (lint.isEnabled(LintCategory.RAW) &&
1486 tree.type.hasTag(CLASS) &&
1487 !TreeInfo.isDiamond(tree) &&
1488 !withinAnonConstr(env) &&
1489 tree.type.isRaw()) {
1490 log.warning(LintCategory.RAW,
1491 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
1495 private boolean withinAnonConstr(Env<AttrContext> env) {
1496 return env.enclClass.name.isEmpty() &&
1497 env.enclMethod != null && env.enclMethod.name == names.init;
1500 /* *************************************************************************
1501 * Exception checking
1502 **************************************************************************/
1504 /* The following methods treat classes as sets that contain
1505 * the class itself and all their subclasses
1508 /** Is given type a subtype of some of the types in given list?
1510 boolean subset(Type t, List<Type> ts) {
1513 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1514 if (types.isSubtype(t, l.head)) return true;
1518 /** Is given type a subtype or supertype of
1519 * some of the types in given list?
1521 boolean intersects(Type t, List<Type> ts) {
1524 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1525 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1529 /** Add type set to given type list, unless it is a subclass of some class
1532 List<Type> incl(Type t, List<Type> ts) {
1533 return (t == null || subset(t, ts)) ? ts : excl(t, ts).prepend(t);
1536 /** Remove type set from type set list.
1538 List<Type> excl(Type t, List<Type> ts) {
1539 if (t == null || ts.isEmpty()) {
1542 List<Type> ts1 = excl(t, ts.tail);
1543 if (types.isSubtype(ts.head, t)) return ts1;
1544 else if (ts1 == ts.tail) return ts;
1545 else return ts1.prepend(ts.head);
1549 /** Form the union of two type set lists.
1551 List<Type> union(List<Type> ts1, List<Type> ts2) {
1552 List<Type> ts = ts1;
1553 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1554 ts = incl(l.head, ts);
1558 /** Form the difference of two type lists.
1560 List<Type> diff(List<Type> ts1, List<Type> ts2) {
1561 List<Type> ts = ts1;
1562 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1563 ts = excl(l.head, ts);
1567 /** Form the intersection of two type lists.
1569 public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1570 List<Type> ts = List.nil();
1571 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1572 if (subset(l.head, ts2)) ts = incl(l.head, ts);
1573 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1574 if (subset(l.head, ts1)) ts = incl(l.head, ts);
1578 /** Is exc an exception symbol that need not be declared?
1580 boolean isUnchecked(ClassSymbol exc) {
1583 exc.isSubClass(syms.errorType.tsym, types) ||
1584 exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1587 /** Is exc an exception type that need not be declared?
1589 boolean isUnchecked(Type exc) {
1591 (exc == null) ? true :
1592 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1593 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1594 exc.hasTag(BOT) || exc.hasTag(ERROR);
1597 /** Same, but handling completion failures.
1599 boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1601 return isUnchecked(exc);
1602 } catch (CompletionFailure ex) {
1603 completionError(pos, ex);
1608 /** Is exc handled by given exception list?
1610 boolean isHandled(Type exc, List<Type> handled) {
1611 return isUnchecked(exc) || subset(exc, handled);
1614 /** Return all exceptions in thrown list that are not in handled list.
1615 * @param thrown The list of thrown exceptions.
1616 * @param handled The list of handled exceptions.
1618 List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1619 List<Type> unhandled = List.nil();
1620 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1621 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1625 /* *************************************************************************
1626 * Overriding/Implementation checking
1627 **************************************************************************/
1629 /** The level of access protection given by a flag set,
1630 * where PRIVATE is highest and PUBLIC is lowest.
1632 static int protection(long flags) {
1633 switch ((short)(flags & AccessFlags)) {
1634 case PRIVATE: return 3;
1635 case PROTECTED: return 1;
1637 case PUBLIC: return 0;
1642 /** A customized "cannot override" error message.
1643 * @param m The overriding method.
1644 * @param other The overridden method.
1645 * @return An internationalized string.
1647 Object cannotOverride(MethodSymbol m, MethodSymbol other) {
1649 if ((other.owner.flags() & INTERFACE) == 0)
1650 key = "cant.override";
1651 else if ((m.owner.flags() & INTERFACE) == 0)
1652 key = "cant.implement";
1654 key = "clashes.with";
1655 return diags.fragment(key, m, m.location(), other, other.location());
1658 /** A customized "override" warning message.
1659 * @param m The overriding method.
1660 * @param other The overridden method.
1661 * @return An internationalized string.
1663 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1665 if ((other.owner.flags() & INTERFACE) == 0)
1666 key = "unchecked.override";
1667 else if ((m.owner.flags() & INTERFACE) == 0)
1668 key = "unchecked.implement";
1670 key = "unchecked.clash.with";
1671 return diags.fragment(key, m, m.location(), other, other.location());
1674 /** A customized "override" warning message.
1675 * @param m The overriding method.
1676 * @param other The overridden method.
1677 * @return An internationalized string.
1679 Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
1681 if ((other.owner.flags() & INTERFACE) == 0)
1682 key = "varargs.override";
1683 else if ((m.owner.flags() & INTERFACE) == 0)
1684 key = "varargs.implement";
1686 key = "varargs.clash.with";
1687 return diags.fragment(key, m, m.location(), other, other.location());
1690 /** Check that this method conforms with overridden method 'other'.
1691 * where `origin' is the class where checking started.
1693 * (1) Do not check overriding of synthetic methods
1694 * (reason: they might be final).
1695 * todo: check whether this is still necessary.
1696 * (2) Admit the case where an interface proxy throws fewer exceptions
1697 * than the method it implements. Augment the proxy methods with the
1698 * undeclared exceptions in this case.
1699 * (3) When generics are enabled, admit the case where an interface proxy
1701 * extended by the result type of the method it implements.
1702 * Change the proxies result type to the smaller type in this case.
1704 * @param tree The tree from which positions
1705 * are extracted for errors.
1706 * @param m The overriding method.
1707 * @param other The overridden method.
1708 * @param origin The class of which the overriding method
1711 void checkOverride(JCTree tree,
1714 ClassSymbol origin) {
1715 // Don't check overriding of synthetic methods or by bridge methods.
1716 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1720 // Error if static method overrides instance method (JLS 8.4.6.2).
1721 if ((m.flags() & STATIC) != 0 &&
1722 (other.flags() & STATIC) == 0) {
1723 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
1724 cannotOverride(m, other));
1725 m.flags_field |= BAD_OVERRIDE;
1729 // Error if instance method overrides static or final
1730 // method (JLS 8.4.6.1).
1731 if ((other.flags() & FINAL) != 0 ||
1732 (m.flags() & STATIC) == 0 &&
1733 (other.flags() & STATIC) != 0) {
1734 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
1735 cannotOverride(m, other),
1736 asFlagSet(other.flags() & (FINAL | STATIC)));
1737 m.flags_field |= BAD_OVERRIDE;
1741 if ((m.owner.flags() & ANNOTATION) != 0) {
1742 // handled in validateAnnotationMethod
1746 // Error if overriding method has weaker access (JLS 8.4.6.3).
1747 if (protection(m.flags()) > protection(other.flags())) {
1748 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
1749 cannotOverride(m, other),
1750 (other.flags() & AccessFlags) == 0 ?
1752 asFlagSet(other.flags() & AccessFlags));
1753 m.flags_field |= BAD_OVERRIDE;
1757 Type mt = types.memberType(origin.type, m);
1758 Type ot = types.memberType(origin.type, other);
1759 // Error if overriding result type is different
1760 // (or, in the case of generics mode, not a subtype) of
1761 // overridden result type. We have to rename any type parameters
1762 // before comparing types.
1763 List<Type> mtvars = mt.getTypeArguments();
1764 List<Type> otvars = ot.getTypeArguments();
1765 Type mtres = mt.getReturnType();
1766 Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1768 overrideWarner.clear();
1769 boolean resultTypesOK =
1770 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1771 if (!resultTypesOK) {
1772 if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1773 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1774 Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1775 other.location()), mtres, otres));
1776 m.flags_field |= BAD_OVERRIDE;
1778 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1779 "override.incompatible.ret",
1780 cannotOverride(m, other),
1782 m.flags_field |= BAD_OVERRIDE;
1785 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1786 warnDeferredUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1787 "override.unchecked.ret",
1788 uncheckedOverrides(m, other),
1792 // Error if overriding method throws an exception not reported
1793 // by overridden method.
1794 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1795 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1796 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1797 if (unhandledErased.nonEmpty()) {
1798 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1799 "override.meth.doesnt.throw",
1800 cannotOverride(m, other),
1801 unhandledUnerased.head);
1802 m.flags_field |= BAD_OVERRIDE;
1805 else if (unhandledUnerased.nonEmpty()) {
1806 warnDeferredUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1807 "override.unchecked.thrown",
1808 cannotOverride(m, other),
1809 unhandledUnerased.head);
1813 // Optional warning if varargs don't agree
1814 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1815 && lint.isEnabled(LintCategory.OVERRIDES)) {
1816 log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1817 ((m.flags() & Flags.VARARGS) != 0)
1818 ? "override.varargs.missing"
1819 : "override.varargs.extra",
1820 varargsOverrides(m, other));
1823 // Warn if instance method overrides bridge method (compiler spec ??)
1824 if ((other.flags() & BRIDGE) != 0) {
1825 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
1826 uncheckedOverrides(m, other));
1829 // Warn if a deprecated method overridden by a non-deprecated one.
1830 if (!isDeprecatedOverrideIgnorable(other, origin)) {
1831 Lint prevLint = setLint(lint.augment(m));
1833 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
1840 private void warnDeferredUnchecked(final DiagnosticPosition pos, final String msg, final Object... args) {
1841 DiagnosticPosition prevPos = deferredLintHandler.setPos(pos);
1843 deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
1845 public void report() {
1846 warnUnchecked(pos, msg, args);
1850 deferredLintHandler.setPos(prevPos);
1854 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1855 // If the method, m, is defined in an interface, then ignore the issue if the method
1856 // is only inherited via a supertype and also implemented in the supertype,
1857 // because in that case, we will rediscover the issue when examining the method
1858 // in the supertype.
1859 // If the method, m, is not defined in an interface, then the only time we need to
1860 // address the issue is when the method is the supertype implemementation: any other
1861 // case, we will have dealt with when examining the supertype classes
1862 ClassSymbol mc = m.enclClass();
1863 Type st = types.supertype(origin.type);
1864 if (!st.hasTag(CLASS))
1866 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1868 if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1869 List<Type> intfs = types.interfaces(origin.type);
1870 return (intfs.contains(mc.type) ? false : (stimpl != null));
1873 return (stimpl != m);
1877 // used to check if there were any unchecked conversions
1878 Warner overrideWarner = new Warner();
1880 /** Check that a class does not inherit two concrete methods
1881 * with the same signature.
1882 * @param pos Position to be used for error reporting.
1883 * @param site The class type to be checked.
1885 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1886 Type sup = types.supertype(site);
1887 if (!sup.hasTag(CLASS)) return;
1890 t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1891 t1 = types.supertype(t1)) {
1892 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1893 if (s1.kind != MTH ||
1894 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1895 !s1.isInheritedIn(site.tsym, types) ||
1896 ((MethodSymbol)s1).implementation(site.tsym,
1900 Type st1 = types.memberType(t1, s1);
1901 int s1ArgsLength = st1.getParameterTypes().length();
1902 if (st1 == s1.type) continue;
1906 t2 = types.supertype(t2)) {
1907 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1910 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1911 s2.type.getParameterTypes().length() != s1ArgsLength ||
1912 !s2.isInheritedIn(site.tsym, types) ||
1913 ((MethodSymbol)s2).implementation(site.tsym,
1917 Type st2 = types.memberType(t2, s2);
1918 if (types.overrideEquivalent(st1, st2))
1919 log.error(pos, "concrete.inheritance.conflict",
1920 s1, t1, s2, t2, sup);
1927 /** Check that classes (or interfaces) do not each define an abstract
1928 * method with same name and arguments but incompatible return types.
1929 * @param pos Position to be used for error reporting.
1930 * @param t1 The first argument type.
1931 * @param t2 The second argument type.
1933 public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1937 if ((site.tsym.flags() & COMPOUND) != 0) {
1938 // special case for intersections: need to eliminate wildcards in supertypes
1939 t1 = types.capture(t1);
1940 t2 = types.capture(t2);
1942 return firstIncompatibility(pos, t1, t2, site) == null;
1945 /** Return the first method which is defined with same args
1946 * but different return types in two given interfaces, or null if none
1948 * @param t1 The first type.
1949 * @param t2 The second type.
1950 * @param site The most derived type.
1951 * @returns symbol from t2 that conflicts with one in t1.
1953 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1954 Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1955 closure(t1, interfaces1);
1956 Map<TypeSymbol,Type> interfaces2;
1958 interfaces2 = interfaces1;
1960 closure(t2, interfaces1, interfaces2 = new HashMap<>());
1962 for (Type t3 : interfaces1.values()) {
1963 for (Type t4 : interfaces2.values()) {
1964 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
1965 if (s != null) return s;
1971 /** Compute all the supertypes of t, indexed by type symbol. */
1972 private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
1973 if (!t.hasTag(CLASS)) return;
1974 if (typeMap.put(t.tsym, t) == null) {
1975 closure(types.supertype(t), typeMap);
1976 for (Type i : types.interfaces(t))
1977 closure(i, typeMap);
1981 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
1982 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
1983 if (!t.hasTag(CLASS)) return;
1984 if (typesSkip.get(t.tsym) != null) return;
1985 if (typeMap.put(t.tsym, t) == null) {
1986 closure(types.supertype(t), typesSkip, typeMap);
1987 for (Type i : types.interfaces(t))
1988 closure(i, typesSkip, typeMap);
1992 /** Return the first method in t2 that conflicts with a method from t1. */
1993 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1994 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1996 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
1997 (s1.flags() & SYNTHETIC) != 0) continue;
1998 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
1999 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
2000 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2001 if (s1 == s2) continue;
2002 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
2003 (s2.flags() & SYNTHETIC) != 0) continue;
2004 if (st1 == null) st1 = types.memberType(t1, s1);
2005 Type st2 = types.memberType(t2, s2);
2006 if (types.overrideEquivalent(st1, st2)) {
2007 List<Type> tvars1 = st1.getTypeArguments();
2008 List<Type> tvars2 = st2.getTypeArguments();
2009 Type rt1 = st1.getReturnType();
2010 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
2012 types.isSameType(rt1, rt2) ||
2013 !rt1.isPrimitiveOrVoid() &&
2014 !rt2.isPrimitiveOrVoid() &&
2015 (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
2016 types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
2017 checkCommonOverriderIn(s1,s2,site);
2019 log.error(pos, "types.incompatible.diff.ret",
2021 "(" + types.memberType(t2, s2).getParameterTypes() + ")");
2024 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2025 !checkCommonOverriderIn(s1, s2, site)) {
2027 "name.clash.same.erasure.no.override",
2037 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2038 Map<TypeSymbol,Type> supertypes = new HashMap<>();
2039 Type st1 = types.memberType(site, s1);
2040 Type st2 = types.memberType(site, s2);
2041 closure(site, supertypes);
2042 for (Type t : supertypes.values()) {
2043 for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2044 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2045 Type st3 = types.memberType(site,s3);
2046 if (types.overrideEquivalent(st3, st1) &&
2047 types.overrideEquivalent(st3, st2) &&
2048 types.returnTypeSubstitutable(st3, st1) &&
2049 types.returnTypeSubstitutable(st3, st2)) {
2057 /** Check that a given method conforms with any method it overrides.
2058 * @param tree The tree from which positions are extracted
2060 * @param m The overriding method.
2062 void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2063 ClassSymbol origin = (ClassSymbol)m.owner;
2064 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
2065 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2066 log.error(tree.pos(), "enum.no.finalize");
2069 for (Type t = origin.type; t.hasTag(CLASS);
2070 t = types.supertype(t)) {
2071 if (t != origin.type) {
2072 checkOverride(tree, t, origin, m);
2074 for (Type t2 : types.interfaces(t)) {
2075 checkOverride(tree, t2, origin, m);
2079 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2080 // Check if this method must override a super method due to being annotated with @Override
2081 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2082 // be treated "as if as they were annotated" with @Override.
2083 boolean mustOverride = explicitOverride ||
2084 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2085 if (mustOverride && !isOverrider(m)) {
2086 DiagnosticPosition pos = tree.pos();
2087 for (JCAnnotation a : tree.getModifiers().annotations) {
2088 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2094 explicitOverride ? Errors.MethodDoesNotOverrideSuperclass :
2095 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2099 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2100 TypeSymbol c = site.tsym;
2101 for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2102 if (m.overrides(sym, origin, types, false)) {
2103 if ((sym.flags() & ABSTRACT) == 0) {
2104 checkOverride(tree, m, (MethodSymbol)sym, origin);
2110 private Filter<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.accepts(s) &&
2111 (s.flags() & BAD_OVERRIDE) == 0;
2113 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2114 ClassSymbol someClass) {
2115 /* At present, annotations cannot possibly have a method that is override
2116 * equivalent with Object.equals(Object) but in any case the condition is
2117 * fine for completeness.
2119 if (syms.objectType.isErroneous() ||
2120 someClass == (ClassSymbol)syms.objectType.tsym ||
2121 someClass.isInterface() || someClass.isEnum() ||
2122 (someClass.flags() & ANNOTATION) != 0 ||
2123 (someClass.flags() & ABSTRACT) != 0) return;
2124 //anonymous inner classes implementing interfaces need especial treatment
2125 if (someClass.isAnonymous()) {
2126 List<Type> interfaces = types.interfaces(someClass.type);
2127 if (interfaces != null && !interfaces.isEmpty() &&
2128 interfaces.head.tsym == syms.comparatorType.tsym) return;
2130 checkClassOverrideEqualsAndHash(pos, someClass);
2133 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2134 ClassSymbol someClass) {
2135 if (lint.isEnabled(LintCategory.OVERRIDES)) {
2136 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2137 .tsym.members().findFirst(names.equals);
2138 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2139 .tsym.members().findFirst(names.hashCode);
2140 MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2141 someClass, false, equalsHasCodeFilter);
2142 boolean overridesEquals = equalsImpl != null && equalsImpl.owner == someClass;
2143 MethodSymbol hasCodeImpl = types.implementation(hashCodeAtObject,
2144 someClass, false, equalsHasCodeFilter);
2145 boolean overridesHashCode = hasCodeImpl != null && hasCodeImpl != hashCodeAtObject;
2147 if (overridesEquals && !overridesHashCode) {
2148 log.warning(LintCategory.OVERRIDES, pos,
2149 "override.equals.but.not.hashcode", someClass);
2154 public void checkModuleName (JCModuleDecl tree) {
2155 Name moduleName = tree.sym.name;
2156 Assert.checkNonNull(moduleName);
2157 if (lint.isEnabled(LintCategory.MODULE)) {
2158 JCExpression qualId = tree.qualId;
2159 while (qualId != null) {
2161 DiagnosticPosition pos;
2162 switch (qualId.getTag()) {
2164 JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2165 componentName = selectNode.name;
2166 pos = selectNode.pos();
2167 qualId = selectNode.selected;
2170 componentName = ((JCIdent) qualId).name;
2175 throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2177 if (componentName != null) {
2178 String moduleNameComponentString = componentName.toString();
2179 int nameLength = moduleNameComponentString.length();
2180 if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2181 log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
2188 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2189 ClashFilter cf = new ClashFilter(origin.type);
2190 return (cf.accepts(s1) &&
2192 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2196 /** Check that all abstract members of given class have definitions.
2197 * @param pos Position to be used for error reporting.
2198 * @param c The class.
2200 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2201 if (c.type == null || c.type.isErroneous()) {
2204 MethodSymbol undef = types.firstUnimplementedAbstract(c);
2205 if (undef != null) {
2206 MethodSymbol undef1 =
2207 new MethodSymbol(undef.flags(), undef.name,
2208 types.memberType(c.type, undef), undef.owner);
2209 log.error(pos, "does.not.override.abstract",
2210 c, undef1, undef1.location());
2214 void checkNonCyclicDecl(JCClassDecl tree) {
2215 CycleChecker cc = new CycleChecker();
2217 if (!cc.errorFound && !cc.partialCheck) {
2218 tree.sym.flags_field |= ACYCLIC;
2222 class CycleChecker extends TreeScanner {
2224 List<Symbol> seenClasses = List.nil();
2225 boolean errorFound = false;
2226 boolean partialCheck = false;
2228 private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2229 if (sym != null && sym.kind == TYP) {
2230 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2231 if (classEnv != null) {
2232 DiagnosticSource prevSource = log.currentSource();
2234 log.useSource(classEnv.toplevel.sourcefile);
2235 scan(classEnv.tree);
2238 log.useSource(prevSource.getFile());
2240 } else if (sym.kind == TYP) {
2241 checkClass(pos, sym, List.nil());
2245 partialCheck = true;
2250 public void visitSelect(JCFieldAccess tree) {
2251 super.visitSelect(tree);
2252 checkSymbol(tree.pos(), tree.sym);
2256 public void visitIdent(JCIdent tree) {
2257 checkSymbol(tree.pos(), tree.sym);
2261 public void visitTypeApply(JCTypeApply tree) {
2266 public void visitTypeArray(JCArrayTypeTree tree) {
2267 scan(tree.elemtype);
2271 public void visitClassDef(JCClassDecl tree) {
2272 List<JCTree> supertypes = List.nil();
2273 if (tree.getExtendsClause() != null) {
2274 supertypes = supertypes.prepend(tree.getExtendsClause());
2276 if (tree.getImplementsClause() != null) {
2277 for (JCTree intf : tree.getImplementsClause()) {
2278 supertypes = supertypes.prepend(intf);
2281 checkClass(tree.pos(), tree.sym, supertypes);
2284 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2285 if (c == null || (c.flags_field & ACYCLIC) != 0)
2287 if (seenClasses.contains(c)) {
2289 noteCyclic(pos, (ClassSymbol)c);
2290 } else if (!c.type.isErroneous()) {
2292 seenClasses = seenClasses.prepend(c);
2293 if (c.type.hasTag(CLASS)) {
2294 if (supertypes.nonEmpty()) {
2298 ClassType ct = (ClassType)c.type;
2299 if (ct.supertype_field == null ||
2300 ct.interfaces_field == null) {
2302 partialCheck = true;
2305 checkSymbol(pos, ct.supertype_field.tsym);
2306 for (Type intf : ct.interfaces_field) {
2307 checkSymbol(pos, intf.tsym);
2310 if (c.owner.kind == TYP) {
2311 checkSymbol(pos, c.owner);
2315 seenClasses = seenClasses.tail;
2321 /** Check for cyclic references. Issue an error if the
2322 * symbol of the type referred to has a LOCKED flag set.
2324 * @param pos Position to be used for error reporting.
2325 * @param t The type referred to.
2327 void checkNonCyclic(DiagnosticPosition pos, Type t) {
2328 checkNonCyclicInternal(pos, t);
2332 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2333 checkNonCyclic1(pos, t, List.nil());
2336 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2338 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2340 if (seen.contains(t)) {
2342 tv.bound = types.createErrorType(t);
2343 log.error(pos, "cyclic.inheritance", t);
2344 } else if (t.hasTag(TYPEVAR)) {
2346 seen = seen.prepend(tv);
2347 for (Type b : types.getBounds(tv))
2348 checkNonCyclic1(pos, b, seen);
2352 /** Check for cyclic references. Issue an error if the
2353 * symbol of the type referred to has a LOCKED flag set.
2355 * @param pos Position to be used for error reporting.
2356 * @param t The type referred to.
2357 * @returns True if the check completed on all attributed classes
2359 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2360 boolean complete = true; // was the check complete?
2361 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2363 if ((c.flags_field & ACYCLIC) != 0) return true;
2365 if ((c.flags_field & LOCKED) != 0) {
2366 noteCyclic(pos, (ClassSymbol)c);
2367 } else if (!c.type.isErroneous()) {
2369 c.flags_field |= LOCKED;
2370 if (c.type.hasTag(CLASS)) {
2371 ClassType clazz = (ClassType)c.type;
2372 if (clazz.interfaces_field != null)
2373 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2374 complete &= checkNonCyclicInternal(pos, l.head);
2375 if (clazz.supertype_field != null) {
2376 Type st = clazz.supertype_field;
2377 if (st != null && st.hasTag(CLASS))
2378 complete &= checkNonCyclicInternal(pos, st);
2380 if (c.owner.kind == TYP)
2381 complete &= checkNonCyclicInternal(pos, c.owner.type);
2384 c.flags_field &= ~LOCKED;
2388 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2389 if (complete) c.flags_field |= ACYCLIC;
2393 /** Note that we found an inheritance cycle. */
2394 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2395 log.error(pos, "cyclic.inheritance", c);
2396 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2397 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2398 Type st = types.supertype(c.type);
2399 if (st.hasTag(CLASS))
2400 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2401 c.type = types.createErrorType(c, c.type);
2402 c.flags_field |= ACYCLIC;
2405 /** Check that all methods which implement some
2406 * method conform to the method they implement.
2407 * @param tree The class definition whose members are checked.
2409 void checkImplementations(JCClassDecl tree) {
2410 checkImplementations(tree, tree.sym, tree.sym);
2413 /** Check that all methods which implement some
2414 * method in `ic' conform to the method they implement.
2416 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2417 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2418 ElementKind kind = l.head.tsym.getKind();
2420 if (!kind.isClass() && !kind.isInterface()) {
2421 //not a class: an error should have already been reported, ignore.
2425 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2426 if ((lc.flags() & ABSTRACT) != 0) {
2427 for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2428 if (sym.kind == MTH &&
2429 (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2430 MethodSymbol absmeth = (MethodSymbol)sym;
2431 MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2432 if (implmeth != null && implmeth != absmeth &&
2433 (implmeth.owner.flags() & INTERFACE) ==
2434 (origin.flags() & INTERFACE)) {
2435 // don't check if implmeth is in a class, yet
2436 // origin is an interface. This case arises only
2437 // if implmeth is declared in Object. The reason is
2438 // that interfaces really don't inherit from
2439 // Object it's just that the compiler represents
2441 checkOverride(tree, implmeth, absmeth, origin);
2449 /** Check that all abstract methods implemented by a class are
2450 * mutually compatible.
2451 * @param pos Position to be used for error reporting.
2452 * @param c The class whose interfaces are checked.
2454 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2455 List<Type> supertypes = types.interfaces(c);
2456 Type supertype = types.supertype(c);
2457 if (supertype.hasTag(CLASS) &&
2458 (supertype.tsym.flags() & ABSTRACT) != 0)
2459 supertypes = supertypes.prepend(supertype);
2460 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2461 if (!l.head.getTypeArguments().isEmpty() &&
2462 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2464 for (List<Type> m = supertypes; m != l; m = m.tail)
2465 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2468 checkCompatibleConcretes(pos, c);
2471 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
2472 Type previous = null;
2473 for (Type ct = c.type; ct != Type.noType && ct != previous; previous = ct, ct = types.supertype(ct)) {
2474 for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) {
2475 // VM allows methods and variables with differing types
2476 if (sym.kind == sym2.kind &&
2477 types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) &&
2479 (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) &&
2480 (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) {
2481 syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym);
2488 /** Check that all non-override equivalent methods accessible from 'site'
2489 * are mutually compatible (JLS 8.4.8/9.4.1).
2491 * @param pos Position to be used for error reporting.
2492 * @param site The class whose methods are checked.
2493 * @param sym The method symbol to be checked.
2495 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2496 if (site == null || site.isErroneous() || sym.type.isErroneous())
2498 ClashFilter cf = new ClashFilter(site);
2499 //for each method m1 that is overridden (directly or indirectly)
2500 //by method 'sym' in 'site'...
2502 List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2503 boolean overridesAny = false;
2504 for (Symbol m1 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2505 if (!sym.overrides(m1, site.tsym, types, false)) {
2510 if (!overridesAny) {
2511 potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1);
2517 overridesAny = true;
2518 potentiallyAmbiguousList = List.nil();
2521 //...check each method m2 that is a member of 'site'
2522 for (Symbol m2 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) {
2523 if (m2 == m1) continue;
2524 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2525 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2526 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
2527 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2528 sym.flags_field |= CLASH;
2529 String key = m1 == sym ?
2530 "name.clash.same.erasure.no.override" :
2531 "name.clash.same.erasure.no.override.1";
2534 sym, sym.location(),
2542 if (!overridesAny) {
2543 for (MethodSymbol m: potentiallyAmbiguousList) {
2544 checkPotentiallyAmbiguousOverloads(pos, site, sym, m);
2549 /** Check that all static methods accessible from 'site' are
2550 * mutually compatible (JLS 8.4.8).
2552 * @param pos Position to be used for error reporting.
2553 * @param site The class whose methods are checked.
2554 * @param sym The method symbol to be checked.
2556 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2557 if (site == null || site.isErroneous())
2559 ClashFilter cf = new ClashFilter(site);
2560 //for each method m1 that is a member of 'site'...
2561 for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2562 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2563 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2564 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck)) {
2565 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2567 "name.clash.same.erasure.no.hide",
2568 sym, sym.location(),
2572 checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
2579 private class ClashFilter implements Filter<Symbol> {
2583 ClashFilter(Type site) {
2587 boolean shouldSkip(Symbol s) {
2588 return (s.flags() & CLASH) != 0 &&
2589 s.owner == site.tsym;
2592 public boolean accepts(Symbol s) {
2593 return s.kind == MTH &&
2594 (s.flags() & SYNTHETIC) == 0 &&
2596 s.isInheritedIn(site.tsym, types) &&
2601 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2602 if (site == null || site.isErroneous()) {
2605 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2606 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2607 Assert.check(m.kind == MTH);
2608 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2609 if (prov.size() > 1) {
2610 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2611 ListBuffer<Symbol> defaults = new ListBuffer<>();
2612 for (MethodSymbol provSym : prov) {
2613 if ((provSym.flags() & DEFAULT) != 0) {
2614 defaults = defaults.append(provSym);
2615 } else if ((provSym.flags() & ABSTRACT) != 0) {
2616 abstracts = abstracts.append(provSym);
2618 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2619 //strong semantics - issue an error if two sibling interfaces
2620 //have two override-equivalent defaults - or if one is abstract
2621 //and the other is default
2623 Symbol s1 = defaults.first();
2625 if (defaults.size() > 1) {
2626 errKey = "types.incompatible.unrelated.defaults";
2627 s2 = defaults.toList().tail.head;
2629 errKey = "types.incompatible.abstract.default";
2630 s2 = abstracts.first();
2632 log.error(pos, errKey,
2633 Kinds.kindName(site.tsym), site,
2634 m.name, types.memberType(site, m).getParameterTypes(),
2635 s1.location(), s2.location());
2644 private class DefaultMethodClashFilter implements Filter<Symbol> {
2648 DefaultMethodClashFilter(Type site) {
2652 public boolean accepts(Symbol s) {
2653 return s.kind == MTH &&
2654 (s.flags() & DEFAULT) != 0 &&
2655 s.isInheritedIn(site.tsym, types) &&
2661 * Report warnings for potentially ambiguous method declarations. Two declarations
2662 * are potentially ambiguous if they feature two unrelated functional interface
2663 * in same argument position (in which case, a call site passing an implicit
2664 * lambda would be ambiguous).
2666 void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2667 MethodSymbol msym1, MethodSymbol msym2) {
2668 if (msym1 != msym2 &&
2669 allowDefaultMethods &&
2670 lint.isEnabled(LintCategory.OVERLOADS) &&
2671 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2672 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2673 Type mt1 = types.memberType(site, msym1);
2674 Type mt2 = types.memberType(site, msym2);
2675 //if both generic methods, adjust type variables
2676 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2677 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2678 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2680 //expand varargs methods if needed
2681 int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2682 List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2683 List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2684 //if arities don't match, exit
2685 if (args1.length() != args2.length()) return;
2686 boolean potentiallyAmbiguous = false;
2687 while (args1.nonEmpty() && args2.nonEmpty()) {
2688 Type s = args1.head;
2689 Type t = args2.head;
2690 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2691 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2692 types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2693 types.findDescriptorType(s).getParameterTypes().length() ==
2694 types.findDescriptorType(t).getParameterTypes().length()) {
2695 potentiallyAmbiguous = true;
2703 if (potentiallyAmbiguous) {
2704 //we found two incompatible functional interfaces with same arity
2705 //this means a call site passing an implicit lambda would be ambigiuous
2706 msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
2707 msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
2708 log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload",
2709 msym1, msym1.location(),
2710 msym2, msym2.location());
2716 void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2717 if (warnOnAnyAccessToMembers ||
2718 (lint.isEnabled(LintCategory.SERIAL) &&
2719 !lint.isSuppressed(LintCategory.SERIAL) &&
2721 Symbol sym = TreeInfo.symbol(tree);
2722 if (!sym.kind.matches(KindSelector.VAL_MTH) || sym.owner.kind == PCK) {
2726 if (sym.kind == VAR) {
2727 if ((sym.flags() & PARAMETER) != 0 ||
2729 sym.name == names._this ||
2730 sym.name == names._super) {
2735 if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
2736 isEffectivelyNonPublic(sym)) {
2738 if (belongsToRestrictedPackage(sym)) {
2739 log.warning(LintCategory.SERIAL, tree.pos(),
2740 "access.to.member.from.serializable.lambda", sym);
2743 log.warning(tree.pos(),
2744 "access.to.member.from.serializable.element", sym);
2750 private boolean isEffectivelyNonPublic(Symbol sym) {
2751 if (sym.packge() == syms.rootPackage) {
2755 while (sym.kind != PCK) {
2756 if ((sym.flags() & PUBLIC) == 0) {
2764 private boolean belongsToRestrictedPackage(Symbol sym) {
2765 String fullName = sym.packge().fullname.toString();
2766 return fullName.startsWith("java.") ||
2767 fullName.startsWith("javax.") ||
2768 fullName.startsWith("sun.") ||
2769 fullName.contains(".internal.");
2772 /** Report a conflict between a user symbol and a synthetic symbol.
2774 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
2775 if (!sym.type.isErroneous()) {
2776 log.error(pos, "synthetic.name.conflict", sym, sym.location());
2780 /** Check that class c does not implement directly or indirectly
2781 * the same parameterized interface with two different argument lists.
2782 * @param pos Position to be used for error reporting.
2783 * @param type The type whose interfaces are checked.
2785 void checkClassBounds(DiagnosticPosition pos, Type type) {
2786 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2789 /** Enter all interfaces of type `type' into the hash table `seensofar'
2790 * with their class symbol as key and their type as value. Make
2791 * sure no class is entered with two different types.
2793 void checkClassBounds(DiagnosticPosition pos,
2794 Map<TypeSymbol,Type> seensofar,
2796 if (type.isErroneous()) return;
2797 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2799 Type oldit = seensofar.put(it.tsym, it);
2800 if (oldit != null) {
2801 List<Type> oldparams = oldit.allparams();
2802 List<Type> newparams = it.allparams();
2803 if (!types.containsTypeEquivalent(oldparams, newparams))
2804 log.error(pos, "cant.inherit.diff.arg",
2805 it.tsym, Type.toString(oldparams),
2806 Type.toString(newparams));
2808 checkClassBounds(pos, seensofar, it);
2810 Type st = types.supertype(type);
2811 if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2814 /** Enter interface into into set.
2815 * If it existed already, issue a "repeated interface" error.
2817 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2818 if (its.contains(it))
2819 log.error(pos, "repeated.interface");
2825 /* *************************************************************************
2827 **************************************************************************/
2830 * Recursively validate annotations values
2832 void validateAnnotationTree(JCTree tree) {
2833 class AnnotationValidator extends TreeScanner {
2835 public void visitAnnotation(JCAnnotation tree) {
2836 if (tree.type != null && !tree.type.isErroneous()) {
2837 super.visitAnnotation(tree);
2838 validateAnnotation(tree);
2842 tree.accept(new AnnotationValidator());
2847 * Annotation types are restricted to primitives, String, an
2848 * enum, an annotation, Class, Class<?>, Class<? extends
2849 * Anything>, arrays of the preceding.
2852 void validateAnnotationType(JCTree restype) {
2853 // restype may be null if an error occurred, so don't bother validating it
2854 if (restype != null) {
2855 validateAnnotationType(restype.pos(), restype.type);
2859 void validateAnnotationType(DiagnosticPosition pos, Type type) {
2860 if (type.isPrimitive()) return;
2861 if (types.isSameType(type, syms.stringType)) return;
2862 if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2863 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2864 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
2865 if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2866 validateAnnotationType(pos, types.elemtype(type));
2869 log.error(pos, "invalid.annotation.member.type");
2873 * "It is also a compile-time error if any method declared in an
2874 * annotation type has a signature that is override-equivalent to
2875 * that of any public or protected method declared in class Object
2876 * or in the interface annotation.Annotation."
2878 * @jls 9.6 Annotation Types
2880 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2881 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2882 Scope s = sup.tsym.members();
2883 for (Symbol sym : s.getSymbolsByName(m.name)) {
2884 if (sym.kind == MTH &&
2885 (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2886 types.overrideEquivalent(m.type, sym.type))
2887 log.error(pos, "intf.annotation.member.clash", sym, sup);
2892 /** Check the annotations of a symbol.
2894 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
2895 for (JCAnnotation a : annotations)
2896 validateAnnotation(a, s);
2899 /** Check the type annotations.
2901 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2902 for (JCAnnotation a : annotations)
2903 validateTypeAnnotation(a, isTypeParameter);
2906 /** Check an annotation of a symbol.
2908 private void validateAnnotation(JCAnnotation a, Symbol s) {
2909 validateAnnotationTree(a);
2911 if (a.type.tsym.isAnnotationType() && !annotationApplicable(a, s))
2912 log.error(a.pos(), "annotation.type.not.applicable");
2914 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
2915 if (s.kind != TYP) {
2916 log.error(a.pos(), "bad.functional.intf.anno");
2917 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
2918 log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s));
2923 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
2924 Assert.checkNonNull(a.type);
2925 validateAnnotationTree(a);
2927 if (a.hasTag(TYPE_ANNOTATION) &&
2928 !a.annotationType.type.isErroneous() &&
2929 !isTypeAnnotation(a, isTypeParameter)) {
2930 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
2935 * Validate the proposed container 'repeatable' on the
2936 * annotation type symbol 's'. Report errors at position
2939 * @param s The (annotation)type declaration annotated with a @Repeatable
2940 * @param repeatable the @Repeatable on 's'
2941 * @param pos where to report errors
2943 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
2944 Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
2947 List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
2949 Assert.check(l.head.fst.name == names.value);
2950 t = ((Attribute.Class)l.head.snd).getValue();
2954 // errors should already have been reported during Annotate
2958 validateValue(t.tsym, s, pos);
2959 validateRetention(t.tsym, s, pos);
2960 validateDocumented(t.tsym, s, pos);
2961 validateInherited(t.tsym, s, pos);
2962 validateTarget(t.tsym, s, pos);
2963 validateDefault(t.tsym, pos);
2966 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2967 Symbol sym = container.members().findFirst(names.value);
2968 if (sym != null && sym.kind == MTH) {
2969 MethodSymbol m = (MethodSymbol) sym;
2970 Type ret = m.getReturnType();
2971 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
2972 log.error(pos, "invalid.repeatable.annotation.value.return",
2973 container, ret, types.makeArrayType(contained.type));
2976 log.error(pos, "invalid.repeatable.annotation.no.value", container);
2980 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
2981 Attribute.RetentionPolicy containerRetention = types.getRetention(container);
2982 Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
2984 boolean error = false;
2985 switch (containedRetention) {
2987 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
2992 if (containerRetention == Attribute.RetentionPolicy.SOURCE) {
2997 log.error(pos, "invalid.repeatable.annotation.retention",
2998 container, containerRetention,
2999 contained, containedRetention);
3003 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3004 if (contained.attribute(syms.documentedType.tsym) != null) {
3005 if (container.attribute(syms.documentedType.tsym) == null) {
3006 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
3011 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3012 if (contained.attribute(syms.inheritedType.tsym) != null) {
3013 if (container.attribute(syms.inheritedType.tsym) == null) {
3014 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
3019 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3020 // The set of targets the container is applicable to must be a subset
3021 // (with respect to annotation target semantics) of the set of targets
3022 // the contained is applicable to. The target sets may be implicit or
3025 Set<Name> containerTargets;
3026 Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3027 if (containerTarget == null) {
3028 containerTargets = getDefaultTargetSet();
3030 containerTargets = new HashSet<>();
3031 for (Attribute app : containerTarget.values) {
3032 if (!(app instanceof Attribute.Enum)) {
3033 continue; // recovery
3035 Attribute.Enum e = (Attribute.Enum)app;
3036 containerTargets.add(e.value.name);
3040 Set<Name> containedTargets;
3041 Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3042 if (containedTarget == null) {
3043 containedTargets = getDefaultTargetSet();
3045 containedTargets = new HashSet<>();
3046 for (Attribute app : containedTarget.values) {
3047 if (!(app instanceof Attribute.Enum)) {
3048 continue; // recovery
3050 Attribute.Enum e = (Attribute.Enum)app;
3051 containedTargets.add(e.value.name);
3055 if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3056 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
3060 /* get a set of names for the default target */
3061 private Set<Name> getDefaultTargetSet() {
3062 if (defaultTargets == null) {
3063 Set<Name> targets = new HashSet<>();
3064 targets.add(names.ANNOTATION_TYPE);
3065 targets.add(names.CONSTRUCTOR);
3066 targets.add(names.FIELD);
3067 targets.add(names.LOCAL_VARIABLE);
3068 targets.add(names.METHOD);
3069 targets.add(names.PACKAGE);
3070 targets.add(names.PARAMETER);
3071 targets.add(names.TYPE);
3073 defaultTargets = java.util.Collections.unmodifiableSet(targets);
3076 return defaultTargets;
3078 private Set<Name> defaultTargets;
3081 /** Checks that s is a subset of t, with respect to ElementType
3082 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3083 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3086 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3087 // Check that all elements in s are present in t
3089 boolean currentElementOk = false;
3092 currentElementOk = true;
3094 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3095 currentElementOk = true;
3097 } else if (n1 == names.TYPE_USE &&
3098 (n2 == names.TYPE ||
3099 n2 == names.ANNOTATION_TYPE ||
3100 n2 == names.TYPE_PARAMETER)) {
3101 currentElementOk = true;
3105 if (!currentElementOk)
3111 private void validateDefault(Symbol container, DiagnosticPosition pos) {
3112 // validate that all other elements of containing type has defaults
3113 Scope scope = container.members();
3114 for(Symbol elm : scope.getSymbols()) {
3115 if (elm.name != names.value &&
3117 ((MethodSymbol)elm).defaultValue == null) {
3119 "invalid.repeatable.annotation.elem.nondefault",
3126 /** Is s a method symbol that overrides a method in a superclass? */
3127 boolean isOverrider(Symbol s) {
3128 if (s.kind != MTH || s.isStatic())
3130 MethodSymbol m = (MethodSymbol)s;
3131 TypeSymbol owner = (TypeSymbol)m.owner;
3132 for (Type sup : types.closure(owner.type)) {
3133 if (sup == owner.type)
3134 continue; // skip "this"
3135 Scope scope = sup.tsym.members();
3136 for (Symbol sym : scope.getSymbolsByName(m.name)) {
3137 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3144 /** Is the annotation applicable to types? */
3145 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3146 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3147 return (targets == null) ?
3150 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3153 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3154 Attribute.Enum e = (Attribute.Enum)a;
3155 return (e.value.name == names.TYPE_USE ||
3156 (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3159 /** Is the annotation applicable to the symbol? */
3160 boolean annotationApplicable(JCAnnotation a, Symbol s) {
3161 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3165 targets = defaultTargetMetaInfo(a, s);
3167 // TODO: can we optimize this?
3168 targets = new Name[arr.values.length];
3169 for (int i=0; i<arr.values.length; ++i) {
3170 Attribute app = arr.values[i];
3171 if (!(app instanceof Attribute.Enum)) {
3172 return true; // recovery
3174 Attribute.Enum e = (Attribute.Enum) app;
3175 targets[i] = e.value.name;
3178 for (Name target : targets) {
3179 if (target == names.TYPE) {
3182 } else if (target == names.FIELD) {
3183 if (s.kind == VAR && s.owner.kind != MTH)
3185 } else if (target == names.METHOD) {
3186 if (s.kind == MTH && !s.isConstructor())
3188 } else if (target == names.PARAMETER) {
3189 if (s.kind == VAR && s.owner.kind == MTH &&
3190 (s.flags() & PARAMETER) != 0) {
3193 } else if (target == names.CONSTRUCTOR) {
3194 if (s.kind == MTH && s.isConstructor())
3196 } else if (target == names.LOCAL_VARIABLE) {
3197 if (s.kind == VAR && s.owner.kind == MTH &&
3198 (s.flags() & PARAMETER) == 0) {
3201 } else if (target == names.ANNOTATION_TYPE) {
3202 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3205 } else if (target == names.PACKAGE) {
3208 } else if (target == names.TYPE_USE) {
3209 if (s.kind == TYP || s.kind == VAR ||
3210 (s.kind == MTH && !s.isConstructor() &&
3211 !s.type.getReturnType().hasTag(VOID)) ||
3212 (s.kind == MTH && s.isConstructor())) {
3215 } else if (target == names.TYPE_PARAMETER) {
3216 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3219 return true; // Unknown ElementType. This should be an error at declaration site,
3220 // assume applicable.
3226 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3227 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3228 if (atTarget == null) return null; // ok, is applicable
3229 Attribute atValue = atTarget.member(names.value);
3230 if (!(atValue instanceof Attribute.Array)) return null; // error recovery
3231 return (Attribute.Array) atValue;
3234 private final Name[] dfltTargetMeta;
3235 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
3236 return dfltTargetMeta;
3239 /** Check an annotation value.
3241 * @param a The annotation tree to check
3242 * @return true if this annotation tree is valid, otherwise false
3244 public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3245 boolean res = false;
3246 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3248 res = validateAnnotation(a);
3250 log.popDiagnosticHandler(diagHandler);
3255 private boolean validateAnnotation(JCAnnotation a) {
3256 boolean isValid = true;
3257 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3259 // collect an inventory of the annotation elements
3260 Set<MethodSymbol> elements = metadata.getAnnotationElements();
3262 // remove the ones that are assigned values
3263 for (JCTree arg : a.args) {
3264 if (!arg.hasTag(ASSIGN)) continue; // recovery
3265 JCAssign assign = (JCAssign)arg;
3266 Symbol m = TreeInfo.symbol(assign.lhs);
3267 if (m == null || m.type.isErroneous()) continue;
3268 if (!elements.remove(m)) {
3270 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
3275 // all the remaining ones better have default values
3276 List<Name> missingDefaults = List.nil();
3277 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3278 for (MethodSymbol m : elements) {
3279 if (m.type.isErroneous() || m.name == m.name.table.names.clinit)
3282 if (!membersWithDefault.contains(m))
3283 missingDefaults = missingDefaults.append(m.name);
3285 missingDefaults = missingDefaults.reverse();
3286 if (missingDefaults.nonEmpty()) {
3288 String key = (missingDefaults.size() > 1)
3289 ? "annotation.missing.default.value.1"
3290 : "annotation.missing.default.value";
3291 log.error(a.pos(), key, a.type, missingDefaults);
3294 return isValid && validateTargetAnnotationValue(a);
3297 /* Validate the special java.lang.annotation.Target annotation */
3298 boolean validateTargetAnnotationValue(JCAnnotation a) {
3299 // special case: java.lang.annotation.Target must not have
3300 // repeated values in its value member
3301 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3302 a.args.tail == null)
3305 boolean isValid = true;
3306 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3307 JCAssign assign = (JCAssign) a.args.head;
3308 Symbol m = TreeInfo.symbol(assign.lhs);
3309 if (m.name != names.value) return false;
3310 JCTree rhs = assign.rhs;
3311 if (!rhs.hasTag(NEWARRAY)) return false;
3312 JCNewArray na = (JCNewArray) rhs;
3313 Set<Symbol> targets = new HashSet<>();
3314 for (JCTree elem : na.elems) {
3315 if (!targets.add(TreeInfo.symbol(elem))) {
3317 log.error(elem.pos(), "repeated.annotation.target");
3323 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3324 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3325 (s.flags() & DEPRECATED) != 0 &&
3326 !syms.deprecatedType.isErroneous() &&
3327 s.attribute(syms.deprecatedType.tsym) == null) {
3328 log.warning(LintCategory.DEP_ANN,
3329 pos, "missing.deprecated.annotation");
3331 // Note: @Deprecated has no effect on local variables, parameters and package decls.
3332 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3333 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3334 log.warning(LintCategory.DEPRECATION, pos,
3335 "deprecated.annotation.has.no.effect", Kinds.kindName(s));
3340 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3341 if ( (s.isDeprecatedForRemoval()
3342 || s.isDeprecated() && !other.isDeprecated())
3343 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)) {
3344 deferredLintHandler.report(() -> warnDeprecated(pos, s));
3348 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3349 if ((s.flags() & PROPRIETARY) != 0) {
3350 deferredLintHandler.report(() -> {
3351 log.mandatoryWarning(pos, "sun.proprietary", s);
3356 void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3357 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3358 log.error(pos, "not.in.profile", s, profile);
3362 /* *************************************************************************
3363 * Check for recursive annotation elements.
3364 **************************************************************************/
3366 /** Check for cycles in the graph of annotation elements.
3368 void checkNonCyclicElements(JCClassDecl tree) {
3369 if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3370 Assert.check((tree.sym.flags_field & LOCKED) == 0);
3372 tree.sym.flags_field |= LOCKED;
3373 for (JCTree def : tree.defs) {
3374 if (!def.hasTag(METHODDEF)) continue;
3375 JCMethodDecl meth = (JCMethodDecl)def;
3376 if (meth.restype != null) {
3377 checkAnnotationResType(meth.pos(), meth.restype.type);
3381 tree.sym.flags_field &= ~LOCKED;
3382 tree.sym.flags_field |= ACYCLIC_ANN;
3386 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3387 if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3389 if ((tsym.flags_field & LOCKED) != 0) {
3390 log.error(pos, "cyclic.annotation.element");
3394 tsym.flags_field |= LOCKED;
3395 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3398 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3401 tsym.flags_field &= ~LOCKED;
3402 tsym.flags_field |= ACYCLIC_ANN;
3406 void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3407 switch (type.getTag()) {
3409 if ((type.tsym.flags() & ANNOTATION) != 0)
3410 checkNonCyclicElementsInternal(pos, type.tsym);
3413 checkAnnotationResType(pos, types.elemtype(type));
3420 /* *************************************************************************
3421 * Check for cycles in the constructor call graph.
3422 **************************************************************************/
3424 /** Check for cycles in the graph of constructors calling other
3427 void checkCyclicConstructors(JCClassDecl tree) {
3428 Map<Symbol,Symbol> callMap = new HashMap<>();
3430 // enter each constructor this-call into the map
3431 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3432 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3433 if (app == null) continue;
3434 JCMethodDecl meth = (JCMethodDecl) l.head;
3435 if (TreeInfo.name(app.meth) == names._this) {
3436 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3437 } else if (meth.sym != null) {
3438 meth.sym.flags_field |= ACYCLIC;
3442 // Check for cycles in the map
3443 Symbol[] ctors = new Symbol[0];
3444 ctors = callMap.keySet().toArray(ctors);
3445 for (Symbol caller : ctors) {
3446 checkCyclicConstructor(tree, caller, callMap);
3450 /** Look in the map to see if the given constructor is part of a
3453 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3454 Map<Symbol,Symbol> callMap) {
3455 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3456 if ((ctor.flags_field & LOCKED) != 0) {
3457 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3458 "recursive.ctor.invocation");
3460 ctor.flags_field |= LOCKED;
3461 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3462 ctor.flags_field &= ~LOCKED;
3464 ctor.flags_field |= ACYCLIC;
3468 /* *************************************************************************
3470 **************************************************************************/
3473 * Check for division by integer constant zero
3474 * @param pos Position for error reporting.
3475 * @param operator The operator for the expression
3476 * @param operand The right hand operand for the expression
3478 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3479 if (operand.constValue() != null
3480 && operand.getTag().isSubRangeOf(LONG)
3481 && ((Number) (operand.constValue())).longValue() == 0) {
3482 int opc = ((OperatorSymbol)operator).opcode;
3483 if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3484 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3485 deferredLintHandler.report(() -> warnDivZero(pos));
3491 * Check for empty statements after if
3493 void checkEmptyIf(JCIf tree) {
3494 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3495 lint.isEnabled(LintCategory.EMPTY))
3496 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
3499 /** Check that symbol is unique in given scope.
3500 * @param pos Position for error reporting.
3501 * @param sym The symbol.
3502 * @param s The scope.
3504 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3505 if (sym.type != null && sym.type.isErroneous())
3507 if (sym.owner.name == names.any) return false;
3508 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
3509 if (sym != byName &&
3510 (byName.flags() & CLASH) == 0 &&
3511 sym.kind == byName.kind &&
3512 sym.name != names.error &&
3514 types.hasSameArgs(sym.type, byName.type) ||
3515 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
3516 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
3517 varargsDuplicateError(pos, sym, byName);
3519 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
3520 duplicateErasureError(pos, sym, byName);
3521 sym.flags_field |= CLASH;
3524 duplicateError(pos, byName);
3532 /** Report duplicate declaration error.
3534 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3535 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3536 log.error(pos, "name.clash.same.erasure", sym1, sym2);
3540 /**Check that types imported through the ordinary imports don't clash with types imported
3541 * by other (static or ordinary) imports. Note that two static imports may import two clashing
3542 * types without an error on the imports.
3543 * @param toplevel The toplevel tree for which the test should be performed.
3545 void checkImportsUnique(JCCompilationUnit toplevel) {
3546 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
3547 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
3548 WriteableScope topLevelScope = toplevel.toplevelScope;
3550 for (JCTree def : toplevel.defs) {
3551 if (!def.hasTag(IMPORT))
3554 JCImport imp = (JCImport) def;
3556 if (imp.importScope == null)
3559 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
3560 if (imp.isStatic()) {
3561 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
3562 staticallyImportedSoFar.enter(sym);
3564 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
3565 ordinallyImportedSoFar.enter(sym);
3569 imp.importScope = null;
3573 /** Check that single-type import is not already imported or top-level defined,
3574 * but make an exception for two single-type imports which denote the same type.
3575 * @param pos Position for error reporting.
3576 * @param ordinallyImportedSoFar A Scope containing types imported so far through
3578 * @param staticallyImportedSoFar A Scope containing types imported so far through
3580 * @param topLevelScope The current file's top-level Scope
3581 * @param sym The symbol.
3582 * @param staticImport Whether or not this was a static import
3584 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
3585 Scope staticallyImportedSoFar, Scope topLevelScope,
3586 Symbol sym, boolean staticImport) {
3587 Filter<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
3588 Symbol clashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
3589 if (clashing == null && !staticImport) {
3590 clashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
3592 if (clashing != null) {
3594 log.error(pos, "already.defined.static.single.import", clashing);
3596 log.error(pos, "already.defined.single.import", clashing);
3599 clashing = topLevelScope.findFirst(sym.name, duplicates);
3600 if (clashing != null) {
3601 log.error(pos, "already.defined.this.unit", clashing);
3607 /** Check that a qualified name is in canonical form (for import decls).
3609 public void checkCanonical(JCTree tree) {
3610 if (!isCanonical(tree))
3611 log.error(tree.pos(), "import.requires.canonical",
3612 TreeInfo.symbol(tree));
3615 private boolean isCanonical(JCTree tree) {
3616 while (tree.hasTag(SELECT)) {
3617 JCFieldAccess s = (JCFieldAccess) tree;
3618 if (s.sym.owner.name != TreeInfo.symbol(s.selected).name)
3625 /** Check that an auxiliary class is not accessed from any other file than its own.
3627 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3628 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3629 (c.flags() & AUXILIARY) != 0 &&
3630 rs.isAccessible(env, c) &&
3631 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3633 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
3638 private class ConversionWarner extends Warner {
3639 final String uncheckedKey;
3641 final Type expected;
3642 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3644 this.uncheckedKey = uncheckedKey;
3646 this.expected = expected;
3650 public void warn(LintCategory lint) {
3651 boolean warned = this.warned;
3653 if (warned) return; // suppress redundant diagnostics
3656 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
3659 if (method != null &&
3660 method.attribute(syms.trustMeType.tsym) != null &&
3661 isTrustMeAllowedOnMethod(method) &&
3662 !types.isReifiable(method.type.getParameterTypes().last())) {
3663 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
3667 throw new AssertionError("Unexpected lint: " + lint);
3672 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3673 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3676 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3677 return new ConversionWarner(pos, "unchecked.assign", found, expected);
3680 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
3681 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
3683 if (functionalType != null) {
3685 types.findDescriptorSymbol((TypeSymbol)cs);
3686 } catch (Types.FunctionDescriptorLookupError ex) {
3687 DiagnosticPosition pos = tree.pos();
3688 for (JCAnnotation a : tree.getModifiers().annotations) {
3689 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3694 log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic());
3699 public void checkImportsResolvable(final JCCompilationUnit toplevel) {
3700 for (final JCImport imp : toplevel.getImports()) {
3701 if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
3703 final JCFieldAccess select = (JCFieldAccess) imp.qualid;
3704 final Symbol origin;
3705 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
3708 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
3709 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
3710 log.error(imp.pos(), "cant.resolve.location",
3712 select.name, List.<Type>nil(), List.<Type>nil(),
3713 Kinds.typeKindName(TreeInfo.symbol(select.selected).type),
3714 TreeInfo.symbol(select.selected).type);
3719 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
3720 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
3721 OUTER: for (JCImport imp : toplevel.getImports()) {
3722 if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk
3723 && ((JCFieldAccess)imp.qualid).selected.type != null) {
3724 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym;
3725 if (toplevel.modle.visiblePackages != null) {
3726 //TODO - unclear: selects like javax.* will get resolved from the current module
3727 //(as javax is not an exported package from any module). And as javax in the current
3728 //module typically does not contain any classes or subpackages, we need to go through
3729 //the visible packages to find a sub-package:
3730 for (PackageSymbol known : toplevel.modle.visiblePackages.values()) {
3731 if (Convert.packagePart(known.fullname) == tsym.flatName())
3735 if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) {
3736 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, "doesnt.exist", tsym);
3742 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
3743 if (tsym == null || !processed.add(tsym))
3746 // also search through inherited names
3747 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
3750 for (Type t : types.interfaces(tsym.type))
3751 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
3754 for (Symbol sym : tsym.members().getSymbolsByName(name)) {
3755 if (sym.isStatic() &&
3756 importAccessible(sym, packge) &&
3757 sym.isMemberOf(origin, types)) {
3765 // is the sym accessible everywhere in packge?
3766 public boolean importAccessible(Symbol sym, PackageSymbol packge) {
3768 int flags = (int)(sym.flags() & AccessFlags);
3777 return sym.packge() == packge;
3779 } catch (ClassFinder.BadClassFile err) {
3781 } catch (CompletionFailure ex) {
3786 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
3787 JCCompilationUnit toplevel = env.toplevel;
3789 if ( toplevel.modle == syms.unnamedModule
3790 || toplevel.modle == syms.noModule
3791 || (check.sym.flags() & COMPOUND) != 0) {
3795 ExportsDirective currentExport = findExport(toplevel.packge);
3797 if ( currentExport == null //not exported
3798 || currentExport.modules != null) //don't check classes in qualified export
3802 Lint lint = env.info.lint;
3803 boolean inSuperType;
3806 public void visitBlock(JCBlock tree) {
3809 public void visitMethodDef(JCMethodDecl tree) {
3810 if (!isAPISymbol(tree.sym))
3812 Lint prevLint = lint;
3814 lint = lint.augment(tree.sym);
3815 if (lint.isEnabled(LintCategory.EXPORTS)) {
3816 super.visitMethodDef(tree);
3823 public void visitVarDef(JCVariableDecl tree) {
3824 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
3826 Lint prevLint = lint;
3828 lint = lint.augment(tree.sym);
3829 if (lint.isEnabled(LintCategory.EXPORTS)) {
3838 public void visitClassDef(JCClassDecl tree) {
3842 if (!isAPISymbol(tree.sym))
3845 Lint prevLint = lint;
3847 lint = lint.augment(tree.sym);
3848 if (lint.isEnabled(LintCategory.EXPORTS)) {
3850 scan(tree.typarams);
3853 scan(tree.extending);
3854 scan(tree.implementing);
3856 inSuperType = false;
3865 public void visitTypeApply(JCTypeApply tree) {
3867 boolean oldInSuperType = inSuperType;
3869 inSuperType = false;
3870 scan(tree.arguments);
3872 inSuperType = oldInSuperType;
3876 public void visitIdent(JCIdent tree) {
3877 Symbol sym = TreeInfo.symbol(tree);
3878 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
3879 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
3884 public void visitSelect(JCFieldAccess tree) {
3885 Symbol sym = TreeInfo.symbol(tree);
3886 Symbol sitesym = TreeInfo.symbol(tree.selected);
3887 if (sym.kind == TYP && sitesym.kind == PCK) {
3888 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
3890 super.visitSelect(tree);
3895 public void visitAnnotation(JCAnnotation tree) {
3896 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
3897 super.visitAnnotation(tree);
3903 private ExportsDirective findExport(PackageSymbol pack) {
3904 for (ExportsDirective d : pack.modle.exports) {
3905 if (d.packge == pack)
3911 private boolean isAPISymbol(Symbol sym) {
3912 while (sym.kind != PCK) {
3913 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
3920 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
3921 if (!isAPISymbol(what) && !inSuperType) { //package private/private element
3922 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
3926 PackageSymbol whatPackage = what.packge();
3927 ExportsDirective whatExport = findExport(whatPackage);
3928 ExportsDirective inExport = findExport(inPackage);
3930 if (whatExport == null) { //package not exported:
3931 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
3935 if (whatExport.modules != null) {
3936 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
3937 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
3941 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
3942 //check that relativeTo.modle requires transitive what.modle, somehow:
3943 List<ModuleSymbol> todo = List.of(inPackage.modle);
3945 while (todo.nonEmpty()) {
3946 ModuleSymbol current = todo.head;
3948 if (current == whatPackage.modle)
3950 for (RequiresDirective req : current.requires) {
3951 if (req.isTransitive()) {
3952 todo = todo.prepend(req.module);
3957 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
3961 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
3962 if (msym.kind != MDL) {
3963 deferredLintHandler.report(() -> {
3964 if (lint.isEnabled(LintCategory.MODULE))
3965 log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym));
3970 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
3971 if (packge.members().isEmpty() &&
3972 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
3973 deferredLintHandler.report(() -> {
3974 if (lint.isEnabled(LintCategory.OPENS))
3975 log.warning(pos, Warnings.PackageEmptyOrNotFound(packge));
3980 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
3981 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
3982 deferredLintHandler.report(() -> {
3983 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) {
3984 log.warning(pos, Warnings.RequiresTransitiveAutomatic);
3985 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) {
3986 log.warning(pos, Warnings.RequiresAutomatic);