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