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