1 /* 2 * Copyright (c) 1999, 2025, 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 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.function.BiConsumer; 30 import java.util.function.BiPredicate; 31 import java.util.function.Predicate; 32 import java.util.function.Supplier; 33 import java.util.function.ToIntBiFunction; 34 import java.util.stream.Collectors; 35 import java.util.stream.StreamSupport; 36 37 import javax.lang.model.element.ElementKind; 38 import javax.lang.model.element.NestingKind; 39 import javax.tools.JavaFileManager; 40 41 import com.sun.source.tree.CaseTree; 42 import com.sun.tools.javac.code.*; 43 import com.sun.tools.javac.code.Attribute.Compound; 44 import com.sun.tools.javac.code.Directive.ExportsDirective; 45 import com.sun.tools.javac.code.Directive.RequiresDirective; 46 import com.sun.tools.javac.code.Source.Feature; 47 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata; 48 import com.sun.tools.javac.jvm.*; 49 import com.sun.tools.javac.resources.CompilerProperties.Errors; 50 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 51 import com.sun.tools.javac.resources.CompilerProperties.Warnings; 52 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings; 53 import com.sun.tools.javac.tree.*; 54 import com.sun.tools.javac.util.*; 55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 56 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 57 import com.sun.tools.javac.util.JCDiagnostic.Error; 58 import com.sun.tools.javac.util.JCDiagnostic.Fragment; 59 import com.sun.tools.javac.util.JCDiagnostic.LintWarning; 60 import com.sun.tools.javac.util.List; 61 62 import com.sun.tools.javac.code.Lint; 63 import com.sun.tools.javac.code.Lint.LintCategory; 64 import com.sun.tools.javac.code.Scope.WriteableScope; 65 import com.sun.tools.javac.code.Type.*; 66 import com.sun.tools.javac.code.Symbol.*; 67 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext; 68 import com.sun.tools.javac.tree.JCTree.*; 69 70 import static com.sun.tools.javac.code.Flags.*; 71 import static com.sun.tools.javac.code.Flags.ANNOTATION; 72 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED; 73 import static com.sun.tools.javac.code.Kinds.*; 74 import static com.sun.tools.javac.code.Kinds.Kind.*; 75 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 76 import static com.sun.tools.javac.code.Scope.LookupKind.RECURSIVE; 77 import static com.sun.tools.javac.code.TypeTag.*; 78 import static com.sun.tools.javac.code.TypeTag.WILDCARD; 79 80 import static com.sun.tools.javac.tree.JCTree.Tag.*; 81 import javax.lang.model.element.Element; 82 import javax.lang.model.element.TypeElement; 83 import javax.lang.model.type.DeclaredType; 84 import javax.lang.model.util.ElementKindVisitor14; 85 86 /** Type checking helper class for the attribution phase. 87 * 88 * <p><b>This is NOT part of any supported API. 89 * If you write code that depends on this, you do so at your own risk. 90 * This code and its internal interfaces are subject to change or 91 * deletion without notice.</b> 92 */ 93 public class Check { 94 protected static final Context.Key<Check> checkKey = new Context.Key<>(); 95 96 // Flag bits indicating which item(s) chosen from a pair of items 97 private static final int FIRST = 0x01; 98 private static final int SECOND = 0x02; 99 100 private final Names names; 101 private final Log log; 102 private final Resolve rs; 103 private final Symtab syms; 104 private final Enter enter; 105 private final DeferredAttr deferredAttr; 106 private final Infer infer; 107 private final Types types; 108 private final TypeAnnotations typeAnnotations; 109 private final JCDiagnostic.Factory diags; 110 private final JavaFileManager fileManager; 111 private final Source source; 112 private final Target target; 113 private final Profile profile; 114 private final Preview preview; 115 private final boolean warnOnAnyAccessToMembers; 116 117 public boolean disablePreviewCheck; 118 119 // The set of lint options currently in effect. It is initialized 120 // from the context, and then is set/reset as needed by Attr as it 121 // visits all the various parts of the trees during attribution. 122 Lint lint; 123 124 // The method being analyzed in Attr - it is set/reset as needed by 125 // Attr as it visits new method declarations. 126 private MethodSymbol method; 127 128 public static Check instance(Context context) { 129 Check instance = context.get(checkKey); 130 if (instance == null) 131 instance = new Check(context); 132 return instance; 133 } 134 135 @SuppressWarnings("this-escape") 136 protected Check(Context context) { 137 context.put(checkKey, this); 138 139 names = Names.instance(context); 140 log = Log.instance(context); 141 rs = Resolve.instance(context); 142 syms = Symtab.instance(context); 143 enter = Enter.instance(context); 144 deferredAttr = DeferredAttr.instance(context); 145 infer = Infer.instance(context); 146 types = Types.instance(context); 147 typeAnnotations = TypeAnnotations.instance(context); 148 diags = JCDiagnostic.Factory.instance(context); 149 Options options = Options.instance(context); 150 lint = Lint.instance(context); 151 fileManager = context.get(JavaFileManager.class); 152 153 source = Source.instance(context); 154 target = Target.instance(context); 155 warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers"); 156 157 disablePreviewCheck = false; 158 159 Target target = Target.instance(context); 160 syntheticNameChar = target.syntheticNameChar(); 161 162 profile = Profile.instance(context); 163 preview = Preview.instance(context); 164 165 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION); 166 boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL); 167 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED); 168 boolean enforceMandatoryWarnings = true; 169 170 deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated, 171 enforceMandatoryWarnings, LintCategory.DEPRECATION, "deprecated"); 172 removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval, 173 enforceMandatoryWarnings, LintCategory.REMOVAL); 174 uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked, 175 enforceMandatoryWarnings, LintCategory.UNCHECKED); 176 177 deferredLintHandler = DeferredLintHandler.instance(context); 178 179 allowModules = Feature.MODULES.allowedInSource(source); 180 allowRecords = Feature.RECORDS.allowedInSource(source); 181 allowSealed = Feature.SEALED_CLASSES.allowedInSource(source); 182 allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) && 183 Feature.VALUE_CLASSES.allowedInSource(source); 184 } 185 186 /** Character for synthetic names 187 */ 188 char syntheticNameChar; 189 190 /** A table mapping flat names of all compiled classes for each module in this run 191 * to their symbols; maintained from outside. 192 */ 193 private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>(); 194 195 /** A handler for messages about deprecated usage. 196 */ 197 private MandatoryWarningHandler deprecationHandler; 198 199 /** A handler for messages about deprecated-for-removal usage. 200 */ 201 private MandatoryWarningHandler removalHandler; 202 203 /** A handler for messages about unchecked or unsafe usage. 204 */ 205 private MandatoryWarningHandler uncheckedHandler; 206 207 /** A handler for deferred lint warnings. 208 */ 209 private DeferredLintHandler deferredLintHandler; 210 211 /** Are modules allowed 212 */ 213 private final boolean allowModules; 214 215 /** Are records allowed 216 */ 217 private final boolean allowRecords; 218 219 /** Are sealed classes allowed 220 */ 221 private final boolean allowSealed; 222 223 /** Are value classes allowed 224 */ 225 private final boolean allowValueClasses; 226 227 /** Whether to force suppression of deprecation and preview warnings. 228 * This happens when attributing import statements for JDK 9+. 229 * @see Feature#DEPRECATION_ON_IMPORT 230 */ 231 private boolean importSuppression; 232 233 /* ************************************************************************* 234 * Errors and Warnings 235 **************************************************************************/ 236 237 Lint setLint(Lint newLint) { 238 Lint prev = lint; 239 lint = newLint; 240 return prev; 241 } 242 243 boolean setImportSuppression(boolean newImportSuppression) { 244 boolean prev = importSuppression; 245 importSuppression = newImportSuppression; 246 return prev; 247 } 248 249 MethodSymbol setMethod(MethodSymbol newMethod) { 250 MethodSymbol prev = method; 251 method = newMethod; 252 return prev; 253 } 254 255 /** Warn about deprecated symbol. 256 * @param pos Position to be used for error reporting. 257 * @param sym The deprecated symbol. 258 */ 259 void warnDeprecated(DiagnosticPosition pos, Symbol sym) { 260 if (sym.isDeprecatedForRemoval()) { 261 if (!lint.isSuppressed(LintCategory.REMOVAL)) { 262 if (sym.kind == MDL) { 263 removalHandler.report(pos, LintWarnings.HasBeenDeprecatedForRemovalModule(sym)); 264 } else { 265 removalHandler.report(pos, LintWarnings.HasBeenDeprecatedForRemoval(sym, sym.location())); 266 } 267 } 268 } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) { 269 if (sym.kind == MDL) { 270 deprecationHandler.report(pos, LintWarnings.HasBeenDeprecatedModule(sym)); 271 } else { 272 deprecationHandler.report(pos, LintWarnings.HasBeenDeprecated(sym, sym.location())); 273 } 274 } 275 } 276 277 /** Log a preview warning. 278 * @param pos Position to be used for error reporting. 279 * @param msg A Warning describing the problem. 280 */ 281 public void warnPreviewAPI(DiagnosticPosition pos, LintWarning warnKey) { 282 if (!importSuppression && !lint.isSuppressed(LintCategory.PREVIEW)) 283 preview.reportPreviewWarning(pos, warnKey); 284 } 285 286 /** Log a preview warning. 287 * @param pos Position to be used for error reporting. 288 * @param msg A Warning describing the problem. 289 */ 290 public void warnRestrictedAPI(DiagnosticPosition pos, Symbol sym) { 291 lint.logIfEnabled(pos, LintWarnings.RestrictedMethod(sym.enclClass(), sym)); 292 } 293 294 /** Warn about unchecked operation. 295 * @param pos Position to be used for error reporting. 296 * @param msg A string describing the problem. 297 */ 298 public void warnUnchecked(DiagnosticPosition pos, LintWarning warnKey) { 299 if (!lint.isSuppressed(LintCategory.UNCHECKED)) 300 uncheckedHandler.report(pos, warnKey); 301 } 302 303 /** 304 * Report any deferred diagnostics. 305 */ 306 public void reportDeferredDiagnostics() { 307 deprecationHandler.reportDeferredDiagnostic(); 308 removalHandler.reportDeferredDiagnostic(); 309 uncheckedHandler.reportDeferredDiagnostic(); 310 } 311 312 313 /** Report a failure to complete a class. 314 * @param pos Position to be used for error reporting. 315 * @param ex The failure to report. 316 */ 317 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) { 318 log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue())); 319 return syms.errType; 320 } 321 322 /** Report an error that wrong type tag was found. 323 * @param pos Position to be used for error reporting. 324 * @param required An internationalized string describing the type tag 325 * required. 326 * @param found The type that was found. 327 */ 328 Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) { 329 // this error used to be raised by the parser, 330 // but has been delayed to this point: 331 if (found instanceof Type type && type.hasTag(VOID)) { 332 log.error(pos, Errors.IllegalStartOfType); 333 return syms.errType; 334 } 335 log.error(pos, Errors.TypeFoundReq(found, required)); 336 return types.createErrorType(found instanceof Type type ? type : syms.errType); 337 } 338 339 /** Report duplicate declaration error. 340 */ 341 void duplicateError(DiagnosticPosition pos, Symbol sym) { 342 if (!sym.type.isErroneous()) { 343 Symbol location = sym.location(); 344 if (location.kind == MTH && 345 ((MethodSymbol)location).isStaticOrInstanceInit()) { 346 log.error(pos, 347 Errors.AlreadyDefinedInClinit(kindName(sym), 348 sym, 349 kindName(sym.location()), 350 kindName(sym.location().enclClass()), 351 sym.location().enclClass())); 352 } else { 353 /* dont error if this is a duplicated parameter of a generated canonical constructor 354 * as we should have issued an error for the duplicated fields 355 */ 356 if (location.kind != MTH || 357 ((sym.owner.flags_field & GENERATEDCONSTR) == 0) || 358 ((sym.owner.flags_field & RECORD) == 0)) { 359 log.error(pos, 360 Errors.AlreadyDefined(kindName(sym), 361 sym, 362 kindName(sym.location()), 363 sym.location())); 364 } 365 } 366 } 367 } 368 369 /** Report array/varargs duplicate declaration 370 */ 371 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 372 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 373 log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location())); 374 } 375 } 376 377 /* ************************************************************************ 378 * duplicate declaration checking 379 *************************************************************************/ 380 381 /** Check that variable does not hide variable with same name in 382 * immediately enclosing local scope. 383 * @param pos Position for error reporting. 384 * @param v The symbol. 385 * @param s The scope. 386 */ 387 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) { 388 for (Symbol sym : s.getSymbolsByName(v.name)) { 389 if (sym.owner != v.owner) break; 390 if (sym.kind == VAR && 391 sym.owner.kind.matches(KindSelector.VAL_MTH) && 392 v.name != names.error) { 393 duplicateError(pos, sym); 394 return; 395 } 396 } 397 } 398 399 /** Check that a class or interface does not hide a class or 400 * interface with same name in immediately enclosing local scope. 401 * @param pos Position for error reporting. 402 * @param c The symbol. 403 * @param s The scope. 404 */ 405 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) { 406 for (Symbol sym : s.getSymbolsByName(c.name)) { 407 if (sym.owner != c.owner) break; 408 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) && 409 sym.owner.kind.matches(KindSelector.VAL_MTH) && 410 c.name != names.error) { 411 duplicateError(pos, sym); 412 return; 413 } 414 } 415 } 416 417 /** Check that class does not have the same name as one of 418 * its enclosing classes, or as a class defined in its enclosing scope. 419 * return true if class is unique in its enclosing scope. 420 * @param pos Position for error reporting. 421 * @param name The class name. 422 * @param s The enclosing scope. 423 */ 424 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) { 425 for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) { 426 if (sym.kind == TYP && sym.name != names.error) { 427 duplicateError(pos, sym); 428 return false; 429 } 430 } 431 for (Symbol sym = s.owner; sym != null; sym = sym.owner) { 432 if (sym.kind == TYP && sym.name == name && sym.name != names.error && 433 !sym.isImplicit()) { 434 duplicateError(pos, sym); 435 return true; 436 } 437 } 438 return true; 439 } 440 441 /* ************************************************************************* 442 * Class name generation 443 **************************************************************************/ 444 445 446 private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>(); 447 448 /** Return name of local class. 449 * This is of the form {@code <enclClass> $ n <classname> } 450 * where 451 * enclClass is the flat name of the enclosing class, 452 * classname is the simple name of the local class 453 */ 454 public Name localClassName(ClassSymbol c) { 455 Name enclFlatname = c.owner.enclClass().flatname; 456 String enclFlatnameStr = enclFlatname.toString(); 457 Pair<Name, Name> key = new Pair<>(enclFlatname, c.name); 458 Integer index = localClassNameIndexes.get(key); 459 for (int i = (index == null) ? 1 : index; ; i++) { 460 Name flatname = names.fromString(enclFlatnameStr 461 + syntheticNameChar + i + c.name); 462 if (getCompiled(c.packge().modle, flatname) == null) { 463 localClassNameIndexes.put(key, i + 1); 464 return flatname; 465 } 466 } 467 } 468 469 public void clearLocalClassNameIndexes(ClassSymbol c) { 470 if (c.owner != null && c.owner.kind != NIL) { 471 localClassNameIndexes.remove(new Pair<>( 472 c.owner.enclClass().flatname, c.name)); 473 } 474 } 475 476 public void newRound() { 477 compiled.clear(); 478 localClassNameIndexes.clear(); 479 } 480 481 public void clear() { 482 deprecationHandler.clear(); 483 removalHandler.clear(); 484 uncheckedHandler.clear(); 485 } 486 487 public void putCompiled(ClassSymbol csym) { 488 compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym); 489 } 490 491 public ClassSymbol getCompiled(ClassSymbol csym) { 492 return compiled.get(Pair.of(csym.packge().modle, csym.flatname)); 493 } 494 495 public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) { 496 return compiled.get(Pair.of(msym, flatname)); 497 } 498 499 public void removeCompiled(ClassSymbol csym) { 500 compiled.remove(Pair.of(csym.packge().modle, csym.flatname)); 501 } 502 503 /* ************************************************************************* 504 * Type Checking 505 **************************************************************************/ 506 507 /** 508 * A check context is an object that can be used to perform compatibility 509 * checks - depending on the check context, meaning of 'compatibility' might 510 * vary significantly. 511 */ 512 public interface CheckContext { 513 /** 514 * Is type 'found' compatible with type 'req' in given context 515 */ 516 boolean compatible(Type found, Type req, Warner warn); 517 /** 518 * Report a check error 519 */ 520 void report(DiagnosticPosition pos, JCDiagnostic details); 521 /** 522 * Obtain a warner for this check context 523 */ 524 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req); 525 526 public InferenceContext inferenceContext(); 527 528 public DeferredAttr.DeferredAttrContext deferredAttrContext(); 529 } 530 531 /** 532 * This class represent a check context that is nested within another check 533 * context - useful to check sub-expressions. The default behavior simply 534 * redirects all method calls to the enclosing check context leveraging 535 * the forwarding pattern. 536 */ 537 static class NestedCheckContext implements CheckContext { 538 CheckContext enclosingContext; 539 540 NestedCheckContext(CheckContext enclosingContext) { 541 this.enclosingContext = enclosingContext; 542 } 543 544 public boolean compatible(Type found, Type req, Warner warn) { 545 return enclosingContext.compatible(found, req, warn); 546 } 547 548 public void report(DiagnosticPosition pos, JCDiagnostic details) { 549 enclosingContext.report(pos, details); 550 } 551 552 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) { 553 return enclosingContext.checkWarner(pos, found, req); 554 } 555 556 public InferenceContext inferenceContext() { 557 return enclosingContext.inferenceContext(); 558 } 559 560 public DeferredAttrContext deferredAttrContext() { 561 return enclosingContext.deferredAttrContext(); 562 } 563 } 564 565 /** 566 * Check context to be used when evaluating assignment/return statements 567 */ 568 CheckContext basicHandler = new CheckContext() { 569 public void report(DiagnosticPosition pos, JCDiagnostic details) { 570 log.error(pos, Errors.ProbFoundReq(details)); 571 } 572 public boolean compatible(Type found, Type req, Warner warn) { 573 return types.isAssignable(found, req, warn); 574 } 575 576 public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) { 577 return convertWarner(pos, found, req); 578 } 579 580 public InferenceContext inferenceContext() { 581 return infer.emptyContext; 582 } 583 584 public DeferredAttrContext deferredAttrContext() { 585 return deferredAttr.emptyDeferredAttrContext; 586 } 587 588 @Override 589 public String toString() { 590 return "CheckContext: basicHandler"; 591 } 592 }; 593 594 /** Check that a given type is assignable to a given proto-type. 595 * If it is, return the type, otherwise return errType. 596 * @param pos Position to be used for error reporting. 597 * @param found The type that was found. 598 * @param req The type that was required. 599 */ 600 public Type checkType(DiagnosticPosition pos, Type found, Type req) { 601 return checkType(pos, found, req, basicHandler); 602 } 603 604 Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) { 605 final InferenceContext inferenceContext = checkContext.inferenceContext(); 606 if (inferenceContext.free(req) || inferenceContext.free(found)) { 607 inferenceContext.addFreeTypeListener(List.of(req, found), 608 solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext)); 609 } 610 if (req.hasTag(ERROR)) 611 return req; 612 if (req.hasTag(NONE)) 613 return found; 614 if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) { 615 return found; 616 } else { 617 if (found.isNumeric() && req.isNumeric()) { 618 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req))); 619 return types.createErrorType(found); 620 } 621 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req))); 622 return types.createErrorType(found); 623 } 624 } 625 626 /** Check that a given type can be cast to a given target type. 627 * Return the result of the cast. 628 * @param pos Position to be used for error reporting. 629 * @param found The type that is being cast. 630 * @param req The target type of the cast. 631 */ 632 Type checkCastable(DiagnosticPosition pos, Type found, Type req) { 633 return checkCastable(pos, found, req, basicHandler); 634 } 635 Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) { 636 if (types.isCastable(found, req, castWarner(pos, found, req))) { 637 return req; 638 } else { 639 checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req))); 640 return types.createErrorType(found); 641 } 642 } 643 644 /** Check for redundant casts (i.e. where source type is a subtype of target type) 645 * The problem should only be reported for non-292 cast 646 */ 647 public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) { 648 if (!tree.type.isErroneous() 649 && types.isSameType(tree.expr.type, tree.clazz.type) 650 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz)) 651 && !is292targetTypeCast(tree)) { 652 deferredLintHandler.report(_l -> { 653 lint.logIfEnabled(tree.pos(), LintWarnings.RedundantCast(tree.clazz.type)); 654 }); 655 } 656 } 657 //where 658 private boolean is292targetTypeCast(JCTypeCast tree) { 659 boolean is292targetTypeCast = false; 660 JCExpression expr = TreeInfo.skipParens(tree.expr); 661 if (expr.hasTag(APPLY)) { 662 JCMethodInvocation apply = (JCMethodInvocation)expr; 663 Symbol sym = TreeInfo.symbol(apply.meth); 664 is292targetTypeCast = sym != null && 665 sym.kind == MTH && 666 (sym.flags() & HYPOTHETICAL) != 0; 667 } 668 return is292targetTypeCast; 669 } 670 671 private static final boolean ignoreAnnotatedCasts = true; 672 673 /** Check that a type is within some bounds. 674 * 675 * Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid 676 * type argument. 677 * @param a The type that should be bounded by bs. 678 * @param bound The bound. 679 */ 680 private boolean checkExtends(Type a, Type bound) { 681 if (a.isUnbound()) { 682 return true; 683 } else if (!a.hasTag(WILDCARD)) { 684 a = types.cvarUpperBound(a); 685 return types.isSubtype(a, bound); 686 } else if (a.isExtendsBound()) { 687 return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings); 688 } else if (a.isSuperBound()) { 689 return !types.notSoftSubtype(types.wildLowerBound(a), bound); 690 } 691 return true; 692 } 693 694 /** Check that type is different from 'void'. 695 * @param pos Position to be used for error reporting. 696 * @param t The type to be checked. 697 */ 698 Type checkNonVoid(DiagnosticPosition pos, Type t) { 699 if (t.hasTag(VOID)) { 700 log.error(pos, Errors.VoidNotAllowedHere); 701 return types.createErrorType(t); 702 } else { 703 return t; 704 } 705 } 706 707 Type checkClassOrArrayType(DiagnosticPosition pos, Type t) { 708 if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) { 709 return typeTagError(pos, 710 diags.fragment(Fragments.TypeReqClassArray), 711 asTypeParam(t)); 712 } else { 713 return t; 714 } 715 } 716 717 /** Check that type is a class or interface type. 718 * @param pos Position to be used for error reporting. 719 * @param t The type to be checked. 720 */ 721 Type checkClassType(DiagnosticPosition pos, Type t) { 722 if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) { 723 return typeTagError(pos, 724 diags.fragment(Fragments.TypeReqClass), 725 asTypeParam(t)); 726 } else { 727 return t; 728 } 729 } 730 //where 731 private Object asTypeParam(Type t) { 732 return (t.hasTag(TYPEVAR)) 733 ? diags.fragment(Fragments.TypeParameter(t)) 734 : t; 735 } 736 737 void checkConstraintsOfValueClass(JCClassDecl tree, ClassSymbol c) { 738 DiagnosticPosition pos = tree.pos(); 739 for (Type st : types.closure(c.type)) { 740 if (st == null || st.tsym == null || st.tsym.kind == ERR) 741 continue; 742 if (st.tsym == syms.objectType.tsym || st.tsym == syms.recordType.tsym || st.isInterface()) 743 continue; 744 if (!st.tsym.isAbstract()) { 745 if (c != st.tsym) { 746 log.error(pos, Errors.ConcreteSupertypeForValueClass(c, st)); 747 } 748 continue; 749 } 750 // dealing with an abstract value or value super class below. 751 for (Symbol s : st.tsym.members().getSymbols(NON_RECURSIVE)) { 752 if (s.kind == MTH) { 753 if ((s.flags() & (SYNCHRONIZED | STATIC)) == SYNCHRONIZED) { 754 log.error(pos, Errors.SuperClassMethodCannotBeSynchronized(s, c, st)); 755 } 756 break; 757 } 758 } 759 } 760 } 761 762 /** Check that type is a valid qualifier for a constructor reference expression 763 */ 764 Type checkConstructorRefType(DiagnosticPosition pos, Type t) { 765 t = checkClassOrArrayType(pos, t); 766 if (t.hasTag(CLASS)) { 767 if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 768 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym)); 769 t = types.createErrorType(t); 770 } else if ((t.tsym.flags() & ENUM) != 0) { 771 log.error(pos, Errors.EnumCantBeInstantiated); 772 t = types.createErrorType(t); 773 } else { 774 t = checkClassType(pos, t, true); 775 } 776 } else if (t.hasTag(ARRAY)) { 777 if (!types.isReifiable(((ArrayType)t).elemtype)) { 778 log.error(pos, Errors.GenericArrayCreation); 779 t = types.createErrorType(t); 780 } 781 } 782 return t; 783 } 784 785 /** Check that type is a class or interface type. 786 * @param pos Position to be used for error reporting. 787 * @param t The type to be checked. 788 * @param noBounds True if type bounds are illegal here. 789 */ 790 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) { 791 t = checkClassType(pos, t); 792 if (noBounds && t.isParameterized()) { 793 List<Type> args = t.getTypeArguments(); 794 while (args.nonEmpty()) { 795 if (args.head.hasTag(WILDCARD)) 796 return typeTagError(pos, 797 diags.fragment(Fragments.TypeReqExact), 798 args.head); 799 args = args.tail; 800 } 801 } 802 return t; 803 } 804 805 /** Check that type is a reference type, i.e. a class, interface or array type 806 * or a type variable. 807 * @param pos Position to be used for error reporting. 808 * @param t The type to be checked. 809 */ 810 Type checkRefType(DiagnosticPosition pos, Type t) { 811 if (t.isReference()) 812 return t; 813 else 814 return typeTagError(pos, 815 diags.fragment(Fragments.TypeReqRef), 816 t); 817 } 818 819 /** Check that type is an identity type, i.e. not a value type. 820 * When not discernible statically, give it the benefit of doubt 821 * and defer to runtime. 822 * 823 * @param pos Position to be used for error reporting. 824 * @param t The type to be checked. 825 */ 826 boolean checkIdentityType(DiagnosticPosition pos, Type t) { 827 if (t.hasTag(TYPEVAR)) { 828 t = types.skipTypeVars(t, false); 829 } 830 if (t.isIntersection()) { 831 IntersectionClassType ict = (IntersectionClassType)t; 832 boolean result = true; 833 for (Type component : ict.getExplicitComponents()) { 834 result &= checkIdentityType(pos, component); 835 } 836 return result; 837 } 838 if (t.isPrimitive() || (t.isValueClass() && !t.tsym.isAbstract())) { 839 typeTagError(pos, diags.fragment(Fragments.TypeReqIdentity), t); 840 return false; 841 } 842 return true; 843 } 844 845 /** Check that each type is a reference type, i.e. a class, interface or array type 846 * or a type variable. 847 * @param trees Original trees, used for error reporting. 848 * @param types The types to be checked. 849 */ 850 List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) { 851 List<JCExpression> tl = trees; 852 for (List<Type> l = types; l.nonEmpty(); l = l.tail) { 853 l.head = checkRefType(tl.head.pos(), l.head); 854 tl = tl.tail; 855 } 856 return types; 857 } 858 859 /** Check that type is a null or reference type. 860 * @param pos Position to be used for error reporting. 861 * @param t The type to be checked. 862 */ 863 Type checkNullOrRefType(DiagnosticPosition pos, Type t) { 864 if (t.isReference() || t.hasTag(BOT)) 865 return t; 866 else 867 return typeTagError(pos, 868 diags.fragment(Fragments.TypeReqRef), 869 t); 870 } 871 872 /** Check that flag set does not contain elements of two conflicting sets. s 873 * Return true if it doesn't. 874 * @param pos Position to be used for error reporting. 875 * @param flags The set of flags to be checked. 876 * @param set1 Conflicting flags set #1. 877 * @param set2 Conflicting flags set #2. 878 */ 879 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) { 880 if ((flags & set1) != 0 && (flags & set2) != 0) { 881 log.error(pos, 882 Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)), 883 asFlagSet(TreeInfo.firstFlag(flags & set2)))); 884 return false; 885 } else 886 return true; 887 } 888 889 /** Check that usage of diamond operator is correct (i.e. diamond should not 890 * be used with non-generic classes or in anonymous class creation expressions) 891 */ 892 Type checkDiamond(JCNewClass tree, Type t) { 893 if (!TreeInfo.isDiamond(tree) || 894 t.isErroneous()) { 895 return checkClassType(tree.clazz.pos(), t, true); 896 } else { 897 if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) { 898 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(), 899 Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name))); 900 } 901 if (t.tsym.type.getTypeArguments().isEmpty()) { 902 log.error(tree.clazz.pos(), 903 Errors.CantApplyDiamond1(t, 904 Fragments.DiamondNonGeneric(t))); 905 return types.createErrorType(t); 906 } else if (tree.typeargs != null && 907 tree.typeargs.nonEmpty()) { 908 log.error(tree.clazz.pos(), 909 Errors.CantApplyDiamond1(t, 910 Fragments.DiamondAndExplicitParams(t))); 911 return types.createErrorType(t); 912 } else { 913 return t; 914 } 915 } 916 } 917 918 /** Check that the type inferred using the diamond operator does not contain 919 * non-denotable types such as captured types or intersection types. 920 * @param t the type inferred using the diamond operator 921 * @return the (possibly empty) list of non-denotable types. 922 */ 923 List<Type> checkDiamondDenotable(ClassType t) { 924 ListBuffer<Type> buf = new ListBuffer<>(); 925 for (Type arg : t.allparams()) { 926 if (!checkDenotable(arg)) { 927 buf.append(arg); 928 } 929 } 930 return buf.toList(); 931 } 932 933 public boolean checkDenotable(Type t) { 934 return denotableChecker.visit(t, null); 935 } 936 // where 937 938 /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable 939 * types. The visit methods return false as soon as a non-denotable type is encountered and true 940 * otherwise. 941 */ 942 private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() { 943 @Override 944 public Boolean visitType(Type t, Void s) { 945 return true; 946 } 947 @Override 948 public Boolean visitClassType(ClassType t, Void s) { 949 if (t.isUnion() || t.isIntersection()) { 950 return false; 951 } 952 for (Type targ : t.allparams()) { 953 if (!visit(targ, s)) { 954 return false; 955 } 956 } 957 return true; 958 } 959 960 @Override 961 public Boolean visitTypeVar(TypeVar t, Void s) { 962 /* Any type variable mentioned in the inferred type must have been declared as a type parameter 963 (i.e cannot have been produced by inference (18.4)) 964 */ 965 return (t.tsym.flags() & SYNTHETIC) == 0; 966 } 967 968 @Override 969 public Boolean visitCapturedType(CapturedType t, Void s) { 970 /* Any type variable mentioned in the inferred type must have been declared as a type parameter 971 (i.e cannot have been produced by capture conversion (5.1.10)) 972 */ 973 return false; 974 } 975 976 @Override 977 public Boolean visitArrayType(ArrayType t, Void s) { 978 return visit(t.elemtype, s); 979 } 980 981 @Override 982 public Boolean visitWildcardType(WildcardType t, Void s) { 983 return visit(t.type, s); 984 } 985 }; 986 987 void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) { 988 MethodSymbol m = tree.sym; 989 boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null; 990 Type varargElemType = null; 991 if (m.isVarArgs()) { 992 varargElemType = types.elemtype(tree.params.last().type); 993 } 994 if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) { 995 if (varargElemType != null) { 996 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? 997 diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) : 998 diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m)); 999 log.error(tree, 1000 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, 1001 msg)); 1002 } else { 1003 log.error(tree, 1004 Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, 1005 Fragments.VarargsTrustmeOnNonVarargsMeth(m))); 1006 } 1007 } else if (hasTrustMeAnno && varargElemType != null && 1008 types.isReifiable(varargElemType)) { 1009 lint.logIfEnabled(tree, LintWarnings.VarargsRedundantTrustmeAnno( 1010 syms.trustMeType.tsym, 1011 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType)))); 1012 } 1013 else if (!hasTrustMeAnno && varargElemType != null && 1014 !types.isReifiable(varargElemType)) { 1015 warnUnchecked(tree.params.head.pos(), LintWarnings.UncheckedVarargsNonReifiableType(varargElemType)); 1016 } 1017 } 1018 //where 1019 private boolean isTrustMeAllowedOnMethod(Symbol s) { 1020 return (s.flags() & VARARGS) != 0 && 1021 (s.isConstructor() || 1022 (s.flags() & (STATIC | FINAL | 1023 (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0); 1024 } 1025 1026 Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) { 1027 //check that resulting type is not the null type 1028 if (t.hasTag(BOT)) { 1029 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull)); 1030 return types.createErrorType(t); 1031 } else if (t.hasTag(VOID)) { 1032 log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid)); 1033 return types.createErrorType(t); 1034 } 1035 1036 //upward project the initializer type 1037 return types.upward(t, types.captures(t)).baseType(); 1038 } 1039 1040 Type checkMethod(final Type mtype, 1041 final Symbol sym, 1042 final Env<AttrContext> env, 1043 final List<JCExpression> argtrees, 1044 final List<Type> argtypes, 1045 final boolean useVarargs, 1046 InferenceContext inferenceContext) { 1047 // System.out.println("call : " + env.tree); 1048 // System.out.println("method : " + owntype); 1049 // System.out.println("actuals: " + argtypes); 1050 if (inferenceContext.free(mtype)) { 1051 inferenceContext.addFreeTypeListener(List.of(mtype), 1052 solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext)); 1053 return mtype; 1054 } 1055 Type owntype = mtype; 1056 List<Type> formals = owntype.getParameterTypes(); 1057 List<Type> nonInferred = sym.type.getParameterTypes(); 1058 if (nonInferred.length() != formals.length()) nonInferred = formals; 1059 Type last = useVarargs ? formals.last() : null; 1060 if (sym.name == names.init && sym.owner == syms.enumSym) { 1061 formals = formals.tail.tail; 1062 nonInferred = nonInferred.tail.tail; 1063 } 1064 if ((sym.flags() & ANONCONSTR_BASED) != 0) { 1065 formals = formals.tail; 1066 nonInferred = nonInferred.tail; 1067 } 1068 List<JCExpression> args = argtrees; 1069 if (args != null) { 1070 //this is null when type-checking a method reference 1071 while (formals.head != last) { 1072 JCTree arg = args.head; 1073 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head); 1074 assertConvertible(arg, arg.type, formals.head, warn); 1075 args = args.tail; 1076 formals = formals.tail; 1077 nonInferred = nonInferred.tail; 1078 } 1079 if (useVarargs) { 1080 Type varArg = types.elemtype(last); 1081 while (args.tail != null) { 1082 JCTree arg = args.head; 1083 Warner warn = convertWarner(arg.pos(), arg.type, varArg); 1084 assertConvertible(arg, arg.type, varArg, warn); 1085 args = args.tail; 1086 } 1087 } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) { 1088 // non-varargs call to varargs method 1089 Type varParam = owntype.getParameterTypes().last(); 1090 Type lastArg = argtypes.last(); 1091 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) && 1092 !types.isSameType(types.erasure(varParam), types.erasure(lastArg))) 1093 log.warning(argtrees.last().pos(), 1094 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam)); 1095 } 1096 } 1097 if (useVarargs) { 1098 Type argtype = owntype.getParameterTypes().last(); 1099 if (!types.isReifiable(argtype) && 1100 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null || 1101 !isTrustMeAllowedOnMethod(sym))) { 1102 warnUnchecked(env.tree.pos(), LintWarnings.UncheckedGenericArrayCreation(argtype)); 1103 } 1104 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype)); 1105 } 1106 return owntype; 1107 } 1108 //where 1109 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) { 1110 if (types.isConvertible(actual, formal, warn)) 1111 return; 1112 1113 if (formal.isCompound() 1114 && types.isSubtype(actual, types.supertype(formal)) 1115 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn)) 1116 return; 1117 } 1118 1119 /** 1120 * Check that type 't' is a valid instantiation of a generic class 1121 * (see JLS 4.5) 1122 * 1123 * @param t class type to be checked 1124 * @return true if 't' is well-formed 1125 */ 1126 public boolean checkValidGenericType(Type t) { 1127 return firstIncompatibleTypeArg(t) == null; 1128 } 1129 //WHERE 1130 private Type firstIncompatibleTypeArg(Type type) { 1131 List<Type> formals = type.tsym.type.allparams(); 1132 List<Type> actuals = type.allparams(); 1133 List<Type> args = type.getTypeArguments(); 1134 List<Type> forms = type.tsym.type.getTypeArguments(); 1135 ListBuffer<Type> bounds_buf = new ListBuffer<>(); 1136 1137 // For matching pairs of actual argument types `a' and 1138 // formal type parameters with declared bound `b' ... 1139 while (args.nonEmpty() && forms.nonEmpty()) { 1140 // exact type arguments needs to know their 1141 // bounds (for upper and lower bound 1142 // calculations). So we create new bounds where 1143 // type-parameters are replaced with actuals argument types. 1144 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals)); 1145 args = args.tail; 1146 forms = forms.tail; 1147 } 1148 1149 args = type.getTypeArguments(); 1150 List<Type> tvars_cap = types.substBounds(formals, 1151 formals, 1152 types.capture(type).allparams()); 1153 while (args.nonEmpty() && tvars_cap.nonEmpty()) { 1154 // Let the actual arguments know their bound 1155 args.head.withTypeVar((TypeVar)tvars_cap.head); 1156 args = args.tail; 1157 tvars_cap = tvars_cap.tail; 1158 } 1159 1160 args = type.getTypeArguments(); 1161 List<Type> bounds = bounds_buf.toList(); 1162 1163 while (args.nonEmpty() && bounds.nonEmpty()) { 1164 Type actual = args.head; 1165 if (!isTypeArgErroneous(actual) && 1166 !bounds.head.isErroneous() && 1167 !checkExtends(actual, bounds.head)) { 1168 return args.head; 1169 } 1170 args = args.tail; 1171 bounds = bounds.tail; 1172 } 1173 1174 args = type.getTypeArguments(); 1175 bounds = bounds_buf.toList(); 1176 1177 for (Type arg : types.capture(type).getTypeArguments()) { 1178 if (arg.hasTag(TYPEVAR) && 1179 arg.getUpperBound().isErroneous() && 1180 !bounds.head.isErroneous() && 1181 !isTypeArgErroneous(args.head)) { 1182 return args.head; 1183 } 1184 bounds = bounds.tail; 1185 args = args.tail; 1186 } 1187 1188 return null; 1189 } 1190 //where 1191 boolean isTypeArgErroneous(Type t) { 1192 return isTypeArgErroneous.visit(t); 1193 } 1194 1195 Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() { 1196 public Boolean visitType(Type t, Void s) { 1197 return t.isErroneous(); 1198 } 1199 @Override 1200 public Boolean visitTypeVar(TypeVar t, Void s) { 1201 return visit(t.getUpperBound()); 1202 } 1203 @Override 1204 public Boolean visitCapturedType(CapturedType t, Void s) { 1205 return visit(t.getUpperBound()) || 1206 visit(t.getLowerBound()); 1207 } 1208 @Override 1209 public Boolean visitWildcardType(WildcardType t, Void s) { 1210 return visit(t.type); 1211 } 1212 }; 1213 1214 /** Check that given modifiers are legal for given symbol and 1215 * return modifiers together with any implicit modifiers for that symbol. 1216 * Warning: we can't use flags() here since this method 1217 * is called during class enter, when flags() would cause a premature 1218 * completion. 1219 * @param flags The set of modifiers given in a definition. 1220 * @param sym The defined symbol. 1221 * @param tree The declaration 1222 */ 1223 long checkFlags(long flags, Symbol sym, JCTree tree) { 1224 final DiagnosticPosition pos = tree.pos(); 1225 long mask; 1226 long implicit = 0; 1227 1228 switch (sym.kind) { 1229 case VAR: 1230 if (TreeInfo.isReceiverParam(tree)) 1231 mask = ReceiverParamFlags; 1232 else if (sym.owner.kind != TYP) 1233 mask = LocalVarFlags; 1234 else if ((sym.owner.flags_field & INTERFACE) != 0) 1235 mask = implicit = InterfaceVarFlags; 1236 else { 1237 boolean isInstanceField = (flags & STATIC) == 0; 1238 boolean isInstanceFieldOfValueClass = isInstanceField && sym.owner.type.isValueClass(); 1239 boolean isRecordField = isInstanceField && (sym.owner.flags_field & RECORD) != 0; 1240 if (allowValueClasses && (isInstanceFieldOfValueClass || isRecordField)) { 1241 implicit |= FINAL | STRICT; 1242 mask = ValueFieldFlags; 1243 } else { 1244 mask = VarFlags; 1245 } 1246 } 1247 break; 1248 case MTH: 1249 if (sym.name == names.init) { 1250 if ((sym.owner.flags_field & ENUM) != 0) { 1251 // enum constructors cannot be declared public or 1252 // protected and must be implicitly or explicitly 1253 // private 1254 implicit = PRIVATE; 1255 mask = PRIVATE; 1256 } else 1257 mask = ConstructorFlags; 1258 } else if ((sym.owner.flags_field & INTERFACE) != 0) { 1259 if ((sym.owner.flags_field & ANNOTATION) != 0) { 1260 mask = AnnotationTypeElementMask; 1261 implicit = PUBLIC | ABSTRACT; 1262 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) { 1263 mask = InterfaceMethodMask; 1264 implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC; 1265 if ((flags & DEFAULT) != 0) { 1266 implicit |= ABSTRACT; 1267 } 1268 } else { 1269 mask = implicit = InterfaceMethodFlags; 1270 } 1271 } else if ((sym.owner.flags_field & RECORD) != 0) { 1272 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ? 1273 RecordMethodFlags & ~SYNCHRONIZED : RecordMethodFlags; 1274 } else { 1275 // value objects do not have an associated monitor/lock 1276 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ? 1277 MethodFlags & ~SYNCHRONIZED : MethodFlags; 1278 } 1279 if ((flags & STRICTFP) != 0) { 1280 warnOnExplicitStrictfp(tree); 1281 } 1282 // Imply STRICTFP if owner has STRICTFP set. 1283 if (((flags|implicit) & Flags.ABSTRACT) == 0 || 1284 ((flags) & Flags.DEFAULT) != 0) 1285 implicit |= sym.owner.flags_field & STRICTFP; 1286 break; 1287 case TYP: 1288 if (sym.owner.kind.matches(KindSelector.VAL_MTH) || 1289 (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) { 1290 boolean implicitlyStatic = !sym.isAnonymous() && 1291 ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0); 1292 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic; 1293 // local statics are allowed only if records are allowed too 1294 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedStaticLocalClassFlags : ExtendedLocalClassFlags; 1295 implicit = implicitlyStatic ? STATIC : implicit; 1296 } else if (sym.owner.kind == TYP) { 1297 // statics in inner classes are allowed only if records are allowed too 1298 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags; 1299 if (sym.owner.owner.kind == PCK || 1300 (sym.owner.flags_field & STATIC) != 0) { 1301 mask |= STATIC; 1302 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) { 1303 log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses); 1304 } 1305 // Nested interfaces and enums are always STATIC (Spec ???) 1306 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC; 1307 } else { 1308 mask = ExtendedClassFlags; 1309 } 1310 if ((flags & (VALUE_CLASS | SEALED | ABSTRACT)) == (VALUE_CLASS | SEALED) || 1311 (flags & (VALUE_CLASS | NON_SEALED | ABSTRACT)) == (VALUE_CLASS | NON_SEALED)) { 1312 log.error(pos, Errors.NonAbstractValueClassCantBeSealedOrNonSealed); 1313 } 1314 // Interfaces are always ABSTRACT 1315 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT; 1316 1317 if ((flags & (INTERFACE | VALUE_CLASS)) == 0) { 1318 implicit |= IDENTITY_TYPE; 1319 } 1320 1321 if ((flags & ENUM) != 0) { 1322 // enums can't be declared abstract, final, sealed or non-sealed or value 1323 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED | VALUE_CLASS); 1324 implicit |= implicitEnumFinalFlag(tree); 1325 } 1326 if ((flags & RECORD) != 0) { 1327 // records can't be declared abstract 1328 mask &= ~ABSTRACT; 1329 implicit |= FINAL; 1330 } 1331 if ((flags & STRICTFP) != 0) { 1332 warnOnExplicitStrictfp(tree); 1333 } 1334 // Imply STRICTFP if owner has STRICTFP set. 1335 implicit |= sym.owner.flags_field & STRICTFP; 1336 1337 // concrete value classes are implicitly final 1338 if ((flags & (ABSTRACT | INTERFACE | VALUE_CLASS)) == VALUE_CLASS) { 1339 implicit |= FINAL; 1340 } 1341 break; 1342 default: 1343 throw new AssertionError(); 1344 } 1345 long illegal = flags & ExtendedStandardFlags & ~mask; 1346 if (illegal != 0) { 1347 if ((illegal & INTERFACE) != 0) { 1348 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere); 1349 mask |= INTERFACE; 1350 } 1351 else { 1352 log.error(pos, 1353 Errors.ModNotAllowedHere(asFlagSet(illegal))); 1354 } 1355 } else if ((sym.kind == TYP || 1356 // ISSUE: Disallowing abstract&private is no longer appropriate 1357 // in the presence of inner classes. Should it be deleted here? 1358 checkDisjoint(pos, flags, 1359 ABSTRACT, 1360 PRIVATE | STATIC | DEFAULT)) 1361 && 1362 checkDisjoint(pos, flags, 1363 STATIC | PRIVATE, 1364 DEFAULT) 1365 && 1366 checkDisjoint(pos, flags, 1367 ABSTRACT | INTERFACE, 1368 FINAL | NATIVE | SYNCHRONIZED) 1369 && 1370 checkDisjoint(pos, flags, 1371 PUBLIC, 1372 PRIVATE | PROTECTED) 1373 && 1374 checkDisjoint(pos, flags, 1375 PRIVATE, 1376 PUBLIC | PROTECTED) 1377 && 1378 // we are using `implicit` here as instance fields of value classes are implicitly final 1379 checkDisjoint(pos, flags | implicit, 1380 FINAL, 1381 VOLATILE) 1382 && 1383 (sym.kind == TYP || 1384 checkDisjoint(pos, flags, 1385 ABSTRACT | NATIVE, 1386 STRICTFP)) 1387 && checkDisjoint(pos, flags, 1388 FINAL, 1389 SEALED | NON_SEALED) 1390 && checkDisjoint(pos, flags, 1391 SEALED, 1392 FINAL | NON_SEALED) 1393 && checkDisjoint(pos, flags, 1394 SEALED, 1395 ANNOTATION) 1396 && checkDisjoint(pos, flags, 1397 VALUE_CLASS, 1398 ANNOTATION) 1399 && checkDisjoint(pos, flags, 1400 VALUE_CLASS, 1401 INTERFACE) ) { 1402 // skip 1403 } 1404 return flags & (mask | ~ExtendedStandardFlags) | implicit; 1405 } 1406 1407 private void warnOnExplicitStrictfp(JCTree tree) { 1408 deferredLintHandler.push(tree); 1409 try { 1410 deferredLintHandler.report(_ -> lint.logIfEnabled(tree.pos(), LintWarnings.Strictfp)); 1411 } finally { 1412 deferredLintHandler.pop(); 1413 } 1414 } 1415 1416 1417 /** Determine if this enum should be implicitly final. 1418 * 1419 * If the enum has no specialized enum constants, it is final. 1420 * 1421 * If the enum does have specialized enum constants, it is 1422 * <i>not</i> final. 1423 */ 1424 private long implicitEnumFinalFlag(JCTree tree) { 1425 if (!tree.hasTag(CLASSDEF)) return 0; 1426 class SpecialTreeVisitor extends JCTree.Visitor { 1427 boolean specialized; 1428 SpecialTreeVisitor() { 1429 this.specialized = false; 1430 } 1431 1432 @Override 1433 public void visitTree(JCTree tree) { /* no-op */ } 1434 1435 @Override 1436 public void visitVarDef(JCVariableDecl tree) { 1437 if ((tree.mods.flags & ENUM) != 0) { 1438 if (tree.init instanceof JCNewClass newClass && newClass.def != null) { 1439 specialized = true; 1440 } 1441 } 1442 } 1443 } 1444 1445 SpecialTreeVisitor sts = new SpecialTreeVisitor(); 1446 JCClassDecl cdef = (JCClassDecl) tree; 1447 for (JCTree defs: cdef.defs) { 1448 defs.accept(sts); 1449 if (sts.specialized) return allowSealed ? SEALED : 0; 1450 } 1451 return FINAL; 1452 } 1453 1454 /* ************************************************************************* 1455 * Type Validation 1456 **************************************************************************/ 1457 1458 /** Validate a type expression. That is, 1459 * check that all type arguments of a parametric type are within 1460 * their bounds. This must be done in a second phase after type attribution 1461 * since a class might have a subclass as type parameter bound. E.g: 1462 * 1463 * <pre>{@code 1464 * class B<A extends C> { ... } 1465 * class C extends B<C> { ... } 1466 * }</pre> 1467 * 1468 * and we can't make sure that the bound is already attributed because 1469 * of possible cycles. 1470 * 1471 * Visitor method: Validate a type expression, if it is not null, catching 1472 * and reporting any completion failures. 1473 */ 1474 void validate(JCTree tree, Env<AttrContext> env) { 1475 validate(tree, env, true); 1476 } 1477 void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) { 1478 new Validator(env).validateTree(tree, checkRaw, true); 1479 } 1480 1481 /** Visitor method: Validate a list of type expressions. 1482 */ 1483 void validate(List<? extends JCTree> trees, Env<AttrContext> env) { 1484 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 1485 validate(l.head, env); 1486 } 1487 1488 /** A visitor class for type validation. 1489 */ 1490 class Validator extends JCTree.Visitor { 1491 1492 boolean checkRaw; 1493 boolean isOuter; 1494 Env<AttrContext> env; 1495 1496 Validator(Env<AttrContext> env) { 1497 this.env = env; 1498 } 1499 1500 @Override 1501 public void visitTypeArray(JCArrayTypeTree tree) { 1502 validateTree(tree.elemtype, checkRaw, isOuter); 1503 } 1504 1505 @Override 1506 public void visitTypeApply(JCTypeApply tree) { 1507 if (tree.type.hasTag(CLASS)) { 1508 List<JCExpression> args = tree.arguments; 1509 List<Type> forms = tree.type.tsym.type.getTypeArguments(); 1510 1511 Type incompatibleArg = firstIncompatibleTypeArg(tree.type); 1512 if (incompatibleArg != null) { 1513 for (JCTree arg : tree.arguments) { 1514 if (arg.type == incompatibleArg) { 1515 log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head)); 1516 } 1517 forms = forms.tail; 1518 } 1519 } 1520 1521 forms = tree.type.tsym.type.getTypeArguments(); 1522 1523 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class; 1524 1525 // For matching pairs of actual argument types `a' and 1526 // formal type parameters with declared bound `b' ... 1527 while (args.nonEmpty() && forms.nonEmpty()) { 1528 validateTree(args.head, 1529 !(isOuter && is_java_lang_Class), 1530 false); 1531 args = args.tail; 1532 forms = forms.tail; 1533 } 1534 1535 // Check that this type is either fully parameterized, or 1536 // not parameterized at all. 1537 if (tree.type.getEnclosingType().isRaw()) 1538 log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam); 1539 if (tree.clazz.hasTag(SELECT)) 1540 visitSelectInternal((JCFieldAccess)tree.clazz); 1541 } 1542 } 1543 1544 @Override 1545 public void visitTypeParameter(JCTypeParameter tree) { 1546 validateTrees(tree.bounds, true, isOuter); 1547 checkClassBounds(tree.pos(), tree.type); 1548 } 1549 1550 @Override 1551 public void visitWildcard(JCWildcard tree) { 1552 if (tree.inner != null) 1553 validateTree(tree.inner, true, isOuter); 1554 } 1555 1556 @Override 1557 public void visitSelect(JCFieldAccess tree) { 1558 if (tree.type.hasTag(CLASS)) { 1559 visitSelectInternal(tree); 1560 1561 // Check that this type is either fully parameterized, or 1562 // not parameterized at all. 1563 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty()) 1564 log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing); 1565 } 1566 } 1567 1568 public void visitSelectInternal(JCFieldAccess tree) { 1569 if (tree.type.tsym.isStatic() && 1570 tree.selected.type.isParameterized()) { 1571 // The enclosing type is not a class, so we are 1572 // looking at a static member type. However, the 1573 // qualifying expression is parameterized. 1574 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType); 1575 } else { 1576 // otherwise validate the rest of the expression 1577 tree.selected.accept(this); 1578 } 1579 } 1580 1581 @Override 1582 public void visitAnnotatedType(JCAnnotatedType tree) { 1583 tree.underlyingType.accept(this); 1584 } 1585 1586 @Override 1587 public void visitTypeIdent(JCPrimitiveTypeTree that) { 1588 if (that.type.hasTag(TypeTag.VOID)) { 1589 log.error(that.pos(), Errors.VoidNotAllowedHere); 1590 } 1591 super.visitTypeIdent(that); 1592 } 1593 1594 /** Default visitor method: do nothing. 1595 */ 1596 @Override 1597 public void visitTree(JCTree tree) { 1598 } 1599 1600 public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) { 1601 if (tree != null) { 1602 boolean prevCheckRaw = this.checkRaw; 1603 this.checkRaw = checkRaw; 1604 this.isOuter = isOuter; 1605 1606 try { 1607 tree.accept(this); 1608 if (checkRaw) 1609 checkRaw(tree, env); 1610 } catch (CompletionFailure ex) { 1611 completionError(tree.pos(), ex); 1612 } finally { 1613 this.checkRaw = prevCheckRaw; 1614 } 1615 } 1616 } 1617 1618 public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) { 1619 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 1620 validateTree(l.head, checkRaw, isOuter); 1621 } 1622 } 1623 1624 void checkRaw(JCTree tree, Env<AttrContext> env) { 1625 if (tree.type.hasTag(CLASS) && 1626 !TreeInfo.isDiamond(tree) && 1627 !withinAnonConstr(env) && 1628 tree.type.isRaw()) { 1629 lint.logIfEnabled(tree.pos(), LintWarnings.RawClassUse(tree.type, tree.type.tsym.type)); 1630 } 1631 } 1632 //where 1633 private boolean withinAnonConstr(Env<AttrContext> env) { 1634 return env.enclClass.name.isEmpty() && 1635 env.enclMethod != null && env.enclMethod.name == names.init; 1636 } 1637 1638 /* ************************************************************************* 1639 * Exception checking 1640 **************************************************************************/ 1641 1642 /* The following methods treat classes as sets that contain 1643 * the class itself and all their subclasses 1644 */ 1645 1646 /** Is given type a subtype of some of the types in given list? 1647 */ 1648 boolean subset(Type t, List<Type> ts) { 1649 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 1650 if (types.isSubtype(t, l.head)) return true; 1651 return false; 1652 } 1653 1654 /** Is given type a subtype or supertype of 1655 * some of the types in given list? 1656 */ 1657 boolean intersects(Type t, List<Type> ts) { 1658 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 1659 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true; 1660 return false; 1661 } 1662 1663 /** Add type set to given type list, unless it is a subclass of some class 1664 * in the list. 1665 */ 1666 List<Type> incl(Type t, List<Type> ts) { 1667 return subset(t, ts) ? ts : excl(t, ts).prepend(t); 1668 } 1669 1670 /** Remove type set from type set list. 1671 */ 1672 List<Type> excl(Type t, List<Type> ts) { 1673 if (ts.isEmpty()) { 1674 return ts; 1675 } else { 1676 List<Type> ts1 = excl(t, ts.tail); 1677 if (types.isSubtype(ts.head, t)) return ts1; 1678 else if (ts1 == ts.tail) return ts; 1679 else return ts1.prepend(ts.head); 1680 } 1681 } 1682 1683 /** Form the union of two type set lists. 1684 */ 1685 List<Type> union(List<Type> ts1, List<Type> ts2) { 1686 List<Type> ts = ts1; 1687 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1688 ts = incl(l.head, ts); 1689 return ts; 1690 } 1691 1692 /** Form the difference of two type lists. 1693 */ 1694 List<Type> diff(List<Type> ts1, List<Type> ts2) { 1695 List<Type> ts = ts1; 1696 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1697 ts = excl(l.head, ts); 1698 return ts; 1699 } 1700 1701 /** Form the intersection of two type lists. 1702 */ 1703 public List<Type> intersect(List<Type> ts1, List<Type> ts2) { 1704 List<Type> ts = List.nil(); 1705 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail) 1706 if (subset(l.head, ts2)) ts = incl(l.head, ts); 1707 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 1708 if (subset(l.head, ts1)) ts = incl(l.head, ts); 1709 return ts; 1710 } 1711 1712 /** Is exc an exception symbol that need not be declared? 1713 */ 1714 boolean isUnchecked(ClassSymbol exc) { 1715 return 1716 exc.kind == ERR || 1717 exc.isSubClass(syms.errorType.tsym, types) || 1718 exc.isSubClass(syms.runtimeExceptionType.tsym, types); 1719 } 1720 1721 /** Is exc an exception type that need not be declared? 1722 */ 1723 boolean isUnchecked(Type exc) { 1724 return 1725 (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) : 1726 (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) : 1727 exc.hasTag(BOT); 1728 } 1729 1730 boolean isChecked(Type exc) { 1731 return !isUnchecked(exc); 1732 } 1733 1734 /** Same, but handling completion failures. 1735 */ 1736 boolean isUnchecked(DiagnosticPosition pos, Type exc) { 1737 try { 1738 return isUnchecked(exc); 1739 } catch (CompletionFailure ex) { 1740 completionError(pos, ex); 1741 return true; 1742 } 1743 } 1744 1745 /** Is exc handled by given exception list? 1746 */ 1747 boolean isHandled(Type exc, List<Type> handled) { 1748 return isUnchecked(exc) || subset(exc, handled); 1749 } 1750 1751 /** Return all exceptions in thrown list that are not in handled list. 1752 * @param thrown The list of thrown exceptions. 1753 * @param handled The list of handled exceptions. 1754 */ 1755 List<Type> unhandled(List<Type> thrown, List<Type> handled) { 1756 List<Type> unhandled = List.nil(); 1757 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1758 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head); 1759 return unhandled; 1760 } 1761 1762 /* ************************************************************************* 1763 * Overriding/Implementation checking 1764 **************************************************************************/ 1765 1766 /** The level of access protection given by a flag set, 1767 * where PRIVATE is highest and PUBLIC is lowest. 1768 */ 1769 static int protection(long flags) { 1770 switch ((short)(flags & AccessFlags)) { 1771 case PRIVATE: return 3; 1772 case PROTECTED: return 1; 1773 default: 1774 case PUBLIC: return 0; 1775 case 0: return 2; 1776 } 1777 } 1778 1779 /** A customized "cannot override" error message. 1780 * @param m The overriding method. 1781 * @param other The overridden method. 1782 * @return An internationalized string. 1783 */ 1784 Fragment cannotOverride(MethodSymbol m, MethodSymbol other) { 1785 Symbol mloc = m.location(); 1786 Symbol oloc = other.location(); 1787 1788 if ((other.owner.flags() & INTERFACE) == 0) 1789 return Fragments.CantOverride(m, mloc, other, oloc); 1790 else if ((m.owner.flags() & INTERFACE) == 0) 1791 return Fragments.CantImplement(m, mloc, other, oloc); 1792 else 1793 return Fragments.ClashesWith(m, mloc, other, oloc); 1794 } 1795 1796 /** A customized "override" warning message. 1797 * @param m The overriding method. 1798 * @param other The overridden method. 1799 * @return An internationalized string. 1800 */ 1801 Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) { 1802 Symbol mloc = m.location(); 1803 Symbol oloc = other.location(); 1804 1805 if ((other.owner.flags() & INTERFACE) == 0) 1806 return Fragments.UncheckedOverride(m, mloc, other, oloc); 1807 else if ((m.owner.flags() & INTERFACE) == 0) 1808 return Fragments.UncheckedImplement(m, mloc, other, oloc); 1809 else 1810 return Fragments.UncheckedClashWith(m, mloc, other, oloc); 1811 } 1812 1813 /** A customized "override" warning message. 1814 * @param m The overriding method. 1815 * @param other The overridden method. 1816 * @return An internationalized string. 1817 */ 1818 Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) { 1819 Symbol mloc = m.location(); 1820 Symbol oloc = other.location(); 1821 1822 if ((other.owner.flags() & INTERFACE) == 0) 1823 return Fragments.VarargsOverride(m, mloc, other, oloc); 1824 else if ((m.owner.flags() & INTERFACE) == 0) 1825 return Fragments.VarargsImplement(m, mloc, other, oloc); 1826 else 1827 return Fragments.VarargsClashWith(m, mloc, other, oloc); 1828 } 1829 1830 /** Check that this method conforms with overridden method 'other'. 1831 * where `origin' is the class where checking started. 1832 * Complications: 1833 * (1) Do not check overriding of synthetic methods 1834 * (reason: they might be final). 1835 * todo: check whether this is still necessary. 1836 * (2) Admit the case where an interface proxy throws fewer exceptions 1837 * than the method it implements. Augment the proxy methods with the 1838 * undeclared exceptions in this case. 1839 * (3) When generics are enabled, admit the case where an interface proxy 1840 * has a result type 1841 * extended by the result type of the method it implements. 1842 * Change the proxies result type to the smaller type in this case. 1843 * 1844 * @param tree The tree from which positions 1845 * are extracted for errors. 1846 * @param m The overriding method. 1847 * @param other The overridden method. 1848 * @param origin The class of which the overriding method 1849 * is a member. 1850 */ 1851 void checkOverride(JCTree tree, 1852 MethodSymbol m, 1853 MethodSymbol other, 1854 ClassSymbol origin) { 1855 // Don't check overriding of synthetic methods or by bridge methods. 1856 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) { 1857 return; 1858 } 1859 1860 // Error if static method overrides instance method (JLS 8.4.8.2). 1861 if ((m.flags() & STATIC) != 0 && 1862 (other.flags() & STATIC) == 0) { 1863 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1864 Errors.OverrideStatic(cannotOverride(m, other))); 1865 m.flags_field |= BAD_OVERRIDE; 1866 return; 1867 } 1868 1869 // Error if instance method overrides static or final 1870 // method (JLS 8.4.8.1). 1871 if ((other.flags() & FINAL) != 0 || 1872 (m.flags() & STATIC) == 0 && 1873 (other.flags() & STATIC) != 0) { 1874 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1875 Errors.OverrideMeth(cannotOverride(m, other), 1876 asFlagSet(other.flags() & (FINAL | STATIC)))); 1877 m.flags_field |= BAD_OVERRIDE; 1878 return; 1879 } 1880 1881 if ((m.owner.flags() & ANNOTATION) != 0) { 1882 // handled in validateAnnotationMethod 1883 return; 1884 } 1885 1886 // Error if overriding method has weaker access (JLS 8.4.8.3). 1887 if (protection(m.flags()) > protection(other.flags())) { 1888 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1889 (other.flags() & AccessFlags) == 0 ? 1890 Errors.OverrideWeakerAccess(cannotOverride(m, other), 1891 "package") : 1892 Errors.OverrideWeakerAccess(cannotOverride(m, other), 1893 asFlagSet(other.flags() & AccessFlags))); 1894 m.flags_field |= BAD_OVERRIDE; 1895 return; 1896 } 1897 1898 if (shouldCheckPreview(m, other, origin)) { 1899 checkPreview(TreeInfo.diagnosticPositionFor(m, tree), 1900 m, origin.type, other); 1901 } 1902 1903 Type mt = types.memberType(origin.type, m); 1904 Type ot = types.memberType(origin.type, other); 1905 // Error if overriding result type is different 1906 // (or, in the case of generics mode, not a subtype) of 1907 // overridden result type. We have to rename any type parameters 1908 // before comparing types. 1909 List<Type> mtvars = mt.getTypeArguments(); 1910 List<Type> otvars = ot.getTypeArguments(); 1911 Type mtres = mt.getReturnType(); 1912 Type otres = types.subst(ot.getReturnType(), otvars, mtvars); 1913 1914 overrideWarner.clear(); 1915 boolean resultTypesOK = 1916 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner); 1917 if (!resultTypesOK) { 1918 if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) { 1919 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1920 Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other, 1921 other.location()), mtres, otres)); 1922 m.flags_field |= BAD_OVERRIDE; 1923 } else { 1924 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1925 Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres)); 1926 m.flags_field |= BAD_OVERRIDE; 1927 } 1928 return; 1929 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 1930 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1931 LintWarnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres)); 1932 } 1933 1934 // Error if overriding method throws an exception not reported 1935 // by overridden method. 1936 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars); 1937 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown)); 1938 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown); 1939 if (unhandledErased.nonEmpty()) { 1940 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1941 Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head)); 1942 m.flags_field |= BAD_OVERRIDE; 1943 return; 1944 } 1945 else if (unhandledUnerased.nonEmpty()) { 1946 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1947 LintWarnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head)); 1948 return; 1949 } 1950 1951 // Optional warning if varargs don't agree 1952 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)) { 1953 lint.logIfEnabled(TreeInfo.diagnosticPositionFor(m, tree), 1954 ((m.flags() & Flags.VARARGS) != 0) 1955 ? LintWarnings.OverrideVarargsMissing(varargsOverrides(m, other)) 1956 : LintWarnings.OverrideVarargsExtra(varargsOverrides(m, other))); 1957 } 1958 1959 // Warn if instance method overrides bridge method (compiler spec ??) 1960 if ((other.flags() & BRIDGE) != 0) { 1961 log.warning(TreeInfo.diagnosticPositionFor(m, tree), 1962 Warnings.OverrideBridge(uncheckedOverrides(m, other))); 1963 } 1964 1965 // Warn if a deprecated method overridden by a non-deprecated one. 1966 if (!isDeprecatedOverrideIgnorable(other, origin)) { 1967 Lint prevLint = setLint(lint.augment(m)); 1968 try { 1969 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other); 1970 } finally { 1971 setLint(prevLint); 1972 } 1973 } 1974 } 1975 // where 1976 private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) { 1977 if (m.owner != origin || 1978 //performance - only do the expensive checks when the overridden method is a Preview API: 1979 ((other.flags() & PREVIEW_API) == 0 && 1980 (other.owner.flags() & PREVIEW_API) == 0)) { 1981 return false; 1982 } 1983 1984 for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) { 1985 if (m != s && m.overrides(s, origin, types, false)) { 1986 //only produce preview warnings or errors if "m" immediatelly overrides "other" 1987 //without intermediate overriding methods: 1988 return s == other; 1989 } 1990 } 1991 1992 return false; 1993 } 1994 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) { 1995 // If the method, m, is defined in an interface, then ignore the issue if the method 1996 // is only inherited via a supertype and also implemented in the supertype, 1997 // because in that case, we will rediscover the issue when examining the method 1998 // in the supertype. 1999 // If the method, m, is not defined in an interface, then the only time we need to 2000 // address the issue is when the method is the supertype implementation: any other 2001 // case, we will have dealt with when examining the supertype classes 2002 ClassSymbol mc = m.enclClass(); 2003 Type st = types.supertype(origin.type); 2004 if (!st.hasTag(CLASS)) 2005 return true; 2006 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false); 2007 2008 if (mc != null && ((mc.flags() & INTERFACE) != 0)) { 2009 List<Type> intfs = types.interfaces(origin.type); 2010 return (intfs.contains(mc.type) ? false : (stimpl != null)); 2011 } 2012 else 2013 return (stimpl != m); 2014 } 2015 2016 2017 // used to check if there were any unchecked conversions 2018 Warner overrideWarner = new Warner(); 2019 2020 /** Check that a class does not inherit two concrete methods 2021 * with the same signature. 2022 * @param pos Position to be used for error reporting. 2023 * @param site The class type to be checked. 2024 */ 2025 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) { 2026 Type sup = types.supertype(site); 2027 if (!sup.hasTag(CLASS)) return; 2028 2029 for (Type t1 = sup; 2030 t1.hasTag(CLASS) && t1.tsym.type.isParameterized(); 2031 t1 = types.supertype(t1)) { 2032 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 2033 if (s1.kind != MTH || 2034 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 2035 !s1.isInheritedIn(site.tsym, types) || 2036 ((MethodSymbol)s1).implementation(site.tsym, 2037 types, 2038 true) != s1) 2039 continue; 2040 Type st1 = types.memberType(t1, s1); 2041 int s1ArgsLength = st1.getParameterTypes().length(); 2042 if (st1 == s1.type) continue; 2043 2044 for (Type t2 = sup; 2045 t2.hasTag(CLASS); 2046 t2 = types.supertype(t2)) { 2047 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 2048 if (s2 == s1 || 2049 s2.kind != MTH || 2050 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 2051 s2.type.getParameterTypes().length() != s1ArgsLength || 2052 !s2.isInheritedIn(site.tsym, types) || 2053 ((MethodSymbol)s2).implementation(site.tsym, 2054 types, 2055 true) != s2) 2056 continue; 2057 Type st2 = types.memberType(t2, s2); 2058 if (types.overrideEquivalent(st1, st2)) 2059 log.error(pos, 2060 Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup)); 2061 } 2062 } 2063 } 2064 } 2065 } 2066 2067 /** Check that classes (or interfaces) do not each define an abstract 2068 * method with same name and arguments but incompatible return types. 2069 * @param pos Position to be used for error reporting. 2070 * @param t1 The first argument type. 2071 * @param t2 The second argument type. 2072 */ 2073 public boolean checkCompatibleAbstracts(DiagnosticPosition pos, 2074 Type t1, 2075 Type t2, 2076 Type site) { 2077 if ((site.tsym.flags() & COMPOUND) != 0) { 2078 // special case for intersections: need to eliminate wildcards in supertypes 2079 t1 = types.capture(t1); 2080 t2 = types.capture(t2); 2081 } 2082 return firstIncompatibility(pos, t1, t2, site) == null; 2083 } 2084 2085 /** Return the first method which is defined with same args 2086 * but different return types in two given interfaces, or null if none 2087 * exists. 2088 * @param t1 The first type. 2089 * @param t2 The second type. 2090 * @param site The most derived type. 2091 * @return symbol from t2 that conflicts with one in t1. 2092 */ 2093 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 2094 Map<TypeSymbol,Type> interfaces1 = new HashMap<>(); 2095 closure(t1, interfaces1); 2096 Map<TypeSymbol,Type> interfaces2; 2097 if (t1 == t2) 2098 interfaces2 = interfaces1; 2099 else 2100 closure(t2, interfaces1, interfaces2 = new HashMap<>()); 2101 2102 for (Type t3 : interfaces1.values()) { 2103 for (Type t4 : interfaces2.values()) { 2104 Symbol s = firstDirectIncompatibility(pos, t3, t4, site); 2105 if (s != null) return s; 2106 } 2107 } 2108 return null; 2109 } 2110 2111 /** Compute all the supertypes of t, indexed by type symbol. */ 2112 private void closure(Type t, Map<TypeSymbol,Type> typeMap) { 2113 if (!t.hasTag(CLASS)) return; 2114 if (typeMap.put(t.tsym, t) == null) { 2115 closure(types.supertype(t), typeMap); 2116 for (Type i : types.interfaces(t)) 2117 closure(i, typeMap); 2118 } 2119 } 2120 2121 /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */ 2122 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) { 2123 if (!t.hasTag(CLASS)) return; 2124 if (typesSkip.get(t.tsym) != null) return; 2125 if (typeMap.put(t.tsym, t) == null) { 2126 closure(types.supertype(t), typesSkip, typeMap); 2127 for (Type i : types.interfaces(t)) 2128 closure(i, typesSkip, typeMap); 2129 } 2130 } 2131 2132 /** Return the first method in t2 that conflicts with a method from t1. */ 2133 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 2134 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 2135 Type st1 = null; 2136 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) || 2137 (s1.flags() & SYNTHETIC) != 0) continue; 2138 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false); 2139 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue; 2140 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 2141 if (s1 == s2) continue; 2142 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) || 2143 (s2.flags() & SYNTHETIC) != 0) continue; 2144 if (st1 == null) st1 = types.memberType(t1, s1); 2145 Type st2 = types.memberType(t2, s2); 2146 if (types.overrideEquivalent(st1, st2)) { 2147 List<Type> tvars1 = st1.getTypeArguments(); 2148 List<Type> tvars2 = st2.getTypeArguments(); 2149 Type rt1 = st1.getReturnType(); 2150 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1); 2151 boolean compat = 2152 types.isSameType(rt1, rt2) || 2153 !rt1.isPrimitiveOrVoid() && 2154 !rt2.isPrimitiveOrVoid() && 2155 (types.covariantReturnType(rt1, rt2, types.noWarnings) || 2156 types.covariantReturnType(rt2, rt1, types.noWarnings)) || 2157 checkCommonOverriderIn(s1,s2,site); 2158 if (!compat) { 2159 if (types.isSameType(t1, t2)) { 2160 log.error(pos, Errors.IncompatibleDiffRetSameType(t1, 2161 s2.name, types.memberType(t2, s2).getParameterTypes())); 2162 } else { 2163 log.error(pos, Errors.TypesIncompatible(t1, t2, 2164 Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes()))); 2165 } 2166 return s2; 2167 } 2168 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) && 2169 !checkCommonOverriderIn(s1, s2, site)) { 2170 log.error(pos, Errors.NameClashSameErasureNoOverride( 2171 s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(), 2172 s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location())); 2173 return s2; 2174 } 2175 } 2176 } 2177 return null; 2178 } 2179 //WHERE 2180 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) { 2181 Map<TypeSymbol,Type> supertypes = new HashMap<>(); 2182 Type st1 = types.memberType(site, s1); 2183 Type st2 = types.memberType(site, s2); 2184 closure(site, supertypes); 2185 for (Type t : supertypes.values()) { 2186 for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) { 2187 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue; 2188 Type st3 = types.memberType(site,s3); 2189 if (types.overrideEquivalent(st3, st1) && 2190 types.overrideEquivalent(st3, st2) && 2191 types.returnTypeSubstitutable(st3, st1) && 2192 types.returnTypeSubstitutable(st3, st2)) { 2193 return true; 2194 } 2195 } 2196 } 2197 return false; 2198 } 2199 2200 /** Check that a given method conforms with any method it overrides. 2201 * @param tree The tree from which positions are extracted 2202 * for errors. 2203 * @param m The overriding method. 2204 */ 2205 void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) { 2206 ClassSymbol origin = (ClassSymbol)m.owner; 2207 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) { 2208 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) { 2209 log.error(tree.pos(), Errors.EnumNoFinalize); 2210 return; 2211 } 2212 } 2213 if (allowValueClasses && origin.isValueClass() && names.finalize.equals(m.name)) { 2214 if (m.overrides(syms.objectFinalize, origin, types, false)) { 2215 log.warning(tree.pos(), Warnings.ValueFinalize); 2216 } 2217 } 2218 if (allowRecords && origin.isRecord()) { 2219 // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable 2220 Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream() 2221 .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst(); 2222 if (recordComponent.isPresent()) { 2223 return; 2224 } 2225 } 2226 2227 for (Type t = origin.type; t.hasTag(CLASS); 2228 t = types.supertype(t)) { 2229 if (t != origin.type) { 2230 checkOverride(tree, t, origin, m); 2231 } 2232 for (Type t2 : types.interfaces(t)) { 2233 checkOverride(tree, t2, origin, m); 2234 } 2235 } 2236 2237 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null; 2238 // Check if this method must override a super method due to being annotated with @Override 2239 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to 2240 // be treated "as if as they were annotated" with @Override. 2241 boolean mustOverride = explicitOverride || 2242 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate()); 2243 if (mustOverride && !isOverrider(m)) { 2244 DiagnosticPosition pos = tree.pos(); 2245 for (JCAnnotation a : tree.getModifiers().annotations) { 2246 if (a.annotationType.type.tsym == syms.overrideType.tsym) { 2247 pos = a.pos(); 2248 break; 2249 } 2250 } 2251 log.error(pos, 2252 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) : 2253 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride)); 2254 } 2255 } 2256 2257 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) { 2258 TypeSymbol c = site.tsym; 2259 for (Symbol sym : c.members().getSymbolsByName(m.name)) { 2260 if (m.overrides(sym, origin, types, false)) { 2261 if ((sym.flags() & ABSTRACT) == 0) { 2262 checkOverride(tree, m, (MethodSymbol)sym, origin); 2263 } 2264 } 2265 } 2266 } 2267 2268 private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) && 2269 (s.flags() & BAD_OVERRIDE) == 0; 2270 2271 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos, 2272 ClassSymbol someClass) { 2273 /* At present, annotations cannot possibly have a method that is override 2274 * equivalent with Object.equals(Object) but in any case the condition is 2275 * fine for completeness. 2276 */ 2277 if (someClass == (ClassSymbol)syms.objectType.tsym || 2278 someClass.isInterface() || someClass.isEnum() || 2279 (someClass.flags() & ANNOTATION) != 0 || 2280 (someClass.flags() & ABSTRACT) != 0) return; 2281 //anonymous inner classes implementing interfaces need especial treatment 2282 if (someClass.isAnonymous()) { 2283 List<Type> interfaces = types.interfaces(someClass.type); 2284 if (interfaces != null && !interfaces.isEmpty() && 2285 interfaces.head.tsym == syms.comparatorType.tsym) return; 2286 } 2287 checkClassOverrideEqualsAndHash(pos, someClass); 2288 } 2289 2290 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos, 2291 ClassSymbol someClass) { 2292 if (lint.isEnabled(LintCategory.OVERRIDES)) { 2293 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType 2294 .tsym.members().findFirst(names.equals); 2295 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType 2296 .tsym.members().findFirst(names.hashCode); 2297 MethodSymbol equalsImpl = types.implementation(equalsAtObject, 2298 someClass, false, equalsHasCodeFilter); 2299 boolean overridesEquals = equalsImpl != null && 2300 equalsImpl.owner == someClass; 2301 boolean overridesHashCode = types.implementation(hashCodeAtObject, 2302 someClass, false, equalsHasCodeFilter) != hashCodeAtObject; 2303 2304 if (overridesEquals && !overridesHashCode) { 2305 log.warning(pos, 2306 LintWarnings.OverrideEqualsButNotHashcode(someClass)); 2307 } 2308 } 2309 } 2310 2311 public void checkHasMain(DiagnosticPosition pos, ClassSymbol c) { 2312 boolean found = false; 2313 2314 for (Symbol sym : c.members().getSymbolsByName(names.main)) { 2315 if (sym.kind == MTH && (sym.flags() & PRIVATE) == 0) { 2316 MethodSymbol meth = (MethodSymbol)sym; 2317 if (!types.isSameType(meth.getReturnType(), syms.voidType)) { 2318 continue; 2319 } 2320 if (meth.params.isEmpty()) { 2321 found = true; 2322 break; 2323 } 2324 if (meth.params.size() != 1) { 2325 continue; 2326 } 2327 if (!types.isSameType(meth.params.head.type, types.makeArrayType(syms.stringType))) { 2328 continue; 2329 } 2330 2331 found = true; 2332 break; 2333 } 2334 } 2335 2336 if (!found) { 2337 log.error(pos, Errors.ImplicitClassDoesNotHaveMainMethod); 2338 } 2339 } 2340 2341 public void checkModuleName (JCModuleDecl tree) { 2342 Name moduleName = tree.sym.name; 2343 Assert.checkNonNull(moduleName); 2344 if (lint.isEnabled(LintCategory.MODULE)) { 2345 JCExpression qualId = tree.qualId; 2346 while (qualId != null) { 2347 Name componentName; 2348 DiagnosticPosition pos; 2349 switch (qualId.getTag()) { 2350 case SELECT: 2351 JCFieldAccess selectNode = ((JCFieldAccess) qualId); 2352 componentName = selectNode.name; 2353 pos = selectNode.pos(); 2354 qualId = selectNode.selected; 2355 break; 2356 case IDENT: 2357 componentName = ((JCIdent) qualId).name; 2358 pos = qualId.pos(); 2359 qualId = null; 2360 break; 2361 default: 2362 throw new AssertionError("Unexpected qualified identifier: " + qualId.toString()); 2363 } 2364 if (componentName != null) { 2365 String moduleNameComponentString = componentName.toString(); 2366 int nameLength = moduleNameComponentString.length(); 2367 if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) { 2368 log.warning(pos, LintWarnings.PoorChoiceForModuleName(componentName)); 2369 } 2370 } 2371 } 2372 } 2373 } 2374 2375 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) { 2376 ClashFilter cf = new ClashFilter(origin.type); 2377 return (cf.test(s1) && 2378 cf.test(s2) && 2379 types.hasSameArgs(s1.erasure(types), s2.erasure(types))); 2380 } 2381 2382 2383 /** Check that all abstract members of given class have definitions. 2384 * @param pos Position to be used for error reporting. 2385 * @param c The class. 2386 */ 2387 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) { 2388 MethodSymbol undef = types.firstUnimplementedAbstract(c); 2389 if (undef != null) { 2390 MethodSymbol undef1 = 2391 new MethodSymbol(undef.flags(), undef.name, 2392 types.memberType(c.type, undef), undef.owner); 2393 log.error(pos, 2394 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location())); 2395 } 2396 } 2397 2398 void checkNonCyclicDecl(JCClassDecl tree) { 2399 CycleChecker cc = new CycleChecker(); 2400 cc.scan(tree); 2401 if (!cc.errorFound && !cc.partialCheck) { 2402 tree.sym.flags_field |= ACYCLIC; 2403 } 2404 } 2405 2406 class CycleChecker extends TreeScanner { 2407 2408 Set<Symbol> seenClasses = new HashSet<>(); 2409 boolean errorFound = false; 2410 boolean partialCheck = false; 2411 2412 private void checkSymbol(DiagnosticPosition pos, Symbol sym) { 2413 if (sym != null && sym.kind == TYP) { 2414 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym); 2415 if (classEnv != null) { 2416 DiagnosticSource prevSource = log.currentSource(); 2417 try { 2418 log.useSource(classEnv.toplevel.sourcefile); 2419 scan(classEnv.tree); 2420 } 2421 finally { 2422 log.useSource(prevSource.getFile()); 2423 } 2424 } else if (sym.kind == TYP) { 2425 checkClass(pos, sym, List.nil()); 2426 } 2427 } else if (sym == null || sym.kind != PCK) { 2428 //not completed yet 2429 partialCheck = true; 2430 } 2431 } 2432 2433 @Override 2434 public void visitSelect(JCFieldAccess tree) { 2435 super.visitSelect(tree); 2436 checkSymbol(tree.pos(), tree.sym); 2437 } 2438 2439 @Override 2440 public void visitIdent(JCIdent tree) { 2441 checkSymbol(tree.pos(), tree.sym); 2442 } 2443 2444 @Override 2445 public void visitTypeApply(JCTypeApply tree) { 2446 scan(tree.clazz); 2447 } 2448 2449 @Override 2450 public void visitTypeArray(JCArrayTypeTree tree) { 2451 scan(tree.elemtype); 2452 } 2453 2454 @Override 2455 public void visitClassDef(JCClassDecl tree) { 2456 List<JCTree> supertypes = List.nil(); 2457 if (tree.getExtendsClause() != null) { 2458 supertypes = supertypes.prepend(tree.getExtendsClause()); 2459 } 2460 if (tree.getImplementsClause() != null) { 2461 for (JCTree intf : tree.getImplementsClause()) { 2462 supertypes = supertypes.prepend(intf); 2463 } 2464 } 2465 checkClass(tree.pos(), tree.sym, supertypes); 2466 } 2467 2468 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) { 2469 if ((c.flags_field & ACYCLIC) != 0) 2470 return; 2471 if (seenClasses.contains(c)) { 2472 errorFound = true; 2473 log.error(pos, Errors.CyclicInheritance(c)); 2474 seenClasses.stream() 2475 .filter(s -> !s.type.isErroneous()) 2476 .filter(ClassSymbol.class::isInstance) 2477 .map(ClassSymbol.class::cast) 2478 .forEach(Check.this::handleCyclic); 2479 } else if (!c.type.isErroneous()) { 2480 try { 2481 seenClasses.add(c); 2482 if (c.type.hasTag(CLASS)) { 2483 if (supertypes.nonEmpty()) { 2484 scan(supertypes); 2485 } 2486 else { 2487 ClassType ct = (ClassType)c.type; 2488 if (ct.supertype_field == null || 2489 ct.interfaces_field == null) { 2490 //not completed yet 2491 partialCheck = true; 2492 return; 2493 } 2494 checkSymbol(pos, ct.supertype_field.tsym); 2495 for (Type intf : ct.interfaces_field) { 2496 checkSymbol(pos, intf.tsym); 2497 } 2498 } 2499 if (c.owner.kind == TYP) { 2500 checkSymbol(pos, c.owner); 2501 } 2502 } 2503 } finally { 2504 seenClasses.remove(c); 2505 } 2506 } 2507 } 2508 } 2509 2510 /** Check for cyclic references. Issue an error if the 2511 * symbol of the type referred to has a LOCKED flag set. 2512 * 2513 * @param pos Position to be used for error reporting. 2514 * @param t The type referred to. 2515 */ 2516 void checkNonCyclic(DiagnosticPosition pos, Type t) { 2517 checkNonCyclicInternal(pos, t); 2518 } 2519 2520 2521 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) { 2522 checkNonCyclic1(pos, t, List.nil()); 2523 } 2524 2525 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) { 2526 final TypeVar tv; 2527 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0) 2528 return; 2529 if (seen.contains(t)) { 2530 tv = (TypeVar)t; 2531 tv.setUpperBound(types.createErrorType(t)); 2532 log.error(pos, Errors.CyclicInheritance(t)); 2533 } else if (t.hasTag(TYPEVAR)) { 2534 tv = (TypeVar)t; 2535 seen = seen.prepend(tv); 2536 for (Type b : types.getBounds(tv)) 2537 checkNonCyclic1(pos, b, seen); 2538 } 2539 } 2540 2541 /** Check for cyclic references. Issue an error if the 2542 * symbol of the type referred to has a LOCKED flag set. 2543 * 2544 * @param pos Position to be used for error reporting. 2545 * @param t The type referred to. 2546 * @return True if the check completed on all attributed classes 2547 */ 2548 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) { 2549 boolean complete = true; // was the check complete? 2550 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG 2551 Symbol c = t.tsym; 2552 if ((c.flags_field & ACYCLIC) != 0) return true; 2553 2554 if ((c.flags_field & LOCKED) != 0) { 2555 log.error(pos, Errors.CyclicInheritance(c)); 2556 handleCyclic((ClassSymbol)c); 2557 } else if (!c.type.isErroneous()) { 2558 try { 2559 c.flags_field |= LOCKED; 2560 if (c.type.hasTag(CLASS)) { 2561 ClassType clazz = (ClassType)c.type; 2562 if (clazz.interfaces_field != null) 2563 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail) 2564 complete &= checkNonCyclicInternal(pos, l.head); 2565 if (clazz.supertype_field != null) { 2566 Type st = clazz.supertype_field; 2567 if (st != null && st.hasTag(CLASS)) 2568 complete &= checkNonCyclicInternal(pos, st); 2569 } 2570 if (c.owner.kind == TYP) 2571 complete &= checkNonCyclicInternal(pos, c.owner.type); 2572 } 2573 } finally { 2574 c.flags_field &= ~LOCKED; 2575 } 2576 } 2577 if (complete) 2578 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted(); 2579 if (complete) c.flags_field |= ACYCLIC; 2580 return complete; 2581 } 2582 2583 /** Handle finding an inheritance cycle on a class by setting 2584 * the class' and its supertypes' types to the error type. 2585 **/ 2586 private void handleCyclic(ClassSymbol c) { 2587 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail) 2588 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType); 2589 Type st = types.supertype(c.type); 2590 if (st.hasTag(CLASS)) 2591 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType); 2592 c.type = types.createErrorType(c, c.type); 2593 c.flags_field |= ACYCLIC; 2594 } 2595 2596 /** Check that all methods which implement some 2597 * method conform to the method they implement. 2598 * @param tree The class definition whose members are checked. 2599 */ 2600 void checkImplementations(JCClassDecl tree) { 2601 checkImplementations(tree, tree.sym, tree.sym); 2602 } 2603 //where 2604 /** Check that all methods which implement some 2605 * method in `ic' conform to the method they implement. 2606 */ 2607 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) { 2608 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) { 2609 ClassSymbol lc = (ClassSymbol)l.head.tsym; 2610 if ((lc.flags() & ABSTRACT) != 0) { 2611 for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) { 2612 if (sym.kind == MTH && 2613 (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) { 2614 MethodSymbol absmeth = (MethodSymbol)sym; 2615 MethodSymbol implmeth = absmeth.implementation(origin, types, false); 2616 if (implmeth != null && implmeth != absmeth && 2617 (implmeth.owner.flags() & INTERFACE) == 2618 (origin.flags() & INTERFACE)) { 2619 // don't check if implmeth is in a class, yet 2620 // origin is an interface. This case arises only 2621 // if implmeth is declared in Object. The reason is 2622 // that interfaces really don't inherit from 2623 // Object it's just that the compiler represents 2624 // things that way. 2625 checkOverride(tree, implmeth, absmeth, origin); 2626 } 2627 } 2628 } 2629 } 2630 } 2631 } 2632 2633 /** Check that all abstract methods implemented by a class are 2634 * mutually compatible. 2635 * @param pos Position to be used for error reporting. 2636 * @param c The class whose interfaces are checked. 2637 */ 2638 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) { 2639 List<Type> supertypes = types.interfaces(c); 2640 Type supertype = types.supertype(c); 2641 if (supertype.hasTag(CLASS) && 2642 (supertype.tsym.flags() & ABSTRACT) != 0) 2643 supertypes = supertypes.prepend(supertype); 2644 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) { 2645 if (!l.head.getTypeArguments().isEmpty() && 2646 !checkCompatibleAbstracts(pos, l.head, l.head, c)) 2647 return; 2648 for (List<Type> m = supertypes; m != l; m = m.tail) 2649 if (!checkCompatibleAbstracts(pos, l.head, m.head, c)) 2650 return; 2651 } 2652 checkCompatibleConcretes(pos, c); 2653 2654 Type identitySuper = null; 2655 for (Type t : types.closure(c)) { 2656 if (t != c) { 2657 if (t.isIdentityClass() && (t.tsym.flags() & VALUE_BASED) == 0) 2658 identitySuper = t; 2659 if (c.isValueClass() && identitySuper != null && identitySuper.tsym != syms.objectType.tsym) { // Object is special 2660 log.error(pos, Errors.ValueTypeHasIdentitySuperType(c, identitySuper)); 2661 break; 2662 } 2663 } 2664 } 2665 } 2666 2667 /** Check that all non-override equivalent methods accessible from 'site' 2668 * are mutually compatible (JLS 8.4.8/9.4.1). 2669 * 2670 * @param pos Position to be used for error reporting. 2671 * @param site The class whose methods are checked. 2672 * @param sym The method symbol to be checked. 2673 */ 2674 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2675 ClashFilter cf = new ClashFilter(site); 2676 //for each method m1 that is overridden (directly or indirectly) 2677 //by method 'sym' in 'site'... 2678 2679 ArrayList<Symbol> symbolsByName = new ArrayList<>(); 2680 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add); 2681 for (Symbol m1 : symbolsByName) { 2682 if (!sym.overrides(m1, site.tsym, types, false)) { 2683 continue; 2684 } 2685 2686 //...check each method m2 that is a member of 'site' 2687 for (Symbol m2 : symbolsByName) { 2688 if (m2 == m1) continue; 2689 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2690 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error 2691 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) && 2692 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) { 2693 sym.flags_field |= CLASH; 2694 if (m1 == sym) { 2695 log.error(pos, Errors.NameClashSameErasureNoOverride( 2696 m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(), 2697 m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location())); 2698 } else { 2699 ClassType ct = (ClassType)site; 2700 String kind = ct.isInterface() ? "interface" : "class"; 2701 log.error(pos, Errors.NameClashSameErasureNoOverride1( 2702 kind, 2703 ct.tsym.name, 2704 m1.name, 2705 types.memberType(site, m1).asMethodType().getParameterTypes(), 2706 m1.location(), 2707 m2.name, 2708 types.memberType(site, m2).asMethodType().getParameterTypes(), 2709 m2.location())); 2710 } 2711 return; 2712 } 2713 } 2714 } 2715 } 2716 2717 /** Check that all static methods accessible from 'site' are 2718 * mutually compatible (JLS 8.4.8). 2719 * 2720 * @param pos Position to be used for error reporting. 2721 * @param site The class whose methods are checked. 2722 * @param sym The method symbol to be checked. 2723 */ 2724 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2725 ClashFilter cf = new ClashFilter(site); 2726 //for each method m1 that is a member of 'site'... 2727 for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) { 2728 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2729 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error 2730 if (!types.isSubSignature(sym.type, types.memberType(site, s))) { 2731 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) { 2732 log.error(pos, 2733 Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location())); 2734 return; 2735 } 2736 } 2737 } 2738 } 2739 2740 //where 2741 private class ClashFilter implements Predicate<Symbol> { 2742 2743 Type site; 2744 2745 ClashFilter(Type site) { 2746 this.site = site; 2747 } 2748 2749 boolean shouldSkip(Symbol s) { 2750 return (s.flags() & CLASH) != 0 && 2751 s.owner == site.tsym; 2752 } 2753 2754 @Override 2755 public boolean test(Symbol s) { 2756 return s.kind == MTH && 2757 (s.flags() & SYNTHETIC) == 0 && 2758 !shouldSkip(s) && 2759 s.isInheritedIn(site.tsym, types) && 2760 !s.isConstructor(); 2761 } 2762 } 2763 2764 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) { 2765 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site); 2766 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) { 2767 Assert.check(m.kind == MTH); 2768 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m); 2769 if (prov.size() > 1) { 2770 ListBuffer<Symbol> abstracts = new ListBuffer<>(); 2771 ListBuffer<Symbol> defaults = new ListBuffer<>(); 2772 for (MethodSymbol provSym : prov) { 2773 if ((provSym.flags() & DEFAULT) != 0) { 2774 defaults = defaults.append(provSym); 2775 } else if ((provSym.flags() & ABSTRACT) != 0) { 2776 abstracts = abstracts.append(provSym); 2777 } 2778 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) { 2779 //strong semantics - issue an error if two sibling interfaces 2780 //have two override-equivalent defaults - or if one is abstract 2781 //and the other is default 2782 Fragment diagKey; 2783 Symbol s1 = defaults.first(); 2784 Symbol s2; 2785 if (defaults.size() > 1) { 2786 s2 = defaults.toList().tail.head; 2787 diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site, 2788 m.name, types.memberType(site, m).getParameterTypes(), 2789 s1.location(), s2.location()); 2790 2791 } else { 2792 s2 = abstracts.first(); 2793 diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site, 2794 m.name, types.memberType(site, m).getParameterTypes(), 2795 s1.location(), s2.location()); 2796 } 2797 log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey)); 2798 break; 2799 } 2800 } 2801 } 2802 } 2803 } 2804 2805 //where 2806 private class DefaultMethodClashFilter implements Predicate<Symbol> { 2807 2808 Type site; 2809 2810 DefaultMethodClashFilter(Type site) { 2811 this.site = site; 2812 } 2813 2814 @Override 2815 public boolean test(Symbol s) { 2816 return s.kind == MTH && 2817 (s.flags() & DEFAULT) != 0 && 2818 s.isInheritedIn(site.tsym, types) && 2819 !s.isConstructor(); 2820 } 2821 } 2822 2823 /** Report warnings for potentially ambiguous method declarations in the given site. */ 2824 void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) { 2825 2826 // Skip if warning not enabled 2827 if (!lint.isEnabled(LintCategory.OVERLOADS)) 2828 return; 2829 2830 // Gather all of site's methods, including overridden methods, grouped by name (except Object methods) 2831 List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site, 2832 new PotentiallyAmbiguousFilter(site), ArrayList::new); 2833 2834 // Build the predicate that determines if site is responsible for an ambiguity 2835 BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups); 2836 2837 // Now remove overridden methods from each group, leaving only site's actual members 2838 methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false))); 2839 2840 // Allow site's own declared methods (only) to apply @SuppressWarnings("overloads") 2841 methodGroups.forEach(list -> list.removeIf( 2842 m -> m.owner == site.tsym && !lint.augment(m).isEnabled(LintCategory.OVERLOADS))); 2843 2844 // Warn about ambiguous overload method pairs for which site is responsible 2845 methodGroups.forEach(list -> compareAndRemove(list, (m1, m2) -> { 2846 2847 // See if this is an ambiguous overload for which "site" is responsible 2848 if (!potentiallyAmbiguousOverload(site, m1, m2) || !responsible.test(m1, m2)) 2849 return 0; 2850 2851 // Locate the warning at one of the methods, if possible 2852 DiagnosticPosition pos = 2853 m1.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m1, tree) : 2854 m2.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m2, tree) : 2855 tree.pos(); 2856 2857 // Log the warning 2858 log.warning(pos, 2859 LintWarnings.PotentiallyAmbiguousOverload( 2860 m1.asMemberOf(site, types), m1.location(), 2861 m2.asMemberOf(site, types), m2.location())); 2862 2863 // Don't warn again for either of these two methods 2864 return FIRST | SECOND; 2865 })); 2866 } 2867 2868 /** Build a predicate that determines, given two methods that are members of the given class, 2869 * whether the class should be held "responsible" if the methods are potentially ambiguous. 2870 * 2871 * Sometimes ambiguous methods are unavoidable because they're inherited from a supertype. 2872 * For example, any subtype of Spliterator.OfInt will have ambiguities for both 2873 * forEachRemaining() and tryAdvance() (in both cases the overloads are IntConsumer and 2874 * Consumer<? super Integer>). So we only want to "blame" a class when that class is 2875 * itself responsible for creating the ambiguity. We declare that a class C is "responsible" 2876 * for the ambiguity between two methods m1 and m2 if there is no direct supertype T of C 2877 * such that m1 and m2, or some overrides thereof, both exist in T and are ambiguous in T. 2878 * As an optimization, we first check if either method is declared in C and does not override 2879 * any other methods; in this case the class is definitely responsible. 2880 */ 2881 BiPredicate<MethodSymbol, MethodSymbol> buildResponsiblePredicate(Type site, 2882 List<? extends Collection<MethodSymbol>> methodGroups) { 2883 2884 // Define the "overrides" predicate 2885 BiPredicate<MethodSymbol, MethodSymbol> overrides = (m1, m2) -> m1.overrides(m2, site.tsym, types, false); 2886 2887 // Map each method declared in site to a list of the supertype method(s) it directly overrides 2888 HashMap<MethodSymbol, ArrayList<MethodSymbol>> overriddenMethodsMap = new HashMap<>(); 2889 methodGroups.forEach(list -> { 2890 for (MethodSymbol m : list) { 2891 2892 // Skip methods not declared in site 2893 if (m.owner != site.tsym) 2894 continue; 2895 2896 // Gather all supertype methods overridden by m, directly or indirectly 2897 ArrayList<MethodSymbol> overriddenMethods = list.stream() 2898 .filter(m2 -> m2 != m && overrides.test(m, m2)) 2899 .collect(Collectors.toCollection(ArrayList::new)); 2900 2901 // Eliminate non-direct overrides 2902 removePreempted(overriddenMethods, overrides); 2903 2904 // Add to map 2905 overriddenMethodsMap.put(m, overriddenMethods); 2906 } 2907 }); 2908 2909 // Build the predicate 2910 return (m1, m2) -> { 2911 2912 // Get corresponding supertype methods (if declared in site) 2913 java.util.List<MethodSymbol> overriddenMethods1 = overriddenMethodsMap.get(m1); 2914 java.util.List<MethodSymbol> overriddenMethods2 = overriddenMethodsMap.get(m2); 2915 2916 // Quick check for the case where a method was added by site itself 2917 if (overriddenMethods1 != null && overriddenMethods1.isEmpty()) 2918 return true; 2919 if (overriddenMethods2 != null && overriddenMethods2.isEmpty()) 2920 return true; 2921 2922 // Get each method's corresponding method(s) from supertypes of site 2923 java.util.List<MethodSymbol> supertypeMethods1 = overriddenMethods1 != null ? 2924 overriddenMethods1 : Collections.singletonList(m1); 2925 java.util.List<MethodSymbol> supertypeMethods2 = overriddenMethods2 != null ? 2926 overriddenMethods2 : Collections.singletonList(m2); 2927 2928 // See if we can blame some direct supertype instead 2929 return types.directSupertypes(site).stream() 2930 .filter(stype -> stype != syms.objectType) 2931 .map(stype -> stype.tsym.type) // view supertype in its original form 2932 .noneMatch(stype -> { 2933 for (MethodSymbol sm1 : supertypeMethods1) { 2934 if (!types.isSubtype(types.erasure(stype), types.erasure(sm1.owner.type))) 2935 continue; 2936 for (MethodSymbol sm2 : supertypeMethods2) { 2937 if (!types.isSubtype(types.erasure(stype), types.erasure(sm2.owner.type))) 2938 continue; 2939 if (potentiallyAmbiguousOverload(stype, sm1, sm2)) 2940 return true; 2941 } 2942 } 2943 return false; 2944 }); 2945 }; 2946 } 2947 2948 /** Gather all of site's methods, including overridden methods, grouped and sorted by name, 2949 * after applying the given filter. 2950 */ 2951 <C extends Collection<MethodSymbol>> List<C> methodsGroupedByName(Type site, 2952 Predicate<Symbol> filter, Supplier<? extends C> groupMaker) { 2953 Iterable<Symbol> symbols = types.membersClosure(site, false).getSymbols(filter, RECURSIVE); 2954 return StreamSupport.stream(symbols.spliterator(), false) 2955 .map(MethodSymbol.class::cast) 2956 .collect(Collectors.groupingBy(m -> m.name, Collectors.toCollection(groupMaker))) 2957 .entrySet() 2958 .stream() 2959 .sorted(Comparator.comparing(e -> e.getKey().toString())) 2960 .map(Map.Entry::getValue) 2961 .collect(List.collector()); 2962 } 2963 2964 /** Compare elements in a list pair-wise in order to remove some of them. 2965 * @param list mutable list of items 2966 * @param comparer returns flag bit(s) to remove FIRST and/or SECOND 2967 */ 2968 <T> void compareAndRemove(java.util.List<T> list, ToIntBiFunction<? super T, ? super T> comparer) { 2969 for (int index1 = 0; index1 < list.size() - 1; index1++) { 2970 T item1 = list.get(index1); 2971 for (int index2 = index1 + 1; index2 < list.size(); index2++) { 2972 T item2 = list.get(index2); 2973 int flags = comparer.applyAsInt(item1, item2); 2974 if ((flags & SECOND) != 0) 2975 list.remove(index2--); // remove item2 2976 if ((flags & FIRST) != 0) { 2977 list.remove(index1--); // remove item1 2978 break; 2979 } 2980 } 2981 } 2982 } 2983 2984 /** Remove elements in a list that are preempted by some other element in the list. 2985 * @param list mutable list of items 2986 * @param preempts decides if one item preempts another, causing the second one to be removed 2987 */ 2988 <T> void removePreempted(java.util.List<T> list, BiPredicate<? super T, ? super T> preempts) { 2989 compareAndRemove(list, (item1, item2) -> { 2990 int flags = 0; 2991 if (preempts.test(item1, item2)) 2992 flags |= SECOND; 2993 if (preempts.test(item2, item1)) 2994 flags |= FIRST; 2995 return flags; 2996 }); 2997 } 2998 2999 /** Filters method candidates for the "potentially ambiguous method" check */ 3000 class PotentiallyAmbiguousFilter extends ClashFilter { 3001 3002 PotentiallyAmbiguousFilter(Type site) { 3003 super(site); 3004 } 3005 3006 @Override 3007 boolean shouldSkip(Symbol s) { 3008 return s.owner.type.tsym == syms.objectType.tsym || super.shouldSkip(s); 3009 } 3010 } 3011 3012 /** 3013 * Report warnings for potentially ambiguous method declarations. Two declarations 3014 * are potentially ambiguous if they feature two unrelated functional interface 3015 * in same argument position (in which case, a call site passing an implicit 3016 * lambda would be ambiguous). This assumes they already have the same name. 3017 */ 3018 boolean potentiallyAmbiguousOverload(Type site, MethodSymbol msym1, MethodSymbol msym2) { 3019 Assert.check(msym1.name == msym2.name); 3020 if (msym1 == msym2) 3021 return false; 3022 Type mt1 = types.memberType(site, msym1); 3023 Type mt2 = types.memberType(site, msym2); 3024 //if both generic methods, adjust type variables 3025 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) && 3026 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) { 3027 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars); 3028 } 3029 //expand varargs methods if needed 3030 int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length()); 3031 List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true); 3032 List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true); 3033 //if arities don't match, exit 3034 if (args1.length() != args2.length()) 3035 return false; 3036 boolean potentiallyAmbiguous = false; 3037 while (args1.nonEmpty() && args2.nonEmpty()) { 3038 Type s = args1.head; 3039 Type t = args2.head; 3040 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) { 3041 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) && 3042 types.findDescriptorType(s).getParameterTypes().length() > 0 && 3043 types.findDescriptorType(s).getParameterTypes().length() == 3044 types.findDescriptorType(t).getParameterTypes().length()) { 3045 potentiallyAmbiguous = true; 3046 } else { 3047 return false; 3048 } 3049 } 3050 args1 = args1.tail; 3051 args2 = args2.tail; 3052 } 3053 return potentiallyAmbiguous; 3054 } 3055 3056 // Apply special flag "-XDwarnOnAccessToMembers" which turns on just this particular warning for all types of access 3057 void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) { 3058 final Lint prevLint = setLint(warnOnAnyAccessToMembers ? lint.enable(LintCategory.SERIAL) : lint); 3059 try { 3060 if (warnOnAnyAccessToMembers || isLambda) 3061 checkAccessFromSerializableElementInner(tree, isLambda); 3062 } finally { 3063 setLint(prevLint); 3064 } 3065 } 3066 3067 private void checkAccessFromSerializableElementInner(final JCTree tree, boolean isLambda) { 3068 if (lint.isEnabled(LintCategory.SERIAL)) { 3069 Symbol sym = TreeInfo.symbol(tree); 3070 if (!sym.kind.matches(KindSelector.VAL_MTH)) { 3071 return; 3072 } 3073 3074 if (sym.kind == VAR) { 3075 if ((sym.flags() & PARAMETER) != 0 || 3076 sym.isDirectlyOrIndirectlyLocal() || 3077 sym.name == names._this || 3078 sym.name == names._super) { 3079 return; 3080 } 3081 } 3082 3083 if (!types.isSubtype(sym.owner.type, syms.serializableType) && 3084 isEffectivelyNonPublic(sym)) { 3085 if (isLambda) { 3086 if (belongsToRestrictedPackage(sym)) { 3087 log.warning(tree.pos(), 3088 LintWarnings.AccessToMemberFromSerializableLambda(sym)); 3089 } 3090 } else { 3091 log.warning(tree.pos(), 3092 LintWarnings.AccessToMemberFromSerializableElement(sym)); 3093 } 3094 } 3095 } 3096 } 3097 3098 private boolean isEffectivelyNonPublic(Symbol sym) { 3099 if (sym.packge() == syms.rootPackage) { 3100 return false; 3101 } 3102 3103 while (sym.kind != PCK) { 3104 if ((sym.flags() & PUBLIC) == 0) { 3105 return true; 3106 } 3107 sym = sym.owner; 3108 } 3109 return false; 3110 } 3111 3112 private boolean belongsToRestrictedPackage(Symbol sym) { 3113 String fullName = sym.packge().fullname.toString(); 3114 return fullName.startsWith("java.") || 3115 fullName.startsWith("javax.") || 3116 fullName.startsWith("sun.") || 3117 fullName.contains(".internal."); 3118 } 3119 3120 /** Check that class c does not implement directly or indirectly 3121 * the same parameterized interface with two different argument lists. 3122 * @param pos Position to be used for error reporting. 3123 * @param type The type whose interfaces are checked. 3124 */ 3125 void checkClassBounds(DiagnosticPosition pos, Type type) { 3126 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type); 3127 } 3128 //where 3129 /** Enter all interfaces of type `type' into the hash table `seensofar' 3130 * with their class symbol as key and their type as value. Make 3131 * sure no class is entered with two different types. 3132 */ 3133 void checkClassBounds(DiagnosticPosition pos, 3134 Map<TypeSymbol,Type> seensofar, 3135 Type type) { 3136 if (type.isErroneous()) return; 3137 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) { 3138 Type it = l.head; 3139 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5 3140 3141 Type oldit = seensofar.put(it.tsym, it); 3142 if (oldit != null) { 3143 List<Type> oldparams = oldit.allparams(); 3144 List<Type> newparams = it.allparams(); 3145 if (!types.containsTypeEquivalent(oldparams, newparams)) 3146 log.error(pos, 3147 Errors.CantInheritDiffArg(it.tsym, 3148 Type.toString(oldparams), 3149 Type.toString(newparams))); 3150 } 3151 checkClassBounds(pos, seensofar, it); 3152 } 3153 Type st = types.supertype(type); 3154 if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4 3155 if (st != Type.noType) checkClassBounds(pos, seensofar, st); 3156 } 3157 3158 /** Enter interface into into set. 3159 * If it existed already, issue a "repeated interface" error. 3160 */ 3161 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Symbol> its) { 3162 if (its.contains(it.tsym)) 3163 log.error(pos, Errors.RepeatedInterface); 3164 else { 3165 its.add(it.tsym); 3166 } 3167 } 3168 3169 /* ************************************************************************* 3170 * Check annotations 3171 **************************************************************************/ 3172 3173 /** 3174 * Recursively validate annotations values 3175 */ 3176 void validateAnnotationTree(JCTree tree) { 3177 class AnnotationValidator extends TreeScanner { 3178 @Override 3179 public void visitAnnotation(JCAnnotation tree) { 3180 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) { 3181 super.visitAnnotation(tree); 3182 validateAnnotation(tree); 3183 } 3184 } 3185 } 3186 tree.accept(new AnnotationValidator()); 3187 } 3188 3189 /** 3190 * {@literal 3191 * Annotation types are restricted to primitives, String, an 3192 * enum, an annotation, Class, Class<?>, Class<? extends 3193 * Anything>, arrays of the preceding. 3194 * } 3195 */ 3196 void validateAnnotationType(JCTree restype) { 3197 // restype may be null if an error occurred, so don't bother validating it 3198 if (restype != null) { 3199 validateAnnotationType(restype.pos(), restype.type); 3200 } 3201 } 3202 3203 void validateAnnotationType(DiagnosticPosition pos, Type type) { 3204 if (type.isPrimitive()) return; 3205 if (types.isSameType(type, syms.stringType)) return; 3206 if ((type.tsym.flags() & Flags.ENUM) != 0) return; 3207 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return; 3208 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return; 3209 if (types.isArray(type) && !types.isArray(types.elemtype(type))) { 3210 validateAnnotationType(pos, types.elemtype(type)); 3211 return; 3212 } 3213 log.error(pos, Errors.InvalidAnnotationMemberType); 3214 } 3215 3216 /** 3217 * "It is also a compile-time error if any method declared in an 3218 * annotation type has a signature that is override-equivalent to 3219 * that of any public or protected method declared in class Object 3220 * or in the interface annotation.Annotation." 3221 * 3222 * @jls 9.6 Annotation Types 3223 */ 3224 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) { 3225 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) { 3226 Scope s = sup.tsym.members(); 3227 for (Symbol sym : s.getSymbolsByName(m.name)) { 3228 if (sym.kind == MTH && 3229 (sym.flags() & (PUBLIC | PROTECTED)) != 0 && 3230 types.overrideEquivalent(m.type, sym.type)) 3231 log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup)); 3232 } 3233 } 3234 } 3235 3236 /** Check the annotations of a symbol. 3237 */ 3238 public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) { 3239 for (JCAnnotation a : annotations) 3240 validateAnnotation(a, declarationTree, s); 3241 } 3242 3243 /** Check the type annotations. 3244 */ 3245 public void validateTypeAnnotations(List<JCAnnotation> annotations, Symbol s, boolean isTypeParameter) { 3246 for (JCAnnotation a : annotations) 3247 validateTypeAnnotation(a, s, isTypeParameter); 3248 } 3249 3250 /** Check an annotation of a symbol. 3251 */ 3252 private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) { 3253 /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method, 3254 * this can impact in particular records for which annotations are forcibly propagated. 3255 */ 3256 validateAnnotationTree(a); 3257 boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord()); 3258 3259 boolean isRecordField = (s.flags_field & RECORD) != 0 && 3260 declarationTree.hasTag(VARDEF) && 3261 s.owner.kind == TYP; 3262 3263 if (isRecordField) { 3264 // first we need to check if the annotation is applicable to records 3265 Name[] targets = getTargetNames(a); 3266 boolean appliesToRecords = false; 3267 for (Name target : targets) { 3268 appliesToRecords = 3269 target == names.FIELD || 3270 target == names.PARAMETER || 3271 target == names.METHOD || 3272 target == names.TYPE_USE || 3273 target == names.RECORD_COMPONENT; 3274 if (appliesToRecords) { 3275 break; 3276 } 3277 } 3278 if (!appliesToRecords) { 3279 log.error(a.pos(), Errors.AnnotationTypeNotApplicable); 3280 } else { 3281 /* lets now find the annotations in the field that are targeted to record components and append them to 3282 * the corresponding record component 3283 */ 3284 ClassSymbol recordClass = (ClassSymbol) s.owner; 3285 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s); 3286 SymbolMetadata metadata = rc.getMetadata(); 3287 if (metadata == null || metadata.isEmpty()) { 3288 /* if not is empty then we have already been here, which is the case if multiple annotations are applied 3289 * to the record component declaration 3290 */ 3291 rc.appendAttributes(s.getRawAttributes().stream().filter(anno -> 3292 Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT) 3293 ).collect(List.collector())); 3294 3295 JCVariableDecl fieldAST = (JCVariableDecl) declarationTree; 3296 for (JCAnnotation fieldAnnot : fieldAST.mods.annotations) { 3297 for (JCAnnotation rcAnnot : rc.declarationFor().mods.annotations) { 3298 if (rcAnnot.pos == fieldAnnot.pos) { 3299 rcAnnot.setType(fieldAnnot.type); 3300 break; 3301 } 3302 } 3303 } 3304 3305 /* At this point, we used to carry over any type annotations from the VARDEF to the record component, but 3306 * that is problematic, since we get here only when *some* annotation is applied to the SE5 (declaration) 3307 * annotation location, inadvertently failing to carry over the type annotations when the VarDef has no 3308 * annotations in the SE5 annotation location. 3309 * 3310 * Now type annotations are assigned to record components in a method that would execute irrespective of 3311 * whether there are SE5 annotations on a VarDef viz com.sun.tools.javac.code.TypeAnnotations.TypeAnnotationPositions.visitVarDef 3312 */ 3313 } 3314 } 3315 } 3316 3317 /* the section below is tricky. Annotations applied to record components are propagated to the corresponding 3318 * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has 3319 * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated 3320 * there is no enough information to propagate only the right annotations. So all the annotations are propagated 3321 * to all the possible locations. 3322 * 3323 * At this point we need to remove all the annotations that are not in place before going on with the annotation 3324 * party. On top of the above there is the issue that there is no AST representing record components, just symbols 3325 * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it 3326 * was both a field and a record component. 3327 * 3328 * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers 3329 * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could 3330 * be see by annotation processors. 3331 * 3332 * The metadata contains both type annotations and declaration annotations. At this point of the game we don't 3333 * need to care about type annotations, they are all in the right place. But we could need to remove declaration 3334 * annotations. So for declaration annotations if they are not applicable to the record member, excluding type 3335 * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not 3336 * applicable either as type annotation and or declaration annotation, only in that case it will be removed. 3337 * 3338 * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for 3339 * further inspection by annotation processors. 3340 * 3341 * For example: 3342 * 3343 * import java.lang.annotation.*; 3344 * 3345 * @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT}) 3346 * @Retention(RetentionPolicy.RUNTIME) 3347 * @interface Anno { } 3348 * 3349 * record R(@Anno String s) {} 3350 * 3351 * at this point we will have for the case of the generated field: 3352 * - @Anno in the modifier 3353 * - @Anno as a type annotation 3354 * - @Anno as a declaration annotation 3355 * 3356 * the last one should be removed because the annotation has not FIELD as target but it was applied as a 3357 * declaration annotation because the field was being treated both as a field and as a record component 3358 * as we have already copied the annotations to the record component, now the field doesn't need to hold 3359 * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it 3360 * is applicable as a type annotation to the type of the field. 3361 */ 3362 3363 if (a.type.tsym.isAnnotationType()) { 3364 Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s); 3365 if (!applicableTargetsOp.isEmpty()) { 3366 Set<Name> applicableTargets = applicableTargetsOp.get(); 3367 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() || 3368 applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE); 3369 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0; 3370 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly; 3371 3372 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) { 3373 if (isCompRecordElementWithNonApplicableDeclAnno) { 3374 /* so we have found an annotation that is not applicable to a record member that was generated by the 3375 * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations 3376 * that are not applicable to the given record member 3377 */ 3378 JCModifiers modifiers = TreeInfo.getModifiers(declarationTree); 3379 /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as 3380 * it could be a type annotation 3381 */ 3382 if (modifiers != null && applicableTargets.isEmpty()) { 3383 ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>(); 3384 for (JCAnnotation anno : modifiers.annotations) { 3385 if (anno != a) { 3386 newAnnotations.add(anno); 3387 } 3388 } 3389 modifiers.annotations = newAnnotations.toList(); 3390 } 3391 // now lets remove it from the symbol 3392 s.getMetadata().removeDeclarationMetadata(a.attribute); 3393 } else { 3394 log.error(a.pos(), Errors.AnnotationTypeNotApplicable); 3395 } 3396 } 3397 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor, 3398 * then this is an error as we know that no compiler generated accessor will be a varargs 3399 * method, better to fail asap 3400 */ 3401 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) { 3402 log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s))); 3403 } 3404 } 3405 } 3406 3407 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 3408 if (s.kind != TYP) { 3409 log.error(a.pos(), Errors.BadFunctionalIntfAnno); 3410 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) { 3411 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s))); 3412 } 3413 } 3414 } 3415 3416 public void validateTypeAnnotation(JCAnnotation a, Symbol s, boolean isTypeParameter) { 3417 Assert.checkNonNull(a.type); 3418 // we just want to validate that the anotation doesn't have any wrong target 3419 if (s != null) getApplicableTargets(a, s); 3420 validateAnnotationTree(a); 3421 3422 if (a.hasTag(TYPE_ANNOTATION) && 3423 !a.annotationType.type.isErroneous() && 3424 !isTypeAnnotation(a, isTypeParameter)) { 3425 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type)); 3426 } 3427 } 3428 3429 /** 3430 * Validate the proposed container 'repeatable' on the 3431 * annotation type symbol 's'. Report errors at position 3432 * 'pos'. 3433 * 3434 * @param s The (annotation)type declaration annotated with a @Repeatable 3435 * @param repeatable the @Repeatable on 's' 3436 * @param pos where to report errors 3437 */ 3438 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) { 3439 Assert.check(types.isSameType(repeatable.type, syms.repeatableType)); 3440 3441 Type t = null; 3442 List<Pair<MethodSymbol,Attribute>> l = repeatable.values; 3443 if (!l.isEmpty()) { 3444 Assert.check(l.head.fst.name == names.value); 3445 if (l.head.snd instanceof Attribute.Class) { 3446 t = ((Attribute.Class)l.head.snd).getValue(); 3447 } 3448 } 3449 3450 if (t == null) { 3451 // errors should already have been reported during Annotate 3452 return; 3453 } 3454 3455 validateValue(t.tsym, s, pos); 3456 validateRetention(t.tsym, s, pos); 3457 validateDocumented(t.tsym, s, pos); 3458 validateInherited(t.tsym, s, pos); 3459 validateTarget(t.tsym, s, pos); 3460 validateDefault(t.tsym, pos); 3461 } 3462 3463 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3464 Symbol sym = container.members().findFirst(names.value); 3465 if (sym != null && sym.kind == MTH) { 3466 MethodSymbol m = (MethodSymbol) sym; 3467 Type ret = m.getReturnType(); 3468 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) { 3469 log.error(pos, 3470 Errors.InvalidRepeatableAnnotationValueReturn(container, 3471 ret, 3472 types.makeArrayType(contained.type))); 3473 } 3474 } else { 3475 log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container)); 3476 } 3477 } 3478 3479 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3480 Attribute.RetentionPolicy containerRetention = types.getRetention(container); 3481 Attribute.RetentionPolicy containedRetention = types.getRetention(contained); 3482 3483 boolean error = false; 3484 switch (containedRetention) { 3485 case RUNTIME: 3486 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) { 3487 error = true; 3488 } 3489 break; 3490 case CLASS: 3491 if (containerRetention == Attribute.RetentionPolicy.SOURCE) { 3492 error = true; 3493 } 3494 } 3495 if (error ) { 3496 log.error(pos, 3497 Errors.InvalidRepeatableAnnotationRetention(container, 3498 containerRetention.name(), 3499 contained, 3500 containedRetention.name())); 3501 } 3502 } 3503 3504 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) { 3505 if (contained.attribute(syms.documentedType.tsym) != null) { 3506 if (container.attribute(syms.documentedType.tsym) == null) { 3507 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained)); 3508 } 3509 } 3510 } 3511 3512 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) { 3513 if (contained.attribute(syms.inheritedType.tsym) != null) { 3514 if (container.attribute(syms.inheritedType.tsym) == null) { 3515 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained)); 3516 } 3517 } 3518 } 3519 3520 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3521 // The set of targets the container is applicable to must be a subset 3522 // (with respect to annotation target semantics) of the set of targets 3523 // the contained is applicable to. The target sets may be implicit or 3524 // explicit. 3525 3526 Set<Name> containerTargets; 3527 Attribute.Array containerTarget = getAttributeTargetAttribute(container); 3528 if (containerTarget == null) { 3529 containerTargets = getDefaultTargetSet(); 3530 } else { 3531 containerTargets = new HashSet<>(); 3532 for (Attribute app : containerTarget.values) { 3533 if (!(app instanceof Attribute.Enum attributeEnum)) { 3534 continue; // recovery 3535 } 3536 containerTargets.add(attributeEnum.value.name); 3537 } 3538 } 3539 3540 Set<Name> containedTargets; 3541 Attribute.Array containedTarget = getAttributeTargetAttribute(contained); 3542 if (containedTarget == null) { 3543 containedTargets = getDefaultTargetSet(); 3544 } else { 3545 containedTargets = new HashSet<>(); 3546 for (Attribute app : containedTarget.values) { 3547 if (!(app instanceof Attribute.Enum attributeEnum)) { 3548 continue; // recovery 3549 } 3550 containedTargets.add(attributeEnum.value.name); 3551 } 3552 } 3553 3554 if (!isTargetSubsetOf(containerTargets, containedTargets)) { 3555 log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained)); 3556 } 3557 } 3558 3559 /* get a set of names for the default target */ 3560 private Set<Name> getDefaultTargetSet() { 3561 if (defaultTargets == null) { 3562 defaultTargets = Set.of(defaultTargetMetaInfo()); 3563 } 3564 3565 return defaultTargets; 3566 } 3567 private Set<Name> defaultTargets; 3568 3569 3570 /** Checks that s is a subset of t, with respect to ElementType 3571 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}, 3572 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE, 3573 * TYPE_PARAMETER}. 3574 */ 3575 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) { 3576 // Check that all elements in s are present in t 3577 for (Name n2 : s) { 3578 boolean currentElementOk = false; 3579 for (Name n1 : t) { 3580 if (n1 == n2) { 3581 currentElementOk = true; 3582 break; 3583 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) { 3584 currentElementOk = true; 3585 break; 3586 } else if (n1 == names.TYPE_USE && 3587 (n2 == names.TYPE || 3588 n2 == names.ANNOTATION_TYPE || 3589 n2 == names.TYPE_PARAMETER)) { 3590 currentElementOk = true; 3591 break; 3592 } 3593 } 3594 if (!currentElementOk) 3595 return false; 3596 } 3597 return true; 3598 } 3599 3600 private void validateDefault(Symbol container, DiagnosticPosition pos) { 3601 // validate that all other elements of containing type has defaults 3602 Scope scope = container.members(); 3603 for(Symbol elm : scope.getSymbols()) { 3604 if (elm.name != names.value && 3605 elm.kind == MTH && 3606 ((MethodSymbol)elm).defaultValue == null) { 3607 log.error(pos, 3608 Errors.InvalidRepeatableAnnotationElemNondefault(container, elm)); 3609 } 3610 } 3611 } 3612 3613 /** Is s a method symbol that overrides a method in a superclass? */ 3614 boolean isOverrider(Symbol s) { 3615 if (s.kind != MTH || s.isStatic()) 3616 return false; 3617 MethodSymbol m = (MethodSymbol)s; 3618 TypeSymbol owner = (TypeSymbol)m.owner; 3619 for (Type sup : types.closure(owner.type)) { 3620 if (sup == owner.type) 3621 continue; // skip "this" 3622 Scope scope = sup.tsym.members(); 3623 for (Symbol sym : scope.getSymbolsByName(m.name)) { 3624 if (!sym.isStatic() && m.overrides(sym, owner, types, true)) 3625 return true; 3626 } 3627 } 3628 return false; 3629 } 3630 3631 /** Is the annotation applicable to types? */ 3632 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 3633 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym); 3634 return (targets == null) ? 3635 (Feature.NO_TARGET_ANNOTATION_APPLICABILITY.allowedInSource(source) && isTypeParameter) : 3636 targets.stream() 3637 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter)); 3638 } 3639 //where 3640 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) { 3641 Attribute.Enum e = (Attribute.Enum)a; 3642 return (e.value.name == names.TYPE_USE || 3643 (isTypeParameter && e.value.name == names.TYPE_PARAMETER)); 3644 } 3645 3646 /** Is the annotation applicable to the symbol? */ 3647 Name[] getTargetNames(JCAnnotation a) { 3648 return getTargetNames(a.annotationType.type.tsym); 3649 } 3650 3651 public Name[] getTargetNames(TypeSymbol annoSym) { 3652 Attribute.Array arr = getAttributeTargetAttribute(annoSym); 3653 Name[] targets; 3654 if (arr == null) { 3655 targets = defaultTargetMetaInfo(); 3656 } else { 3657 // TODO: can we optimize this? 3658 targets = new Name[arr.values.length]; 3659 for (int i=0; i<arr.values.length; ++i) { 3660 Attribute app = arr.values[i]; 3661 if (!(app instanceof Attribute.Enum attributeEnum)) { 3662 return new Name[0]; 3663 } 3664 targets[i] = attributeEnum.value.name; 3665 } 3666 } 3667 return targets; 3668 } 3669 3670 boolean annotationApplicable(JCAnnotation a, Symbol s) { 3671 Optional<Set<Name>> targets = getApplicableTargets(a, s); 3672 /* the optional could be empty if the annotation is unknown in that case 3673 * we return that it is applicable and if it is erroneous that should imply 3674 * an error at the declaration site 3675 */ 3676 return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty(); 3677 } 3678 3679 Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) { 3680 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym); 3681 Name[] targets; 3682 Set<Name> applicableTargets = new HashSet<>(); 3683 3684 if (arr == null) { 3685 targets = defaultTargetMetaInfo(); 3686 } else { 3687 // TODO: can we optimize this? 3688 targets = new Name[arr.values.length]; 3689 for (int i=0; i<arr.values.length; ++i) { 3690 Attribute app = arr.values[i]; 3691 if (!(app instanceof Attribute.Enum attributeEnum)) { 3692 // recovery 3693 return Optional.empty(); 3694 } 3695 targets[i] = attributeEnum.value.name; 3696 } 3697 } 3698 for (Name target : targets) { 3699 if (target == names.TYPE) { 3700 if (s.kind == TYP) 3701 applicableTargets.add(names.TYPE); 3702 } else if (target == names.FIELD) { 3703 if (s.kind == VAR && s.owner.kind != MTH) 3704 applicableTargets.add(names.FIELD); 3705 } else if (target == names.RECORD_COMPONENT) { 3706 if (s.getKind() == ElementKind.RECORD_COMPONENT) { 3707 applicableTargets.add(names.RECORD_COMPONENT); 3708 } 3709 } else if (target == names.METHOD) { 3710 if (s.kind == MTH && !s.isConstructor()) 3711 applicableTargets.add(names.METHOD); 3712 } else if (target == names.PARAMETER) { 3713 if (s.kind == VAR && 3714 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) { 3715 applicableTargets.add(names.PARAMETER); 3716 } 3717 } else if (target == names.CONSTRUCTOR) { 3718 if (s.kind == MTH && s.isConstructor()) 3719 applicableTargets.add(names.CONSTRUCTOR); 3720 } else if (target == names.LOCAL_VARIABLE) { 3721 if (s.kind == VAR && s.owner.kind == MTH && 3722 (s.flags() & PARAMETER) == 0) { 3723 applicableTargets.add(names.LOCAL_VARIABLE); 3724 } 3725 } else if (target == names.ANNOTATION_TYPE) { 3726 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) { 3727 applicableTargets.add(names.ANNOTATION_TYPE); 3728 } 3729 } else if (target == names.PACKAGE) { 3730 if (s.kind == PCK) 3731 applicableTargets.add(names.PACKAGE); 3732 } else if (target == names.TYPE_USE) { 3733 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) { 3734 //cannot type annotate implicitly typed locals 3735 continue; 3736 } else if (s.kind == TYP || s.kind == VAR || 3737 (s.kind == MTH && !s.isConstructor() && 3738 !s.type.getReturnType().hasTag(VOID)) || 3739 (s.kind == MTH && s.isConstructor())) { 3740 applicableTargets.add(names.TYPE_USE); 3741 } 3742 } else if (target == names.TYPE_PARAMETER) { 3743 if (s.kind == TYP && s.type.hasTag(TYPEVAR)) 3744 applicableTargets.add(names.TYPE_PARAMETER); 3745 } else if (target == names.MODULE) { 3746 if (s.kind == MDL) 3747 applicableTargets.add(names.MODULE); 3748 } else { 3749 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target)); 3750 return Optional.empty(); // Unknown ElementType 3751 } 3752 } 3753 return Optional.of(applicableTargets); 3754 } 3755 3756 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) { 3757 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget(); 3758 if (atTarget == null) return null; // ok, is applicable 3759 Attribute atValue = atTarget.member(names.value); 3760 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null; 3761 } 3762 3763 private Name[] dfltTargetMeta; 3764 private Name[] defaultTargetMetaInfo() { 3765 if (dfltTargetMeta == null) { 3766 ArrayList<Name> defaultTargets = new ArrayList<>(); 3767 defaultTargets.add(names.PACKAGE); 3768 defaultTargets.add(names.TYPE); 3769 defaultTargets.add(names.FIELD); 3770 defaultTargets.add(names.METHOD); 3771 defaultTargets.add(names.CONSTRUCTOR); 3772 defaultTargets.add(names.ANNOTATION_TYPE); 3773 defaultTargets.add(names.LOCAL_VARIABLE); 3774 defaultTargets.add(names.PARAMETER); 3775 if (allowRecords) { 3776 defaultTargets.add(names.RECORD_COMPONENT); 3777 } 3778 if (allowModules) { 3779 defaultTargets.add(names.MODULE); 3780 } 3781 dfltTargetMeta = defaultTargets.toArray(new Name[0]); 3782 } 3783 return dfltTargetMeta; 3784 } 3785 3786 /** Check an annotation value. 3787 * 3788 * @param a The annotation tree to check 3789 * @return true if this annotation tree is valid, otherwise false 3790 */ 3791 public boolean validateAnnotationDeferErrors(JCAnnotation a) { 3792 boolean res = false; 3793 final Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler(); 3794 try { 3795 res = validateAnnotation(a); 3796 } finally { 3797 log.popDiagnosticHandler(diagHandler); 3798 } 3799 return res; 3800 } 3801 3802 private boolean validateAnnotation(JCAnnotation a) { 3803 boolean isValid = true; 3804 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata(); 3805 3806 // collect an inventory of the annotation elements 3807 Set<MethodSymbol> elements = metadata.getAnnotationElements(); 3808 3809 // remove the ones that are assigned values 3810 for (JCTree arg : a.args) { 3811 if (!arg.hasTag(ASSIGN)) continue; // recovery 3812 JCAssign assign = (JCAssign)arg; 3813 Symbol m = TreeInfo.symbol(assign.lhs); 3814 if (m == null || m.type.isErroneous()) continue; 3815 if (!elements.remove(m)) { 3816 isValid = false; 3817 log.error(assign.lhs.pos(), 3818 Errors.DuplicateAnnotationMemberValue(m.name, a.type)); 3819 } 3820 } 3821 3822 // all the remaining ones better have default values 3823 List<Name> missingDefaults = List.nil(); 3824 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault(); 3825 for (MethodSymbol m : elements) { 3826 if (m.type.isErroneous()) 3827 continue; 3828 3829 if (!membersWithDefault.contains(m)) 3830 missingDefaults = missingDefaults.append(m.name); 3831 } 3832 missingDefaults = missingDefaults.reverse(); 3833 if (missingDefaults.nonEmpty()) { 3834 isValid = false; 3835 Error errorKey = (missingDefaults.size() > 1) 3836 ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults) 3837 : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults); 3838 log.error(a.pos(), errorKey); 3839 } 3840 3841 return isValid && validateTargetAnnotationValue(a); 3842 } 3843 3844 /* Validate the special java.lang.annotation.Target annotation */ 3845 boolean validateTargetAnnotationValue(JCAnnotation a) { 3846 // special case: java.lang.annotation.Target must not have 3847 // repeated values in its value member 3848 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym || 3849 a.args.tail == null) 3850 return true; 3851 3852 boolean isValid = true; 3853 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery 3854 JCAssign assign = (JCAssign) a.args.head; 3855 Symbol m = TreeInfo.symbol(assign.lhs); 3856 if (m.name != names.value) return false; 3857 JCTree rhs = assign.rhs; 3858 if (!rhs.hasTag(NEWARRAY)) return false; 3859 JCNewArray na = (JCNewArray) rhs; 3860 Set<Symbol> targets = new HashSet<>(); 3861 for (JCTree elem : na.elems) { 3862 if (!targets.add(TreeInfo.symbol(elem))) { 3863 isValid = false; 3864 log.error(elem.pos(), Errors.RepeatedAnnotationTarget); 3865 } 3866 } 3867 return isValid; 3868 } 3869 3870 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { 3871 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() && 3872 (s.flags() & DEPRECATED) != 0 && 3873 !syms.deprecatedType.isErroneous() && 3874 s.attribute(syms.deprecatedType.tsym) == null) { 3875 log.warning(pos, LintWarnings.MissingDeprecatedAnnotation); 3876 } 3877 // Note: @Deprecated has no effect on local variables, parameters and package decls. 3878 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) { 3879 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) { 3880 log.warning(pos, 3881 LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s))); 3882 } 3883 } 3884 } 3885 3886 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) { 3887 checkDeprecated(() -> pos, other, s); 3888 } 3889 3890 void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) { 3891 if (!importSuppression 3892 && (s.isDeprecatedForRemoval() || s.isDeprecated() && !other.isDeprecated()) 3893 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null) 3894 && s.kind != Kind.PCK) { 3895 deferredLintHandler.report(_l -> warnDeprecated(pos.get(), s)); 3896 } 3897 } 3898 3899 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) { 3900 if ((s.flags() & PROPRIETARY) != 0) { 3901 deferredLintHandler.report(_l -> { 3902 log.mandatoryWarning(pos, Warnings.SunProprietary(s)); 3903 }); 3904 } 3905 } 3906 3907 void checkProfile(final DiagnosticPosition pos, final Symbol s) { 3908 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) { 3909 log.error(pos, Errors.NotInProfile(s, profile)); 3910 } 3911 } 3912 3913 void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) { 3914 checkPreview(pos, other, Type.noType, s); 3915 } 3916 3917 void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) { 3918 boolean sIsPreview; 3919 Symbol previewSymbol; 3920 if ((s.flags() & PREVIEW_API) != 0) { 3921 sIsPreview = true; 3922 previewSymbol= s; 3923 } else if ((s.kind == Kind.MTH || s.kind == Kind.VAR) && 3924 site.tsym != null && 3925 (site.tsym.flags() & PREVIEW_API) == 0 && 3926 (s.owner.flags() & PREVIEW_API) != 0) { 3927 //calling a method, or using a field, whose owner is a preview, but 3928 //using a site that is not a preview. Also produce an error or warning: 3929 sIsPreview = true; 3930 previewSymbol = s.owner; 3931 } else { 3932 sIsPreview = false; 3933 previewSymbol = null; 3934 } 3935 if (sIsPreview && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) { 3936 if ((previewSymbol.flags() & PREVIEW_REFLECTIVE) == 0) { 3937 if (!preview.isEnabled()) { 3938 log.error(pos, Errors.IsPreview(s)); 3939 } else { 3940 preview.markUsesPreview(pos); 3941 warnPreviewAPI(pos, LintWarnings.IsPreview(s)); 3942 } 3943 } else { 3944 warnPreviewAPI(pos, LintWarnings.IsPreviewReflective(s)); 3945 } 3946 } 3947 if (preview.declaredUsingPreviewFeature(s)) { 3948 if (preview.isEnabled()) { 3949 //for preview disabled do presumably so not need to do anything? 3950 //If "s" is compiled from source, then there was an error for it already; 3951 //if "s" is from classfile, there already was an error for the classfile. 3952 preview.markUsesPreview(pos); 3953 warnPreviewAPI(pos, LintWarnings.DeclaredUsingPreview(kindName(s), s)); 3954 } 3955 } 3956 } 3957 3958 void checkRestricted(DiagnosticPosition pos, Symbol s) { 3959 if (s.kind == MTH && (s.flags() & RESTRICTED) != 0) { 3960 deferredLintHandler.report(_l -> warnRestrictedAPI(pos, s)); 3961 } 3962 } 3963 3964 /* ************************************************************************* 3965 * Check for recursive annotation elements. 3966 **************************************************************************/ 3967 3968 /** Check for cycles in the graph of annotation elements. 3969 */ 3970 void checkNonCyclicElements(JCClassDecl tree) { 3971 if ((tree.sym.flags_field & ANNOTATION) == 0) return; 3972 Assert.check((tree.sym.flags_field & LOCKED) == 0); 3973 try { 3974 tree.sym.flags_field |= LOCKED; 3975 for (JCTree def : tree.defs) { 3976 if (!def.hasTag(METHODDEF)) continue; 3977 JCMethodDecl meth = (JCMethodDecl)def; 3978 checkAnnotationResType(meth.pos(), meth.restype.type); 3979 } 3980 } finally { 3981 tree.sym.flags_field &= ~LOCKED; 3982 tree.sym.flags_field |= ACYCLIC_ANN; 3983 } 3984 } 3985 3986 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) { 3987 if ((tsym.flags_field & ACYCLIC_ANN) != 0) 3988 return; 3989 if ((tsym.flags_field & LOCKED) != 0) { 3990 log.error(pos, Errors.CyclicAnnotationElement(tsym)); 3991 return; 3992 } 3993 try { 3994 tsym.flags_field |= LOCKED; 3995 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) { 3996 if (s.kind != MTH) 3997 continue; 3998 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType()); 3999 } 4000 } finally { 4001 tsym.flags_field &= ~LOCKED; 4002 tsym.flags_field |= ACYCLIC_ANN; 4003 } 4004 } 4005 4006 void checkAnnotationResType(DiagnosticPosition pos, Type type) { 4007 switch (type.getTag()) { 4008 case CLASS: 4009 if ((type.tsym.flags() & ANNOTATION) != 0) 4010 checkNonCyclicElementsInternal(pos, type.tsym); 4011 break; 4012 case ARRAY: 4013 checkAnnotationResType(pos, types.elemtype(type)); 4014 break; 4015 default: 4016 break; // int etc 4017 } 4018 } 4019 4020 /* ************************************************************************* 4021 * Check for cycles in the constructor call graph. 4022 **************************************************************************/ 4023 4024 /** Check for cycles in the graph of constructors calling other 4025 * constructors. 4026 */ 4027 void checkCyclicConstructors(JCClassDecl tree) { 4028 // use LinkedHashMap so we generate errors deterministically 4029 Map<Symbol,Symbol> callMap = new LinkedHashMap<>(); 4030 4031 // enter each constructor this-call into the map 4032 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 4033 if (!TreeInfo.isConstructor(l.head)) 4034 continue; 4035 JCMethodDecl meth = (JCMethodDecl)l.head; 4036 JCMethodInvocation app = TreeInfo.findConstructorCall(meth); 4037 if (app != null && TreeInfo.name(app.meth) == names._this) { 4038 callMap.put(meth.sym, TreeInfo.symbol(app.meth)); 4039 } else { 4040 meth.sym.flags_field |= ACYCLIC; 4041 } 4042 } 4043 4044 // Check for cycles in the map 4045 Symbol[] ctors = new Symbol[0]; 4046 ctors = callMap.keySet().toArray(ctors); 4047 for (Symbol caller : ctors) { 4048 checkCyclicConstructor(tree, caller, callMap); 4049 } 4050 } 4051 4052 /** Look in the map to see if the given constructor is part of a 4053 * call cycle. 4054 */ 4055 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor, 4056 Map<Symbol,Symbol> callMap) { 4057 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) { 4058 if ((ctor.flags_field & LOCKED) != 0) { 4059 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)), 4060 Errors.RecursiveCtorInvocation); 4061 } else { 4062 ctor.flags_field |= LOCKED; 4063 checkCyclicConstructor(tree, callMap.remove(ctor), callMap); 4064 ctor.flags_field &= ~LOCKED; 4065 } 4066 ctor.flags_field |= ACYCLIC; 4067 } 4068 } 4069 4070 /* ************************************************************************* 4071 * Verify the proper placement of super()/this() calls. 4072 * 4073 * - super()/this() may only appear in constructors 4074 * - There must be at most one super()/this() call per constructor 4075 * - The super()/this() call, if any, must be a top-level statement in the 4076 * constructor, i.e., not nested inside any other statement or block 4077 * - There must be no return statements prior to the super()/this() call 4078 **************************************************************************/ 4079 4080 void checkSuperInitCalls(JCClassDecl tree) { 4081 new SuperThisChecker().check(tree); 4082 } 4083 4084 private class SuperThisChecker extends TreeScanner { 4085 4086 // Match this scan stack: 1=JCMethodDecl, 2=JCExpressionStatement, 3=JCMethodInvocation 4087 private static final int MATCH_SCAN_DEPTH = 3; 4088 4089 private boolean constructor; // is this method a constructor? 4090 private boolean firstStatement; // at the first statement in method? 4091 private JCReturn earlyReturn; // first return prior to the super()/init(), if any 4092 private Name initCall; // whichever of "super" or "init" we've seen already 4093 private int scanDepth; // current scan recursion depth in method body 4094 4095 public void check(JCClassDecl classDef) { 4096 scan(classDef.defs); 4097 } 4098 4099 @Override 4100 public void visitMethodDef(JCMethodDecl tree) { 4101 Assert.check(!constructor); 4102 Assert.check(earlyReturn == null); 4103 Assert.check(initCall == null); 4104 Assert.check(scanDepth == 1); 4105 4106 // Initialize state for this method 4107 constructor = TreeInfo.isConstructor(tree); 4108 try { 4109 4110 // Scan method body 4111 if (tree.body != null) { 4112 firstStatement = true; 4113 for (List<JCStatement> l = tree.body.stats; l.nonEmpty(); l = l.tail) { 4114 scan(l.head); 4115 firstStatement = false; 4116 } 4117 } 4118 4119 // Verify no 'return' seen prior to an explicit super()/this() call 4120 if (constructor && earlyReturn != null && initCall != null) 4121 log.error(earlyReturn.pos(), Errors.ReturnBeforeSuperclassInitialized); 4122 } finally { 4123 firstStatement = false; 4124 constructor = false; 4125 earlyReturn = null; 4126 initCall = null; 4127 } 4128 } 4129 4130 @Override 4131 public void scan(JCTree tree) { 4132 scanDepth++; 4133 try { 4134 super.scan(tree); 4135 } finally { 4136 scanDepth--; 4137 } 4138 } 4139 4140 @Override 4141 public void visitApply(JCMethodInvocation apply) { 4142 do { 4143 4144 // Is this a super() or this() call? 4145 Name methodName = TreeInfo.name(apply.meth); 4146 if (methodName != names._super && methodName != names._this) 4147 break; 4148 4149 // super()/this() calls must only appear in a constructor 4150 if (!constructor) { 4151 log.error(apply.pos(), Errors.CallMustOnlyAppearInCtor); 4152 break; 4153 } 4154 4155 // super()/this() calls must be a top level statement 4156 if (scanDepth != MATCH_SCAN_DEPTH) { 4157 log.error(apply.pos(), Errors.CtorCallsNotAllowedHere); 4158 break; 4159 } 4160 4161 // super()/this() calls must not appear more than once 4162 if (initCall != null) { 4163 log.error(apply.pos(), Errors.RedundantSuperclassInit); 4164 break; 4165 } 4166 4167 // If super()/this() isn't first, require flexible constructors feature 4168 if (!firstStatement) 4169 preview.checkSourceLevel(apply.pos(), Feature.FLEXIBLE_CONSTRUCTORS); 4170 4171 // We found a legitimate super()/this() call; remember it 4172 initCall = methodName; 4173 } while (false); 4174 4175 // Proceed 4176 super.visitApply(apply); 4177 } 4178 4179 @Override 4180 public void visitReturn(JCReturn tree) { 4181 if (constructor && initCall == null && earlyReturn == null) 4182 earlyReturn = tree; // we have seen a return but not (yet) a super()/this() 4183 super.visitReturn(tree); 4184 } 4185 4186 @Override 4187 public void visitClassDef(JCClassDecl tree) { 4188 // don't descend any further 4189 } 4190 4191 @Override 4192 public void visitLambda(JCLambda tree) { 4193 final boolean constructorPrev = constructor; 4194 final boolean firstStatementPrev = firstStatement; 4195 final JCReturn earlyReturnPrev = earlyReturn; 4196 final Name initCallPrev = initCall; 4197 final int scanDepthPrev = scanDepth; 4198 constructor = false; 4199 firstStatement = false; 4200 earlyReturn = null; 4201 initCall = null; 4202 scanDepth = 0; 4203 try { 4204 super.visitLambda(tree); 4205 } finally { 4206 constructor = constructorPrev; 4207 firstStatement = firstStatementPrev; 4208 earlyReturn = earlyReturnPrev; 4209 initCall = initCallPrev; 4210 scanDepth = scanDepthPrev; 4211 } 4212 } 4213 } 4214 4215 /* ************************************************************************* 4216 * Miscellaneous 4217 **************************************************************************/ 4218 4219 /** 4220 * Check for division by integer constant zero 4221 * @param pos Position for error reporting. 4222 * @param operator The operator for the expression 4223 * @param operand The right hand operand for the expression 4224 */ 4225 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { 4226 if (operand.constValue() != null 4227 && operand.getTag().isSubRangeOf(LONG) 4228 && ((Number) (operand.constValue())).longValue() == 0) { 4229 int opc = ((OperatorSymbol)operator).opcode; 4230 if (opc == ByteCodes.idiv || opc == ByteCodes.imod 4231 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) { 4232 deferredLintHandler.report(_ -> lint.logIfEnabled(pos, LintWarnings.DivZero)); 4233 } 4234 } 4235 } 4236 4237 /** 4238 * Check for possible loss of precission 4239 * @param pos Position for error reporting. 4240 * @param found The computed type of the tree 4241 * @param req The computed type of the tree 4242 */ 4243 void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) { 4244 if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) { 4245 deferredLintHandler.report(_ -> 4246 lint.logIfEnabled(pos, LintWarnings.PossibleLossOfPrecision(found, req))); 4247 } 4248 } 4249 4250 /** 4251 * Check for empty statements after if 4252 */ 4253 void checkEmptyIf(JCIf tree) { 4254 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) { 4255 lint.logIfEnabled(tree.thenpart.pos(), LintWarnings.EmptyIf); 4256 } 4257 } 4258 4259 /** Check that symbol is unique in given scope. 4260 * @param pos Position for error reporting. 4261 * @param sym The symbol. 4262 * @param s The scope. 4263 */ 4264 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) { 4265 if (sym.type.isErroneous()) 4266 return true; 4267 if (sym.owner.name == names.any) return false; 4268 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) { 4269 if (sym != byName && 4270 (byName.flags() & CLASH) == 0 && 4271 sym.kind == byName.kind && 4272 sym.name != names.error && 4273 (sym.kind != MTH || 4274 types.hasSameArgs(sym.type, byName.type) || 4275 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) { 4276 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) { 4277 sym.flags_field |= CLASH; 4278 varargsDuplicateError(pos, sym, byName); 4279 return true; 4280 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) { 4281 duplicateErasureError(pos, sym, byName); 4282 sym.flags_field |= CLASH; 4283 return true; 4284 } else if ((sym.flags() & MATCH_BINDING) != 0 && 4285 (byName.flags() & MATCH_BINDING) != 0 && 4286 (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) { 4287 if (!sym.type.isErroneous()) { 4288 log.error(pos, Errors.MatchBindingExists); 4289 sym.flags_field |= CLASH; 4290 } 4291 return false; 4292 } else { 4293 duplicateError(pos, byName); 4294 return false; 4295 } 4296 } 4297 } 4298 return true; 4299 } 4300 4301 /** Report duplicate declaration error. 4302 */ 4303 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 4304 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 4305 log.error(pos, Errors.NameClashSameErasure(sym1, sym2)); 4306 } 4307 } 4308 4309 /**Check that types imported through the ordinary imports don't clash with types imported 4310 * by other (static or ordinary) imports. Note that two static imports may import two clashing 4311 * types without an error on the imports. 4312 * @param toplevel The toplevel tree for which the test should be performed. 4313 */ 4314 void checkImportsUnique(JCCompilationUnit toplevel) { 4315 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge); 4316 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge); 4317 WriteableScope topLevelScope = toplevel.toplevelScope; 4318 4319 for (JCTree def : toplevel.defs) { 4320 if (!def.hasTag(IMPORT)) 4321 continue; 4322 4323 JCImport imp = (JCImport) def; 4324 4325 if (imp.importScope == null) 4326 continue; 4327 4328 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) { 4329 if (imp.isStatic()) { 4330 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true); 4331 staticallyImportedSoFar.enter(sym); 4332 } else { 4333 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false); 4334 ordinallyImportedSoFar.enter(sym); 4335 } 4336 } 4337 4338 imp.importScope = null; 4339 } 4340 } 4341 4342 /** Check that single-type import is not already imported or top-level defined, 4343 * but make an exception for two single-type imports which denote the same type. 4344 * @param pos Position for error reporting. 4345 * @param ordinallyImportedSoFar A Scope containing types imported so far through 4346 * ordinary imports. 4347 * @param staticallyImportedSoFar A Scope containing types imported so far through 4348 * static imports. 4349 * @param topLevelScope The current file's top-level Scope 4350 * @param sym The symbol. 4351 * @param staticImport Whether or not this was a static import 4352 */ 4353 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar, 4354 Scope staticallyImportedSoFar, Scope topLevelScope, 4355 Symbol sym, boolean staticImport) { 4356 Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous(); 4357 Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates); 4358 Symbol staticClashing = null; 4359 if (ordinaryClashing == null && !staticImport) { 4360 staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates); 4361 } 4362 if (ordinaryClashing != null || staticClashing != null) { 4363 if (ordinaryClashing != null) 4364 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing)); 4365 else 4366 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing)); 4367 return false; 4368 } 4369 Symbol clashing = topLevelScope.findFirst(sym.name, duplicates); 4370 if (clashing != null) { 4371 log.error(pos, Errors.AlreadyDefinedThisUnit(clashing)); 4372 return false; 4373 } 4374 return true; 4375 } 4376 4377 /** Check that a qualified name is in canonical form (for import decls). 4378 */ 4379 public void checkCanonical(JCTree tree) { 4380 if (!isCanonical(tree)) 4381 log.error(tree.pos(), 4382 Errors.ImportRequiresCanonical(TreeInfo.symbol(tree))); 4383 } 4384 // where 4385 private boolean isCanonical(JCTree tree) { 4386 while (tree.hasTag(SELECT)) { 4387 JCFieldAccess s = (JCFieldAccess) tree; 4388 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName()) 4389 return false; 4390 tree = s.selected; 4391 } 4392 return true; 4393 } 4394 4395 /** Check that an auxiliary class is not accessed from any other file than its own. 4396 */ 4397 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) { 4398 if ((c.flags() & AUXILIARY) != 0 && 4399 rs.isAccessible(env, c) && 4400 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile)) 4401 { 4402 lint.logIfEnabled(pos, 4403 LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile)); 4404 } 4405 } 4406 4407 /** 4408 * Check for a default constructor in an exported package. 4409 */ 4410 void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) { 4411 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) && 4412 ((c.flags() & (ENUM | RECORD)) == 0) && 4413 !c.isAnonymous() && 4414 ((c.flags() & (PUBLIC | PROTECTED)) != 0) && 4415 Feature.MODULES.allowedInSource(source)) { 4416 NestingKind nestingKind = c.getNestingKind(); 4417 switch (nestingKind) { 4418 case ANONYMOUS, 4419 LOCAL -> {return;} 4420 case TOP_LEVEL -> {;} // No additional checks needed 4421 case MEMBER -> { 4422 // For nested member classes, all the enclosing 4423 // classes must be public or protected. 4424 Symbol owner = c.owner; 4425 while (owner != null && owner.kind == TYP) { 4426 if ((owner.flags() & (PUBLIC | PROTECTED)) == 0) 4427 return; 4428 owner = owner.owner; 4429 } 4430 } 4431 } 4432 4433 // Only check classes in named packages exported by its module 4434 PackageSymbol pkg = c.packge(); 4435 if (!pkg.isUnnamed()) { 4436 ModuleSymbol modle = pkg.modle; 4437 for (ExportsDirective exportDir : modle.exports) { 4438 // Report warning only if the containing 4439 // package is unconditionally exported 4440 if (exportDir.packge.equals(pkg)) { 4441 if (exportDir.modules == null || exportDir.modules.isEmpty()) { 4442 // Warning may be suppressed by 4443 // annotations; check again for being 4444 // enabled in the deferred context. 4445 deferredLintHandler.report(_ -> 4446 lint.logIfEnabled(pos, LintWarnings.MissingExplicitCtor(c, pkg, modle))); 4447 } else { 4448 return; 4449 } 4450 } 4451 } 4452 } 4453 } 4454 return; 4455 } 4456 4457 private class ConversionWarner extends Warner { 4458 final String uncheckedKey; 4459 final Type found; 4460 final Type expected; 4461 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) { 4462 super(pos); 4463 this.uncheckedKey = uncheckedKey; 4464 this.found = found; 4465 this.expected = expected; 4466 } 4467 4468 @Override 4469 public void warn(LintCategory lint) { 4470 boolean warned = this.warned; 4471 super.warn(lint); 4472 if (warned) return; // suppress redundant diagnostics 4473 switch (lint) { 4474 case UNCHECKED: 4475 Check.this.warnUnchecked(pos(), LintWarnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected)); 4476 break; 4477 case VARARGS: 4478 if (method != null && 4479 method.attribute(syms.trustMeType.tsym) != null && 4480 isTrustMeAllowedOnMethod(method) && 4481 !types.isReifiable(method.type.getParameterTypes().last())) { 4482 Check.this.lint.logIfEnabled(pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last())); 4483 } 4484 break; 4485 default: 4486 throw new AssertionError("Unexpected lint: " + lint); 4487 } 4488 } 4489 } 4490 4491 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) { 4492 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected); 4493 } 4494 4495 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) { 4496 return new ConversionWarner(pos, "unchecked.assign", found, expected); 4497 } 4498 4499 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) { 4500 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym); 4501 4502 if (functionalType != null) { 4503 try { 4504 types.findDescriptorSymbol((TypeSymbol)cs); 4505 } catch (Types.FunctionDescriptorLookupError ex) { 4506 DiagnosticPosition pos = tree.pos(); 4507 for (JCAnnotation a : tree.getModifiers().annotations) { 4508 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 4509 pos = a.pos(); 4510 break; 4511 } 4512 } 4513 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic())); 4514 } 4515 } 4516 } 4517 4518 public void checkImportsResolvable(final JCCompilationUnit toplevel) { 4519 for (final JCImportBase impBase : toplevel.getImports()) { 4520 if (!(impBase instanceof JCImport imp)) 4521 continue; 4522 if (!imp.staticImport || !imp.qualid.hasTag(SELECT)) 4523 continue; 4524 final JCFieldAccess select = imp.qualid; 4525 final Symbol origin; 4526 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP) 4527 continue; 4528 4529 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected); 4530 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) { 4531 log.error(imp.pos(), 4532 Errors.CantResolveLocation(KindName.STATIC, 4533 select.name, 4534 null, 4535 null, 4536 Fragments.Location(kindName(site), 4537 site, 4538 null))); 4539 } 4540 } 4541 } 4542 4543 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2) 4544 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) { 4545 OUTER: for (JCImportBase impBase : toplevel.getImports()) { 4546 if (impBase instanceof JCImport imp && !imp.staticImport && 4547 TreeInfo.name(imp.qualid) == names.asterisk) { 4548 TypeSymbol tsym = imp.qualid.selected.type.tsym; 4549 if (tsym.kind == PCK && tsym.members().isEmpty() && 4550 !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) { 4551 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.qualid.selected.pos(), Errors.DoesntExist(tsym)); 4552 } 4553 } 4554 } 4555 } 4556 4557 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) { 4558 if (tsym == null || !processed.add(tsym)) 4559 return false; 4560 4561 // also search through inherited names 4562 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed)) 4563 return true; 4564 4565 for (Type t : types.interfaces(tsym.type)) 4566 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed)) 4567 return true; 4568 4569 for (Symbol sym : tsym.members().getSymbolsByName(name)) { 4570 if (sym.isStatic() && 4571 importAccessible(sym, packge) && 4572 sym.isMemberOf(origin, types)) { 4573 return true; 4574 } 4575 } 4576 4577 return false; 4578 } 4579 4580 // is the sym accessible everywhere in packge? 4581 public boolean importAccessible(Symbol sym, PackageSymbol packge) { 4582 try { 4583 int flags = (int)(sym.flags() & AccessFlags); 4584 switch (flags) { 4585 default: 4586 case PUBLIC: 4587 return true; 4588 case PRIVATE: 4589 return false; 4590 case 0: 4591 case PROTECTED: 4592 return sym.packge() == packge; 4593 } 4594 } catch (ClassFinder.BadClassFile err) { 4595 throw err; 4596 } catch (CompletionFailure ex) { 4597 return false; 4598 } 4599 } 4600 4601 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) { 4602 JCCompilationUnit toplevel = env.toplevel; 4603 4604 if ( toplevel.modle == syms.unnamedModule 4605 || toplevel.modle == syms.noModule 4606 || (check.sym.flags() & COMPOUND) != 0) { 4607 return ; 4608 } 4609 4610 ExportsDirective currentExport = findExport(toplevel.packge); 4611 4612 if ( currentExport == null //not exported 4613 || currentExport.modules != null) //don't check classes in qualified export 4614 return ; 4615 4616 new TreeScanner() { 4617 Lint lint = env.info.lint; 4618 boolean inSuperType; 4619 4620 @Override 4621 public void visitBlock(JCBlock tree) { 4622 } 4623 @Override 4624 public void visitMethodDef(JCMethodDecl tree) { 4625 if (!isAPISymbol(tree.sym)) 4626 return; 4627 Lint prevLint = lint; 4628 try { 4629 lint = lint.augment(tree.sym); 4630 if (lint.isEnabled(LintCategory.EXPORTS)) { 4631 super.visitMethodDef(tree); 4632 } 4633 } finally { 4634 lint = prevLint; 4635 } 4636 } 4637 @Override 4638 public void visitVarDef(JCVariableDecl tree) { 4639 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH) 4640 return; 4641 Lint prevLint = lint; 4642 try { 4643 lint = lint.augment(tree.sym); 4644 if (lint.isEnabled(LintCategory.EXPORTS)) { 4645 scan(tree.mods); 4646 scan(tree.vartype); 4647 } 4648 } finally { 4649 lint = prevLint; 4650 } 4651 } 4652 @Override 4653 public void visitClassDef(JCClassDecl tree) { 4654 if (tree != check) 4655 return ; 4656 4657 if (!isAPISymbol(tree.sym)) 4658 return ; 4659 4660 Lint prevLint = lint; 4661 try { 4662 lint = lint.augment(tree.sym); 4663 if (lint.isEnabled(LintCategory.EXPORTS)) { 4664 scan(tree.mods); 4665 scan(tree.typarams); 4666 try { 4667 inSuperType = true; 4668 scan(tree.extending); 4669 scan(tree.implementing); 4670 } finally { 4671 inSuperType = false; 4672 } 4673 scan(tree.defs); 4674 } 4675 } finally { 4676 lint = prevLint; 4677 } 4678 } 4679 @Override 4680 public void visitTypeApply(JCTypeApply tree) { 4681 scan(tree.clazz); 4682 boolean oldInSuperType = inSuperType; 4683 try { 4684 inSuperType = false; 4685 scan(tree.arguments); 4686 } finally { 4687 inSuperType = oldInSuperType; 4688 } 4689 } 4690 @Override 4691 public void visitIdent(JCIdent tree) { 4692 Symbol sym = TreeInfo.symbol(tree); 4693 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) { 4694 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 4695 } 4696 } 4697 4698 @Override 4699 public void visitSelect(JCFieldAccess tree) { 4700 Symbol sym = TreeInfo.symbol(tree); 4701 Symbol sitesym = TreeInfo.symbol(tree.selected); 4702 if (sym.kind == TYP && sitesym.kind == PCK) { 4703 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 4704 } else { 4705 super.visitSelect(tree); 4706 } 4707 } 4708 4709 @Override 4710 public void visitAnnotation(JCAnnotation tree) { 4711 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null) 4712 super.visitAnnotation(tree); 4713 } 4714 4715 }.scan(check); 4716 } 4717 //where: 4718 private ExportsDirective findExport(PackageSymbol pack) { 4719 for (ExportsDirective d : pack.modle.exports) { 4720 if (d.packge == pack) 4721 return d; 4722 } 4723 4724 return null; 4725 } 4726 private boolean isAPISymbol(Symbol sym) { 4727 while (sym.kind != PCK) { 4728 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) { 4729 return false; 4730 } 4731 sym = sym.owner; 4732 } 4733 return true; 4734 } 4735 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) { 4736 if (!isAPISymbol(what) && !inSuperType) { //package private/private element 4737 log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); 4738 return ; 4739 } 4740 4741 PackageSymbol whatPackage = what.packge(); 4742 ExportsDirective whatExport = findExport(whatPackage); 4743 ExportsDirective inExport = findExport(inPackage); 4744 4745 if (whatExport == null) { //package not exported: 4746 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle)); 4747 return ; 4748 } 4749 4750 if (whatExport.modules != null) { 4751 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) { 4752 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); 4753 } 4754 } 4755 4756 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) { 4757 //check that relativeTo.modle requires transitive what.modle, somehow: 4758 List<ModuleSymbol> todo = List.of(inPackage.modle); 4759 4760 while (todo.nonEmpty()) { 4761 ModuleSymbol current = todo.head; 4762 todo = todo.tail; 4763 if (current == whatPackage.modle) 4764 return ; //OK 4765 if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0) 4766 continue; //for automatic modules, don't look into their dependencies 4767 for (RequiresDirective req : current.requires) { 4768 if (req.isTransitive()) { 4769 todo = todo.prepend(req.module); 4770 } 4771 } 4772 } 4773 4774 log.warning(pos, LintWarnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle)); 4775 } 4776 } 4777 4778 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) { 4779 if (msym.kind != MDL) { 4780 deferredLintHandler.report(_ -> 4781 lint.logIfEnabled(pos, LintWarnings.ModuleNotFound(msym))); 4782 } 4783 } 4784 4785 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) { 4786 if (packge.members().isEmpty() && 4787 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) { 4788 deferredLintHandler.report(_ -> 4789 lint.logIfEnabled(pos, LintWarnings.PackageEmptyOrNotFound(packge))); 4790 } 4791 } 4792 4793 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) { 4794 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) { 4795 deferredLintHandler.report(_ -> { 4796 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) { 4797 log.warning(pos, LintWarnings.RequiresTransitiveAutomatic); 4798 } else { 4799 lint.logIfEnabled(pos, LintWarnings.RequiresAutomatic); 4800 } 4801 }); 4802 } 4803 } 4804 4805 /** 4806 * Verify the case labels conform to the constraints. Checks constraints related 4807 * combinations of patterns and other labels. 4808 * 4809 * @param cases the cases that should be checked. 4810 */ 4811 void checkSwitchCaseStructure(List<JCCase> cases) { 4812 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4813 JCCase c = l.head; 4814 if (c.labels.head instanceof JCConstantCaseLabel constLabel) { 4815 if (TreeInfo.isNull(constLabel.expr)) { 4816 if (c.labels.tail.nonEmpty()) { 4817 if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) { 4818 if (c.labels.tail.tail.nonEmpty()) { 4819 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination); 4820 } 4821 } else { 4822 log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination); 4823 } 4824 } 4825 } else { 4826 for (JCCaseLabel label : c.labels.tail) { 4827 if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) { 4828 log.error(label.pos(), Errors.InvalidCaseLabelCombination); 4829 break; 4830 } 4831 } 4832 } 4833 } else if (c.labels.tail.nonEmpty()) { 4834 var patterCaseLabels = c.labels.stream().filter(ll -> ll instanceof JCPatternCaseLabel).map(cl -> (JCPatternCaseLabel)cl); 4835 var allUnderscore = patterCaseLabels.allMatch(pcl -> !hasBindings(pcl.getPattern())); 4836 4837 if (!allUnderscore) { 4838 log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern); 4839 } 4840 4841 boolean allPatternCaseLabels = c.labels.stream().allMatch(p -> p instanceof JCPatternCaseLabel); 4842 4843 if (allPatternCaseLabels) { 4844 preview.checkSourceLevel(c.labels.tail.head.pos(), Feature.UNNAMED_VARIABLES); 4845 } 4846 4847 for (JCCaseLabel label : c.labels.tail) { 4848 if (label instanceof JCConstantCaseLabel) { 4849 log.error(label.pos(), Errors.InvalidCaseLabelCombination); 4850 break; 4851 } 4852 } 4853 } 4854 } 4855 4856 boolean isCaseStatementGroup = cases.nonEmpty() && 4857 cases.head.caseKind == CaseTree.CaseKind.STATEMENT; 4858 4859 if (isCaseStatementGroup) { 4860 boolean previousCompletessNormally = false; 4861 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4862 JCCase c = l.head; 4863 if (previousCompletessNormally && 4864 c.stats.nonEmpty() && 4865 c.labels.head instanceof JCPatternCaseLabel patternLabel && 4866 (hasBindings(patternLabel.pat) || hasBindings(c.guard))) { 4867 log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern); 4868 } else if (c.stats.isEmpty() && 4869 c.labels.head instanceof JCPatternCaseLabel patternLabel && 4870 (hasBindings(patternLabel.pat) || hasBindings(c.guard)) && 4871 hasStatements(l.tail)) { 4872 log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern); 4873 } 4874 previousCompletessNormally = c.completesNormally; 4875 } 4876 } 4877 } 4878 4879 boolean hasBindings(JCTree p) { 4880 boolean[] bindings = new boolean[1]; 4881 4882 new TreeScanner() { 4883 @Override 4884 public void visitBindingPattern(JCBindingPattern tree) { 4885 bindings[0] |= !tree.var.sym.isUnnamedVariable(); 4886 super.visitBindingPattern(tree); 4887 } 4888 }.scan(p); 4889 4890 return bindings[0]; 4891 } 4892 4893 boolean hasStatements(List<JCCase> cases) { 4894 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4895 if (l.head.stats.nonEmpty()) { 4896 return true; 4897 } 4898 } 4899 4900 return false; 4901 } 4902 void checkSwitchCaseLabelDominated(JCCaseLabel unconditionalCaseLabel, List<JCCase> cases) { 4903 List<Pair<JCCase, JCCaseLabel>> caseLabels = List.nil(); 4904 boolean seenDefault = false; 4905 boolean seenDefaultLabel = false; 4906 boolean warnDominatedByDefault = false; 4907 boolean unconditionalFound = false; 4908 4909 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4910 JCCase c = l.head; 4911 for (JCCaseLabel label : c.labels) { 4912 if (label.hasTag(DEFAULTCASELABEL)) { 4913 seenDefault = true; 4914 seenDefaultLabel |= 4915 TreeInfo.isNullCaseLabel(c.labels.head); 4916 continue; 4917 } 4918 if (TreeInfo.isNullCaseLabel(label)) { 4919 if (seenDefault) { 4920 log.error(label.pos(), Errors.PatternDominated); 4921 } 4922 continue; 4923 } 4924 if (seenDefault && !warnDominatedByDefault) { 4925 if (label.hasTag(PATTERNCASELABEL) || 4926 (label instanceof JCConstantCaseLabel && seenDefaultLabel)) { 4927 log.error(label.pos(), Errors.PatternDominated); 4928 warnDominatedByDefault = true; 4929 } 4930 } 4931 Type currentType = labelType(label); 4932 for (Pair<JCCase, JCCaseLabel> caseAndLabel : caseLabels) { 4933 JCCase testCase = caseAndLabel.fst; 4934 JCCaseLabel testCaseLabel = caseAndLabel.snd; 4935 Type testType = labelType(testCaseLabel); 4936 boolean dominated = false; 4937 if (types.isUnconditionallyExact(currentType, testType) && 4938 !currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) { 4939 //the current label is potentially dominated by the existing (test) label, check: 4940 if (label instanceof JCConstantCaseLabel) { 4941 dominated |= !(testCaseLabel instanceof JCConstantCaseLabel) && 4942 TreeInfo.unguardedCase(testCase); 4943 } else if (label instanceof JCPatternCaseLabel patternCL && 4944 testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel && 4945 (testCase.equals(c) || TreeInfo.unguardedCase(testCase))) { 4946 dominated = patternDominated(testPatternCaseLabel.pat, 4947 patternCL.pat); 4948 } 4949 } 4950 4951 if (dominated) { 4952 log.error(label.pos(), Errors.PatternDominated); 4953 } 4954 } 4955 caseLabels = caseLabels.prepend(Pair.of(c, label)); 4956 } 4957 } 4958 } 4959 //where: 4960 private Type labelType(JCCaseLabel label) { 4961 return types.erasure(switch (label.getTag()) { 4962 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type; 4963 case CONSTANTCASELABEL -> ((JCConstantCaseLabel) label).expr.type; 4964 default -> throw Assert.error("Unexpected tree kind: " + label.getTag()); 4965 }); 4966 } 4967 private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) { 4968 Type existingPatternType = types.erasure(existingPattern.type); 4969 Type currentPatternType = types.erasure(currentPattern.type); 4970 if (!types.isUnconditionallyExact(currentPatternType, existingPatternType)) { 4971 return false; 4972 } 4973 if (currentPattern instanceof JCBindingPattern || 4974 currentPattern instanceof JCAnyPattern) { 4975 return existingPattern instanceof JCBindingPattern || 4976 existingPattern instanceof JCAnyPattern; 4977 } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) { 4978 if (existingPattern instanceof JCBindingPattern || 4979 existingPattern instanceof JCAnyPattern) { 4980 return true; 4981 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) { 4982 List<JCPattern> existingNested = existingRecordPattern.nested; 4983 List<JCPattern> currentNested = currentRecordPattern.nested; 4984 if (existingNested.size() != currentNested.size()) { 4985 return false; 4986 } 4987 while (existingNested.nonEmpty()) { 4988 if (!patternDominated(existingNested.head, currentNested.head)) { 4989 return false; 4990 } 4991 existingNested = existingNested.tail; 4992 currentNested = currentNested.tail; 4993 } 4994 return true; 4995 } else { 4996 Assert.error("Unknown pattern: " + existingPattern.getTag()); 4997 } 4998 } else { 4999 Assert.error("Unknown pattern: " + currentPattern.getTag()); 5000 } 5001 return false; 5002 } 5003 5004 /** check if a type is a subtype of Externalizable, if that is available. */ 5005 boolean isExternalizable(Type t) { 5006 try { 5007 syms.externalizableType.complete(); 5008 } catch (CompletionFailure e) { 5009 return false; 5010 } 5011 return types.isSubtype(t, syms.externalizableType); 5012 } 5013 5014 /** 5015 * Check structure of serialization declarations. 5016 */ 5017 public void checkSerialStructure(Env<AttrContext> env, JCClassDecl tree, ClassSymbol c) { 5018 (new SerialTypeVisitor(env)).visit(c, tree); 5019 } 5020 5021 /** 5022 * This visitor will warn if a serialization-related field or 5023 * method is declared in a suspicious or incorrect way. In 5024 * particular, it will warn for cases where the runtime 5025 * serialization mechanism will silently ignore a mis-declared 5026 * entity. 5027 * 5028 * Distinguished serialization-related fields and methods: 5029 * 5030 * Methods: 5031 * 5032 * private void writeObject(ObjectOutputStream stream) throws IOException 5033 * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException 5034 * 5035 * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException 5036 * private void readObjectNoData() throws ObjectStreamException 5037 * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException 5038 * 5039 * Fields: 5040 * 5041 * private static final long serialVersionUID 5042 * private static final ObjectStreamField[] serialPersistentFields 5043 * 5044 * Externalizable: methods defined on the interface 5045 * public void writeExternal(ObjectOutput) throws IOException 5046 * public void readExternal(ObjectInput) throws IOException 5047 */ 5048 private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> { 5049 Env<AttrContext> env; 5050 SerialTypeVisitor(Env<AttrContext> env) { 5051 this.lint = Check.this.lint; 5052 this.env = env; 5053 } 5054 5055 private static final Set<String> serialMethodNames = 5056 Set.of("writeObject", "writeReplace", 5057 "readObject", "readObjectNoData", 5058 "readResolve"); 5059 5060 private static final Set<String> serialFieldNames = 5061 Set.of("serialVersionUID", "serialPersistentFields"); 5062 5063 // Type of serialPersistentFields 5064 private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass); 5065 5066 Lint lint; 5067 5068 @Override 5069 public Void defaultAction(Element e, JCClassDecl p) { 5070 throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), "")); 5071 } 5072 5073 @Override 5074 public Void visitType(TypeElement e, JCClassDecl p) { 5075 runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param)); 5076 return null; 5077 } 5078 5079 @Override 5080 public Void visitTypeAsClass(TypeElement e, 5081 JCClassDecl p) { 5082 // Anonymous classes filtered out by caller. 5083 5084 ClassSymbol c = (ClassSymbol)e; 5085 5086 checkCtorAccess(p, c); 5087 5088 // Check for missing serialVersionUID; check *not* done 5089 // for enums or records. 5090 VarSymbol svuidSym = null; 5091 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { 5092 if (sym.kind == VAR) { 5093 svuidSym = (VarSymbol)sym; 5094 break; 5095 } 5096 } 5097 5098 if (svuidSym == null) { 5099 log.warning(p.pos(), LintWarnings.MissingSVUID(c)); 5100 } 5101 5102 // Check for serialPersistentFields to gate checks for 5103 // non-serializable non-transient instance fields 5104 boolean serialPersistentFieldsPresent = 5105 c.members() 5106 .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR) 5107 .iterator() 5108 .hasNext(); 5109 5110 // Check declarations of serialization-related methods and 5111 // fields 5112 final boolean[] hasWriteReplace = {false}; 5113 for(Symbol el : c.getEnclosedElements()) { 5114 runUnderLint(el, p, (enclosed, tree) -> { 5115 String name = null; 5116 switch(enclosed.getKind()) { 5117 case FIELD -> { 5118 if (!serialPersistentFieldsPresent) { 5119 var flags = enclosed.flags(); 5120 if ( ((flags & TRANSIENT) == 0) && 5121 ((flags & STATIC) == 0)) { 5122 Type varType = enclosed.asType(); 5123 if (!canBeSerialized(varType)) { 5124 // Note per JLS arrays are 5125 // serializable even if the 5126 // component type is not. 5127 log.warning( 5128 TreeInfo.diagnosticPositionFor(enclosed, tree), 5129 LintWarnings.NonSerializableInstanceField); 5130 } else if (varType.hasTag(ARRAY)) { 5131 ArrayType arrayType = (ArrayType)varType; 5132 Type elementType = arrayType.elemtype; 5133 while (elementType.hasTag(ARRAY)) { 5134 arrayType = (ArrayType)elementType; 5135 elementType = arrayType.elemtype; 5136 } 5137 if (!canBeSerialized(elementType)) { 5138 log.warning( 5139 TreeInfo.diagnosticPositionFor(enclosed, tree), 5140 LintWarnings.NonSerializableInstanceFieldArray(elementType)); 5141 } 5142 } 5143 } 5144 } 5145 5146 name = enclosed.getSimpleName().toString(); 5147 if (serialFieldNames.contains(name)) { 5148 VarSymbol field = (VarSymbol)enclosed; 5149 switch (name) { 5150 case "serialVersionUID" -> checkSerialVersionUID(tree, e, field); 5151 case "serialPersistentFields" -> checkSerialPersistentFields(tree, e, field); 5152 default -> throw new AssertionError(); 5153 } 5154 } 5155 } 5156 5157 // Correctly checking the serialization-related 5158 // methods is subtle. For the methods declared to be 5159 // private or directly declared in the class, the 5160 // enclosed elements of the class can be checked in 5161 // turn. However, writeReplace and readResolve can be 5162 // declared in a superclass and inherited. Note that 5163 // the runtime lookup walks the superclass chain 5164 // looking for writeReplace/readResolve via 5165 // Class.getDeclaredMethod. This differs from calling 5166 // Elements.getAllMembers(TypeElement) as the latter 5167 // will also pull in default methods from 5168 // superinterfaces. In other words, the runtime checks 5169 // (which long predate default methods on interfaces) 5170 // do not admit the possibility of inheriting methods 5171 // this way, a difference from general inheritance. 5172 5173 // The current implementation just checks the enclosed 5174 // elements and does not directly check the inherited 5175 // methods. If all the types are being checked this is 5176 // less of a concern; however, there are cases that 5177 // could be missed. In particular, readResolve and 5178 // writeReplace could, in principle, by inherited from 5179 // a non-serializable superclass and thus not checked 5180 // even if compiled with a serializable child class. 5181 case METHOD -> { 5182 var method = (MethodSymbol)enclosed; 5183 name = method.getSimpleName().toString(); 5184 if (serialMethodNames.contains(name)) { 5185 switch (name) { 5186 case "writeObject" -> checkWriteObject(tree, e, method); 5187 case "writeReplace" -> {hasWriteReplace[0] = true; hasAppropriateWriteReplace(tree, method, true);} 5188 case "readObject" -> checkReadObject(tree,e, method); 5189 case "readObjectNoData" -> checkReadObjectNoData(tree, e, method); 5190 case "readResolve" -> checkReadResolve(tree, e, method); 5191 default -> throw new AssertionError(); 5192 } 5193 } 5194 } 5195 } 5196 }); 5197 } 5198 if (!hasWriteReplace[0] && 5199 (c.isValueClass() || hasAbstractValueSuperClass(c, Set.of(syms.numberType.tsym))) && 5200 !c.isAbstract() && !c.isRecord() && 5201 types.unboxedType(c.type) == Type.noType) { 5202 // we need to check if the class is inheriting an appropriate writeReplace method 5203 MethodSymbol ms = null; 5204 Log.DiagnosticHandler discardHandler = log.new DiscardDiagnosticHandler(); 5205 try { 5206 ms = rs.resolveInternalMethod(env.tree, env, c.type, names.writeReplace, List.nil(), List.nil()); 5207 } catch (FatalError fe) { 5208 // ignore no method was found 5209 } finally { 5210 log.popDiagnosticHandler(discardHandler); 5211 } 5212 if (ms == null || !hasAppropriateWriteReplace(p, ms, false)) { 5213 log.warning(p.pos(), 5214 c.isValueClass() ? LintWarnings.SerializableValueClassWithoutWriteReplace1 : 5215 LintWarnings.SerializableValueClassWithoutWriteReplace2); 5216 } 5217 } 5218 return null; 5219 } 5220 5221 boolean canBeSerialized(Type type) { 5222 return type.isPrimitive() || rs.isSerializable(type); 5223 } 5224 5225 private boolean hasAbstractValueSuperClass(Symbol c, Set<Symbol> excluding) { 5226 while (c.getKind() == ElementKind.CLASS) { 5227 Type sup = ((ClassSymbol)c).getSuperclass(); 5228 if (!sup.hasTag(CLASS) || sup.isErroneous() || 5229 sup.tsym == syms.objectType.tsym) { 5230 return false; 5231 } 5232 // if it is a value super class it has to be abstract 5233 if (sup.isValueClass() && !excluding.contains(sup.tsym)) { 5234 return true; 5235 } 5236 c = sup.tsym; 5237 } 5238 return false; 5239 } 5240 5241 /** 5242 * Check that Externalizable class needs a public no-arg 5243 * constructor. 5244 * 5245 * Check that a Serializable class has access to the no-arg 5246 * constructor of its first nonserializable superclass. 5247 */ 5248 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) { 5249 if (isExternalizable(c.type)) { 5250 for(var sym : c.getEnclosedElements()) { 5251 if (sym.isConstructor() && 5252 ((sym.flags() & PUBLIC) == PUBLIC)) { 5253 if (((MethodSymbol)sym).getParameters().isEmpty()) { 5254 return; 5255 } 5256 } 5257 } 5258 log.warning(tree.pos(), 5259 LintWarnings.ExternalizableMissingPublicNoArgCtor); 5260 } else { 5261 // Approximate access to the no-arg constructor up in 5262 // the superclass chain by checking that the 5263 // constructor is not private. This may not handle 5264 // some cross-package situations correctly. 5265 Type superClass = c.getSuperclass(); 5266 // java.lang.Object is *not* Serializable so this loop 5267 // should terminate. 5268 while (rs.isSerializable(superClass) ) { 5269 try { 5270 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass(); 5271 } catch(ClassCastException cce) { 5272 return ; // Don't try to recover 5273 } 5274 } 5275 // Non-Serializable superclass 5276 try { 5277 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement())); 5278 for(var sym : supertype.getEnclosedElements()) { 5279 if (sym.isConstructor()) { 5280 MethodSymbol ctor = (MethodSymbol)sym; 5281 if (ctor.getParameters().isEmpty()) { 5282 if (((ctor.flags() & PRIVATE) == PRIVATE) || 5283 // Handle nested classes and implicit this$0 5284 (supertype.getNestingKind() == NestingKind.MEMBER && 5285 ((supertype.flags() & STATIC) == 0))) 5286 log.warning(tree.pos(), 5287 LintWarnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName())); 5288 } 5289 } 5290 } 5291 } catch (ClassCastException cce) { 5292 return ; // Don't try to recover 5293 } 5294 return; 5295 } 5296 } 5297 5298 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) { 5299 // To be effective, serialVersionUID must be marked static 5300 // and final, but private is recommended. But alas, in 5301 // practice there are many non-private serialVersionUID 5302 // fields. 5303 if ((svuid.flags() & (STATIC | FINAL)) != 5304 (STATIC | FINAL)) { 5305 log.warning( 5306 TreeInfo.diagnosticPositionFor(svuid, tree), 5307 LintWarnings.ImproperSVUID((Symbol)e)); 5308 } 5309 5310 // check svuid has type long 5311 if (!svuid.type.hasTag(LONG)) { 5312 log.warning( 5313 TreeInfo.diagnosticPositionFor(svuid, tree), 5314 LintWarnings.LongSVUID((Symbol)e)); 5315 } 5316 5317 if (svuid.getConstValue() == null) 5318 log.warning( 5319 TreeInfo.diagnosticPositionFor(svuid, tree), 5320 LintWarnings.ConstantSVUID((Symbol)e)); 5321 } 5322 5323 private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) { 5324 // To be effective, serialPersisentFields must be private, static, and final. 5325 if ((spf.flags() & (PRIVATE | STATIC | FINAL)) != 5326 (PRIVATE | STATIC | FINAL)) { 5327 log.warning( 5328 TreeInfo.diagnosticPositionFor(spf, tree), 5329 LintWarnings.ImproperSPF); 5330 } 5331 5332 if (!types.isSameType(spf.type, OSF_TYPE)) { 5333 log.warning( 5334 TreeInfo.diagnosticPositionFor(spf, tree), 5335 LintWarnings.OSFArraySPF); 5336 } 5337 5338 if (isExternalizable((Type)(e.asType()))) { 5339 log.warning( 5340 TreeInfo.diagnosticPositionFor(spf, tree), 5341 LintWarnings.IneffectualSerialFieldExternalizable); 5342 } 5343 5344 // Warn if serialPersistentFields is initialized to a 5345 // literal null. 5346 JCTree spfDecl = TreeInfo.declarationFor(spf, tree); 5347 if (spfDecl != null && spfDecl.getTag() == VARDEF) { 5348 JCVariableDecl variableDef = (JCVariableDecl) spfDecl; 5349 JCExpression initExpr = variableDef.init; 5350 if (initExpr != null && TreeInfo.isNull(initExpr)) { 5351 log.warning(initExpr.pos(), 5352 LintWarnings.SPFNullInit); 5353 } 5354 } 5355 } 5356 5357 private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) { 5358 // The "synchronized" modifier is seen in the wild on 5359 // readObject and writeObject methods and is generally 5360 // innocuous. 5361 5362 // private void writeObject(ObjectOutputStream stream) throws IOException 5363 checkPrivateNonStaticMethod(tree, method); 5364 isExpectedReturnType(tree, method, syms.voidType, true); 5365 checkOneArg(tree, e, method, syms.objectOutputStreamType); 5366 hasExpectedExceptions(tree, method, true, syms.ioExceptionType); 5367 checkExternalizable(tree, e, method); 5368 } 5369 5370 private boolean hasAppropriateWriteReplace(JCClassDecl tree, MethodSymbol method, boolean warn) { 5371 // ANY-ACCESS-MODIFIER Object writeReplace() throws 5372 // ObjectStreamException 5373 5374 // Excluding abstract, could have a more complicated 5375 // rule based on abstract-ness of the class 5376 return isConcreteInstanceMethod(tree, method, warn) && 5377 isExpectedReturnType(tree, method, syms.objectType, warn) && 5378 hasNoArgs(tree, method, warn) && 5379 hasExpectedExceptions(tree, method, warn, syms.objectStreamExceptionType); 5380 } 5381 5382 private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) { 5383 // The "synchronized" modifier is seen in the wild on 5384 // readObject and writeObject methods and is generally 5385 // innocuous. 5386 5387 // private void readObject(ObjectInputStream stream) 5388 // throws IOException, ClassNotFoundException 5389 checkPrivateNonStaticMethod(tree, method); 5390 isExpectedReturnType(tree, method, syms.voidType, true); 5391 checkOneArg(tree, e, method, syms.objectInputStreamType); 5392 hasExpectedExceptions(tree, method, true, syms.ioExceptionType, syms.classNotFoundExceptionType); 5393 checkExternalizable(tree, e, method); 5394 } 5395 5396 private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) { 5397 // private void readObjectNoData() throws ObjectStreamException 5398 checkPrivateNonStaticMethod(tree, method); 5399 isExpectedReturnType(tree, method, syms.voidType, true); 5400 hasNoArgs(tree, method, true); 5401 hasExpectedExceptions(tree, method, true, syms.objectStreamExceptionType); 5402 checkExternalizable(tree, e, method); 5403 } 5404 5405 private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) { 5406 // ANY-ACCESS-MODIFIER Object readResolve() 5407 // throws ObjectStreamException 5408 5409 // Excluding abstract, could have a more complicated 5410 // rule based on abstract-ness of the class 5411 isConcreteInstanceMethod(tree, method, true); 5412 isExpectedReturnType(tree, method, syms.objectType, true); 5413 hasNoArgs(tree, method, true); 5414 hasExpectedExceptions(tree, method, true, syms.objectStreamExceptionType); 5415 } 5416 5417 private void checkWriteExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) { 5418 //public void writeExternal(ObjectOutput) throws IOException 5419 checkExternMethodRecord(tree, e, method, syms.objectOutputType, isExtern); 5420 } 5421 5422 private void checkReadExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) { 5423 // public void readExternal(ObjectInput) throws IOException 5424 checkExternMethodRecord(tree, e, method, syms.objectInputType, isExtern); 5425 } 5426 5427 private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType, 5428 boolean isExtern) { 5429 if (isExtern && isExternMethod(tree, e, method, argType)) { 5430 log.warning( 5431 TreeInfo.diagnosticPositionFor(method, tree), 5432 LintWarnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString())); 5433 } 5434 } 5435 5436 void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) { 5437 var flags = method.flags(); 5438 if ((flags & PRIVATE) == 0) { 5439 log.warning( 5440 TreeInfo.diagnosticPositionFor(method, tree), 5441 LintWarnings.SerialMethodNotPrivate(method.getSimpleName())); 5442 } 5443 5444 if ((flags & STATIC) != 0) { 5445 log.warning( 5446 TreeInfo.diagnosticPositionFor(method, tree), 5447 LintWarnings.SerialMethodStatic(method.getSimpleName())); 5448 } 5449 } 5450 5451 /** 5452 * Per section 1.12 "Serialization of Enum Constants" of 5453 * the serialization specification, due to the special 5454 * serialization handling of enums, any writeObject, 5455 * readObject, writeReplace, and readResolve methods are 5456 * ignored as are serialPersistentFields and 5457 * serialVersionUID fields. 5458 */ 5459 @Override 5460 public Void visitTypeAsEnum(TypeElement e, 5461 JCClassDecl p) { 5462 boolean isExtern = isExternalizable((Type)e.asType()); 5463 for(Element el : e.getEnclosedElements()) { 5464 runUnderLint(el, p, (enclosed, tree) -> { 5465 String name = enclosed.getSimpleName().toString(); 5466 switch(enclosed.getKind()) { 5467 case FIELD -> { 5468 var field = (VarSymbol)enclosed; 5469 if (serialFieldNames.contains(name)) { 5470 log.warning( 5471 TreeInfo.diagnosticPositionFor(field, tree), 5472 LintWarnings.IneffectualSerialFieldEnum(name)); 5473 } 5474 } 5475 5476 case METHOD -> { 5477 var method = (MethodSymbol)enclosed; 5478 if (serialMethodNames.contains(name)) { 5479 log.warning( 5480 TreeInfo.diagnosticPositionFor(method, tree), 5481 LintWarnings.IneffectualSerialMethodEnum(name)); 5482 } 5483 5484 if (isExtern) { 5485 switch(name) { 5486 case "writeExternal" -> checkWriteExternalEnum(tree, e, method); 5487 case "readExternal" -> checkReadExternalEnum(tree, e, method); 5488 } 5489 } 5490 } 5491 5492 // Also perform checks on any class bodies of enum constants, see JLS 8.9.1. 5493 case ENUM_CONSTANT -> { 5494 var field = (VarSymbol)enclosed; 5495 JCVariableDecl decl = (JCVariableDecl) TreeInfo.declarationFor(field, p); 5496 if (decl.init instanceof JCNewClass nc && nc.def != null) { 5497 ClassSymbol enumConstantType = nc.def.sym; 5498 visitTypeAsEnum(enumConstantType, p); 5499 } 5500 } 5501 5502 }}); 5503 } 5504 return null; 5505 } 5506 5507 private void checkWriteExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) { 5508 //public void writeExternal(ObjectOutput) throws IOException 5509 checkExternMethodEnum(tree, e, method, syms.objectOutputType); 5510 } 5511 5512 private void checkReadExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) { 5513 // public void readExternal(ObjectInput) throws IOException 5514 checkExternMethodEnum(tree, e, method, syms.objectInputType); 5515 } 5516 5517 private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) { 5518 if (isExternMethod(tree, e, method, argType)) { 5519 log.warning( 5520 TreeInfo.diagnosticPositionFor(method, tree), 5521 LintWarnings.IneffectualExternMethodEnum(method.getSimpleName().toString())); 5522 } 5523 } 5524 5525 private boolean isExternMethod(JCClassDecl tree, Element e, MethodSymbol method, Type argType) { 5526 long flags = method.flags(); 5527 Type rtype = method.getReturnType(); 5528 5529 // Not necessary to check throws clause in this context 5530 return (flags & PUBLIC) != 0 && (flags & STATIC) == 0 && 5531 types.isSameType(syms.voidType, rtype) && 5532 hasExactlyOneArgWithType(tree, e, method, argType); 5533 } 5534 5535 /** 5536 * Most serialization-related fields and methods on interfaces 5537 * are ineffectual or problematic. 5538 */ 5539 @Override 5540 public Void visitTypeAsInterface(TypeElement e, 5541 JCClassDecl p) { 5542 for(Element el : e.getEnclosedElements()) { 5543 runUnderLint(el, p, (enclosed, tree) -> { 5544 String name = null; 5545 switch(enclosed.getKind()) { 5546 case FIELD -> { 5547 var field = (VarSymbol)enclosed; 5548 name = field.getSimpleName().toString(); 5549 switch(name) { 5550 case "serialPersistentFields" -> { 5551 log.warning( 5552 TreeInfo.diagnosticPositionFor(field, tree), 5553 LintWarnings.IneffectualSerialFieldInterface); 5554 } 5555 5556 case "serialVersionUID" -> { 5557 checkSerialVersionUID(tree, e, field); 5558 } 5559 } 5560 } 5561 5562 case METHOD -> { 5563 var method = (MethodSymbol)enclosed; 5564 name = enclosed.getSimpleName().toString(); 5565 if (serialMethodNames.contains(name)) { 5566 switch (name) { 5567 case 5568 "readObject", 5569 "readObjectNoData", 5570 "writeObject" -> checkPrivateMethod(tree, e, method); 5571 5572 case 5573 "writeReplace", 5574 "readResolve" -> checkDefaultIneffective(tree, e, method); 5575 5576 default -> throw new AssertionError(); 5577 } 5578 5579 } 5580 }} 5581 }); 5582 } 5583 5584 return null; 5585 } 5586 5587 private void checkPrivateMethod(JCClassDecl tree, 5588 Element e, 5589 MethodSymbol method) { 5590 if ((method.flags() & PRIVATE) == 0) { 5591 log.warning( 5592 TreeInfo.diagnosticPositionFor(method, tree), 5593 LintWarnings.NonPrivateMethodWeakerAccess); 5594 } 5595 } 5596 5597 private void checkDefaultIneffective(JCClassDecl tree, 5598 Element e, 5599 MethodSymbol method) { 5600 if ((method.flags() & DEFAULT) == DEFAULT) { 5601 log.warning( 5602 TreeInfo.diagnosticPositionFor(method, tree), 5603 LintWarnings.DefaultIneffective); 5604 5605 } 5606 } 5607 5608 @Override 5609 public Void visitTypeAsAnnotationType(TypeElement e, 5610 JCClassDecl p) { 5611 // Per the JLS, annotation types are not serializeable 5612 return null; 5613 } 5614 5615 /** 5616 * From the Java Object Serialization Specification, 1.13 5617 * Serialization of Records: 5618 * 5619 * "The process by which record objects are serialized or 5620 * externalized cannot be customized; any class-specific 5621 * writeObject, readObject, readObjectNoData, writeExternal, 5622 * and readExternal methods defined by record classes are 5623 * ignored during serialization and deserialization. However, 5624 * a substitute object to be serialized or a designate 5625 * replacement may be specified, by the writeReplace and 5626 * readResolve methods, respectively. Any 5627 * serialPersistentFields field declaration is 5628 * ignored. Documenting serializable fields and data for 5629 * record classes is unnecessary, since there is no variation 5630 * in the serial form, other than whether a substitute or 5631 * replacement object is used. The serialVersionUID of a 5632 * record class is 0L unless explicitly declared. The 5633 * requirement for matching serialVersionUID values is waived 5634 * for record classes." 5635 */ 5636 @Override 5637 public Void visitTypeAsRecord(TypeElement e, 5638 JCClassDecl p) { 5639 boolean isExtern = isExternalizable((Type)e.asType()); 5640 for(Element el : e.getEnclosedElements()) { 5641 runUnderLint(el, p, (enclosed, tree) -> { 5642 String name = enclosed.getSimpleName().toString(); 5643 switch(enclosed.getKind()) { 5644 case FIELD -> { 5645 var field = (VarSymbol)enclosed; 5646 switch(name) { 5647 case "serialPersistentFields" -> { 5648 log.warning( 5649 TreeInfo.diagnosticPositionFor(field, tree), 5650 LintWarnings.IneffectualSerialFieldRecord); 5651 } 5652 5653 case "serialVersionUID" -> { 5654 // Could generate additional warning that 5655 // svuid value is not checked to match for 5656 // records. 5657 checkSerialVersionUID(tree, e, field); 5658 }} 5659 } 5660 5661 case METHOD -> { 5662 var method = (MethodSymbol)enclosed; 5663 switch(name) { 5664 case "writeReplace" -> hasAppropriateWriteReplace(tree, method, true); 5665 case "readResolve" -> checkReadResolve(tree, e, method); 5666 5667 case "writeExternal" -> checkWriteExternalRecord(tree, e, method, isExtern); 5668 case "readExternal" -> checkReadExternalRecord(tree, e, method, isExtern); 5669 5670 default -> { 5671 if (serialMethodNames.contains(name)) { 5672 log.warning( 5673 TreeInfo.diagnosticPositionFor(method, tree), 5674 LintWarnings.IneffectualSerialMethodRecord(name)); 5675 } 5676 }} 5677 }}}); 5678 } 5679 return null; 5680 } 5681 5682 boolean isConcreteInstanceMethod(JCClassDecl tree, 5683 MethodSymbol method, 5684 boolean warn) { 5685 if ((method.flags() & (STATIC | ABSTRACT)) != 0) { 5686 if (warn) { 5687 log.warning( 5688 TreeInfo.diagnosticPositionFor(method, tree), 5689 LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName())); 5690 } 5691 return false; 5692 } 5693 return true; 5694 } 5695 5696 private boolean isExpectedReturnType(JCClassDecl tree, 5697 MethodSymbol method, 5698 Type expectedReturnType, 5699 boolean warn) { 5700 // Note: there may be complications checking writeReplace 5701 // and readResolve since they return Object and could, in 5702 // principle, have covariant overrides and any synthetic 5703 // bridge method would not be represented here for 5704 // checking. 5705 Type rtype = method.getReturnType(); 5706 if (!types.isSameType(expectedReturnType, rtype)) { 5707 if (warn) { 5708 log.warning( 5709 TreeInfo.diagnosticPositionFor(method, tree), 5710 LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(), 5711 rtype, expectedReturnType)); 5712 } 5713 return false; 5714 } 5715 return true; 5716 } 5717 5718 private void checkOneArg(JCClassDecl tree, 5719 Element enclosing, 5720 MethodSymbol method, 5721 Type expectedType) { 5722 String name = method.getSimpleName().toString(); 5723 5724 var parameters= method.getParameters(); 5725 5726 if (parameters.size() != 1) { 5727 log.warning( 5728 TreeInfo.diagnosticPositionFor(method, tree), 5729 LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size())); 5730 return; 5731 } 5732 5733 Type parameterType = parameters.get(0).asType(); 5734 if (!types.isSameType(parameterType, expectedType)) { 5735 log.warning( 5736 TreeInfo.diagnosticPositionFor(method, tree), 5737 LintWarnings.SerialMethodParameterType(method.getSimpleName(), 5738 expectedType, 5739 parameterType)); 5740 } 5741 } 5742 5743 private boolean hasExactlyOneArgWithType(JCClassDecl tree, 5744 Element enclosing, 5745 MethodSymbol method, 5746 Type expectedType) { 5747 var parameters = method.getParameters(); 5748 return (parameters.size() == 1) && 5749 types.isSameType(parameters.get(0).asType(), expectedType); 5750 } 5751 5752 5753 boolean hasNoArgs(JCClassDecl tree, MethodSymbol method, boolean warn) { 5754 var parameters = method.getParameters(); 5755 if (!parameters.isEmpty()) { 5756 if (warn) { 5757 log.warning( 5758 TreeInfo.diagnosticPositionFor(parameters.get(0), tree), 5759 LintWarnings.SerialMethodNoArgs(method.getSimpleName())); 5760 } 5761 return false; 5762 } 5763 return true; 5764 } 5765 5766 private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) { 5767 // If the enclosing class is externalizable, warn for the method 5768 if (isExternalizable((Type)enclosing.asType())) { 5769 log.warning( 5770 TreeInfo.diagnosticPositionFor(method, tree), 5771 LintWarnings.IneffectualSerialMethodExternalizable(method.getSimpleName())); 5772 } 5773 return; 5774 } 5775 5776 private boolean hasExpectedExceptions(JCClassDecl tree, 5777 MethodSymbol method, 5778 boolean warn, 5779 Type... declaredExceptions) { 5780 for (Type thrownType: method.getThrownTypes()) { 5781 // For each exception in the throws clause of the 5782 // method, if not an Error and not a RuntimeException, 5783 // check if the exception is a subtype of a declared 5784 // exception from the throws clause of the 5785 // serialization method in question. 5786 if (types.isSubtype(thrownType, syms.runtimeExceptionType) || 5787 types.isSubtype(thrownType, syms.errorType) ) { 5788 continue; 5789 } else { 5790 boolean declared = false; 5791 for (Type declaredException : declaredExceptions) { 5792 if (types.isSubtype(thrownType, declaredException)) { 5793 declared = true; 5794 continue; 5795 } 5796 } 5797 if (!declared) { 5798 if (warn) { 5799 log.warning( 5800 TreeInfo.diagnosticPositionFor(method, tree), 5801 LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(), 5802 thrownType)); 5803 } 5804 return false; 5805 } 5806 } 5807 } 5808 return true; 5809 } 5810 5811 private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) { 5812 Lint prevLint = lint; 5813 try { 5814 lint = lint.augment((Symbol) symbol); 5815 5816 if (lint.isEnabled(LintCategory.SERIAL)) { 5817 task.accept(symbol, p); 5818 } 5819 5820 return null; 5821 } finally { 5822 lint = prevLint; 5823 } 5824 } 5825 5826 } 5827 5828 }