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