Check.java revision 4184:3b9297698293
1/* 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. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package com.sun.tools.javac.comp; 27 28import java.util.*; 29 30import javax.tools.JavaFileManager; 31 32import com.sun.tools.javac.code.*; 33import com.sun.tools.javac.code.Attribute.Compound; 34import com.sun.tools.javac.code.Directive.ExportsDirective; 35import com.sun.tools.javac.code.Directive.RequiresDirective; 36import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata; 37import com.sun.tools.javac.jvm.*; 38import com.sun.tools.javac.resources.CompilerProperties.Errors; 39import com.sun.tools.javac.resources.CompilerProperties.Fragments; 40import com.sun.tools.javac.resources.CompilerProperties.Warnings; 41import com.sun.tools.javac.tree.*; 42import com.sun.tools.javac.util.*; 43import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 44import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 45import com.sun.tools.javac.util.List; 46 47import com.sun.tools.javac.code.Lint; 48import com.sun.tools.javac.code.Lint.LintCategory; 49import com.sun.tools.javac.code.Scope.WriteableScope; 50import com.sun.tools.javac.code.Type.*; 51import com.sun.tools.javac.code.Symbol.*; 52import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext; 53import com.sun.tools.javac.comp.Infer.FreeTypeListener; 54import com.sun.tools.javac.tree.JCTree.*; 55 56import static com.sun.tools.javac.code.Flags.*; 57import static com.sun.tools.javac.code.Flags.ANNOTATION; 58import static com.sun.tools.javac.code.Flags.SYNCHRONIZED; 59import static com.sun.tools.javac.code.Kinds.*; 60import static com.sun.tools.javac.code.Kinds.Kind.*; 61import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 62import static com.sun.tools.javac.code.TypeTag.*; 63import static com.sun.tools.javac.code.TypeTag.WILDCARD; 64 65import static com.sun.tools.javac.tree.JCTree.Tag.*; 66 67/** Type checking helper class for the attribution phase. 68 * 69 * <p><b>This is NOT part of any supported API. 70 * If you write code that depends on this, you do so at your own risk. 71 * This code and its internal interfaces are subject to change or 72 * deletion without notice.</b> 73 */ 74public class Check { 75 protected static final Context.Key<Check> checkKey = new Context.Key<>(); 76 77 private final Names names; 78 private final Log log; 79 private final Resolve rs; 80 private final Symtab syms; 81 private final Enter enter; 82 private final DeferredAttr deferredAttr; 83 private final Infer infer; 84 private final Types types; 85 private final TypeAnnotations typeAnnotations; 86 private final JCDiagnostic.Factory diags; 87 private final JavaFileManager fileManager; 88 private final Source source; 89 private final Profile profile; 90 private final boolean warnOnAnyAccessToMembers; 91 92 // The set of lint options currently in effect. It is initialized 93 // from the context, and then is set/reset as needed by Attr as it 94 // visits all the various parts of the trees during attribution. 95 private Lint lint; 96 97 // The method being analyzed in Attr - it is set/reset as needed by 98 // Attr as it visits new method declarations. 99 private MethodSymbol method; 100 101 public static Check instance(Context context) { 102 Check instance = context.get(checkKey); 103 if (instance == null) 104 instance = new Check(context); 105 return instance; 106 } 107 108 protected Check(Context context) { 109 context.put(checkKey, this); 110 111 names = Names.instance(context); 112 dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE, 113 names.FIELD, names.METHOD, names.CONSTRUCTOR, 114 names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER}; 115 log = Log.instance(context); 116 rs = Resolve.instance(context); 117 syms = Symtab.instance(context); 118 enter = Enter.instance(context); 119 deferredAttr = DeferredAttr.instance(context); 120 infer = Infer.instance(context); 121 types = Types.instance(context); 122 typeAnnotations = TypeAnnotations.instance(context); 123 diags = JCDiagnostic.Factory.instance(context); 124 Options options = Options.instance(context); 125 lint = Lint.instance(context); 126 fileManager = context.get(JavaFileManager.class); 127 128 source = Source.instance(context); 129 allowSimplifiedVarargs = source.allowSimplifiedVarargs(); 130 allowDefaultMethods = source.allowDefaultMethods(); 131 allowStrictMethodClashCheck = source.allowStrictMethodClashCheck(); 132 allowPrivateSafeVarargs = source.allowPrivateSafeVarargs(); 133 allowDiamondWithAnonymousClassCreation = source.allowDiamondWithAnonymousClassCreation(); 134 warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers"); 135 136 Target target = Target.instance(context); 137 syntheticNameChar = target.syntheticNameChar(); 138 139 profile = Profile.instance(context); 140 141 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION); 142 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL); 143 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED); 144 boolean enforceMandatoryWarnings = true; 145 146 deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated, 147 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION); 148 removalHandler = new MandatoryWarningHandler(log, verboseRemoval, 149 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL); 150 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked, 151 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED); 152 sunApiHandler = new MandatoryWarningHandler(log, false, 153 enforceMandatoryWarnings, "sunapi", null); 154 155 deferredLintHandler = DeferredLintHandler.instance(context); 156 } 157 158 /** Switch: simplified varargs enabled? 159 */ 160 boolean allowSimplifiedVarargs; 161 162 /** Switch: default methods enabled? 163 */ 164 boolean allowDefaultMethods; 165 166 /** Switch: should unrelated return types trigger a method clash? 167 */ 168 boolean allowStrictMethodClashCheck; 169 170 /** Switch: can the @SafeVarargs annotation be applied to private methods? 171 */ 172 boolean allowPrivateSafeVarargs; 173 174 /** Switch: can diamond inference be used in anonymous instance creation ? 175 */ 176 boolean allowDiamondWithAnonymousClassCreation; 177 178 /** Character for synthetic names 179 */ 180 char syntheticNameChar; 181 182 /** A table mapping flat names of all compiled classes for each module in this run 183 * to their symbols; maintained from outside. 184 */ 185 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>(); 186 187 /** A handler for messages about deprecated usage. 188 */ 189 private MandatoryWarningHandler deprecationHandler; 190 191 /** A handler for messages about deprecated-for-removal usage. 192 */ 193 private MandatoryWarningHandler removalHandler; 194 195 /** A handler for messages about unchecked or unsafe usage. 196 */ 197 private MandatoryWarningHandler uncheckedHandler; 198 199 /** A handler for messages about using proprietary API. 200 */ 201 private MandatoryWarningHandler sunApiHandler; 202 203 /** A handler for deferred lint warnings. 204 */ 205 private DeferredLintHandler deferredLintHandler; 206 207/* ************************************************************************* 208 * Errors and Warnings 209 **************************************************************************/ 210 211 Lint setLint(Lint newLint) { 212 Lint prev = lint; 213 lint = newLint; 214 return prev; 215 } 216 217 MethodSymbol setMethod(MethodSymbol newMethod) { 218 MethodSymbol prev = method; 219 method = newMethod; 220 return prev; 221 } 222 223 /** Warn about deprecated symbol. 224 * @param pos Position to be used for error reporting. 225 * @param sym The deprecated symbol. 226 */ 227 void warnDeprecated(DiagnosticPosition pos, Symbol sym) { 228 if (sym.isDeprecatedForRemoval()) { 229 if (!lint.isSuppressed(LintCategory.REMOVAL)) { 230 if (sym.kind == MDL) { 231 removalHandler.report(pos, "has.been.deprecated.for.removal.module", sym); 232 } else { 233 removalHandler.report(pos, "has.been.deprecated.for.removal", sym, sym.location()); 234 } 235 } 236 } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) { 237 if (sym.kind == MDL) { 238 deprecationHandler.report(pos, "has.been.deprecated.module", sym); 239 } else { 240 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location()); 241 } 242 } 243 } 244 245 /** Warn about unchecked operation. 246 * @param pos Position to be used for error reporting. 247 * @param msg A string describing the problem. 248 */ 249 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) { 250 if (!lint.isSuppressed(LintCategory.UNCHECKED)) 251 uncheckedHandler.report(pos, msg, args); 252 } 253 254 /** Warn about unsafe vararg method decl. 255 * @param pos Position to be used for error reporting. 256 */ 257 void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) { 258 if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs) 259 log.warning(LintCategory.VARARGS, pos, key, args); 260 } 261 262 public void warnStatic(DiagnosticPosition pos, String msg, Object... args) { 263 if (lint.isEnabled(LintCategory.STATIC)) 264 log.warning(LintCategory.STATIC, pos, msg, args); 265 } 266 267 /** Warn about division by integer constant zero. 268 * @param pos Position to be used for error reporting. 269 */ 270 void warnDivZero(DiagnosticPosition pos) { 271 if (lint.isEnabled(LintCategory.DIVZERO)) 272 log.warning(LintCategory.DIVZERO, pos, "div.zero"); 273 } 274 275 /** 276 * Report any deferred diagnostics. 277 */ 278 public void reportDeferredDiagnostics() { 279 deprecationHandler.reportDeferredDiagnostic(); 280 removalHandler.reportDeferredDiagnostic(); 281 uncheckedHandler.reportDeferredDiagnostic(); 282 sunApiHandler.reportDeferredDiagnostic(); 283 } 284 285 286 /** Report a failure to complete a class. 287 * @param pos Position to be used for error reporting. 288 * @param ex The failure to report. 289 */ 290 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) { 291 log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue()); 292 if (ex instanceof ClassFinder.BadClassFile) throw new Abort(); 293 else return syms.errType; 294 } 295 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 299 * required. 300 * @param found The type that was found. 301 */ 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"); 307 return syms.errType; 308 } 309 log.error(pos, "type.found.req", found, required); 310 return types.createErrorType(found instanceof Type ? (Type)found : syms.errType); 311 } 312 313 /** Report an error that symbol cannot be referenced before super 314 * has been called. 315 * @param pos Position to be used for error reporting. 316 * @param sym The referenced symbol. 317 */ 318 void earlyRefError(DiagnosticPosition pos, Symbol sym) { 319 log.error(pos, "cant.ref.before.ctor.called", sym); 320 } 321 322 /** Report duplicate declaration error. 323 */ 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()); 332 } else { 333 log.error(pos, "already.defined", kindName(sym), sym, 334 kindName(sym.location()), sym.location()); 335 } 336 } 337 } 338 339 /** Report array/varargs duplicate declaration 340 */ 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()); 344 } 345 } 346 347/* ************************************************************************ 348 * duplicate declaration checking 349 *************************************************************************/ 350 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. 356 */ 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); 364 return; 365 } 366 } 367 } 368 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. 374 */ 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); 382 return; 383 } 384 } 385 } 386 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. 393 */ 394 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) { 395 for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) { 396 if (sym.kind == TYP && sym.name != names.error) { 397 duplicateError(pos, sym); 398 return false; 399 } 400 } 401 for (Symbol sym = s.owner; sym != null; sym = sym.owner) { 402 if (sym.kind == TYP && sym.name == name && sym.name != names.error) { 403 duplicateError(pos, sym); 404 return true; 405 } 406 } 407 return true; 408 } 409 410/* ************************************************************************* 411 * Class name generation 412 **************************************************************************/ 413 414 415 private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>(); 416 417 /** Return name of local class. 418 * This is of the form {@code <enclClass> $ n <classname> } 419 * where 420 * enclClass is the flat name of the enclosing class, 421 * classname is the simple name of the local class 422 */ 423 Name localClassName(ClassSymbol c) { 424 Name enclFlatname = c.owner.enclClass().flatname; 425 String enclFlatnameStr = enclFlatname.toString(); 426 Pair<Name, Name> key = new Pair<>(enclFlatname, c.name); 427 Integer index = localClassNameIndexes.get(key); 428 for (int i = (index == null) ? 1 : index; ; i++) { 429 Name flatname = names.fromString(enclFlatnameStr 430 + syntheticNameChar + i + c.name); 431 if (getCompiled(c.packge().modle, flatname) == null) { 432 localClassNameIndexes.put(key, i + 1); 433 return flatname; 434 } 435 } 436 } 437 438 void clearLocalClassNameIndexes(ClassSymbol c) { 439 if (c.owner != null && c.owner.kind != NIL) { 440 localClassNameIndexes.remove(new Pair<>( 441 c.owner.enclClass().flatname, c.name)); 442 } 443 } 444 445 public void newRound() { 446 compiled.clear(); 447 localClassNameIndexes.clear(); 448 } 449 450 public void putCompiled(ClassSymbol csym) { 451 compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym); 452 } 453 454 public ClassSymbol getCompiled(ClassSymbol csym) { 455 return compiled.get(Pair.of(csym.packge().modle, csym.flatname)); 456 } 457 458 public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) { 459 return compiled.get(Pair.of(msym, flatname)); 460 } 461 462 public void removeCompiled(ClassSymbol csym) { 463 compiled.remove(Pair.of(csym.packge().modle, csym.flatname)); 464 } 465 466/* ************************************************************************* 467 * Type Checking 468 **************************************************************************/ 469 470 /** 471 * A check context is an object that can be used to perform compatibility 472 * checks - depending on the check context, meaning of 'compatibility' might 473 * vary significantly. 474 */ 475 public interface CheckContext { 476 /** 477 * Is type 'found' compatible with type 'req' in given context 478 */ 479 boolean compatible(Type found, Type req, Warner warn); 480 /** 481 * Report a check error 482 */ 483 void report(DiagnosticPosition pos, JCDiagnostic details); 484 /** 485 * Obtain a warner for this check context 486 */ 487 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req); 488 489 public InferenceContext inferenceContext(); 490 491 public DeferredAttr.DeferredAttrContext deferredAttrContext(); 492 } 493 494 /** 495 * This class represent a check context that is nested within another check 496 * context - useful to check sub-expressions. The default behavior simply 497 * redirects all method calls to the enclosing check context leveraging 498 * the forwarding pattern. 499 */ 500 static class NestedCheckContext implements CheckContext { 501 CheckContext enclosingContext; 502 503 NestedCheckContext(CheckContext enclosingContext) { 504 this.enclosingContext = enclosingContext; 505 } 506 507 public boolean compatible(Type found, Type req, Warner warn) { 508 return enclosingContext.compatible(found, req, warn); 509 } 510 511 public void report(DiagnosticPosition pos, JCDiagnostic details) { 512 enclosingContext.report(pos, details); 513 } 514 515 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) { 516 return enclosingContext.checkWarner(pos, found, req); 517 } 518 519 public InferenceContext inferenceContext() { 520 return enclosingContext.inferenceContext(); 521 } 522 523 public DeferredAttrContext deferredAttrContext() { 524 return enclosingContext.deferredAttrContext(); 525 } 526 } 527 528 /** 529 * Check context to be used when evaluating assignment/return statements 530 */ 531 CheckContext basicHandler = new CheckContext() { 532 public void report(DiagnosticPosition pos, JCDiagnostic details) { 533 log.error(pos, "prob.found.req", details); 534 } 535 public boolean compatible(Type found, Type req, Warner warn) { 536 return types.isAssignable(found, req, warn); 537 } 538 539 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) { 540 return convertWarner(pos, found, req); 541 } 542 543 public InferenceContext inferenceContext() { 544 return infer.emptyContext; 545 } 546 547 public DeferredAttrContext deferredAttrContext() { 548 return deferredAttr.emptyDeferredAttrContext; 549 } 550 551 @Override 552 public String toString() { 553 return "CheckContext: basicHandler"; 554 } 555 }; 556 557 /** Check that a given type is assignable to a given proto-type. 558 * If it is, return the type, otherwise return errType. 559 * @param pos Position to be used for error reporting. 560 * @param found The type that was found. 561 * @param req The type that was required. 562 */ 563 public Type checkType(DiagnosticPosition pos, Type found, Type req) { 564 return checkType(pos, found, req, basicHandler); 565 } 566 567 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) { 568 final InferenceContext inferenceContext = checkContext.inferenceContext(); 569 if (inferenceContext.free(req) || inferenceContext.free(found)) { 570 inferenceContext.addFreeTypeListener(List.of(req, found), 571 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext)); 572 } 573 if (req.hasTag(ERROR)) 574 return req; 575 if (req.hasTag(NONE)) 576 return found; 577 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) { 578 return found; 579 } else { 580 if (found.isNumeric() && req.isNumeric()) { 581 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req)); 582 return types.createErrorType(found); 583 } 584 checkContext.report(pos, diags.fragment("inconvertible.types", found, req)); 585 return types.createErrorType(found); 586 } 587 } 588 589 /** Check that a given type can be cast to a given target type. 590 * Return the result of the cast. 591 * @param pos Position to be used for error reporting. 592 * @param found The type that is being cast. 593 * @param req The target type of the cast. 594 */ 595 Type checkCastable(DiagnosticPosition pos, Type found, Type req) { 596 return checkCastable(pos, found, req, basicHandler); 597 } 598 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) { 599 if (types.isCastable(found, req, castWarner(pos, found, req))) { 600 return req; 601 } else { 602 checkContext.report(pos, diags.fragment("inconvertible.types", found, req)); 603 return types.createErrorType(found); 604 } 605 } 606 607 /** Check for redundant casts (i.e. where source type is a subtype of target type) 608 * The problem should only be reported for non-292 cast 609 */ 610 public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) { 611 if (!tree.type.isErroneous() 612 && types.isSameType(tree.expr.type, tree.clazz.type) 613 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz)) 614 && !is292targetTypeCast(tree)) { 615 deferredLintHandler.report(() -> { 616 if (lint.isEnabled(LintCategory.CAST)) 617 log.warning(LintCategory.CAST, 618 tree.pos(), "redundant.cast", tree.clazz.type); 619 }); 620 } 621 } 622 //where 623 private boolean is292targetTypeCast(JCTypeCast tree) { 624 boolean is292targetTypeCast = false; 625 JCExpression expr = TreeInfo.skipParens(tree.expr); 626 if (expr.hasTag(APPLY)) { 627 JCMethodInvocation apply = (JCMethodInvocation)expr; 628 Symbol sym = TreeInfo.symbol(apply.meth); 629 is292targetTypeCast = sym != null && 630 sym.kind == MTH && 631 (sym.flags() & HYPOTHETICAL) != 0; 632 } 633 return is292targetTypeCast; 634 } 635 636 private static final boolean ignoreAnnotatedCasts = true; 637 638 /** Check that a type is within some bounds. 639 * 640 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid 641 * type argument. 642 * @param a The type that should be bounded by bs. 643 * @param bound The bound. 644 */ 645 private boolean checkExtends(Type a, Type bound) { 646 if (a.isUnbound()) { 647 return true; 648 } else if (!a.hasTag(WILDCARD)) { 649 a = types.cvarUpperBound(a); 650 return types.isSubtype(a, bound); 651 } else if (a.isExtendsBound()) { 652 return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings); 653 } else if (a.isSuperBound()) { 654 return !types.notSoftSubtype(types.wildLowerBound(a), bound); 655 } 656 return true; 657 } 658 659 /** Check that type is different from 'void'. 660 * @param pos Position to be used for error reporting. 661 * @param t The type to be checked. 662 */ 663 Type checkNonVoid(DiagnosticPosition pos, Type t) { 664 if (t.hasTag(VOID)) { 665 log.error(pos, "void.not.allowed.here"); 666 return types.createErrorType(t); 667 } else { 668 return t; 669 } 670 } 671 672 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) { 673 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) { 674 return typeTagError(pos, 675 diags.fragment("type.req.class.array"), 676 asTypeParam(t)); 677 } else { 678 return t; 679 } 680 } 681 682 /** Check that type is a class or interface type. 683 * @param pos Position to be used for error reporting. 684 * @param t The type to be checked. 685 */ 686 Type checkClassType(DiagnosticPosition pos, Type t) { 687 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) { 688 return typeTagError(pos, 689 diags.fragment("type.req.class"), 690 asTypeParam(t)); 691 } else { 692 return t; 693 } 694 } 695 //where 696 private Object asTypeParam(Type t) { 697 return (t.hasTag(TYPEVAR)) 698 ? diags.fragment("type.parameter", t) 699 : t; 700 } 701 702 /** Check that type is a valid qualifier for a constructor reference expression 703 */ 704 Type checkConstructorRefType(DiagnosticPosition pos, Type t) { 705 t = checkClassOrArrayType(pos, t); 706 if (t.hasTag(CLASS)) { 707 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 708 log.error(pos, "abstract.cant.be.instantiated", t.tsym); 709 t = types.createErrorType(t); 710 } else if ((t.tsym.flags() & ENUM) != 0) { 711 log.error(pos, "enum.cant.be.instantiated"); 712 t = types.createErrorType(t); 713 } else { 714 t = checkClassType(pos, t, true); 715 } 716 } else if (t.hasTag(ARRAY)) { 717 if (!types.isReifiable(((ArrayType)t).elemtype)) { 718 log.error(pos, "generic.array.creation"); 719 t = types.createErrorType(t); 720 } 721 } 722 return t; 723 } 724 725 /** Check that type is a class or interface type. 726 * @param pos Position to be used for error reporting. 727 * @param t The type to be checked. 728 * @param noBounds True if type bounds are illegal here. 729 */ 730 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) { 731 t = checkClassType(pos, t); 732 if (noBounds && t.isParameterized()) { 733 List<Type> args = t.getTypeArguments(); 734 while (args.nonEmpty()) { 735 if (args.head.hasTag(WILDCARD)) 736 return typeTagError(pos, 737 diags.fragment("type.req.exact"), 738 args.head); 739 args = args.tail; 740 } 741 } 742 return t; 743 } 744 745 /** Check that type is a reference type, i.e. a class, interface or array type 746 * or a type variable. 747 * @param pos Position to be used for error reporting. 748 * @param t The type to be checked. 749 */ 750 Type checkRefType(DiagnosticPosition pos, Type t) { 751 if (t.isReference()) 752 return t; 753 else 754 return typeTagError(pos, 755 diags.fragment("type.req.ref"), 756 t); 757 } 758 759 /** Check that each type is a reference type, i.e. a class, interface or array type 760 * or a type variable. 761 * @param trees Original trees, used for error reporting. 762 * @param types The types to be checked. 763 */ 764 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) { 765 List<JCExpression> tl = trees; 766 for (List<Type> l = types; l.nonEmpty(); l = l.tail) { 767 l.head = checkRefType(tl.head.pos(), l.head); 768 tl = tl.tail; 769 } 770 return types; 771 } 772 773 /** Check that type is a null or reference type. 774 * @param pos Position to be used for error reporting. 775 * @param t The type to be checked. 776 */ 777 Type checkNullOrRefType(DiagnosticPosition pos, Type t) { 778 if (t.isReference() || t.hasTag(BOT)) 779 return t; 780 else 781 return typeTagError(pos, 782 diags.fragment("type.req.ref"), 783 t); 784 } 785 786 /** Check that flag set does not contain elements of two conflicting sets. s 787 * Return true if it doesn't. 788 * @param pos Position to be used for error reporting. 789 * @param flags The set of flags to be checked. 790 * @param set1 Conflicting flags set #1. 791 * @param set2 Conflicting flags set #2. 792 */ 793 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) { 794 if ((flags & set1) != 0 && (flags & set2) != 0) { 795 log.error(pos, 796 "illegal.combination.of.modifiers", 797 asFlagSet(TreeInfo.firstFlag(flags & set1)), 798 asFlagSet(TreeInfo.firstFlag(flags & set2))); 799 return false; 800 } else 801 return true; 802 } 803 804 /** Check that usage of diamond operator is correct (i.e. diamond should not 805 * be used with non-generic classes or in anonymous class creation expressions) 806 */ 807 Type checkDiamond(JCNewClass tree, Type t) { 808 if (!TreeInfo.isDiamond(tree) || 809 t.isErroneous()) { 810 return checkClassType(tree.clazz.pos(), t, true); 811 } else { 812 if (tree.def != null && !allowDiamondWithAnonymousClassCreation) { 813 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(), 814 Errors.CantApplyDiamond1(t, Fragments.DiamondAndAnonClassNotSupportedInSource(source.name))); 815 } 816 if (t.tsym.type.getTypeArguments().isEmpty()) { 817 log.error(tree.clazz.pos(), 818 "cant.apply.diamond.1", 819 t, diags.fragment("diamond.non.generic", t)); 820 return types.createErrorType(t); 821 } else if (tree.typeargs != null && 822 tree.typeargs.nonEmpty()) { 823 log.error(tree.clazz.pos(), 824 "cant.apply.diamond.1", 825 t, diags.fragment("diamond.and.explicit.params", t)); 826 return types.createErrorType(t); 827 } else { 828 return t; 829 } 830 } 831 } 832 833 /** Check that the type inferred using the diamond operator does not contain 834 * non-denotable types such as captured types or intersection types. 835 * @param t the type inferred using the diamond operator 836 * @return the (possibly empty) list of non-denotable types. 837 */ 838 List<Type> checkDiamondDenotable(ClassType t) { 839 ListBuffer<Type> buf = new ListBuffer<>(); 840 for (Type arg : t.allparams()) { 841 if (!diamondTypeChecker.visit(arg, null)) { 842 buf.append(arg); 843 } 844 } 845 return buf.toList(); 846 } 847 // where 848 849 /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable 850 * types. The visit methods return false as soon as a non-denotable type is encountered and true 851 * otherwise. 852 */ 853 private static final Types.SimpleVisitor<Boolean, Void> diamondTypeChecker = new Types.SimpleVisitor<Boolean, Void>() { 854 @Override 855 public Boolean visitType(Type t, Void s) { 856 return true; 857 } 858 @Override 859 public Boolean visitClassType(ClassType t, Void s) { 860 if (t.isCompound()) { 861 return false; 862 } 863 for (Type targ : t.allparams()) { 864 if (!visit(targ, s)) { 865 return false; 866 } 867 } 868 return true; 869 } 870 871 @Override 872 public Boolean visitTypeVar(TypeVar t, Void s) { 873 /* Any type variable mentioned in the inferred type must have been declared as a type parameter 874 (i.e cannot have been produced by inference (18.4)) 875 */ 876 return t.tsym.owner.type.getTypeArguments().contains(t); 877 } 878 879 @Override 880 public Boolean visitCapturedType(CapturedType t, Void s) { 881 /* Any type variable mentioned in the inferred type must have been declared as a type parameter 882 (i.e cannot have been produced by capture conversion (5.1.10)) 883 */ 884 return false; 885 } 886 887 @Override 888 public Boolean visitArrayType(ArrayType t, Void s) { 889 return visit(t.elemtype, s); 890 } 891 892 @Override 893 public Boolean visitWildcardType(WildcardType t, Void s) { 894 return visit(t.type, s); 895 } 896 }; 897 898 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) { 899 MethodSymbol m = tree.sym; 900 if (!allowSimplifiedVarargs) return; 901 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null; 902 Type varargElemType = null; 903 if (m.isVarArgs()) { 904 varargElemType = types.elemtype(tree.params.last().type); 905 } 906 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) { 907 if (varargElemType != null) { 908 log.error(tree, 909 "varargs.invalid.trustme.anno", 910 syms.trustMeType.tsym, 911 allowPrivateSafeVarargs ? 912 diags.fragment("varargs.trustme.on.virtual.varargs", m) : 913 diags.fragment("varargs.trustme.on.virtual.varargs.final.only", m)); 914 } else { 915 log.error(tree, 916 "varargs.invalid.trustme.anno", 917 syms.trustMeType.tsym, 918 diags.fragment("varargs.trustme.on.non.varargs.meth", m)); 919 } 920 } else if (hasTrustMeAnno && varargElemType != null && 921 types.isReifiable(varargElemType)) { 922 warnUnsafeVararg(tree, 923 "varargs.redundant.trustme.anno", 924 syms.trustMeType.tsym, 925 diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType)); 926 } 927 else if (!hasTrustMeAnno && varargElemType != null && 928 !types.isReifiable(varargElemType)) { 929 warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType); 930 } 931 } 932 //where 933 private boolean isTrustMeAllowedOnMethod(Symbol s) { 934 return (s.flags() & VARARGS) != 0 && 935 (s.isConstructor() || 936 (s.flags() & (STATIC | FINAL | 937 (allowPrivateSafeVarargs ? PRIVATE : 0) )) != 0); 938 } 939 940 Type checkMethod(final Type mtype, 941 final Symbol sym, 942 final Env<AttrContext> env, 943 final List<JCExpression> argtrees, 944 final List<Type> argtypes, 945 final boolean useVarargs, 946 InferenceContext inferenceContext) { 947 // System.out.println("call : " + env.tree); 948 // System.out.println("method : " + owntype); 949 // System.out.println("actuals: " + argtypes); 950 if (inferenceContext.free(mtype)) { 951 inferenceContext.addFreeTypeListener(List.of(mtype), 952 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext)); 953 return mtype; 954 } 955 Type owntype = mtype; 956 List<Type> formals = owntype.getParameterTypes(); 957 List<Type> nonInferred = sym.type.getParameterTypes(); 958 if (nonInferred.length() != formals.length()) nonInferred = formals; 959 Type last = useVarargs ? formals.last() : null; 960 if (sym.name == names.init && sym.owner == syms.enumSym) { 961 formals = formals.tail.tail; 962 nonInferred = nonInferred.tail.tail; 963 } 964 List<JCExpression> args = argtrees; 965 if (args != null) { 966 //this is null when type-checking a method reference 967 while (formals.head != last) { 968 JCTree arg = args.head; 969 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head); 970 assertConvertible(arg, arg.type, formals.head, warn); 971 args = args.tail; 972 formals = formals.tail; 973 nonInferred = nonInferred.tail; 974 } 975 if (useVarargs) { 976 Type varArg = types.elemtype(last); 977 while (args.tail != null) { 978 JCTree arg = args.head; 979 Warner warn = convertWarner(arg.pos(), arg.type, varArg); 980 assertConvertible(arg, arg.type, varArg, warn); 981 args = args.tail; 982 } 983 } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) { 984 // non-varargs call to varargs method 985 Type varParam = owntype.getParameterTypes().last(); 986 Type lastArg = argtypes.last(); 987 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) && 988 !types.isSameType(types.erasure(varParam), types.erasure(lastArg))) 989 log.warning(argtrees.last().pos(), "inexact.non-varargs.call", 990 types.elemtype(varParam), varParam); 991 } 992 } 993 if (useVarargs) { 994 Type argtype = owntype.getParameterTypes().last(); 995 if (!types.isReifiable(argtype) && 996 (!allowSimplifiedVarargs || 997 sym.baseSymbol().attribute(syms.trustMeType.tsym) == null || 998 !isTrustMeAllowedOnMethod(sym))) { 999 warnUnchecked(env.tree.pos(), 1000 "unchecked.generic.array.creation", 1001 argtype); 1002 } 1003 if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) { 1004 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype)); 1005 } 1006 } 1007 return owntype; 1008 } 1009 //where 1010 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) { 1011 if (types.isConvertible(actual, formal, warn)) 1012 return; 1013 1014 if (formal.isCompound() 1015 && types.isSubtype(actual, types.supertype(formal)) 1016 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn)) 1017 return; 1018 } 1019 1020 /** 1021 * Check that type 't' is a valid instantiation of a generic class 1022 * (see JLS 4.5) 1023 * 1024 * @param t class type to be checked 1025 * @return true if 't' is well-formed 1026 */ 1027 public boolean checkValidGenericType(Type t) { 1028 return firstIncompatibleTypeArg(t) == null; 1029 } 1030 //WHERE 1031 private Type firstIncompatibleTypeArg(Type type) { 1032 List<Type> formals = type.tsym.type.allparams(); 1033 List<Type> actuals = type.allparams(); 1034 List<Type> args = type.getTypeArguments(); 1035 List<Type> forms = type.tsym.type.getTypeArguments(); 1036 ListBuffer<Type> bounds_buf = new ListBuffer<>(); 1037 1038 // For matching pairs of actual argument types `a' and 1039 // formal type parameters with declared bound `b' ... 1040 while (args.nonEmpty() && forms.nonEmpty()) { 1041 // exact type arguments needs to know their 1042 // bounds (for upper and lower bound 1043 // calculations). So we create new bounds where 1044 // type-parameters are replaced with actuals argument types. 1045 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals)); 1046 args = args.tail; 1047 forms = forms.tail; 1048 } 1049 1050 args = type.getTypeArguments(); 1051 List<Type> tvars_cap = types.substBounds(formals, 1052 formals, 1053 types.capture(type).allparams()); 1054 while (args.nonEmpty() && tvars_cap.nonEmpty()) { 1055 // Let the actual arguments know their bound 1056 args.head.withTypeVar((TypeVar)tvars_cap.head); 1057 args = args.tail; 1058 tvars_cap = tvars_cap.tail; 1059 } 1060 1061 args = type.getTypeArguments(); 1062 List<Type> bounds = bounds_buf.toList(); 1063 1064 while (args.nonEmpty() && bounds.nonEmpty()) { 1065 Type actual = args.head; 1066 if (!isTypeArgErroneous(actual) && 1067 !bounds.head.isErroneous() && 1068 !checkExtends(actual, bounds.head)) { 1069 return args.head; 1070 } 1071 args = args.tail; 1072 bounds = bounds.tail; 1073 } 1074 1075 args = type.getTypeArguments(); 1076 bounds = bounds_buf.toList(); 1077 1078 for (Type arg : types.capture(type).getTypeArguments()) { 1079 if (arg.hasTag(TYPEVAR) && 1080 arg.getUpperBound().isErroneous() && 1081 !bounds.head.isErroneous() && 1082 !isTypeArgErroneous(args.head)) { 1083 return args.head; 1084 } 1085 bounds = bounds.tail; 1086 args = args.tail; 1087 } 1088 1089 return null; 1090 } 1091 //where 1092 boolean isTypeArgErroneous(Type t) { 1093 return isTypeArgErroneous.visit(t); 1094 } 1095 1096 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() { 1097 public Boolean visitType(Type t, Void s) { 1098 return t.isErroneous(); 1099 } 1100 @Override 1101 public Boolean visitTypeVar(TypeVar t, Void s) { 1102 return visit(t.getUpperBound()); 1103 } 1104 @Override 1105 public Boolean visitCapturedType(CapturedType t, Void s) { 1106 return visit(t.getUpperBound()) || 1107 visit(t.getLowerBound()); 1108 } 1109 @Override 1110 public Boolean visitWildcardType(WildcardType t, Void s) { 1111 return visit(t.type); 1112 } 1113 }; 1114 1115 /** Check that given modifiers are legal for given symbol and 1116 * return modifiers together with any implicit modifiers for that symbol. 1117 * Warning: we can't use flags() here since this method 1118 * is called during class enter, when flags() would cause a premature 1119 * completion. 1120 * @param pos Position to be used for error reporting. 1121 * @param flags The set of modifiers given in a definition. 1122 * @param sym The defined symbol. 1123 */ 1124 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) { 1125 long mask; 1126 long implicit = 0; 1127 1128 switch (sym.kind) { 1129 case VAR: 1130 if (TreeInfo.isReceiverParam(tree)) 1131 mask = ReceiverParamFlags; 1132 else if (sym.owner.kind != TYP) 1133 mask = LocalVarFlags; 1134 else if ((sym.owner.flags_field & INTERFACE) != 0) 1135 mask = implicit = InterfaceVarFlags; 1136 else 1137 mask = VarFlags; 1138 break; 1139 case MTH: 1140 if (sym.name == names.init) { 1141 if ((sym.owner.flags_field & ENUM) != 0) { 1142 // enum constructors cannot be declared public or 1143 // protected and must be implicitly or explicitly 1144 // private 1145 implicit = PRIVATE; 1146 mask = PRIVATE; 1147 } else 1148 mask = ConstructorFlags; 1149 } else if ((sym.owner.flags_field & INTERFACE) != 0) { 1150 if ((sym.owner.flags_field & ANNOTATION) != 0) { 1151 mask = AnnotationTypeElementMask; 1152 implicit = PUBLIC | ABSTRACT; 1153 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) { 1154 mask = InterfaceMethodMask; 1155 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC; 1156 if ((flags & DEFAULT) != 0) { 1157 implicit |= ABSTRACT; 1158 } 1159 } else { 1160 mask = implicit = InterfaceMethodFlags; 1161 } 1162 } else { 1163 mask = MethodFlags; 1164 } 1165 // Imply STRICTFP if owner has STRICTFP set. 1166 if (((flags|implicit) & Flags.ABSTRACT) == 0 || 1167 ((flags) & Flags.DEFAULT) != 0) 1168 implicit |= sym.owner.flags_field & STRICTFP; 1169 break; 1170 case TYP: 1171 if (sym.isLocal()) { 1172 mask = LocalClassFlags; 1173 if ((sym.owner.flags_field & STATIC) == 0 && 1174 (flags & ENUM) != 0) 1175 log.error(pos, "enums.must.be.static"); 1176 } else if (sym.owner.kind == TYP) { 1177 mask = MemberClassFlags; 1178 if (sym.owner.owner.kind == PCK || 1179 (sym.owner.flags_field & STATIC) != 0) 1180 mask |= STATIC; 1181 else if ((flags & ENUM) != 0) 1182 log.error(pos, "enums.must.be.static"); 1183 // Nested interfaces and enums are always STATIC (Spec ???) 1184 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC; 1185 } else { 1186 mask = ClassFlags; 1187 } 1188 // Interfaces are always ABSTRACT 1189 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT; 1190 1191 if ((flags & ENUM) != 0) { 1192 // enums can't be declared abstract or final 1193 mask &= ~(ABSTRACT | FINAL); 1194 implicit |= implicitEnumFinalFlag(tree); 1195 } 1196 // Imply STRICTFP if owner has STRICTFP set. 1197 implicit |= sym.owner.flags_field & STRICTFP; 1198 break; 1199 default: 1200 throw new AssertionError(); 1201 } 1202 long illegal = flags & ExtendedStandardFlags & ~mask; 1203 if (illegal != 0) { 1204 if ((illegal & INTERFACE) != 0) { 1205 log.error(pos, "intf.not.allowed.here"); 1206 mask |= INTERFACE; 1207 } 1208 else { 1209 log.error(pos, 1210 "mod.not.allowed.here", asFlagSet(illegal)); 1211 } 1212 } 1213 else if ((sym.kind == TYP || 1214 // ISSUE: Disallowing abstract&private is no longer appropriate 1215 // in the presence of inner classes. Should it be deleted here? 1216 checkDisjoint(pos, flags, 1217 ABSTRACT, 1218 PRIVATE | STATIC | DEFAULT)) 1219 && 1220 checkDisjoint(pos, flags, 1221 STATIC | PRIVATE, 1222 DEFAULT) 1223 && 1224 checkDisjoint(pos, flags, 1225 ABSTRACT | INTERFACE, 1226 FINAL | NATIVE | SYNCHRONIZED) 1227 && 1228 checkDisjoint(pos, flags, 1229 PUBLIC, 1230 PRIVATE | PROTECTED) 1231 && 1232 checkDisjoint(pos, flags, 1233 PRIVATE, 1234 PUBLIC | PROTECTED) 1235 && 1236 checkDisjoint(pos, flags, 1237 FINAL, 1238 VOLATILE) 1239 && 1240 (sym.kind == TYP || 1241 checkDisjoint(pos, flags, 1242 ABSTRACT | NATIVE, 1243 STRICTFP))) { 1244 // skip 1245 } 1246 return flags & (mask | ~ExtendedStandardFlags) | implicit; 1247 } 1248 1249 1250 /** Determine if this enum should be implicitly final. 1251 * 1252 * If the enum has no specialized enum contants, it is final. 1253 * 1254 * If the enum does have specialized enum contants, it is 1255 * <i>not</i> final. 1256 */ 1257 private long implicitEnumFinalFlag(JCTree tree) { 1258 if (!tree.hasTag(CLASSDEF)) return 0; 1259 class SpecialTreeVisitor extends JCTree.Visitor { 1260 boolean specialized; 1261 SpecialTreeVisitor() { 1262 this.specialized = false; 1263 } 1264 1265 @Override 1266 public void visitTree(JCTree tree) { /* no-op */ } 1267 1268 @Override 1269 public void visitVarDef(JCVariableDecl tree) { 1270 if ((tree.mods.flags & ENUM) != 0) { 1271 if (tree.init instanceof JCNewClass && 1272 ((JCNewClass) tree.init).def != null) { 1273 specialized = true; 1274 } 1275 } 1276 } 1277 } 1278 1279 SpecialTreeVisitor sts = new SpecialTreeVisitor(); 1280 JCClassDecl cdef = (JCClassDecl) tree; 1281 for (JCTree defs: cdef.defs) { 1282 defs.accept(sts); 1283 if (sts.specialized) return 0; 1284 } 1285 return FINAL; 1286 } 1287 1288/* ************************************************************************* 1289 * Type Validation 1290 **************************************************************************/ 1291 1292 /** Validate a type expression. That is, 1293 * check that all type arguments of a parametric type are within 1294 * their bounds. This must be done in a second phase after type attribution 1295 * since a class might have a subclass as type parameter bound. E.g: 1296 * 1297 * <pre>{@code 1298 * class B<A extends C> { ... } 1299 * class C extends B<C> { ... } 1300 * }</pre> 1301 * 1302 * and we can't make sure that the bound is already attributed because 1303 * of possible cycles. 1304 * 1305 * Visitor method: Validate a type expression, if it is not null, catching 1306 * and reporting any completion failures. 1307 */ 1308 void validate(JCTree tree, Env<AttrContext> env) { 1309 validate(tree, env, true); 1310 } 1311 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) { 1312 new Validator(env).validateTree(tree, checkRaw, true); 1313 } 1314 1315 /** Visitor method: Validate a list of type expressions. 1316 */ 1317 void validate(List<? extends JCTree> trees, Env<AttrContext> env) { 1318 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 1319 validate(l.head, env); 1320 } 1321 1322 /** A visitor class for type validation. 1323 */ 1324 class Validator extends JCTree.Visitor { 1325 1326 boolean checkRaw; 1327 boolean isOuter; 1328 Env<AttrContext> env; 1329 1330 Validator(Env<AttrContext> env) { 1331 this.env = env; 1332 } 1333 1334 @Override 1335 public void visitTypeArray(JCArrayTypeTree tree) { 1336 validateTree(tree.elemtype, checkRaw, isOuter); 1337 } 1338 1339 @Override 1340 public void visitTypeApply(JCTypeApply tree) { 1341 if (tree.type.hasTag(CLASS)) { 1342 List<JCExpression> args = tree.arguments; 1343 List<Type> forms = tree.type.tsym.type.getTypeArguments(); 1344 1345 Type incompatibleArg = firstIncompatibleTypeArg(tree.type); 1346 if (incompatibleArg != null) { 1347 for (JCTree arg : tree.arguments) { 1348 if (arg.type == incompatibleArg) { 1349 log.error(arg, "not.within.bounds", incompatibleArg, forms.head); 1350 } 1351 forms = forms.tail; 1352 } 1353 } 1354 1355 forms = tree.type.tsym.type.getTypeArguments(); 1356 1357 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class; 1358 1359 // For matching pairs of actual argument types `a' and 1360 // formal type parameters with declared bound `b' ... 1361 while (args.nonEmpty() && forms.nonEmpty()) { 1362 validateTree(args.head, 1363 !(isOuter && is_java_lang_Class), 1364 false); 1365 args = args.tail; 1366 forms = forms.tail; 1367 } 1368 1369 // Check that this type is either fully parameterized, or 1370 // not parameterized at all. 1371 if (tree.type.getEnclosingType().isRaw()) 1372 log.error(tree.pos(), "improperly.formed.type.inner.raw.param"); 1373 if (tree.clazz.hasTag(SELECT)) 1374 visitSelectInternal((JCFieldAccess)tree.clazz); 1375 } 1376 } 1377 1378 @Override 1379 public void visitTypeParameter(JCTypeParameter tree) { 1380 validateTrees(tree.bounds, true, isOuter); 1381 checkClassBounds(tree.pos(), tree.type); 1382 } 1383 1384 @Override 1385 public void visitWildcard(JCWildcard tree) { 1386 if (tree.inner != null) 1387 validateTree(tree.inner, true, isOuter); 1388 } 1389 1390 @Override 1391 public void visitSelect(JCFieldAccess tree) { 1392 if (tree.type.hasTag(CLASS)) { 1393 visitSelectInternal(tree); 1394 1395 // Check that this type is either fully parameterized, or 1396 // not parameterized at all. 1397 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty()) 1398 log.error(tree.pos(), "improperly.formed.type.param.missing"); 1399 } 1400 } 1401 1402 public void visitSelectInternal(JCFieldAccess tree) { 1403 if (tree.type.tsym.isStatic() && 1404 tree.selected.type.isParameterized()) { 1405 // The enclosing type is not a class, so we are 1406 // looking at a static member type. However, the 1407 // qualifying expression is parameterized. 1408 log.error(tree.pos(), "cant.select.static.class.from.param.type"); 1409 } else { 1410 // otherwise validate the rest of the expression 1411 tree.selected.accept(this); 1412 } 1413 } 1414 1415 @Override 1416 public void visitAnnotatedType(JCAnnotatedType tree) { 1417 tree.underlyingType.accept(this); 1418 } 1419 1420 @Override 1421 public void visitTypeIdent(JCPrimitiveTypeTree that) { 1422 if (that.type.hasTag(TypeTag.VOID)) { 1423 log.error(that.pos(), "void.not.allowed.here"); 1424 } 1425 super.visitTypeIdent(that); 1426 } 1427 1428 /** Default visitor method: do nothing. 1429 */ 1430 @Override 1431 public void visitTree(JCTree tree) { 1432 } 1433 1434 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) { 1435 if (tree != null) { 1436 boolean prevCheckRaw = this.checkRaw; 1437 this.checkRaw = checkRaw; 1438 this.isOuter = isOuter; 1439 1440 try { 1441 tree.accept(this); 1442 if (checkRaw) 1443 checkRaw(tree, env); 1444 } catch (CompletionFailure ex) { 1445 completionError(tree.pos(), ex); 1446 } finally { 1447 this.checkRaw = prevCheckRaw; 1448 } 1449 } 1450 } 1451 1452 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) { 1453 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 1454 validateTree(l.head, checkRaw, isOuter); 1455 } 1456 } 1457 1458 void checkRaw(JCTree tree, Env<AttrContext> env) { 1459 if (lint.isEnabled(LintCategory.RAW) && 1460 tree.type.hasTag(CLASS) && 1461 !TreeInfo.isDiamond(tree) && 1462 !withinAnonConstr(env) && 1463 tree.type.isRaw()) { 1464 log.warning(LintCategory.RAW, 1465 tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type); 1466 } 1467 } 1468 //where 1469 private boolean withinAnonConstr(Env<AttrContext> env) { 1470 return env.enclClass.name.isEmpty() && 1471 env.enclMethod != null && env.enclMethod.name == names.init; 1472 } 1473 1474/* ************************************************************************* 1475 * Exception checking 1476 **************************************************************************/ 1477 1478 /* The following methods treat classes as sets that contain 1479 * the class itself and all their subclasses 1480 */ 1481 1482 /** Is given type a subtype of some of the types in given list? 1483 */ 1484 boolean subset(Type t, List<Type> ts) { 1485 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 1486 if (types.isSubtype(t, l.head)) return true; 1487 return false; 1488 } 1489 1490 /** Is given type a subtype or supertype of 1491 * some of the types in given list? 1492 */ 1493 boolean intersects(Type t, List<Type> ts) { 1494 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 1495 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true; 1496 return false; 1497 } 1498 1499 /** Add type set to given type list, unless it is a subclass of some class 1500 * in the list. 1501 */ 1502 List<Type> incl(Type t, List<Type> ts) { 1503 return subset(t, ts) ? ts : excl(t, ts).prepend(t); 1504 } 1505 1506 /** Remove type set from type set list. 1507 */ 1508 List<Type> excl(Type t, List<Type> ts) { 1509 if (ts.isEmpty()) { 1510 return ts; 1511 } else { 1512 List<Type> ts1 = excl(t, ts.tail); 1513 if (types.isSubtype(ts.head, t)) return ts1; 1514 else if (ts1 == ts.tail) return ts; 1515 else return ts1.prepend(ts.head); 1516 } 1517 } 1518 1519 /** Form the union of two type set lists. 1520 */ 1521 List<Type> union(List<Type> ts1, List<Type> ts2) { 1522 List<Type> ts = ts1; 1523 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1524 ts = incl(l.head, ts); 1525 return ts; 1526 } 1527 1528 /** Form the difference of two type lists. 1529 */ 1530 List<Type> diff(List<Type> ts1, List<Type> ts2) { 1531 List<Type> ts = ts1; 1532 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1533 ts = excl(l.head, ts); 1534 return ts; 1535 } 1536 1537 /** Form the intersection of two type lists. 1538 */ 1539 public List<Type> intersect(List<Type> ts1, List<Type> ts2) { 1540 List<Type> ts = List.nil(); 1541 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail) 1542 if (subset(l.head, ts2)) ts = incl(l.head, ts); 1543 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1544 if (subset(l.head, ts1)) ts = incl(l.head, ts); 1545 return ts; 1546 } 1547 1548 /** Is exc an exception symbol that need not be declared? 1549 */ 1550 boolean isUnchecked(ClassSymbol exc) { 1551 return 1552 exc.kind == ERR || 1553 exc.isSubClass(syms.errorType.tsym, types) || 1554 exc.isSubClass(syms.runtimeExceptionType.tsym, types); 1555 } 1556 1557 /** Is exc an exception type that need not be declared? 1558 */ 1559 boolean isUnchecked(Type exc) { 1560 return 1561 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) : 1562 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) : 1563 exc.hasTag(BOT); 1564 } 1565 1566 /** Same, but handling completion failures. 1567 */ 1568 boolean isUnchecked(DiagnosticPosition pos, Type exc) { 1569 try { 1570 return isUnchecked(exc); 1571 } catch (CompletionFailure ex) { 1572 completionError(pos, ex); 1573 return true; 1574 } 1575 } 1576 1577 /** Is exc handled by given exception list? 1578 */ 1579 boolean isHandled(Type exc, List<Type> handled) { 1580 return isUnchecked(exc) || subset(exc, handled); 1581 } 1582 1583 /** Return all exceptions in thrown list that are not in handled list. 1584 * @param thrown The list of thrown exceptions. 1585 * @param handled The list of handled exceptions. 1586 */ 1587 List<Type> unhandled(List<Type> thrown, List<Type> handled) { 1588 List<Type> unhandled = List.nil(); 1589 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1590 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head); 1591 return unhandled; 1592 } 1593 1594/* ************************************************************************* 1595 * Overriding/Implementation checking 1596 **************************************************************************/ 1597 1598 /** The level of access protection given by a flag set, 1599 * where PRIVATE is highest and PUBLIC is lowest. 1600 */ 1601 static int protection(long flags) { 1602 switch ((short)(flags & AccessFlags)) { 1603 case PRIVATE: return 3; 1604 case PROTECTED: return 1; 1605 default: 1606 case PUBLIC: return 0; 1607 case 0: return 2; 1608 } 1609 } 1610 1611 /** A customized "cannot override" error message. 1612 * @param m The overriding method. 1613 * @param other The overridden method. 1614 * @return An internationalized string. 1615 */ 1616 Object cannotOverride(MethodSymbol m, MethodSymbol other) { 1617 String key; 1618 if ((other.owner.flags() & INTERFACE) == 0) 1619 key = "cant.override"; 1620 else if ((m.owner.flags() & INTERFACE) == 0) 1621 key = "cant.implement"; 1622 else 1623 key = "clashes.with"; 1624 return diags.fragment(key, m, m.location(), other, other.location()); 1625 } 1626 1627 /** A customized "override" warning message. 1628 * @param m The overriding method. 1629 * @param other The overridden method. 1630 * @return An internationalized string. 1631 */ 1632 Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) { 1633 String key; 1634 if ((other.owner.flags() & INTERFACE) == 0) 1635 key = "unchecked.override"; 1636 else if ((m.owner.flags() & INTERFACE) == 0) 1637 key = "unchecked.implement"; 1638 else 1639 key = "unchecked.clash.with"; 1640 return diags.fragment(key, m, m.location(), other, other.location()); 1641 } 1642 1643 /** A customized "override" warning message. 1644 * @param m The overriding method. 1645 * @param other The overridden method. 1646 * @return An internationalized string. 1647 */ 1648 Object varargsOverrides(MethodSymbol m, MethodSymbol other) { 1649 String key; 1650 if ((other.owner.flags() & INTERFACE) == 0) 1651 key = "varargs.override"; 1652 else if ((m.owner.flags() & INTERFACE) == 0) 1653 key = "varargs.implement"; 1654 else 1655 key = "varargs.clash.with"; 1656 return diags.fragment(key, m, m.location(), other, other.location()); 1657 } 1658 1659 /** Check that this method conforms with overridden method 'other'. 1660 * where `origin' is the class where checking started. 1661 * Complications: 1662 * (1) Do not check overriding of synthetic methods 1663 * (reason: they might be final). 1664 * todo: check whether this is still necessary. 1665 * (2) Admit the case where an interface proxy throws fewer exceptions 1666 * than the method it implements. Augment the proxy methods with the 1667 * undeclared exceptions in this case. 1668 * (3) When generics are enabled, admit the case where an interface proxy 1669 * has a result type 1670 * extended by the result type of the method it implements. 1671 * Change the proxies result type to the smaller type in this case. 1672 * 1673 * @param tree The tree from which positions 1674 * are extracted for errors. 1675 * @param m The overriding method. 1676 * @param other The overridden method. 1677 * @param origin The class of which the overriding method 1678 * is a member. 1679 */ 1680 void checkOverride(JCTree tree, 1681 MethodSymbol m, 1682 MethodSymbol other, 1683 ClassSymbol origin) { 1684 // Don't check overriding of synthetic methods or by bridge methods. 1685 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) { 1686 return; 1687 } 1688 1689 // Error if static method overrides instance method (JLS 8.4.6.2). 1690 if ((m.flags() & STATIC) != 0 && 1691 (other.flags() & STATIC) == 0) { 1692 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static", 1693 cannotOverride(m, other)); 1694 m.flags_field |= BAD_OVERRIDE; 1695 return; 1696 } 1697 1698 // Error if instance method overrides static or final 1699 // method (JLS 8.4.6.1). 1700 if ((other.flags() & FINAL) != 0 || 1701 (m.flags() & STATIC) == 0 && 1702 (other.flags() & STATIC) != 0) { 1703 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth", 1704 cannotOverride(m, other), 1705 asFlagSet(other.flags() & (FINAL | STATIC))); 1706 m.flags_field |= BAD_OVERRIDE; 1707 return; 1708 } 1709 1710 if ((m.owner.flags() & ANNOTATION) != 0) { 1711 // handled in validateAnnotationMethod 1712 return; 1713 } 1714 1715 // Error if overriding method has weaker access (JLS 8.4.6.3). 1716 if (protection(m.flags()) > protection(other.flags())) { 1717 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access", 1718 cannotOverride(m, other), 1719 (other.flags() & AccessFlags) == 0 ? 1720 "package" : 1721 asFlagSet(other.flags() & AccessFlags)); 1722 m.flags_field |= BAD_OVERRIDE; 1723 return; 1724 } 1725 1726 Type mt = types.memberType(origin.type, m); 1727 Type ot = types.memberType(origin.type, other); 1728 // Error if overriding result type is different 1729 // (or, in the case of generics mode, not a subtype) of 1730 // overridden result type. We have to rename any type parameters 1731 // before comparing types. 1732 List<Type> mtvars = mt.getTypeArguments(); 1733 List<Type> otvars = ot.getTypeArguments(); 1734 Type mtres = mt.getReturnType(); 1735 Type otres = types.subst(ot.getReturnType(), otvars, mtvars); 1736 1737 overrideWarner.clear(); 1738 boolean resultTypesOK = 1739 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner); 1740 if (!resultTypesOK) { 1741 if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) { 1742 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1743 Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other, 1744 other.location()), mtres, otres)); 1745 m.flags_field |= BAD_OVERRIDE; 1746 } else { 1747 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1748 "override.incompatible.ret", 1749 cannotOverride(m, other), 1750 mtres, otres); 1751 m.flags_field |= BAD_OVERRIDE; 1752 } 1753 return; 1754 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 1755 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1756 "override.unchecked.ret", 1757 uncheckedOverrides(m, other), 1758 mtres, otres); 1759 } 1760 1761 // Error if overriding method throws an exception not reported 1762 // by overridden method. 1763 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars); 1764 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown)); 1765 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown); 1766 if (unhandledErased.nonEmpty()) { 1767 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1768 "override.meth.doesnt.throw", 1769 cannotOverride(m, other), 1770 unhandledUnerased.head); 1771 m.flags_field |= BAD_OVERRIDE; 1772 return; 1773 } 1774 else if (unhandledUnerased.nonEmpty()) { 1775 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1776 "override.unchecked.thrown", 1777 cannotOverride(m, other), 1778 unhandledUnerased.head); 1779 return; 1780 } 1781 1782 // Optional warning if varargs don't agree 1783 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0) 1784 && lint.isEnabled(LintCategory.OVERRIDES)) { 1785 log.warning(TreeInfo.diagnosticPositionFor(m, tree), 1786 ((m.flags() & Flags.VARARGS) != 0) 1787 ? "override.varargs.missing" 1788 : "override.varargs.extra", 1789 varargsOverrides(m, other)); 1790 } 1791 1792 // Warn if instance method overrides bridge method (compiler spec ??) 1793 if ((other.flags() & BRIDGE) != 0) { 1794 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge", 1795 uncheckedOverrides(m, other)); 1796 } 1797 1798 // Warn if a deprecated method overridden by a non-deprecated one. 1799 if (!isDeprecatedOverrideIgnorable(other, origin)) { 1800 Lint prevLint = setLint(lint.augment(m)); 1801 try { 1802 checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other); 1803 } finally { 1804 setLint(prevLint); 1805 } 1806 } 1807 } 1808 // where 1809 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) { 1810 // If the method, m, is defined in an interface, then ignore the issue if the method 1811 // is only inherited via a supertype and also implemented in the supertype, 1812 // because in that case, we will rediscover the issue when examining the method 1813 // in the supertype. 1814 // If the method, m, is not defined in an interface, then the only time we need to 1815 // address the issue is when the method is the supertype implemementation: any other 1816 // case, we will have dealt with when examining the supertype classes 1817 ClassSymbol mc = m.enclClass(); 1818 Type st = types.supertype(origin.type); 1819 if (!st.hasTag(CLASS)) 1820 return true; 1821 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false); 1822 1823 if (mc != null && ((mc.flags() & INTERFACE) != 0)) { 1824 List<Type> intfs = types.interfaces(origin.type); 1825 return (intfs.contains(mc.type) ? false : (stimpl != null)); 1826 } 1827 else 1828 return (stimpl != m); 1829 } 1830 1831 1832 // used to check if there were any unchecked conversions 1833 Warner overrideWarner = new Warner(); 1834 1835 /** Check that a class does not inherit two concrete methods 1836 * with the same signature. 1837 * @param pos Position to be used for error reporting. 1838 * @param site The class type to be checked. 1839 */ 1840 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) { 1841 Type sup = types.supertype(site); 1842 if (!sup.hasTag(CLASS)) return; 1843 1844 for (Type t1 = sup; 1845 t1.hasTag(CLASS) && t1.tsym.type.isParameterized(); 1846 t1 = types.supertype(t1)) { 1847 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 1848 if (s1.kind != MTH || 1849 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1850 !s1.isInheritedIn(site.tsym, types) || 1851 ((MethodSymbol)s1).implementation(site.tsym, 1852 types, 1853 true) != s1) 1854 continue; 1855 Type st1 = types.memberType(t1, s1); 1856 int s1ArgsLength = st1.getParameterTypes().length(); 1857 if (st1 == s1.type) continue; 1858 1859 for (Type t2 = sup; 1860 t2.hasTag(CLASS); 1861 t2 = types.supertype(t2)) { 1862 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 1863 if (s2 == s1 || 1864 s2.kind != MTH || 1865 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1866 s2.type.getParameterTypes().length() != s1ArgsLength || 1867 !s2.isInheritedIn(site.tsym, types) || 1868 ((MethodSymbol)s2).implementation(site.tsym, 1869 types, 1870 true) != s2) 1871 continue; 1872 Type st2 = types.memberType(t2, s2); 1873 if (types.overrideEquivalent(st1, st2)) 1874 log.error(pos, "concrete.inheritance.conflict", 1875 s1, t1, s2, t2, sup); 1876 } 1877 } 1878 } 1879 } 1880 } 1881 1882 /** Check that classes (or interfaces) do not each define an abstract 1883 * method with same name and arguments but incompatible return types. 1884 * @param pos Position to be used for error reporting. 1885 * @param t1 The first argument type. 1886 * @param t2 The second argument type. 1887 */ 1888 public boolean checkCompatibleAbstracts(DiagnosticPosition pos, 1889 Type t1, 1890 Type t2, 1891 Type site) { 1892 if ((site.tsym.flags() & COMPOUND) != 0) { 1893 // special case for intersections: need to eliminate wildcards in supertypes 1894 t1 = types.capture(t1); 1895 t2 = types.capture(t2); 1896 } 1897 return firstIncompatibility(pos, t1, t2, site) == null; 1898 } 1899 1900 /** Return the first method which is defined with same args 1901 * but different return types in two given interfaces, or null if none 1902 * exists. 1903 * @param t1 The first type. 1904 * @param t2 The second type. 1905 * @param site The most derived type. 1906 * @returns symbol from t2 that conflicts with one in t1. 1907 */ 1908 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 1909 Map<TypeSymbol,Type> interfaces1 = new HashMap<>(); 1910 closure(t1, interfaces1); 1911 Map<TypeSymbol,Type> interfaces2; 1912 if (t1 == t2) 1913 interfaces2 = interfaces1; 1914 else 1915 closure(t2, interfaces1, interfaces2 = new HashMap<>()); 1916 1917 for (Type t3 : interfaces1.values()) { 1918 for (Type t4 : interfaces2.values()) { 1919 Symbol s = firstDirectIncompatibility(pos, t3, t4, site); 1920 if (s != null) return s; 1921 } 1922 } 1923 return null; 1924 } 1925 1926 /** Compute all the supertypes of t, indexed by type symbol. */ 1927 private void closure(Type t, Map<TypeSymbol,Type> typeMap) { 1928 if (!t.hasTag(CLASS)) return; 1929 if (typeMap.put(t.tsym, t) == null) { 1930 closure(types.supertype(t), typeMap); 1931 for (Type i : types.interfaces(t)) 1932 closure(i, typeMap); 1933 } 1934 } 1935 1936 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */ 1937 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) { 1938 if (!t.hasTag(CLASS)) return; 1939 if (typesSkip.get(t.tsym) != null) return; 1940 if (typeMap.put(t.tsym, t) == null) { 1941 closure(types.supertype(t), typesSkip, typeMap); 1942 for (Type i : types.interfaces(t)) 1943 closure(i, typesSkip, typeMap); 1944 } 1945 } 1946 1947 /** Return the first method in t2 that conflicts with a method from t1. */ 1948 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 1949 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 1950 Type st1 = null; 1951 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) || 1952 (s1.flags() & SYNTHETIC) != 0) continue; 1953 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false); 1954 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue; 1955 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 1956 if (s1 == s2) continue; 1957 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) || 1958 (s2.flags() & SYNTHETIC) != 0) continue; 1959 if (st1 == null) st1 = types.memberType(t1, s1); 1960 Type st2 = types.memberType(t2, s2); 1961 if (types.overrideEquivalent(st1, st2)) { 1962 List<Type> tvars1 = st1.getTypeArguments(); 1963 List<Type> tvars2 = st2.getTypeArguments(); 1964 Type rt1 = st1.getReturnType(); 1965 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1); 1966 boolean compat = 1967 types.isSameType(rt1, rt2) || 1968 !rt1.isPrimitiveOrVoid() && 1969 !rt2.isPrimitiveOrVoid() && 1970 (types.covariantReturnType(rt1, rt2, types.noWarnings) || 1971 types.covariantReturnType(rt2, rt1, types.noWarnings)) || 1972 checkCommonOverriderIn(s1,s2,site); 1973 if (!compat) { 1974 log.error(pos, "types.incompatible.diff.ret", 1975 t1, t2, s2.name + 1976 "(" + types.memberType(t2, s2).getParameterTypes() + ")"); 1977 return s2; 1978 } 1979 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) && 1980 !checkCommonOverriderIn(s1, s2, site)) { 1981 log.error(pos, Errors.NameClashSameErasureNoOverride( 1982 s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(), 1983 s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location())); 1984 return s2; 1985 } 1986 } 1987 } 1988 return null; 1989 } 1990 //WHERE 1991 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) { 1992 Map<TypeSymbol,Type> supertypes = new HashMap<>(); 1993 Type st1 = types.memberType(site, s1); 1994 Type st2 = types.memberType(site, s2); 1995 closure(site, supertypes); 1996 for (Type t : supertypes.values()) { 1997 for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) { 1998 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue; 1999 Type st3 = types.memberType(site,s3); 2000 if (types.overrideEquivalent(st3, st1) && 2001 types.overrideEquivalent(st3, st2) && 2002 types.returnTypeSubstitutable(st3, st1) && 2003 types.returnTypeSubstitutable(st3, st2)) { 2004 return true; 2005 } 2006 } 2007 } 2008 return false; 2009 } 2010 2011 /** Check that a given method conforms with any method it overrides. 2012 * @param tree The tree from which positions are extracted 2013 * for errors. 2014 * @param m The overriding method. 2015 */ 2016 void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) { 2017 ClassSymbol origin = (ClassSymbol)m.owner; 2018 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) 2019 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) { 2020 log.error(tree.pos(), "enum.no.finalize"); 2021 return; 2022 } 2023 for (Type t = origin.type; t.hasTag(CLASS); 2024 t = types.supertype(t)) { 2025 if (t != origin.type) { 2026 checkOverride(tree, t, origin, m); 2027 } 2028 for (Type t2 : types.interfaces(t)) { 2029 checkOverride(tree, t2, origin, m); 2030 } 2031 } 2032 2033 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null; 2034 // Check if this method must override a super method due to being annotated with @Override 2035 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to 2036 // be treated "as if as they were annotated" with @Override. 2037 boolean mustOverride = explicitOverride || 2038 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate()); 2039 if (mustOverride && !isOverrider(m)) { 2040 DiagnosticPosition pos = tree.pos(); 2041 for (JCAnnotation a : tree.getModifiers().annotations) { 2042 if (a.annotationType.type.tsym == syms.overrideType.tsym) { 2043 pos = a.pos(); 2044 break; 2045 } 2046 } 2047 log.error(pos, 2048 explicitOverride ? Errors.MethodDoesNotOverrideSuperclass : 2049 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride)); 2050 } 2051 } 2052 2053 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) { 2054 TypeSymbol c = site.tsym; 2055 for (Symbol sym : c.members().getSymbolsByName(m.name)) { 2056 if (m.overrides(sym, origin, types, false)) { 2057 if ((sym.flags() & ABSTRACT) == 0) { 2058 checkOverride(tree, m, (MethodSymbol)sym, origin); 2059 } 2060 } 2061 } 2062 } 2063 2064 private Filter<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.accepts(s) && 2065 (s.flags() & BAD_OVERRIDE) == 0; 2066 2067 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos, 2068 ClassSymbol someClass) { 2069 /* At present, annotations cannot possibly have a method that is override 2070 * equivalent with Object.equals(Object) but in any case the condition is 2071 * fine for completeness. 2072 */ 2073 if (someClass == (ClassSymbol)syms.objectType.tsym || 2074 someClass.isInterface() || someClass.isEnum() || 2075 (someClass.flags() & ANNOTATION) != 0 || 2076 (someClass.flags() & ABSTRACT) != 0) return; 2077 //anonymous inner classes implementing interfaces need especial treatment 2078 if (someClass.isAnonymous()) { 2079 List<Type> interfaces = types.interfaces(someClass.type); 2080 if (interfaces != null && !interfaces.isEmpty() && 2081 interfaces.head.tsym == syms.comparatorType.tsym) return; 2082 } 2083 checkClassOverrideEqualsAndHash(pos, someClass); 2084 } 2085 2086 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos, 2087 ClassSymbol someClass) { 2088 if (lint.isEnabled(LintCategory.OVERRIDES)) { 2089 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType 2090 .tsym.members().findFirst(names.equals); 2091 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType 2092 .tsym.members().findFirst(names.hashCode); 2093 boolean overridesEquals = types.implementation(equalsAtObject, 2094 someClass, false, equalsHasCodeFilter).owner == someClass; 2095 boolean overridesHashCode = types.implementation(hashCodeAtObject, 2096 someClass, false, equalsHasCodeFilter) != hashCodeAtObject; 2097 2098 if (overridesEquals && !overridesHashCode) { 2099 log.warning(LintCategory.OVERRIDES, pos, 2100 "override.equals.but.not.hashcode", someClass); 2101 } 2102 } 2103 } 2104 2105 public void checkModuleName (JCModuleDecl tree) { 2106 Name moduleName = tree.sym.name; 2107 Assert.checkNonNull(moduleName); 2108 if (lint.isEnabled(LintCategory.MODULE)) { 2109 JCExpression qualId = tree.qualId; 2110 while (qualId != null) { 2111 Name componentName; 2112 DiagnosticPosition pos; 2113 switch (qualId.getTag()) { 2114 case SELECT: 2115 JCFieldAccess selectNode = ((JCFieldAccess) qualId); 2116 componentName = selectNode.name; 2117 pos = selectNode.pos(); 2118 qualId = selectNode.selected; 2119 break; 2120 case IDENT: 2121 componentName = ((JCIdent) qualId).name; 2122 pos = qualId.pos(); 2123 qualId = null; 2124 break; 2125 default: 2126 throw new AssertionError("Unexpected qualified identifier: " + qualId.toString()); 2127 } 2128 if (componentName != null) { 2129 String moduleNameComponentString = componentName.toString(); 2130 int nameLength = moduleNameComponentString.length(); 2131 if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) { 2132 log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName)); 2133 } 2134 } 2135 } 2136 } 2137 } 2138 2139 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) { 2140 ClashFilter cf = new ClashFilter(origin.type); 2141 return (cf.accepts(s1) && 2142 cf.accepts(s2) && 2143 types.hasSameArgs(s1.erasure(types), s2.erasure(types))); 2144 } 2145 2146 2147 /** Check that all abstract members of given class have definitions. 2148 * @param pos Position to be used for error reporting. 2149 * @param c The class. 2150 */ 2151 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) { 2152 MethodSymbol undef = types.firstUnimplementedAbstract(c); 2153 if (undef != null) { 2154 MethodSymbol undef1 = 2155 new MethodSymbol(undef.flags(), undef.name, 2156 types.memberType(c.type, undef), undef.owner); 2157 log.error(pos, "does.not.override.abstract", 2158 c, undef1, undef1.location()); 2159 } 2160 } 2161 2162 void checkNonCyclicDecl(JCClassDecl tree) { 2163 CycleChecker cc = new CycleChecker(); 2164 cc.scan(tree); 2165 if (!cc.errorFound && !cc.partialCheck) { 2166 tree.sym.flags_field |= ACYCLIC; 2167 } 2168 } 2169 2170 class CycleChecker extends TreeScanner { 2171 2172 List<Symbol> seenClasses = List.nil(); 2173 boolean errorFound = false; 2174 boolean partialCheck = false; 2175 2176 private void checkSymbol(DiagnosticPosition pos, Symbol sym) { 2177 if (sym != null && sym.kind == TYP) { 2178 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym); 2179 if (classEnv != null) { 2180 DiagnosticSource prevSource = log.currentSource(); 2181 try { 2182 log.useSource(classEnv.toplevel.sourcefile); 2183 scan(classEnv.tree); 2184 } 2185 finally { 2186 log.useSource(prevSource.getFile()); 2187 } 2188 } else if (sym.kind == TYP) { 2189 checkClass(pos, sym, List.nil()); 2190 } 2191 } else { 2192 //not completed yet 2193 partialCheck = true; 2194 } 2195 } 2196 2197 @Override 2198 public void visitSelect(JCFieldAccess tree) { 2199 super.visitSelect(tree); 2200 checkSymbol(tree.pos(), tree.sym); 2201 } 2202 2203 @Override 2204 public void visitIdent(JCIdent tree) { 2205 checkSymbol(tree.pos(), tree.sym); 2206 } 2207 2208 @Override 2209 public void visitTypeApply(JCTypeApply tree) { 2210 scan(tree.clazz); 2211 } 2212 2213 @Override 2214 public void visitTypeArray(JCArrayTypeTree tree) { 2215 scan(tree.elemtype); 2216 } 2217 2218 @Override 2219 public void visitClassDef(JCClassDecl tree) { 2220 List<JCTree> supertypes = List.nil(); 2221 if (tree.getExtendsClause() != null) { 2222 supertypes = supertypes.prepend(tree.getExtendsClause()); 2223 } 2224 if (tree.getImplementsClause() != null) { 2225 for (JCTree intf : tree.getImplementsClause()) { 2226 supertypes = supertypes.prepend(intf); 2227 } 2228 } 2229 checkClass(tree.pos(), tree.sym, supertypes); 2230 } 2231 2232 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) { 2233 if ((c.flags_field & ACYCLIC) != 0) 2234 return; 2235 if (seenClasses.contains(c)) { 2236 errorFound = true; 2237 noteCyclic(pos, (ClassSymbol)c); 2238 } else if (!c.type.isErroneous()) { 2239 try { 2240 seenClasses = seenClasses.prepend(c); 2241 if (c.type.hasTag(CLASS)) { 2242 if (supertypes.nonEmpty()) { 2243 scan(supertypes); 2244 } 2245 else { 2246 ClassType ct = (ClassType)c.type; 2247 if (ct.supertype_field == null || 2248 ct.interfaces_field == null) { 2249 //not completed yet 2250 partialCheck = true; 2251 return; 2252 } 2253 checkSymbol(pos, ct.supertype_field.tsym); 2254 for (Type intf : ct.interfaces_field) { 2255 checkSymbol(pos, intf.tsym); 2256 } 2257 } 2258 if (c.owner.kind == TYP) { 2259 checkSymbol(pos, c.owner); 2260 } 2261 } 2262 } finally { 2263 seenClasses = seenClasses.tail; 2264 } 2265 } 2266 } 2267 } 2268 2269 /** Check for cyclic references. Issue an error if the 2270 * symbol of the type referred to has a LOCKED flag set. 2271 * 2272 * @param pos Position to be used for error reporting. 2273 * @param t The type referred to. 2274 */ 2275 void checkNonCyclic(DiagnosticPosition pos, Type t) { 2276 checkNonCyclicInternal(pos, t); 2277 } 2278 2279 2280 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) { 2281 checkNonCyclic1(pos, t, List.nil()); 2282 } 2283 2284 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) { 2285 final TypeVar tv; 2286 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0) 2287 return; 2288 if (seen.contains(t)) { 2289 tv = (TypeVar)t; 2290 tv.bound = types.createErrorType(t); 2291 log.error(pos, "cyclic.inheritance", t); 2292 } else if (t.hasTag(TYPEVAR)) { 2293 tv = (TypeVar)t; 2294 seen = seen.prepend(tv); 2295 for (Type b : types.getBounds(tv)) 2296 checkNonCyclic1(pos, b, seen); 2297 } 2298 } 2299 2300 /** Check for cyclic references. Issue an error if the 2301 * symbol of the type referred to has a LOCKED flag set. 2302 * 2303 * @param pos Position to be used for error reporting. 2304 * @param t The type referred to. 2305 * @returns True if the check completed on all attributed classes 2306 */ 2307 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) { 2308 boolean complete = true; // was the check complete? 2309 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG 2310 Symbol c = t.tsym; 2311 if ((c.flags_field & ACYCLIC) != 0) return true; 2312 2313 if ((c.flags_field & LOCKED) != 0) { 2314 noteCyclic(pos, (ClassSymbol)c); 2315 } else if (!c.type.isErroneous()) { 2316 try { 2317 c.flags_field |= LOCKED; 2318 if (c.type.hasTag(CLASS)) { 2319 ClassType clazz = (ClassType)c.type; 2320 if (clazz.interfaces_field != null) 2321 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail) 2322 complete &= checkNonCyclicInternal(pos, l.head); 2323 if (clazz.supertype_field != null) { 2324 Type st = clazz.supertype_field; 2325 if (st != null && st.hasTag(CLASS)) 2326 complete &= checkNonCyclicInternal(pos, st); 2327 } 2328 if (c.owner.kind == TYP) 2329 complete &= checkNonCyclicInternal(pos, c.owner.type); 2330 } 2331 } finally { 2332 c.flags_field &= ~LOCKED; 2333 } 2334 } 2335 if (complete) 2336 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted(); 2337 if (complete) c.flags_field |= ACYCLIC; 2338 return complete; 2339 } 2340 2341 /** Note that we found an inheritance cycle. */ 2342 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) { 2343 log.error(pos, "cyclic.inheritance", c); 2344 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail) 2345 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType); 2346 Type st = types.supertype(c.type); 2347 if (st.hasTag(CLASS)) 2348 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType); 2349 c.type = types.createErrorType(c, c.type); 2350 c.flags_field |= ACYCLIC; 2351 } 2352 2353 /** Check that all methods which implement some 2354 * method conform to the method they implement. 2355 * @param tree The class definition whose members are checked. 2356 */ 2357 void checkImplementations(JCClassDecl tree) { 2358 checkImplementations(tree, tree.sym, tree.sym); 2359 } 2360 //where 2361 /** Check that all methods which implement some 2362 * method in `ic' conform to the method they implement. 2363 */ 2364 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) { 2365 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) { 2366 ClassSymbol lc = (ClassSymbol)l.head.tsym; 2367 if ((lc.flags() & ABSTRACT) != 0) { 2368 for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) { 2369 if (sym.kind == MTH && 2370 (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) { 2371 MethodSymbol absmeth = (MethodSymbol)sym; 2372 MethodSymbol implmeth = absmeth.implementation(origin, types, false); 2373 if (implmeth != null && implmeth != absmeth && 2374 (implmeth.owner.flags() & INTERFACE) == 2375 (origin.flags() & INTERFACE)) { 2376 // don't check if implmeth is in a class, yet 2377 // origin is an interface. This case arises only 2378 // if implmeth is declared in Object. The reason is 2379 // that interfaces really don't inherit from 2380 // Object it's just that the compiler represents 2381 // things that way. 2382 checkOverride(tree, implmeth, absmeth, origin); 2383 } 2384 } 2385 } 2386 } 2387 } 2388 } 2389 2390 /** Check that all abstract methods implemented by a class are 2391 * mutually compatible. 2392 * @param pos Position to be used for error reporting. 2393 * @param c The class whose interfaces are checked. 2394 */ 2395 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) { 2396 List<Type> supertypes = types.interfaces(c); 2397 Type supertype = types.supertype(c); 2398 if (supertype.hasTag(CLASS) && 2399 (supertype.tsym.flags() & ABSTRACT) != 0) 2400 supertypes = supertypes.prepend(supertype); 2401 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) { 2402 if (!l.head.getTypeArguments().isEmpty() && 2403 !checkCompatibleAbstracts(pos, l.head, l.head, c)) 2404 return; 2405 for (List<Type> m = supertypes; m != l; m = m.tail) 2406 if (!checkCompatibleAbstracts(pos, l.head, m.head, c)) 2407 return; 2408 } 2409 checkCompatibleConcretes(pos, c); 2410 } 2411 2412 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) { 2413 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) { 2414 for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) { 2415 // VM allows methods and variables with differing types 2416 if (sym.kind == sym2.kind && 2417 types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) && 2418 sym != sym2 && 2419 (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) && 2420 (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) { 2421 syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym); 2422 return; 2423 } 2424 } 2425 } 2426 } 2427 2428 /** Check that all non-override equivalent methods accessible from 'site' 2429 * are mutually compatible (JLS 8.4.8/9.4.1). 2430 * 2431 * @param pos Position to be used for error reporting. 2432 * @param site The class whose methods are checked. 2433 * @param sym The method symbol to be checked. 2434 */ 2435 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2436 ClashFilter cf = new ClashFilter(site); 2437 //for each method m1 that is overridden (directly or indirectly) 2438 //by method 'sym' in 'site'... 2439 2440 List<MethodSymbol> potentiallyAmbiguousList = List.nil(); 2441 boolean overridesAny = false; 2442 for (Symbol m1 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) { 2443 if (!sym.overrides(m1, site.tsym, types, false)) { 2444 if (m1 == sym) { 2445 continue; 2446 } 2447 2448 if (!overridesAny) { 2449 potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1); 2450 } 2451 continue; 2452 } 2453 2454 if (m1 != sym) { 2455 overridesAny = true; 2456 potentiallyAmbiguousList = List.nil(); 2457 } 2458 2459 //...check each method m2 that is a member of 'site' 2460 for (Symbol m2 : types.membersClosure(site, false).getSymbolsByName(sym.name, cf)) { 2461 if (m2 == m1) continue; 2462 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2463 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error 2464 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) && 2465 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) { 2466 sym.flags_field |= CLASH; 2467 if (m1 == sym) { 2468 log.error(pos, Errors.NameClashSameErasureNoOverride( 2469 m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(), 2470 m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location())); 2471 } else { 2472 ClassType ct = (ClassType)site; 2473 String kind = ct.isInterface() ? "interface" : "class"; 2474 log.error(pos, Errors.NameClashSameErasureNoOverride1( 2475 kind, 2476 ct.tsym.name, 2477 m1.name, 2478 types.memberType(site, m1).asMethodType().getParameterTypes(), 2479 m1.location(), 2480 m2.name, 2481 types.memberType(site, m2).asMethodType().getParameterTypes(), 2482 m2.location())); 2483 } 2484 return; 2485 } 2486 } 2487 } 2488 2489 if (!overridesAny) { 2490 for (MethodSymbol m: potentiallyAmbiguousList) { 2491 checkPotentiallyAmbiguousOverloads(pos, site, sym, m); 2492 } 2493 } 2494 } 2495 2496 /** Check that all static methods accessible from 'site' are 2497 * mutually compatible (JLS 8.4.8). 2498 * 2499 * @param pos Position to be used for error reporting. 2500 * @param site The class whose methods are checked. 2501 * @param sym The method symbol to be checked. 2502 */ 2503 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2504 ClashFilter cf = new ClashFilter(site); 2505 //for each method m1 that is a member of 'site'... 2506 for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) { 2507 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2508 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error 2509 if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck)) { 2510 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) { 2511 log.error(pos, 2512 "name.clash.same.erasure.no.hide", 2513 sym, sym.location(), 2514 s, s.location()); 2515 return; 2516 } else { 2517 checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s); 2518 } 2519 } 2520 } 2521 } 2522 2523 //where 2524 private class ClashFilter implements Filter<Symbol> { 2525 2526 Type site; 2527 2528 ClashFilter(Type site) { 2529 this.site = site; 2530 } 2531 2532 boolean shouldSkip(Symbol s) { 2533 return (s.flags() & CLASH) != 0 && 2534 s.owner == site.tsym; 2535 } 2536 2537 public boolean accepts(Symbol s) { 2538 return s.kind == MTH && 2539 (s.flags() & SYNTHETIC) == 0 && 2540 !shouldSkip(s) && 2541 s.isInheritedIn(site.tsym, types) && 2542 !s.isConstructor(); 2543 } 2544 } 2545 2546 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) { 2547 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site); 2548 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) { 2549 Assert.check(m.kind == MTH); 2550 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m); 2551 if (prov.size() > 1) { 2552 ListBuffer<Symbol> abstracts = new ListBuffer<>(); 2553 ListBuffer<Symbol> defaults = new ListBuffer<>(); 2554 for (MethodSymbol provSym : prov) { 2555 if ((provSym.flags() & DEFAULT) != 0) { 2556 defaults = defaults.append(provSym); 2557 } else if ((provSym.flags() & ABSTRACT) != 0) { 2558 abstracts = abstracts.append(provSym); 2559 } 2560 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) { 2561 //strong semantics - issue an error if two sibling interfaces 2562 //have two override-equivalent defaults - or if one is abstract 2563 //and the other is default 2564 String errKey; 2565 Symbol s1 = defaults.first(); 2566 Symbol s2; 2567 if (defaults.size() > 1) { 2568 errKey = "types.incompatible.unrelated.defaults"; 2569 s2 = defaults.toList().tail.head; 2570 } else { 2571 errKey = "types.incompatible.abstract.default"; 2572 s2 = abstracts.first(); 2573 } 2574 log.error(pos, errKey, 2575 Kinds.kindName(site.tsym), site, 2576 m.name, types.memberType(site, m).getParameterTypes(), 2577 s1.location(), s2.location()); 2578 break; 2579 } 2580 } 2581 } 2582 } 2583 } 2584 2585 //where 2586 private class DefaultMethodClashFilter implements Filter<Symbol> { 2587 2588 Type site; 2589 2590 DefaultMethodClashFilter(Type site) { 2591 this.site = site; 2592 } 2593 2594 public boolean accepts(Symbol s) { 2595 return s.kind == MTH && 2596 (s.flags() & DEFAULT) != 0 && 2597 s.isInheritedIn(site.tsym, types) && 2598 !s.isConstructor(); 2599 } 2600 } 2601 2602 /** 2603 * Report warnings for potentially ambiguous method declarations. Two declarations 2604 * are potentially ambiguous if they feature two unrelated functional interface 2605 * in same argument position (in which case, a call site passing an implicit 2606 * lambda would be ambiguous). 2607 */ 2608 void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site, 2609 MethodSymbol msym1, MethodSymbol msym2) { 2610 if (msym1 != msym2 && 2611 allowDefaultMethods && 2612 lint.isEnabled(LintCategory.OVERLOADS) && 2613 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 && 2614 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) { 2615 Type mt1 = types.memberType(site, msym1); 2616 Type mt2 = types.memberType(site, msym2); 2617 //if both generic methods, adjust type variables 2618 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) && 2619 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) { 2620 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars); 2621 } 2622 //expand varargs methods if needed 2623 int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length()); 2624 List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true); 2625 List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true); 2626 //if arities don't match, exit 2627 if (args1.length() != args2.length()) return; 2628 boolean potentiallyAmbiguous = false; 2629 while (args1.nonEmpty() && args2.nonEmpty()) { 2630 Type s = args1.head; 2631 Type t = args2.head; 2632 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) { 2633 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) && 2634 types.findDescriptorType(s).getParameterTypes().length() > 0 && 2635 types.findDescriptorType(s).getParameterTypes().length() == 2636 types.findDescriptorType(t).getParameterTypes().length()) { 2637 potentiallyAmbiguous = true; 2638 } else { 2639 break; 2640 } 2641 } 2642 args1 = args1.tail; 2643 args2 = args2.tail; 2644 } 2645 if (potentiallyAmbiguous) { 2646 //we found two incompatible functional interfaces with same arity 2647 //this means a call site passing an implicit lambda would be ambigiuous 2648 msym1.flags_field |= POTENTIALLY_AMBIGUOUS; 2649 msym2.flags_field |= POTENTIALLY_AMBIGUOUS; 2650 log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload", 2651 msym1, msym1.location(), 2652 msym2, msym2.location()); 2653 return; 2654 } 2655 } 2656 } 2657 2658 void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) { 2659 if (warnOnAnyAccessToMembers || 2660 (lint.isEnabled(LintCategory.SERIAL) && 2661 !lint.isSuppressed(LintCategory.SERIAL) && 2662 isLambda)) { 2663 Symbol sym = TreeInfo.symbol(tree); 2664 if (!sym.kind.matches(KindSelector.VAL_MTH)) { 2665 return; 2666 } 2667 2668 if (sym.kind == VAR) { 2669 if ((sym.flags() & PARAMETER) != 0 || 2670 sym.isLocal() || 2671 sym.name == names._this || 2672 sym.name == names._super) { 2673 return; 2674 } 2675 } 2676 2677 if (!types.isSubtype(sym.owner.type, syms.serializableType) && 2678 isEffectivelyNonPublic(sym)) { 2679 if (isLambda) { 2680 if (belongsToRestrictedPackage(sym)) { 2681 log.warning(LintCategory.SERIAL, tree.pos(), 2682 "access.to.member.from.serializable.lambda", sym); 2683 } 2684 } else { 2685 log.warning(tree.pos(), 2686 "access.to.member.from.serializable.element", sym); 2687 } 2688 } 2689 } 2690 } 2691 2692 private boolean isEffectivelyNonPublic(Symbol sym) { 2693 if (sym.packge() == syms.rootPackage) { 2694 return false; 2695 } 2696 2697 while (sym.kind != PCK) { 2698 if ((sym.flags() & PUBLIC) == 0) { 2699 return true; 2700 } 2701 sym = sym.owner; 2702 } 2703 return false; 2704 } 2705 2706 private boolean belongsToRestrictedPackage(Symbol sym) { 2707 String fullName = sym.packge().fullname.toString(); 2708 return fullName.startsWith("java.") || 2709 fullName.startsWith("javax.") || 2710 fullName.startsWith("sun.") || 2711 fullName.contains(".internal."); 2712 } 2713 2714 /** Report a conflict between a user symbol and a synthetic symbol. 2715 */ 2716 private void syntheticError(DiagnosticPosition pos, Symbol sym) { 2717 if (!sym.type.isErroneous()) { 2718 log.error(pos, "synthetic.name.conflict", sym, sym.location()); 2719 } 2720 } 2721 2722 /** Check that class c does not implement directly or indirectly 2723 * the same parameterized interface with two different argument lists. 2724 * @param pos Position to be used for error reporting. 2725 * @param type The type whose interfaces are checked. 2726 */ 2727 void checkClassBounds(DiagnosticPosition pos, Type type) { 2728 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type); 2729 } 2730//where 2731 /** Enter all interfaces of type `type' into the hash table `seensofar' 2732 * with their class symbol as key and their type as value. Make 2733 * sure no class is entered with two different types. 2734 */ 2735 void checkClassBounds(DiagnosticPosition pos, 2736 Map<TypeSymbol,Type> seensofar, 2737 Type type) { 2738 if (type.isErroneous()) return; 2739 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) { 2740 Type it = l.head; 2741 Type oldit = seensofar.put(it.tsym, it); 2742 if (oldit != null) { 2743 List<Type> oldparams = oldit.allparams(); 2744 List<Type> newparams = it.allparams(); 2745 if (!types.containsTypeEquivalent(oldparams, newparams)) 2746 log.error(pos, "cant.inherit.diff.arg", 2747 it.tsym, Type.toString(oldparams), 2748 Type.toString(newparams)); 2749 } 2750 checkClassBounds(pos, seensofar, it); 2751 } 2752 Type st = types.supertype(type); 2753 if (st != Type.noType) checkClassBounds(pos, seensofar, st); 2754 } 2755 2756 /** Enter interface into into set. 2757 * If it existed already, issue a "repeated interface" error. 2758 */ 2759 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) { 2760 if (its.contains(it)) 2761 log.error(pos, "repeated.interface"); 2762 else { 2763 its.add(it); 2764 } 2765 } 2766 2767/* ************************************************************************* 2768 * Check annotations 2769 **************************************************************************/ 2770 2771 /** 2772 * Recursively validate annotations values 2773 */ 2774 void validateAnnotationTree(JCTree tree) { 2775 class AnnotationValidator extends TreeScanner { 2776 @Override 2777 public void visitAnnotation(JCAnnotation tree) { 2778 if (!tree.type.isErroneous()) { 2779 super.visitAnnotation(tree); 2780 validateAnnotation(tree); 2781 } 2782 } 2783 } 2784 tree.accept(new AnnotationValidator()); 2785 } 2786 2787 /** 2788 * {@literal 2789 * Annotation types are restricted to primitives, String, an 2790 * enum, an annotation, Class, Class<?>, Class<? extends 2791 * Anything>, arrays of the preceding. 2792 * } 2793 */ 2794 void validateAnnotationType(JCTree restype) { 2795 // restype may be null if an error occurred, so don't bother validating it 2796 if (restype != null) { 2797 validateAnnotationType(restype.pos(), restype.type); 2798 } 2799 } 2800 2801 void validateAnnotationType(DiagnosticPosition pos, Type type) { 2802 if (type.isPrimitive()) return; 2803 if (types.isSameType(type, syms.stringType)) return; 2804 if ((type.tsym.flags() & Flags.ENUM) != 0) return; 2805 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return; 2806 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return; 2807 if (types.isArray(type) && !types.isArray(types.elemtype(type))) { 2808 validateAnnotationType(pos, types.elemtype(type)); 2809 return; 2810 } 2811 log.error(pos, "invalid.annotation.member.type"); 2812 } 2813 2814 /** 2815 * "It is also a compile-time error if any method declared in an 2816 * annotation type has a signature that is override-equivalent to 2817 * that of any public or protected method declared in class Object 2818 * or in the interface annotation.Annotation." 2819 * 2820 * @jls 9.6 Annotation Types 2821 */ 2822 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) { 2823 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) { 2824 Scope s = sup.tsym.members(); 2825 for (Symbol sym : s.getSymbolsByName(m.name)) { 2826 if (sym.kind == MTH && 2827 (sym.flags() & (PUBLIC | PROTECTED)) != 0 && 2828 types.overrideEquivalent(m.type, sym.type)) 2829 log.error(pos, "intf.annotation.member.clash", sym, sup); 2830 } 2831 } 2832 } 2833 2834 /** Check the annotations of a symbol. 2835 */ 2836 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) { 2837 for (JCAnnotation a : annotations) 2838 validateAnnotation(a, s); 2839 } 2840 2841 /** Check the type annotations. 2842 */ 2843 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) { 2844 for (JCAnnotation a : annotations) 2845 validateTypeAnnotation(a, isTypeParameter); 2846 } 2847 2848 /** Check an annotation of a symbol. 2849 */ 2850 private void validateAnnotation(JCAnnotation a, Symbol s) { 2851 validateAnnotationTree(a); 2852 2853 if (a.type.tsym.isAnnotationType() && !annotationApplicable(a, s)) 2854 log.error(a.pos(), "annotation.type.not.applicable"); 2855 2856 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 2857 if (s.kind != TYP) { 2858 log.error(a.pos(), "bad.functional.intf.anno"); 2859 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) { 2860 log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s)); 2861 } 2862 } 2863 } 2864 2865 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 2866 Assert.checkNonNull(a.type); 2867 validateAnnotationTree(a); 2868 2869 if (a.hasTag(TYPE_ANNOTATION) && 2870 !a.annotationType.type.isErroneous() && 2871 !isTypeAnnotation(a, isTypeParameter)) { 2872 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type)); 2873 } 2874 } 2875 2876 /** 2877 * Validate the proposed container 'repeatable' on the 2878 * annotation type symbol 's'. Report errors at position 2879 * 'pos'. 2880 * 2881 * @param s The (annotation)type declaration annotated with a @Repeatable 2882 * @param repeatable the @Repeatable on 's' 2883 * @param pos where to report errors 2884 */ 2885 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) { 2886 Assert.check(types.isSameType(repeatable.type, syms.repeatableType)); 2887 2888 Type t = null; 2889 List<Pair<MethodSymbol,Attribute>> l = repeatable.values; 2890 if (!l.isEmpty()) { 2891 Assert.check(l.head.fst.name == names.value); 2892 t = ((Attribute.Class)l.head.snd).getValue(); 2893 } 2894 2895 if (t == null) { 2896 // errors should already have been reported during Annotate 2897 return; 2898 } 2899 2900 validateValue(t.tsym, s, pos); 2901 validateRetention(t.tsym, s, pos); 2902 validateDocumented(t.tsym, s, pos); 2903 validateInherited(t.tsym, s, pos); 2904 validateTarget(t.tsym, s, pos); 2905 validateDefault(t.tsym, pos); 2906 } 2907 2908 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2909 Symbol sym = container.members().findFirst(names.value); 2910 if (sym != null && sym.kind == MTH) { 2911 MethodSymbol m = (MethodSymbol) sym; 2912 Type ret = m.getReturnType(); 2913 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) { 2914 log.error(pos, "invalid.repeatable.annotation.value.return", 2915 container, ret, types.makeArrayType(contained.type)); 2916 } 2917 } else { 2918 log.error(pos, "invalid.repeatable.annotation.no.value", container); 2919 } 2920 } 2921 2922 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2923 Attribute.RetentionPolicy containerRetention = types.getRetention(container); 2924 Attribute.RetentionPolicy containedRetention = types.getRetention(contained); 2925 2926 boolean error = false; 2927 switch (containedRetention) { 2928 case RUNTIME: 2929 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) { 2930 error = true; 2931 } 2932 break; 2933 case CLASS: 2934 if (containerRetention == Attribute.RetentionPolicy.SOURCE) { 2935 error = true; 2936 } 2937 } 2938 if (error ) { 2939 log.error(pos, "invalid.repeatable.annotation.retention", 2940 container, containerRetention, 2941 contained, containedRetention); 2942 } 2943 } 2944 2945 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) { 2946 if (contained.attribute(syms.documentedType.tsym) != null) { 2947 if (container.attribute(syms.documentedType.tsym) == null) { 2948 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained); 2949 } 2950 } 2951 } 2952 2953 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) { 2954 if (contained.attribute(syms.inheritedType.tsym) != null) { 2955 if (container.attribute(syms.inheritedType.tsym) == null) { 2956 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained); 2957 } 2958 } 2959 } 2960 2961 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2962 // The set of targets the container is applicable to must be a subset 2963 // (with respect to annotation target semantics) of the set of targets 2964 // the contained is applicable to. The target sets may be implicit or 2965 // explicit. 2966 2967 Set<Name> containerTargets; 2968 Attribute.Array containerTarget = getAttributeTargetAttribute(container); 2969 if (containerTarget == null) { 2970 containerTargets = getDefaultTargetSet(); 2971 } else { 2972 containerTargets = new HashSet<>(); 2973 for (Attribute app : containerTarget.values) { 2974 if (!(app instanceof Attribute.Enum)) { 2975 continue; // recovery 2976 } 2977 Attribute.Enum e = (Attribute.Enum)app; 2978 containerTargets.add(e.value.name); 2979 } 2980 } 2981 2982 Set<Name> containedTargets; 2983 Attribute.Array containedTarget = getAttributeTargetAttribute(contained); 2984 if (containedTarget == null) { 2985 containedTargets = getDefaultTargetSet(); 2986 } else { 2987 containedTargets = new HashSet<>(); 2988 for (Attribute app : containedTarget.values) { 2989 if (!(app instanceof Attribute.Enum)) { 2990 continue; // recovery 2991 } 2992 Attribute.Enum e = (Attribute.Enum)app; 2993 containedTargets.add(e.value.name); 2994 } 2995 } 2996 2997 if (!isTargetSubsetOf(containerTargets, containedTargets)) { 2998 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained); 2999 } 3000 } 3001 3002 /* get a set of names for the default target */ 3003 private Set<Name> getDefaultTargetSet() { 3004 if (defaultTargets == null) { 3005 Set<Name> targets = new HashSet<>(); 3006 targets.add(names.ANNOTATION_TYPE); 3007 targets.add(names.CONSTRUCTOR); 3008 targets.add(names.FIELD); 3009 targets.add(names.LOCAL_VARIABLE); 3010 targets.add(names.METHOD); 3011 targets.add(names.PACKAGE); 3012 targets.add(names.PARAMETER); 3013 targets.add(names.TYPE); 3014 3015 defaultTargets = java.util.Collections.unmodifiableSet(targets); 3016 } 3017 3018 return defaultTargets; 3019 } 3020 private Set<Name> defaultTargets; 3021 3022 3023 /** Checks that s is a subset of t, with respect to ElementType 3024 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}, 3025 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE, 3026 * TYPE_PARAMETER}. 3027 */ 3028 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) { 3029 // Check that all elements in s are present in t 3030 for (Name n2 : s) { 3031 boolean currentElementOk = false; 3032 for (Name n1 : t) { 3033 if (n1 == n2) { 3034 currentElementOk = true; 3035 break; 3036 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) { 3037 currentElementOk = true; 3038 break; 3039 } else if (n1 == names.TYPE_USE && 3040 (n2 == names.TYPE || 3041 n2 == names.ANNOTATION_TYPE || 3042 n2 == names.TYPE_PARAMETER)) { 3043 currentElementOk = true; 3044 break; 3045 } 3046 } 3047 if (!currentElementOk) 3048 return false; 3049 } 3050 return true; 3051 } 3052 3053 private void validateDefault(Symbol container, DiagnosticPosition pos) { 3054 // validate that all other elements of containing type has defaults 3055 Scope scope = container.members(); 3056 for(Symbol elm : scope.getSymbols()) { 3057 if (elm.name != names.value && 3058 elm.kind == MTH && 3059 ((MethodSymbol)elm).defaultValue == null) { 3060 log.error(pos, 3061 "invalid.repeatable.annotation.elem.nondefault", 3062 container, 3063 elm); 3064 } 3065 } 3066 } 3067 3068 /** Is s a method symbol that overrides a method in a superclass? */ 3069 boolean isOverrider(Symbol s) { 3070 if (s.kind != MTH || s.isStatic()) 3071 return false; 3072 MethodSymbol m = (MethodSymbol)s; 3073 TypeSymbol owner = (TypeSymbol)m.owner; 3074 for (Type sup : types.closure(owner.type)) { 3075 if (sup == owner.type) 3076 continue; // skip "this" 3077 Scope scope = sup.tsym.members(); 3078 for (Symbol sym : scope.getSymbolsByName(m.name)) { 3079 if (!sym.isStatic() && m.overrides(sym, owner, types, true)) 3080 return true; 3081 } 3082 } 3083 return false; 3084 } 3085 3086 /** Is the annotation applicable to types? */ 3087 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 3088 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym); 3089 return (targets == null) ? 3090 false : 3091 targets.stream() 3092 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter)); 3093 } 3094 //where 3095 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) { 3096 Attribute.Enum e = (Attribute.Enum)a; 3097 return (e.value.name == names.TYPE_USE || 3098 (isTypeParameter && e.value.name == names.TYPE_PARAMETER)); 3099 } 3100 3101 /** Is the annotation applicable to the symbol? */ 3102 boolean annotationApplicable(JCAnnotation a, Symbol s) { 3103 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym); 3104 Name[] targets; 3105 3106 if (arr == null) { 3107 targets = defaultTargetMetaInfo(a, s); 3108 } else { 3109 // TODO: can we optimize this? 3110 targets = new Name[arr.values.length]; 3111 for (int i=0; i<arr.values.length; ++i) { 3112 Attribute app = arr.values[i]; 3113 if (!(app instanceof Attribute.Enum)) { 3114 return true; // recovery 3115 } 3116 Attribute.Enum e = (Attribute.Enum) app; 3117 targets[i] = e.value.name; 3118 } 3119 } 3120 for (Name target : targets) { 3121 if (target == names.TYPE) { 3122 if (s.kind == TYP) 3123 return true; 3124 } else if (target == names.FIELD) { 3125 if (s.kind == VAR && s.owner.kind != MTH) 3126 return true; 3127 } else if (target == names.METHOD) { 3128 if (s.kind == MTH && !s.isConstructor()) 3129 return true; 3130 } else if (target == names.PARAMETER) { 3131 if (s.kind == VAR && s.owner.kind == MTH && 3132 (s.flags() & PARAMETER) != 0) { 3133 return true; 3134 } 3135 } else if (target == names.CONSTRUCTOR) { 3136 if (s.kind == MTH && s.isConstructor()) 3137 return true; 3138 } else if (target == names.LOCAL_VARIABLE) { 3139 if (s.kind == VAR && s.owner.kind == MTH && 3140 (s.flags() & PARAMETER) == 0) { 3141 return true; 3142 } 3143 } else if (target == names.ANNOTATION_TYPE) { 3144 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) { 3145 return true; 3146 } 3147 } else if (target == names.PACKAGE) { 3148 if (s.kind == PCK) 3149 return true; 3150 } else if (target == names.TYPE_USE) { 3151 if (s.kind == TYP || s.kind == VAR || 3152 (s.kind == MTH && !s.isConstructor() && 3153 !s.type.getReturnType().hasTag(VOID)) || 3154 (s.kind == MTH && s.isConstructor())) { 3155 return true; 3156 } 3157 } else if (target == names.TYPE_PARAMETER) { 3158 if (s.kind == TYP && s.type.hasTag(TYPEVAR)) 3159 return true; 3160 } else 3161 return true; // Unknown ElementType. This should be an error at declaration site, 3162 // assume applicable. 3163 } 3164 return false; 3165 } 3166 3167 3168 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) { 3169 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget(); 3170 if (atTarget == null) return null; // ok, is applicable 3171 Attribute atValue = atTarget.member(names.value); 3172 if (!(atValue instanceof Attribute.Array)) return null; // error recovery 3173 return (Attribute.Array) atValue; 3174 } 3175 3176 private final Name[] dfltTargetMeta; 3177 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) { 3178 return dfltTargetMeta; 3179 } 3180 3181 /** Check an annotation value. 3182 * 3183 * @param a The annotation tree to check 3184 * @return true if this annotation tree is valid, otherwise false 3185 */ 3186 public boolean validateAnnotationDeferErrors(JCAnnotation a) { 3187 boolean res = false; 3188 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log); 3189 try { 3190 res = validateAnnotation(a); 3191 } finally { 3192 log.popDiagnosticHandler(diagHandler); 3193 } 3194 return res; 3195 } 3196 3197 private boolean validateAnnotation(JCAnnotation a) { 3198 boolean isValid = true; 3199 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata(); 3200 3201 // collect an inventory of the annotation elements 3202 Set<MethodSymbol> elements = metadata.getAnnotationElements(); 3203 3204 // remove the ones that are assigned values 3205 for (JCTree arg : a.args) { 3206 if (!arg.hasTag(ASSIGN)) continue; // recovery 3207 JCAssign assign = (JCAssign)arg; 3208 Symbol m = TreeInfo.symbol(assign.lhs); 3209 if (m == null || m.type.isErroneous()) continue; 3210 if (!elements.remove(m)) { 3211 isValid = false; 3212 log.error(assign.lhs.pos(), "duplicate.annotation.member.value", 3213 m.name, a.type); 3214 } 3215 } 3216 3217 // all the remaining ones better have default values 3218 List<Name> missingDefaults = List.nil(); 3219 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault(); 3220 for (MethodSymbol m : elements) { 3221 if (m.type.isErroneous()) 3222 continue; 3223 3224 if (!membersWithDefault.contains(m)) 3225 missingDefaults = missingDefaults.append(m.name); 3226 } 3227 missingDefaults = missingDefaults.reverse(); 3228 if (missingDefaults.nonEmpty()) { 3229 isValid = false; 3230 String key = (missingDefaults.size() > 1) 3231 ? "annotation.missing.default.value.1" 3232 : "annotation.missing.default.value"; 3233 log.error(a.pos(), key, a.type, missingDefaults); 3234 } 3235 3236 return isValid && validateTargetAnnotationValue(a); 3237 } 3238 3239 /* Validate the special java.lang.annotation.Target annotation */ 3240 boolean validateTargetAnnotationValue(JCAnnotation a) { 3241 // special case: java.lang.annotation.Target must not have 3242 // repeated values in its value member 3243 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym || 3244 a.args.tail == null) 3245 return true; 3246 3247 boolean isValid = true; 3248 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery 3249 JCAssign assign = (JCAssign) a.args.head; 3250 Symbol m = TreeInfo.symbol(assign.lhs); 3251 if (m.name != names.value) return false; 3252 JCTree rhs = assign.rhs; 3253 if (!rhs.hasTag(NEWARRAY)) return false; 3254 JCNewArray na = (JCNewArray) rhs; 3255 Set<Symbol> targets = new HashSet<>(); 3256 for (JCTree elem : na.elems) { 3257 if (!targets.add(TreeInfo.symbol(elem))) { 3258 isValid = false; 3259 log.error(elem.pos(), "repeated.annotation.target"); 3260 } 3261 } 3262 return isValid; 3263 } 3264 3265 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { 3266 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() && 3267 (s.flags() & DEPRECATED) != 0 && 3268 !syms.deprecatedType.isErroneous() && 3269 s.attribute(syms.deprecatedType.tsym) == null) { 3270 log.warning(LintCategory.DEP_ANN, 3271 pos, "missing.deprecated.annotation"); 3272 } 3273 // Note: @Deprecated has no effect on local variables, parameters and package decls. 3274 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) { 3275 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) { 3276 log.warning(LintCategory.DEPRECATION, pos, 3277 "deprecated.annotation.has.no.effect", Kinds.kindName(s)); 3278 } 3279 } 3280 } 3281 3282 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) { 3283 if ( (s.isDeprecatedForRemoval() 3284 || s.isDeprecated() && !other.isDeprecated()) 3285 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)) { 3286 deferredLintHandler.report(() -> warnDeprecated(pos, s)); 3287 } 3288 } 3289 3290 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) { 3291 if ((s.flags() & PROPRIETARY) != 0) { 3292 deferredLintHandler.report(() -> { 3293 log.mandatoryWarning(pos, "sun.proprietary", s); 3294 }); 3295 } 3296 } 3297 3298 void checkProfile(final DiagnosticPosition pos, final Symbol s) { 3299 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) { 3300 log.error(pos, "not.in.profile", s, profile); 3301 } 3302 } 3303 3304/* ************************************************************************* 3305 * Check for recursive annotation elements. 3306 **************************************************************************/ 3307 3308 /** Check for cycles in the graph of annotation elements. 3309 */ 3310 void checkNonCyclicElements(JCClassDecl tree) { 3311 if ((tree.sym.flags_field & ANNOTATION) == 0) return; 3312 Assert.check((tree.sym.flags_field & LOCKED) == 0); 3313 try { 3314 tree.sym.flags_field |= LOCKED; 3315 for (JCTree def : tree.defs) { 3316 if (!def.hasTag(METHODDEF)) continue; 3317 JCMethodDecl meth = (JCMethodDecl)def; 3318 checkAnnotationResType(meth.pos(), meth.restype.type); 3319 } 3320 } finally { 3321 tree.sym.flags_field &= ~LOCKED; 3322 tree.sym.flags_field |= ACYCLIC_ANN; 3323 } 3324 } 3325 3326 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) { 3327 if ((tsym.flags_field & ACYCLIC_ANN) != 0) 3328 return; 3329 if ((tsym.flags_field & LOCKED) != 0) { 3330 log.error(pos, "cyclic.annotation.element"); 3331 return; 3332 } 3333 try { 3334 tsym.flags_field |= LOCKED; 3335 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) { 3336 if (s.kind != MTH) 3337 continue; 3338 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType()); 3339 } 3340 } finally { 3341 tsym.flags_field &= ~LOCKED; 3342 tsym.flags_field |= ACYCLIC_ANN; 3343 } 3344 } 3345 3346 void checkAnnotationResType(DiagnosticPosition pos, Type type) { 3347 switch (type.getTag()) { 3348 case CLASS: 3349 if ((type.tsym.flags() & ANNOTATION) != 0) 3350 checkNonCyclicElementsInternal(pos, type.tsym); 3351 break; 3352 case ARRAY: 3353 checkAnnotationResType(pos, types.elemtype(type)); 3354 break; 3355 default: 3356 break; // int etc 3357 } 3358 } 3359 3360/* ************************************************************************* 3361 * Check for cycles in the constructor call graph. 3362 **************************************************************************/ 3363 3364 /** Check for cycles in the graph of constructors calling other 3365 * constructors. 3366 */ 3367 void checkCyclicConstructors(JCClassDecl tree) { 3368 Map<Symbol,Symbol> callMap = new HashMap<>(); 3369 3370 // enter each constructor this-call into the map 3371 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 3372 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head); 3373 if (app == null) continue; 3374 JCMethodDecl meth = (JCMethodDecl) l.head; 3375 if (TreeInfo.name(app.meth) == names._this) { 3376 callMap.put(meth.sym, TreeInfo.symbol(app.meth)); 3377 } else { 3378 meth.sym.flags_field |= ACYCLIC; 3379 } 3380 } 3381 3382 // Check for cycles in the map 3383 Symbol[] ctors = new Symbol[0]; 3384 ctors = callMap.keySet().toArray(ctors); 3385 for (Symbol caller : ctors) { 3386 checkCyclicConstructor(tree, caller, callMap); 3387 } 3388 } 3389 3390 /** Look in the map to see if the given constructor is part of a 3391 * call cycle. 3392 */ 3393 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor, 3394 Map<Symbol,Symbol> callMap) { 3395 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) { 3396 if ((ctor.flags_field & LOCKED) != 0) { 3397 log.error(TreeInfo.diagnosticPositionFor(ctor, tree), 3398 "recursive.ctor.invocation"); 3399 } else { 3400 ctor.flags_field |= LOCKED; 3401 checkCyclicConstructor(tree, callMap.remove(ctor), callMap); 3402 ctor.flags_field &= ~LOCKED; 3403 } 3404 ctor.flags_field |= ACYCLIC; 3405 } 3406 } 3407 3408/* ************************************************************************* 3409 * Miscellaneous 3410 **************************************************************************/ 3411 3412 /** 3413 * Check for division by integer constant zero 3414 * @param pos Position for error reporting. 3415 * @param operator The operator for the expression 3416 * @param operand The right hand operand for the expression 3417 */ 3418 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { 3419 if (operand.constValue() != null 3420 && operand.getTag().isSubRangeOf(LONG) 3421 && ((Number) (operand.constValue())).longValue() == 0) { 3422 int opc = ((OperatorSymbol)operator).opcode; 3423 if (opc == ByteCodes.idiv || opc == ByteCodes.imod 3424 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) { 3425 deferredLintHandler.report(() -> warnDivZero(pos)); 3426 } 3427 } 3428 } 3429 3430 /** 3431 * Check for empty statements after if 3432 */ 3433 void checkEmptyIf(JCIf tree) { 3434 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null && 3435 lint.isEnabled(LintCategory.EMPTY)) 3436 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if"); 3437 } 3438 3439 /** Check that symbol is unique in given scope. 3440 * @param pos Position for error reporting. 3441 * @param sym The symbol. 3442 * @param s The scope. 3443 */ 3444 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) { 3445 if (sym.type.isErroneous()) 3446 return true; 3447 if (sym.owner.name == names.any) return false; 3448 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) { 3449 if (sym != byName && 3450 (byName.flags() & CLASH) == 0 && 3451 sym.kind == byName.kind && 3452 sym.name != names.error && 3453 (sym.kind != MTH || 3454 types.hasSameArgs(sym.type, byName.type) || 3455 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) { 3456 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) { 3457 varargsDuplicateError(pos, sym, byName); 3458 return true; 3459 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) { 3460 duplicateErasureError(pos, sym, byName); 3461 sym.flags_field |= CLASH; 3462 return true; 3463 } else { 3464 duplicateError(pos, byName); 3465 return false; 3466 } 3467 } 3468 } 3469 return true; 3470 } 3471 3472 /** Report duplicate declaration error. 3473 */ 3474 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 3475 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 3476 log.error(pos, "name.clash.same.erasure", sym1, sym2); 3477 } 3478 } 3479 3480 /**Check that types imported through the ordinary imports don't clash with types imported 3481 * by other (static or ordinary) imports. Note that two static imports may import two clashing 3482 * types without an error on the imports. 3483 * @param toplevel The toplevel tree for which the test should be performed. 3484 */ 3485 void checkImportsUnique(JCCompilationUnit toplevel) { 3486 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge); 3487 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge); 3488 WriteableScope topLevelScope = toplevel.toplevelScope; 3489 3490 for (JCTree def : toplevel.defs) { 3491 if (!def.hasTag(IMPORT)) 3492 continue; 3493 3494 JCImport imp = (JCImport) def; 3495 3496 if (imp.importScope == null) 3497 continue; 3498 3499 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) { 3500 if (imp.isStatic()) { 3501 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true); 3502 staticallyImportedSoFar.enter(sym); 3503 } else { 3504 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false); 3505 ordinallyImportedSoFar.enter(sym); 3506 } 3507 } 3508 3509 imp.importScope = null; 3510 } 3511 } 3512 3513 /** Check that single-type import is not already imported or top-level defined, 3514 * but make an exception for two single-type imports which denote the same type. 3515 * @param pos Position for error reporting. 3516 * @param ordinallyImportedSoFar A Scope containing types imported so far through 3517 * ordinary imports. 3518 * @param staticallyImportedSoFar A Scope containing types imported so far through 3519 * static imports. 3520 * @param topLevelScope The current file's top-level Scope 3521 * @param sym The symbol. 3522 * @param staticImport Whether or not this was a static import 3523 */ 3524 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar, 3525 Scope staticallyImportedSoFar, Scope topLevelScope, 3526 Symbol sym, boolean staticImport) { 3527 Filter<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous(); 3528 Symbol clashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates); 3529 if (clashing == null && !staticImport) { 3530 clashing = staticallyImportedSoFar.findFirst(sym.name, duplicates); 3531 } 3532 if (clashing != null) { 3533 if (staticImport) 3534 log.error(pos, "already.defined.static.single.import", clashing); 3535 else 3536 log.error(pos, "already.defined.single.import", clashing); 3537 return false; 3538 } 3539 clashing = topLevelScope.findFirst(sym.name, duplicates); 3540 if (clashing != null) { 3541 log.error(pos, "already.defined.this.unit", clashing); 3542 return false; 3543 } 3544 return true; 3545 } 3546 3547 /** Check that a qualified name is in canonical form (for import decls). 3548 */ 3549 public void checkCanonical(JCTree tree) { 3550 if (!isCanonical(tree)) 3551 log.error(tree.pos(), "import.requires.canonical", 3552 TreeInfo.symbol(tree)); 3553 } 3554 // where 3555 private boolean isCanonical(JCTree tree) { 3556 while (tree.hasTag(SELECT)) { 3557 JCFieldAccess s = (JCFieldAccess) tree; 3558 if (s.sym.owner.name != TreeInfo.symbol(s.selected).name) 3559 return false; 3560 tree = s.selected; 3561 } 3562 return true; 3563 } 3564 3565 /** Check that an auxiliary class is not accessed from any other file than its own. 3566 */ 3567 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) { 3568 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) && 3569 (c.flags() & AUXILIARY) != 0 && 3570 rs.isAccessible(env, c) && 3571 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile)) 3572 { 3573 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file", 3574 c, c.sourcefile); 3575 } 3576 } 3577 3578 private class ConversionWarner extends Warner { 3579 final String uncheckedKey; 3580 final Type found; 3581 final Type expected; 3582 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) { 3583 super(pos); 3584 this.uncheckedKey = uncheckedKey; 3585 this.found = found; 3586 this.expected = expected; 3587 } 3588 3589 @Override 3590 public void warn(LintCategory lint) { 3591 boolean warned = this.warned; 3592 super.warn(lint); 3593 if (warned) return; // suppress redundant diagnostics 3594 switch (lint) { 3595 case UNCHECKED: 3596 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected); 3597 break; 3598 case VARARGS: 3599 if (method != null && 3600 method.attribute(syms.trustMeType.tsym) != null && 3601 isTrustMeAllowedOnMethod(method) && 3602 !types.isReifiable(method.type.getParameterTypes().last())) { 3603 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last()); 3604 } 3605 break; 3606 default: 3607 throw new AssertionError("Unexpected lint: " + lint); 3608 } 3609 } 3610 } 3611 3612 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) { 3613 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected); 3614 } 3615 3616 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) { 3617 return new ConversionWarner(pos, "unchecked.assign", found, expected); 3618 } 3619 3620 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) { 3621 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym); 3622 3623 if (functionalType != null) { 3624 try { 3625 types.findDescriptorSymbol((TypeSymbol)cs); 3626 } catch (Types.FunctionDescriptorLookupError ex) { 3627 DiagnosticPosition pos = tree.pos(); 3628 for (JCAnnotation a : tree.getModifiers().annotations) { 3629 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 3630 pos = a.pos(); 3631 break; 3632 } 3633 } 3634 log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic()); 3635 } 3636 } 3637 } 3638 3639 public void checkImportsResolvable(final JCCompilationUnit toplevel) { 3640 for (final JCImport imp : toplevel.getImports()) { 3641 if (!imp.staticImport || !imp.qualid.hasTag(SELECT)) 3642 continue; 3643 final JCFieldAccess select = (JCFieldAccess) imp.qualid; 3644 final Symbol origin; 3645 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP) 3646 continue; 3647 3648 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected); 3649 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) { 3650 log.error(imp.pos(), "cant.resolve.location", 3651 KindName.STATIC, 3652 select.name, List.<Type>nil(), List.<Type>nil(), 3653 Kinds.typeKindName(TreeInfo.symbol(select.selected).type), 3654 TreeInfo.symbol(select.selected).type); 3655 } 3656 } 3657 } 3658 3659 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2) 3660 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) { 3661 OUTER: for (JCImport imp : toplevel.getImports()) { 3662 if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) { 3663 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym; 3664 if (toplevel.modle.visiblePackages != null) { 3665 //TODO - unclear: selects like javax.* will get resolved from the current module 3666 //(as javax is not an exported package from any module). And as javax in the current 3667 //module typically does not contain any classes or subpackages, we need to go through 3668 //the visible packages to find a sub-package: 3669 for (PackageSymbol known : toplevel.modle.visiblePackages.values()) { 3670 if (Convert.packagePart(known.fullname) == tsym.flatName()) 3671 continue OUTER; 3672 } 3673 } 3674 if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) { 3675 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, "doesnt.exist", tsym); 3676 } 3677 } 3678 } 3679 } 3680 3681 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) { 3682 if (tsym == null || !processed.add(tsym)) 3683 return false; 3684 3685 // also search through inherited names 3686 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed)) 3687 return true; 3688 3689 for (Type t : types.interfaces(tsym.type)) 3690 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed)) 3691 return true; 3692 3693 for (Symbol sym : tsym.members().getSymbolsByName(name)) { 3694 if (sym.isStatic() && 3695 importAccessible(sym, packge) && 3696 sym.isMemberOf(origin, types)) { 3697 return true; 3698 } 3699 } 3700 3701 return false; 3702 } 3703 3704 // is the sym accessible everywhere in packge? 3705 public boolean importAccessible(Symbol sym, PackageSymbol packge) { 3706 try { 3707 int flags = (int)(sym.flags() & AccessFlags); 3708 switch (flags) { 3709 default: 3710 case PUBLIC: 3711 return true; 3712 case PRIVATE: 3713 return false; 3714 case 0: 3715 case PROTECTED: 3716 return sym.packge() == packge; 3717 } 3718 } catch (ClassFinder.BadClassFile err) { 3719 throw err; 3720 } catch (CompletionFailure ex) { 3721 return false; 3722 } 3723 } 3724 3725 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) { 3726 JCCompilationUnit toplevel = env.toplevel; 3727 3728 if ( toplevel.modle == syms.unnamedModule 3729 || toplevel.modle == syms.noModule 3730 || (check.sym.flags() & COMPOUND) != 0) { 3731 return ; 3732 } 3733 3734 ExportsDirective currentExport = findExport(toplevel.packge); 3735 3736 if ( currentExport == null //not exported 3737 || currentExport.modules != null) //don't check classes in qualified export 3738 return ; 3739 3740 new TreeScanner() { 3741 Lint lint = env.info.lint; 3742 boolean inSuperType; 3743 3744 @Override 3745 public void visitBlock(JCBlock tree) { 3746 } 3747 @Override 3748 public void visitMethodDef(JCMethodDecl tree) { 3749 if (!isAPISymbol(tree.sym)) 3750 return; 3751 Lint prevLint = lint; 3752 try { 3753 lint = lint.augment(tree.sym); 3754 if (lint.isEnabled(LintCategory.EXPORTS)) { 3755 super.visitMethodDef(tree); 3756 } 3757 } finally { 3758 lint = prevLint; 3759 } 3760 } 3761 @Override 3762 public void visitVarDef(JCVariableDecl tree) { 3763 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH) 3764 return; 3765 Lint prevLint = lint; 3766 try { 3767 lint = lint.augment(tree.sym); 3768 if (lint.isEnabled(LintCategory.EXPORTS)) { 3769 scan(tree.mods); 3770 scan(tree.vartype); 3771 } 3772 } finally { 3773 lint = prevLint; 3774 } 3775 } 3776 @Override 3777 public void visitClassDef(JCClassDecl tree) { 3778 if (tree != check) 3779 return ; 3780 3781 if (!isAPISymbol(tree.sym)) 3782 return ; 3783 3784 Lint prevLint = lint; 3785 try { 3786 lint = lint.augment(tree.sym); 3787 if (lint.isEnabled(LintCategory.EXPORTS)) { 3788 scan(tree.mods); 3789 scan(tree.typarams); 3790 try { 3791 inSuperType = true; 3792 scan(tree.extending); 3793 scan(tree.implementing); 3794 } finally { 3795 inSuperType = false; 3796 } 3797 scan(tree.defs); 3798 } 3799 } finally { 3800 lint = prevLint; 3801 } 3802 } 3803 @Override 3804 public void visitTypeApply(JCTypeApply tree) { 3805 scan(tree.clazz); 3806 boolean oldInSuperType = inSuperType; 3807 try { 3808 inSuperType = false; 3809 scan(tree.arguments); 3810 } finally { 3811 inSuperType = oldInSuperType; 3812 } 3813 } 3814 @Override 3815 public void visitIdent(JCIdent tree) { 3816 Symbol sym = TreeInfo.symbol(tree); 3817 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) { 3818 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 3819 } 3820 } 3821 3822 @Override 3823 public void visitSelect(JCFieldAccess tree) { 3824 Symbol sym = TreeInfo.symbol(tree); 3825 Symbol sitesym = TreeInfo.symbol(tree.selected); 3826 if (sym.kind == TYP && sitesym.kind == PCK) { 3827 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 3828 } else { 3829 super.visitSelect(tree); 3830 } 3831 } 3832 3833 @Override 3834 public void visitAnnotation(JCAnnotation tree) { 3835 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null) 3836 super.visitAnnotation(tree); 3837 } 3838 3839 }.scan(check); 3840 } 3841 //where: 3842 private ExportsDirective findExport(PackageSymbol pack) { 3843 for (ExportsDirective d : pack.modle.exports) { 3844 if (d.packge == pack) 3845 return d; 3846 } 3847 3848 return null; 3849 } 3850 private boolean isAPISymbol(Symbol sym) { 3851 while (sym.kind != PCK) { 3852 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) { 3853 return false; 3854 } 3855 sym = sym.owner; 3856 } 3857 return true; 3858 } 3859 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) { 3860 if (!isAPISymbol(what) && !inSuperType) { //package private/private element 3861 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); 3862 return ; 3863 } 3864 3865 PackageSymbol whatPackage = what.packge(); 3866 ExportsDirective whatExport = findExport(whatPackage); 3867 ExportsDirective inExport = findExport(inPackage); 3868 3869 if (whatExport == null) { //package not exported: 3870 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle)); 3871 return ; 3872 } 3873 3874 if (whatExport.modules != null) { 3875 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) { 3876 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); 3877 } 3878 } 3879 3880 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) { 3881 //check that relativeTo.modle requires transitive what.modle, somehow: 3882 List<ModuleSymbol> todo = List.of(inPackage.modle); 3883 3884 while (todo.nonEmpty()) { 3885 ModuleSymbol current = todo.head; 3886 todo = todo.tail; 3887 if (current == whatPackage.modle) 3888 return ; //OK 3889 for (RequiresDirective req : current.requires) { 3890 if (req.isTransitive()) { 3891 todo = todo.prepend(req.module); 3892 } 3893 } 3894 } 3895 3896 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle)); 3897 } 3898 } 3899 3900 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) { 3901 if (msym.kind != MDL) { 3902 deferredLintHandler.report(() -> { 3903 if (lint.isEnabled(LintCategory.MODULE)) 3904 log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym)); 3905 }); 3906 } 3907 } 3908 3909 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) { 3910 if (packge.members().isEmpty() && 3911 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) { 3912 deferredLintHandler.report(() -> { 3913 if (lint.isEnabled(LintCategory.OPENS)) 3914 log.warning(pos, Warnings.PackageEmptyOrNotFound(packge)); 3915 }); 3916 } 3917 } 3918 3919 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) { 3920 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) { 3921 deferredLintHandler.report(() -> { 3922 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) { 3923 log.warning(pos, Warnings.RequiresTransitiveAutomatic); 3924 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) { 3925 log.warning(pos, Warnings.RequiresAutomatic); 3926 } 3927 }); 3928 } 3929 } 3930 3931} 3932