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