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)).baseType(); 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 if (shouldCheckPreview(m, other, origin)) { 1832 checkPreview(tree.pos(), m, other); 1833 } 1834 1835 Type mt = types.memberType(origin.type, m); 1836 Type ot = types.memberType(origin.type, other); 1837 // Error if overriding result type is different 1838 // (or, in the case of generics mode, not a subtype) of 1839 // overridden result type. We have to rename any type parameters 1840 // before comparing types. 1841 List<Type> mtvars = mt.getTypeArguments(); 1842 List<Type> otvars = ot.getTypeArguments(); 1843 Type mtres = mt.getReturnType(); 1844 Type otres = types.subst(ot.getReturnType(), otvars, mtvars); 1845 1846 overrideWarner.clear(); 1847 boolean resultTypesOK = 1848 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner); 1849 if (!resultTypesOK) { 1850 if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) { 1851 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1852 Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other, 1853 other.location()), mtres, otres)); 1854 m.flags_field |= BAD_OVERRIDE; 1855 } else { 1856 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1857 Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres)); 1858 m.flags_field |= BAD_OVERRIDE; 1859 } 1860 return; 1861 } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 1862 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1863 Warnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres)); 1864 } 1865 1866 // Error if overriding method throws an exception not reported 1867 // by overridden method. 1868 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars); 1869 List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown)); 1870 List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown); 1871 if (unhandledErased.nonEmpty()) { 1872 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1873 Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head)); 1874 m.flags_field |= BAD_OVERRIDE; 1875 return; 1876 } 1877 else if (unhandledUnerased.nonEmpty()) { 1878 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1879 Warnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head)); 1880 return; 1881 } 1882 1883 // Optional warning if varargs don't agree 1884 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0) 1885 && lint.isEnabled(LintCategory.OVERRIDES)) { 1886 log.warning(TreeInfo.diagnosticPositionFor(m, tree), 1887 ((m.flags() & Flags.VARARGS) != 0) 1888 ? Warnings.OverrideVarargsMissing(varargsOverrides(m, other)) 1889 : Warnings.OverrideVarargsExtra(varargsOverrides(m, other))); 1890 } 1891 1892 // Warn if instance method overrides bridge method (compiler spec ??) 1893 if ((other.flags() & BRIDGE) != 0) { 1894 log.warning(TreeInfo.diagnosticPositionFor(m, tree), 1895 Warnings.OverrideBridge(uncheckedOverrides(m, other))); 1896 } 1897 1898 // Warn if a deprecated method overridden by a non-deprecated one. 1899 if (!isDeprecatedOverrideIgnorable(other, origin)) { 1900 Lint prevLint = setLint(lint.augment(m)); 1901 try { 1902 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other); 1903 } finally { 1904 setLint(prevLint); 1905 } 1906 } 1907 } 1908 // where 1909 private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) { 1910 if (m.owner != origin || 1911 //performance - only do the expensive checks when the overridden method is a Preview API: 1912 (other.flags() & PREVIEW_API) == 0) { 1913 return false; 1914 } 1915 1916 for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) { 1917 if (m != s && m.overrides(s, origin, types, false)) { 1918 //only produce preview warnings or errors if "m" immediatelly overrides "other" 1919 //without intermediate overriding methods: 1920 return s == other; 1921 } 1922 } 1923 1924 return false; 1925 } 1926 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) { 1927 // If the method, m, is defined in an interface, then ignore the issue if the method 1928 // is only inherited via a supertype and also implemented in the supertype, 1929 // because in that case, we will rediscover the issue when examining the method 1930 // in the supertype. 1931 // If the method, m, is not defined in an interface, then the only time we need to 1932 // address the issue is when the method is the supertype implementation: any other 1933 // case, we will have dealt with when examining the supertype classes 1934 ClassSymbol mc = m.enclClass(); 1935 Type st = types.supertype(origin.type); 1936 if (!st.hasTag(CLASS)) 1937 return true; 1938 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false); 1939 1940 if (mc != null && ((mc.flags() & INTERFACE) != 0)) { 1941 List<Type> intfs = types.interfaces(origin.type); 1942 return (intfs.contains(mc.type) ? false : (stimpl != null)); 1943 } 1944 else 1945 return (stimpl != m); 1946 } 1947 1948 1949 // used to check if there were any unchecked conversions 1950 Warner overrideWarner = new Warner(); 1951 1952 /** Check that a class does not inherit two concrete methods 1953 * with the same signature. 1954 * @param pos Position to be used for error reporting. 1955 * @param site The class type to be checked. 1956 */ 1957 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) { 1958 Type sup = types.supertype(site); 1959 if (!sup.hasTag(CLASS)) return; 1960 1961 for (Type t1 = sup; 1962 t1.hasTag(CLASS) && t1.tsym.type.isParameterized(); 1963 t1 = types.supertype(t1)) { 1964 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 1965 if (s1.kind != MTH || 1966 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1967 !s1.isInheritedIn(site.tsym, types) || 1968 ((MethodSymbol)s1).implementation(site.tsym, 1969 types, 1970 true) != s1) 1971 continue; 1972 Type st1 = types.memberType(t1, s1); 1973 int s1ArgsLength = st1.getParameterTypes().length(); 1974 if (st1 == s1.type) continue; 1975 1976 for (Type t2 = sup; 1977 t2.hasTag(CLASS); 1978 t2 = types.supertype(t2)) { 1979 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 1980 if (s2 == s1 || 1981 s2.kind != MTH || 1982 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1983 s2.type.getParameterTypes().length() != s1ArgsLength || 1984 !s2.isInheritedIn(site.tsym, types) || 1985 ((MethodSymbol)s2).implementation(site.tsym, 1986 types, 1987 true) != s2) 1988 continue; 1989 Type st2 = types.memberType(t2, s2); 1990 if (types.overrideEquivalent(st1, st2)) 1991 log.error(pos, 1992 Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup)); 1993 } 1994 } 1995 } 1996 } 1997 } 1998 1999 /** Check that classes (or interfaces) do not each define an abstract 2000 * method with same name and arguments but incompatible return types. 2001 * @param pos Position to be used for error reporting. 2002 * @param t1 The first argument type. 2003 * @param t2 The second argument type. 2004 */ 2005 public boolean checkCompatibleAbstracts(DiagnosticPosition pos, 2006 Type t1, 2007 Type t2, 2008 Type site) { 2009 if ((site.tsym.flags() & COMPOUND) != 0) { 2010 // special case for intersections: need to eliminate wildcards in supertypes 2011 t1 = types.capture(t1); 2012 t2 = types.capture(t2); 2013 } 2014 return firstIncompatibility(pos, t1, t2, site) == null; 2015 } 2016 2017 /** Return the first method which is defined with same args 2018 * but different return types in two given interfaces, or null if none 2019 * exists. 2020 * @param t1 The first type. 2021 * @param t2 The second type. 2022 * @param site The most derived type. 2023 * @return symbol from t2 that conflicts with one in t1. 2024 */ 2025 private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 2026 Map<TypeSymbol,Type> interfaces1 = new HashMap<>(); 2027 closure(t1, interfaces1); 2028 Map<TypeSymbol,Type> interfaces2; 2029 if (t1 == t2) 2030 interfaces2 = interfaces1; 2031 else 2032 closure(t2, interfaces1, interfaces2 = new HashMap<>()); 2033 2034 for (Type t3 : interfaces1.values()) { 2035 for (Type t4 : interfaces2.values()) { 2036 Symbol s = firstDirectIncompatibility(pos, t3, t4, site); 2037 if (s != null) return s; 2038 } 2039 } 2040 return null; 2041 } 2042 2043 /** Compute all the supertypes of t, indexed by type symbol. */ 2044 private void closure(Type t, Map<TypeSymbol,Type> typeMap) { 2045 if (!t.hasTag(CLASS)) return; 2046 if (typeMap.put(t.tsym, t) == null) { 2047 closure(types.supertype(t), typeMap); 2048 for (Type i : types.interfaces(t)) 2049 closure(i, typeMap); 2050 } 2051 } 2052 2053 /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */ 2054 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) { 2055 if (!t.hasTag(CLASS)) return; 2056 if (typesSkip.get(t.tsym) != null) return; 2057 if (typeMap.put(t.tsym, t) == null) { 2058 closure(types.supertype(t), typesSkip, typeMap); 2059 for (Type i : types.interfaces(t)) 2060 closure(i, typesSkip, typeMap); 2061 } 2062 } 2063 2064 /** Return the first method in t2 that conflicts with a method from t1. */ 2065 private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) { 2066 for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) { 2067 Type st1 = null; 2068 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) || 2069 (s1.flags() & SYNTHETIC) != 0) continue; 2070 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false); 2071 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue; 2072 for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) { 2073 if (s1 == s2) continue; 2074 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) || 2075 (s2.flags() & SYNTHETIC) != 0) continue; 2076 if (st1 == null) st1 = types.memberType(t1, s1); 2077 Type st2 = types.memberType(t2, s2); 2078 if (types.overrideEquivalent(st1, st2)) { 2079 List<Type> tvars1 = st1.getTypeArguments(); 2080 List<Type> tvars2 = st2.getTypeArguments(); 2081 Type rt1 = st1.getReturnType(); 2082 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1); 2083 boolean compat = 2084 types.isSameType(rt1, rt2) || 2085 !rt1.isPrimitiveOrVoid() && 2086 !rt2.isPrimitiveOrVoid() && 2087 (types.covariantReturnType(rt1, rt2, types.noWarnings) || 2088 types.covariantReturnType(rt2, rt1, types.noWarnings)) || 2089 checkCommonOverriderIn(s1,s2,site); 2090 if (!compat) { 2091 if (types.isSameType(t1, t2)) { 2092 log.error(pos, Errors.IncompatibleDiffRetSameType(t1, 2093 s2.name, types.memberType(t2, s2).getParameterTypes())); 2094 } else { 2095 log.error(pos, Errors.TypesIncompatible(t1, t2, 2096 Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes()))); 2097 } 2098 return s2; 2099 } 2100 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) && 2101 !checkCommonOverriderIn(s1, s2, site)) { 2102 log.error(pos, Errors.NameClashSameErasureNoOverride( 2103 s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(), 2104 s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location())); 2105 return s2; 2106 } 2107 } 2108 } 2109 return null; 2110 } 2111 //WHERE 2112 boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) { 2113 Map<TypeSymbol,Type> supertypes = new HashMap<>(); 2114 Type st1 = types.memberType(site, s1); 2115 Type st2 = types.memberType(site, s2); 2116 closure(site, supertypes); 2117 for (Type t : supertypes.values()) { 2118 for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) { 2119 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue; 2120 Type st3 = types.memberType(site,s3); 2121 if (types.overrideEquivalent(st3, st1) && 2122 types.overrideEquivalent(st3, st2) && 2123 types.returnTypeSubstitutable(st3, st1) && 2124 types.returnTypeSubstitutable(st3, st2)) { 2125 return true; 2126 } 2127 } 2128 } 2129 return false; 2130 } 2131 2132 /** Check that a given method conforms with any method it overrides. 2133 * @param tree The tree from which positions are extracted 2134 * for errors. 2135 * @param m The overriding method. 2136 */ 2137 void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) { 2138 ClassSymbol origin = (ClassSymbol)m.owner; 2139 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) { 2140 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) { 2141 log.error(tree.pos(), Errors.EnumNoFinalize); 2142 return; 2143 } 2144 } 2145 if (allowRecords && origin.isRecord()) { 2146 // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable 2147 Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream() 2148 .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst(); 2149 if (recordComponent.isPresent()) { 2150 return; 2151 } 2152 } 2153 2154 for (Type t = origin.type; t.hasTag(CLASS); 2155 t = types.supertype(t)) { 2156 if (t != origin.type) { 2157 checkOverride(tree, t, origin, m); 2158 } 2159 for (Type t2 : types.interfaces(t)) { 2160 checkOverride(tree, t2, origin, m); 2161 } 2162 } 2163 2164 final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null; 2165 // Check if this method must override a super method due to being annotated with @Override 2166 // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to 2167 // be treated "as if as they were annotated" with @Override. 2168 boolean mustOverride = explicitOverride || 2169 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate()); 2170 if (mustOverride && !isOverrider(m)) { 2171 DiagnosticPosition pos = tree.pos(); 2172 for (JCAnnotation a : tree.getModifiers().annotations) { 2173 if (a.annotationType.type.tsym == syms.overrideType.tsym) { 2174 pos = a.pos(); 2175 break; 2176 } 2177 } 2178 log.error(pos, 2179 explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) : 2180 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride)); 2181 } 2182 } 2183 2184 void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) { 2185 TypeSymbol c = site.tsym; 2186 for (Symbol sym : c.members().getSymbolsByName(m.name)) { 2187 if (m.overrides(sym, origin, types, false)) { 2188 if ((sym.flags() & ABSTRACT) == 0) { 2189 checkOverride(tree, m, (MethodSymbol)sym, origin); 2190 } 2191 } 2192 } 2193 } 2194 2195 private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) && 2196 (s.flags() & BAD_OVERRIDE) == 0; 2197 2198 public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos, 2199 ClassSymbol someClass) { 2200 /* At present, annotations cannot possibly have a method that is override 2201 * equivalent with Object.equals(Object) but in any case the condition is 2202 * fine for completeness. 2203 */ 2204 if (someClass == (ClassSymbol)syms.objectType.tsym || 2205 someClass.isInterface() || someClass.isEnum() || 2206 (someClass.flags() & ANNOTATION) != 0 || 2207 (someClass.flags() & ABSTRACT) != 0) return; 2208 //anonymous inner classes implementing interfaces need especial treatment 2209 if (someClass.isAnonymous()) { 2210 List<Type> interfaces = types.interfaces(someClass.type); 2211 if (interfaces != null && !interfaces.isEmpty() && 2212 interfaces.head.tsym == syms.comparatorType.tsym) return; 2213 } 2214 checkClassOverrideEqualsAndHash(pos, someClass); 2215 } 2216 2217 private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos, 2218 ClassSymbol someClass) { 2219 if (lint.isEnabled(LintCategory.OVERRIDES)) { 2220 MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType 2221 .tsym.members().findFirst(names.equals); 2222 MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType 2223 .tsym.members().findFirst(names.hashCode); 2224 MethodSymbol equalsImpl = types.implementation(equalsAtObject, 2225 someClass, false, equalsHasCodeFilter); 2226 boolean overridesEquals = equalsImpl != null && 2227 equalsImpl.owner == someClass; 2228 boolean overridesHashCode = types.implementation(hashCodeAtObject, 2229 someClass, false, equalsHasCodeFilter) != hashCodeAtObject; 2230 2231 if (overridesEquals && !overridesHashCode) { 2232 log.warning(LintCategory.OVERRIDES, pos, 2233 Warnings.OverrideEqualsButNotHashcode(someClass)); 2234 } 2235 } 2236 } 2237 2238 public void checkModuleName (JCModuleDecl tree) { 2239 Name moduleName = tree.sym.name; 2240 Assert.checkNonNull(moduleName); 2241 if (lint.isEnabled(LintCategory.MODULE)) { 2242 JCExpression qualId = tree.qualId; 2243 while (qualId != null) { 2244 Name componentName; 2245 DiagnosticPosition pos; 2246 switch (qualId.getTag()) { 2247 case SELECT: 2248 JCFieldAccess selectNode = ((JCFieldAccess) qualId); 2249 componentName = selectNode.name; 2250 pos = selectNode.pos(); 2251 qualId = selectNode.selected; 2252 break; 2253 case IDENT: 2254 componentName = ((JCIdent) qualId).name; 2255 pos = qualId.pos(); 2256 qualId = null; 2257 break; 2258 default: 2259 throw new AssertionError("Unexpected qualified identifier: " + qualId.toString()); 2260 } 2261 if (componentName != null) { 2262 String moduleNameComponentString = componentName.toString(); 2263 int nameLength = moduleNameComponentString.length(); 2264 if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) { 2265 log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName)); 2266 } 2267 } 2268 } 2269 } 2270 } 2271 2272 private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) { 2273 ClashFilter cf = new ClashFilter(origin.type); 2274 return (cf.test(s1) && 2275 cf.test(s2) && 2276 types.hasSameArgs(s1.erasure(types), s2.erasure(types))); 2277 } 2278 2279 2280 /** Check that all abstract members of given class have definitions. 2281 * @param pos Position to be used for error reporting. 2282 * @param c The class. 2283 */ 2284 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) { 2285 MethodSymbol undef = types.firstUnimplementedAbstract(c); 2286 if (undef != null) { 2287 MethodSymbol undef1 = 2288 new MethodSymbol(undef.flags(), undef.name, 2289 types.memberType(c.type, undef), undef.owner); 2290 log.error(pos, 2291 Errors.DoesNotOverrideAbstract(c, undef1, undef1.location())); 2292 } 2293 } 2294 2295 void checkNonCyclicDecl(JCClassDecl tree) { 2296 CycleChecker cc = new CycleChecker(); 2297 cc.scan(tree); 2298 if (!cc.errorFound && !cc.partialCheck) { 2299 tree.sym.flags_field |= ACYCLIC; 2300 } 2301 } 2302 2303 class CycleChecker extends TreeScanner { 2304 2305 Set<Symbol> seenClasses = new HashSet<>(); 2306 boolean errorFound = false; 2307 boolean partialCheck = false; 2308 2309 private void checkSymbol(DiagnosticPosition pos, Symbol sym) { 2310 if (sym != null && sym.kind == TYP) { 2311 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym); 2312 if (classEnv != null) { 2313 DiagnosticSource prevSource = log.currentSource(); 2314 try { 2315 log.useSource(classEnv.toplevel.sourcefile); 2316 scan(classEnv.tree); 2317 } 2318 finally { 2319 log.useSource(prevSource.getFile()); 2320 } 2321 } else if (sym.kind == TYP) { 2322 checkClass(pos, sym, List.nil()); 2323 } 2324 } else if (sym == null || sym.kind != PCK) { 2325 //not completed yet 2326 partialCheck = true; 2327 } 2328 } 2329 2330 @Override 2331 public void visitSelect(JCFieldAccess tree) { 2332 super.visitSelect(tree); 2333 checkSymbol(tree.pos(), tree.sym); 2334 } 2335 2336 @Override 2337 public void visitIdent(JCIdent tree) { 2338 checkSymbol(tree.pos(), tree.sym); 2339 } 2340 2341 @Override 2342 public void visitTypeApply(JCTypeApply tree) { 2343 scan(tree.clazz); 2344 } 2345 2346 @Override 2347 public void visitTypeArray(JCArrayTypeTree tree) { 2348 scan(tree.elemtype); 2349 } 2350 2351 @Override 2352 public void visitClassDef(JCClassDecl tree) { 2353 List<JCTree> supertypes = List.nil(); 2354 if (tree.getExtendsClause() != null) { 2355 supertypes = supertypes.prepend(tree.getExtendsClause()); 2356 } 2357 if (tree.getImplementsClause() != null) { 2358 for (JCTree intf : tree.getImplementsClause()) { 2359 supertypes = supertypes.prepend(intf); 2360 } 2361 } 2362 checkClass(tree.pos(), tree.sym, supertypes); 2363 } 2364 2365 void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) { 2366 if ((c.flags_field & ACYCLIC) != 0) 2367 return; 2368 if (seenClasses.contains(c)) { 2369 errorFound = true; 2370 noteCyclic(pos, (ClassSymbol)c); 2371 } else if (!c.type.isErroneous()) { 2372 try { 2373 seenClasses.add(c); 2374 if (c.type.hasTag(CLASS)) { 2375 if (supertypes.nonEmpty()) { 2376 scan(supertypes); 2377 } 2378 else { 2379 ClassType ct = (ClassType)c.type; 2380 if (ct.supertype_field == null || 2381 ct.interfaces_field == null) { 2382 //not completed yet 2383 partialCheck = true; 2384 return; 2385 } 2386 checkSymbol(pos, ct.supertype_field.tsym); 2387 for (Type intf : ct.interfaces_field) { 2388 checkSymbol(pos, intf.tsym); 2389 } 2390 } 2391 if (c.owner.kind == TYP) { 2392 checkSymbol(pos, c.owner); 2393 } 2394 } 2395 } finally { 2396 seenClasses.remove(c); 2397 } 2398 } 2399 } 2400 } 2401 2402 /** Check for cyclic references. Issue an error if the 2403 * symbol of the type referred to has a LOCKED flag set. 2404 * 2405 * @param pos Position to be used for error reporting. 2406 * @param t The type referred to. 2407 */ 2408 void checkNonCyclic(DiagnosticPosition pos, Type t) { 2409 checkNonCyclicInternal(pos, t); 2410 } 2411 2412 2413 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) { 2414 checkNonCyclic1(pos, t, List.nil()); 2415 } 2416 2417 private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) { 2418 final TypeVar tv; 2419 if (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0) 2420 return; 2421 if (seen.contains(t)) { 2422 tv = (TypeVar)t; 2423 tv.setUpperBound(types.createErrorType(t)); 2424 log.error(pos, Errors.CyclicInheritance(t)); 2425 } else if (t.hasTag(TYPEVAR)) { 2426 tv = (TypeVar)t; 2427 seen = seen.prepend(tv); 2428 for (Type b : types.getBounds(tv)) 2429 checkNonCyclic1(pos, b, seen); 2430 } 2431 } 2432 2433 /** Check for cyclic references. Issue an error if the 2434 * symbol of the type referred to has a LOCKED flag set. 2435 * 2436 * @param pos Position to be used for error reporting. 2437 * @param t The type referred to. 2438 * @returns True if the check completed on all attributed classes 2439 */ 2440 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) { 2441 boolean complete = true; // was the check complete? 2442 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG 2443 Symbol c = t.tsym; 2444 if ((c.flags_field & ACYCLIC) != 0) return true; 2445 2446 if ((c.flags_field & LOCKED) != 0) { 2447 noteCyclic(pos, (ClassSymbol)c); 2448 } else if (!c.type.isErroneous()) { 2449 try { 2450 c.flags_field |= LOCKED; 2451 if (c.type.hasTag(CLASS)) { 2452 ClassType clazz = (ClassType)c.type; 2453 if (clazz.interfaces_field != null) 2454 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail) 2455 complete &= checkNonCyclicInternal(pos, l.head); 2456 if (clazz.supertype_field != null) { 2457 Type st = clazz.supertype_field; 2458 if (st != null && st.hasTag(CLASS)) 2459 complete &= checkNonCyclicInternal(pos, st); 2460 } 2461 if (c.owner.kind == TYP) 2462 complete &= checkNonCyclicInternal(pos, c.owner.type); 2463 } 2464 } finally { 2465 c.flags_field &= ~LOCKED; 2466 } 2467 } 2468 if (complete) 2469 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted(); 2470 if (complete) c.flags_field |= ACYCLIC; 2471 return complete; 2472 } 2473 2474 /** Note that we found an inheritance cycle. */ 2475 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) { 2476 log.error(pos, Errors.CyclicInheritance(c)); 2477 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail) 2478 l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType); 2479 Type st = types.supertype(c.type); 2480 if (st.hasTag(CLASS)) 2481 ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType); 2482 c.type = types.createErrorType(c, c.type); 2483 c.flags_field |= ACYCLIC; 2484 } 2485 2486 /** Check that all methods which implement some 2487 * method conform to the method they implement. 2488 * @param tree The class definition whose members are checked. 2489 */ 2490 void checkImplementations(JCClassDecl tree) { 2491 checkImplementations(tree, tree.sym, tree.sym); 2492 } 2493 //where 2494 /** Check that all methods which implement some 2495 * method in `ic' conform to the method they implement. 2496 */ 2497 void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) { 2498 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) { 2499 ClassSymbol lc = (ClassSymbol)l.head.tsym; 2500 if ((lc.flags() & ABSTRACT) != 0) { 2501 for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) { 2502 if (sym.kind == MTH && 2503 (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) { 2504 MethodSymbol absmeth = (MethodSymbol)sym; 2505 MethodSymbol implmeth = absmeth.implementation(origin, types, false); 2506 if (implmeth != null && implmeth != absmeth && 2507 (implmeth.owner.flags() & INTERFACE) == 2508 (origin.flags() & INTERFACE)) { 2509 // don't check if implmeth is in a class, yet 2510 // origin is an interface. This case arises only 2511 // if implmeth is declared in Object. The reason is 2512 // that interfaces really don't inherit from 2513 // Object it's just that the compiler represents 2514 // things that way. 2515 checkOverride(tree, implmeth, absmeth, origin); 2516 } 2517 } 2518 } 2519 } 2520 } 2521 } 2522 2523 /** Check that all abstract methods implemented by a class are 2524 * mutually compatible. 2525 * @param pos Position to be used for error reporting. 2526 * @param c The class whose interfaces are checked. 2527 */ 2528 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) { 2529 List<Type> supertypes = types.interfaces(c); 2530 Type supertype = types.supertype(c); 2531 if (supertype.hasTag(CLASS) && 2532 (supertype.tsym.flags() & ABSTRACT) != 0) 2533 supertypes = supertypes.prepend(supertype); 2534 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) { 2535 if (!l.head.getTypeArguments().isEmpty() && 2536 !checkCompatibleAbstracts(pos, l.head, l.head, c)) 2537 return; 2538 for (List<Type> m = supertypes; m != l; m = m.tail) 2539 if (!checkCompatibleAbstracts(pos, l.head, m.head, c)) 2540 return; 2541 } 2542 checkCompatibleConcretes(pos, c); 2543 } 2544 2545 /** Check that all non-override equivalent methods accessible from 'site' 2546 * are mutually compatible (JLS 8.4.8/9.4.1). 2547 * 2548 * @param pos Position to be used for error reporting. 2549 * @param site The class whose methods are checked. 2550 * @param sym The method symbol to be checked. 2551 */ 2552 void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2553 ClashFilter cf = new ClashFilter(site); 2554 //for each method m1 that is overridden (directly or indirectly) 2555 //by method 'sym' in 'site'... 2556 2557 List<MethodSymbol> potentiallyAmbiguousList = List.nil(); 2558 boolean overridesAny = false; 2559 ArrayList<Symbol> symbolsByName = new ArrayList<>(); 2560 types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add); 2561 for (Symbol m1 : symbolsByName) { 2562 if (!sym.overrides(m1, site.tsym, types, false)) { 2563 if (m1 == sym) { 2564 continue; 2565 } 2566 2567 if (!overridesAny) { 2568 potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1); 2569 } 2570 continue; 2571 } 2572 2573 if (m1 != sym) { 2574 overridesAny = true; 2575 potentiallyAmbiguousList = List.nil(); 2576 } 2577 2578 //...check each method m2 that is a member of 'site' 2579 for (Symbol m2 : symbolsByName) { 2580 if (m2 == m1) continue; 2581 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2582 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error 2583 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) && 2584 types.hasSameArgs(m2.erasure(types), m1.erasure(types))) { 2585 sym.flags_field |= CLASH; 2586 if (m1 == sym) { 2587 log.error(pos, Errors.NameClashSameErasureNoOverride( 2588 m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(), 2589 m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location())); 2590 } else { 2591 ClassType ct = (ClassType)site; 2592 String kind = ct.isInterface() ? "interface" : "class"; 2593 log.error(pos, Errors.NameClashSameErasureNoOverride1( 2594 kind, 2595 ct.tsym.name, 2596 m1.name, 2597 types.memberType(site, m1).asMethodType().getParameterTypes(), 2598 m1.location(), 2599 m2.name, 2600 types.memberType(site, m2).asMethodType().getParameterTypes(), 2601 m2.location())); 2602 } 2603 return; 2604 } 2605 } 2606 } 2607 2608 if (!overridesAny) { 2609 for (MethodSymbol m: potentiallyAmbiguousList) { 2610 checkPotentiallyAmbiguousOverloads(pos, site, sym, m); 2611 } 2612 } 2613 } 2614 2615 /** Check that all static methods accessible from 'site' are 2616 * mutually compatible (JLS 8.4.8). 2617 * 2618 * @param pos Position to be used for error reporting. 2619 * @param site The class whose methods are checked. 2620 * @param sym The method symbol to be checked. 2621 */ 2622 void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) { 2623 ClashFilter cf = new ClashFilter(site); 2624 //for each method m1 that is a member of 'site'... 2625 for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) { 2626 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as 2627 //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error 2628 if (!types.isSubSignature(sym.type, types.memberType(site, s))) { 2629 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) { 2630 log.error(pos, 2631 Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location())); 2632 return; 2633 } else { 2634 checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s); 2635 } 2636 } 2637 } 2638 } 2639 2640 //where 2641 private class ClashFilter implements Predicate<Symbol> { 2642 2643 Type site; 2644 2645 ClashFilter(Type site) { 2646 this.site = site; 2647 } 2648 2649 boolean shouldSkip(Symbol s) { 2650 return (s.flags() & CLASH) != 0 && 2651 s.owner == site.tsym; 2652 } 2653 2654 @Override 2655 public boolean test(Symbol s) { 2656 return s.kind == MTH && 2657 (s.flags() & SYNTHETIC) == 0 && 2658 !shouldSkip(s) && 2659 s.isInheritedIn(site.tsym, types) && 2660 !s.isConstructor(); 2661 } 2662 } 2663 2664 void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) { 2665 DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site); 2666 for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) { 2667 Assert.check(m.kind == MTH); 2668 List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m); 2669 if (prov.size() > 1) { 2670 ListBuffer<Symbol> abstracts = new ListBuffer<>(); 2671 ListBuffer<Symbol> defaults = new ListBuffer<>(); 2672 for (MethodSymbol provSym : prov) { 2673 if ((provSym.flags() & DEFAULT) != 0) { 2674 defaults = defaults.append(provSym); 2675 } else if ((provSym.flags() & ABSTRACT) != 0) { 2676 abstracts = abstracts.append(provSym); 2677 } 2678 if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) { 2679 //strong semantics - issue an error if two sibling interfaces 2680 //have two override-equivalent defaults - or if one is abstract 2681 //and the other is default 2682 Fragment diagKey; 2683 Symbol s1 = defaults.first(); 2684 Symbol s2; 2685 if (defaults.size() > 1) { 2686 s2 = defaults.toList().tail.head; 2687 diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site, 2688 m.name, types.memberType(site, m).getParameterTypes(), 2689 s1.location(), s2.location()); 2690 2691 } else { 2692 s2 = abstracts.first(); 2693 diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site, 2694 m.name, types.memberType(site, m).getParameterTypes(), 2695 s1.location(), s2.location()); 2696 } 2697 log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey)); 2698 break; 2699 } 2700 } 2701 } 2702 } 2703 } 2704 2705 //where 2706 private class DefaultMethodClashFilter implements Predicate<Symbol> { 2707 2708 Type site; 2709 2710 DefaultMethodClashFilter(Type site) { 2711 this.site = site; 2712 } 2713 2714 @Override 2715 public boolean test(Symbol s) { 2716 return s.kind == MTH && 2717 (s.flags() & DEFAULT) != 0 && 2718 s.isInheritedIn(site.tsym, types) && 2719 !s.isConstructor(); 2720 } 2721 } 2722 2723 /** 2724 * Report warnings for potentially ambiguous method declarations. Two declarations 2725 * are potentially ambiguous if they feature two unrelated functional interface 2726 * in same argument position (in which case, a call site passing an implicit 2727 * lambda would be ambiguous). 2728 */ 2729 void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site, 2730 MethodSymbol msym1, MethodSymbol msym2) { 2731 if (msym1 != msym2 && 2732 lint.isEnabled(LintCategory.OVERLOADS) && 2733 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 && 2734 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) { 2735 Type mt1 = types.memberType(site, msym1); 2736 Type mt2 = types.memberType(site, msym2); 2737 //if both generic methods, adjust type variables 2738 if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) && 2739 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) { 2740 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars); 2741 } 2742 //expand varargs methods if needed 2743 int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length()); 2744 List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true); 2745 List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true); 2746 //if arities don't match, exit 2747 if (args1.length() != args2.length()) return; 2748 boolean potentiallyAmbiguous = false; 2749 while (args1.nonEmpty() && args2.nonEmpty()) { 2750 Type s = args1.head; 2751 Type t = args2.head; 2752 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) { 2753 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) && 2754 types.findDescriptorType(s).getParameterTypes().length() > 0 && 2755 types.findDescriptorType(s).getParameterTypes().length() == 2756 types.findDescriptorType(t).getParameterTypes().length()) { 2757 potentiallyAmbiguous = true; 2758 } else { 2759 return; 2760 } 2761 } 2762 args1 = args1.tail; 2763 args2 = args2.tail; 2764 } 2765 if (potentiallyAmbiguous) { 2766 //we found two incompatible functional interfaces with same arity 2767 //this means a call site passing an implicit lambda would be ambiguous 2768 msym1.flags_field |= POTENTIALLY_AMBIGUOUS; 2769 msym2.flags_field |= POTENTIALLY_AMBIGUOUS; 2770 log.warning(LintCategory.OVERLOADS, pos, 2771 Warnings.PotentiallyAmbiguousOverload(msym1, msym1.location(), 2772 msym2, msym2.location())); 2773 return; 2774 } 2775 } 2776 } 2777 2778 void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) { 2779 if (warnOnAnyAccessToMembers || 2780 (lint.isEnabled(LintCategory.SERIAL) && 2781 !lint.isSuppressed(LintCategory.SERIAL) && 2782 isLambda)) { 2783 Symbol sym = TreeInfo.symbol(tree); 2784 if (!sym.kind.matches(KindSelector.VAL_MTH)) { 2785 return; 2786 } 2787 2788 if (sym.kind == VAR) { 2789 if ((sym.flags() & PARAMETER) != 0 || 2790 sym.isDirectlyOrIndirectlyLocal() || 2791 sym.name == names._this || 2792 sym.name == names._super) { 2793 return; 2794 } 2795 } 2796 2797 if (!types.isSubtype(sym.owner.type, syms.serializableType) && 2798 isEffectivelyNonPublic(sym)) { 2799 if (isLambda) { 2800 if (belongsToRestrictedPackage(sym)) { 2801 log.warning(LintCategory.SERIAL, tree.pos(), 2802 Warnings.AccessToMemberFromSerializableLambda(sym)); 2803 } 2804 } else { 2805 log.warning(tree.pos(), 2806 Warnings.AccessToMemberFromSerializableElement(sym)); 2807 } 2808 } 2809 } 2810 } 2811 2812 private boolean isEffectivelyNonPublic(Symbol sym) { 2813 if (sym.packge() == syms.rootPackage) { 2814 return false; 2815 } 2816 2817 while (sym.kind != PCK) { 2818 if ((sym.flags() & PUBLIC) == 0) { 2819 return true; 2820 } 2821 sym = sym.owner; 2822 } 2823 return false; 2824 } 2825 2826 private boolean belongsToRestrictedPackage(Symbol sym) { 2827 String fullName = sym.packge().fullname.toString(); 2828 return fullName.startsWith("java.") || 2829 fullName.startsWith("javax.") || 2830 fullName.startsWith("sun.") || 2831 fullName.contains(".internal."); 2832 } 2833 2834 /** Check that class c does not implement directly or indirectly 2835 * the same parameterized interface with two different argument lists. 2836 * @param pos Position to be used for error reporting. 2837 * @param type The type whose interfaces are checked. 2838 */ 2839 void checkClassBounds(DiagnosticPosition pos, Type type) { 2840 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type); 2841 } 2842 //where 2843 /** Enter all interfaces of type `type' into the hash table `seensofar' 2844 * with their class symbol as key and their type as value. Make 2845 * sure no class is entered with two different types. 2846 */ 2847 void checkClassBounds(DiagnosticPosition pos, 2848 Map<TypeSymbol,Type> seensofar, 2849 Type type) { 2850 if (type.isErroneous()) return; 2851 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) { 2852 Type it = l.head; 2853 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5 2854 2855 Type oldit = seensofar.put(it.tsym, it); 2856 if (oldit != null) { 2857 List<Type> oldparams = oldit.allparams(); 2858 List<Type> newparams = it.allparams(); 2859 if (!types.containsTypeEquivalent(oldparams, newparams)) 2860 log.error(pos, 2861 Errors.CantInheritDiffArg(it.tsym, 2862 Type.toString(oldparams), 2863 Type.toString(newparams))); 2864 } 2865 checkClassBounds(pos, seensofar, it); 2866 } 2867 Type st = types.supertype(type); 2868 if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4 2869 if (st != Type.noType) checkClassBounds(pos, seensofar, st); 2870 } 2871 2872 /** Enter interface into into set. 2873 * If it existed already, issue a "repeated interface" error. 2874 */ 2875 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) { 2876 if (its.contains(it)) 2877 log.error(pos, Errors.RepeatedInterface); 2878 else { 2879 its.add(it); 2880 } 2881 } 2882 2883 /* ************************************************************************* 2884 * Check annotations 2885 **************************************************************************/ 2886 2887 /** 2888 * Recursively validate annotations values 2889 */ 2890 void validateAnnotationTree(JCTree tree) { 2891 class AnnotationValidator extends TreeScanner { 2892 @Override 2893 public void visitAnnotation(JCAnnotation tree) { 2894 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) { 2895 super.visitAnnotation(tree); 2896 validateAnnotation(tree); 2897 } 2898 } 2899 } 2900 tree.accept(new AnnotationValidator()); 2901 } 2902 2903 /** 2904 * {@literal 2905 * Annotation types are restricted to primitives, String, an 2906 * enum, an annotation, Class, Class<?>, Class<? extends 2907 * Anything>, arrays of the preceding. 2908 * } 2909 */ 2910 void validateAnnotationType(JCTree restype) { 2911 // restype may be null if an error occurred, so don't bother validating it 2912 if (restype != null) { 2913 validateAnnotationType(restype.pos(), restype.type); 2914 } 2915 } 2916 2917 void validateAnnotationType(DiagnosticPosition pos, Type type) { 2918 if (type.isPrimitive()) return; 2919 if (types.isSameType(type, syms.stringType)) return; 2920 if ((type.tsym.flags() & Flags.ENUM) != 0) return; 2921 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return; 2922 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return; 2923 if (types.isArray(type) && !types.isArray(types.elemtype(type))) { 2924 validateAnnotationType(pos, types.elemtype(type)); 2925 return; 2926 } 2927 log.error(pos, Errors.InvalidAnnotationMemberType); 2928 } 2929 2930 /** 2931 * "It is also a compile-time error if any method declared in an 2932 * annotation type has a signature that is override-equivalent to 2933 * that of any public or protected method declared in class Object 2934 * or in the interface annotation.Annotation." 2935 * 2936 * @jls 9.6 Annotation Types 2937 */ 2938 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) { 2939 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) { 2940 Scope s = sup.tsym.members(); 2941 for (Symbol sym : s.getSymbolsByName(m.name)) { 2942 if (sym.kind == MTH && 2943 (sym.flags() & (PUBLIC | PROTECTED)) != 0 && 2944 types.overrideEquivalent(m.type, sym.type)) 2945 log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup)); 2946 } 2947 } 2948 } 2949 2950 /** Check the annotations of a symbol. 2951 */ 2952 public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) { 2953 for (JCAnnotation a : annotations) 2954 validateAnnotation(a, declarationTree, s); 2955 } 2956 2957 /** Check the type annotations. 2958 */ 2959 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) { 2960 for (JCAnnotation a : annotations) 2961 validateTypeAnnotation(a, isTypeParameter); 2962 } 2963 2964 /** Check an annotation of a symbol. 2965 */ 2966 private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) { 2967 /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method, 2968 * this can impact in particular records for which annotations are forcibly propagated. 2969 */ 2970 validateAnnotationTree(a); 2971 boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord()); 2972 2973 boolean isRecordField = (s.flags_field & RECORD) != 0 && 2974 declarationTree.hasTag(VARDEF) && 2975 s.owner.kind == TYP; 2976 2977 if (isRecordField) { 2978 // first we need to check if the annotation is applicable to records 2979 Name[] targets = getTargetNames(a); 2980 boolean appliesToRecords = false; 2981 for (Name target : targets) { 2982 appliesToRecords = 2983 target == names.FIELD || 2984 target == names.PARAMETER || 2985 target == names.METHOD || 2986 target == names.TYPE_USE || 2987 target == names.RECORD_COMPONENT; 2988 if (appliesToRecords) { 2989 break; 2990 } 2991 } 2992 if (!appliesToRecords) { 2993 log.error(a.pos(), Errors.AnnotationTypeNotApplicable); 2994 } else { 2995 /* lets now find the annotations in the field that are targeted to record components and append them to 2996 * the corresponding record component 2997 */ 2998 ClassSymbol recordClass = (ClassSymbol) s.owner; 2999 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s); 3000 SymbolMetadata metadata = rc.getMetadata(); 3001 if (metadata == null || metadata.isEmpty()) { 3002 /* if not is empty then we have already been here, which is the case if multiple annotations are applied 3003 * to the record component declaration 3004 */ 3005 rc.appendAttributes(s.getRawAttributes().stream().filter(anno -> 3006 Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT) 3007 ).collect(List.collector())); 3008 3009 JCVariableDecl fieldAST = (JCVariableDecl) declarationTree; 3010 for (JCAnnotation fieldAnnot : fieldAST.mods.annotations) { 3011 for (JCAnnotation rcAnnot : rc.declarationFor().mods.annotations) { 3012 if (rcAnnot.pos == fieldAnnot.pos) { 3013 rcAnnot.setType(fieldAnnot.type); 3014 break; 3015 } 3016 } 3017 } 3018 3019 /* At this point, we used to carry over any type annotations from the VARDEF to the record component, but 3020 * that is problematic, since we get here only when *some* annotation is applied to the SE5 (declaration) 3021 * annotation location, inadvertently failing to carry over the type annotations when the VarDef has no 3022 * annotations in the SE5 annotation location. 3023 * 3024 * Now type annotations are assigned to record components in a method that would execute irrespective of 3025 * whether there are SE5 annotations on a VarDef viz com.sun.tools.javac.code.TypeAnnotations.TypeAnnotationPositions.visitVarDef 3026 */ 3027 } 3028 } 3029 } 3030 3031 /* the section below is tricky. Annotations applied to record components are propagated to the corresponding 3032 * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has 3033 * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated 3034 * there is no enough information to propagate only the right annotations. So all the annotations are propagated 3035 * to all the possible locations. 3036 * 3037 * At this point we need to remove all the annotations that are not in place before going on with the annotation 3038 * party. On top of the above there is the issue that there is no AST representing record components, just symbols 3039 * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it 3040 * was both a field and a record component. 3041 * 3042 * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers 3043 * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could 3044 * be see by annotation processors. 3045 * 3046 * The metadata contains both type annotations and declaration annotations. At this point of the game we don't 3047 * need to care about type annotations, they are all in the right place. But we could need to remove declaration 3048 * annotations. So for declaration annotations if they are not applicable to the record member, excluding type 3049 * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not 3050 * applicable either as type annotation and or declaration annotation, only in that case it will be removed. 3051 * 3052 * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for 3053 * further inspection by annotation processors. 3054 * 3055 * For example: 3056 * 3057 * import java.lang.annotation.*; 3058 * 3059 * @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT}) 3060 * @Retention(RetentionPolicy.RUNTIME) 3061 * @interface Anno { } 3062 * 3063 * record R(@Anno String s) {} 3064 * 3065 * at this point we will have for the case of the generated field: 3066 * - @Anno in the modifier 3067 * - @Anno as a type annotation 3068 * - @Anno as a declaration annotation 3069 * 3070 * the last one should be removed because the annotation has not FIELD as target but it was applied as a 3071 * declaration annotation because the field was being treated both as a field and as a record component 3072 * as we have already copied the annotations to the record component, now the field doesn't need to hold 3073 * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it 3074 * is applicable as a type annotation to the type of the field. 3075 */ 3076 3077 if (a.type.tsym.isAnnotationType()) { 3078 Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s); 3079 if (!applicableTargetsOp.isEmpty()) { 3080 Set<Name> applicableTargets = applicableTargetsOp.get(); 3081 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() || 3082 applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE); 3083 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0; 3084 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly; 3085 3086 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) { 3087 if (isCompRecordElementWithNonApplicableDeclAnno) { 3088 /* so we have found an annotation that is not applicable to a record member that was generated by the 3089 * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations 3090 * that are not applicable to the given record member 3091 */ 3092 JCModifiers modifiers = TreeInfo.getModifiers(declarationTree); 3093 /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as 3094 * it could be a type annotation 3095 */ 3096 if (modifiers != null && applicableTargets.isEmpty()) { 3097 ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>(); 3098 for (JCAnnotation anno : modifiers.annotations) { 3099 if (anno != a) { 3100 newAnnotations.add(anno); 3101 } 3102 } 3103 modifiers.annotations = newAnnotations.toList(); 3104 } 3105 // now lets remove it from the symbol 3106 s.getMetadata().removeDeclarationMetadata(a.attribute); 3107 } else { 3108 log.error(a.pos(), Errors.AnnotationTypeNotApplicable); 3109 } 3110 } 3111 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor, 3112 * then this is an error as we know that no compiler generated accessor will be a varargs 3113 * method, better to fail asap 3114 */ 3115 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) { 3116 log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s))); 3117 } 3118 } 3119 } 3120 3121 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 3122 if (s.kind != TYP) { 3123 log.error(a.pos(), Errors.BadFunctionalIntfAnno); 3124 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) { 3125 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s))); 3126 } 3127 } 3128 } 3129 3130 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 3131 Assert.checkNonNull(a.type); 3132 validateAnnotationTree(a); 3133 3134 if (a.hasTag(TYPE_ANNOTATION) && 3135 !a.annotationType.type.isErroneous() && 3136 !isTypeAnnotation(a, isTypeParameter)) { 3137 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type)); 3138 } 3139 } 3140 3141 /** 3142 * Validate the proposed container 'repeatable' on the 3143 * annotation type symbol 's'. Report errors at position 3144 * 'pos'. 3145 * 3146 * @param s The (annotation)type declaration annotated with a @Repeatable 3147 * @param repeatable the @Repeatable on 's' 3148 * @param pos where to report errors 3149 */ 3150 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) { 3151 Assert.check(types.isSameType(repeatable.type, syms.repeatableType)); 3152 3153 Type t = null; 3154 List<Pair<MethodSymbol,Attribute>> l = repeatable.values; 3155 if (!l.isEmpty()) { 3156 Assert.check(l.head.fst.name == names.value); 3157 if (l.head.snd instanceof Attribute.Class) { 3158 t = ((Attribute.Class)l.head.snd).getValue(); 3159 } 3160 } 3161 3162 if (t == null) { 3163 // errors should already have been reported during Annotate 3164 return; 3165 } 3166 3167 validateValue(t.tsym, s, pos); 3168 validateRetention(t.tsym, s, pos); 3169 validateDocumented(t.tsym, s, pos); 3170 validateInherited(t.tsym, s, pos); 3171 validateTarget(t.tsym, s, pos); 3172 validateDefault(t.tsym, pos); 3173 } 3174 3175 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3176 Symbol sym = container.members().findFirst(names.value); 3177 if (sym != null && sym.kind == MTH) { 3178 MethodSymbol m = (MethodSymbol) sym; 3179 Type ret = m.getReturnType(); 3180 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) { 3181 log.error(pos, 3182 Errors.InvalidRepeatableAnnotationValueReturn(container, 3183 ret, 3184 types.makeArrayType(contained.type))); 3185 } 3186 } else { 3187 log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container)); 3188 } 3189 } 3190 3191 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3192 Attribute.RetentionPolicy containerRetention = types.getRetention(container); 3193 Attribute.RetentionPolicy containedRetention = types.getRetention(contained); 3194 3195 boolean error = false; 3196 switch (containedRetention) { 3197 case RUNTIME: 3198 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) { 3199 error = true; 3200 } 3201 break; 3202 case CLASS: 3203 if (containerRetention == Attribute.RetentionPolicy.SOURCE) { 3204 error = true; 3205 } 3206 } 3207 if (error ) { 3208 log.error(pos, 3209 Errors.InvalidRepeatableAnnotationRetention(container, 3210 containerRetention.name(), 3211 contained, 3212 containedRetention.name())); 3213 } 3214 } 3215 3216 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) { 3217 if (contained.attribute(syms.documentedType.tsym) != null) { 3218 if (container.attribute(syms.documentedType.tsym) == null) { 3219 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained)); 3220 } 3221 } 3222 } 3223 3224 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) { 3225 if (contained.attribute(syms.inheritedType.tsym) != null) { 3226 if (container.attribute(syms.inheritedType.tsym) == null) { 3227 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained)); 3228 } 3229 } 3230 } 3231 3232 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 3233 // The set of targets the container is applicable to must be a subset 3234 // (with respect to annotation target semantics) of the set of targets 3235 // the contained is applicable to. The target sets may be implicit or 3236 // explicit. 3237 3238 Set<Name> containerTargets; 3239 Attribute.Array containerTarget = getAttributeTargetAttribute(container); 3240 if (containerTarget == null) { 3241 containerTargets = getDefaultTargetSet(); 3242 } else { 3243 containerTargets = new HashSet<>(); 3244 for (Attribute app : containerTarget.values) { 3245 if (!(app instanceof Attribute.Enum attributeEnum)) { 3246 continue; // recovery 3247 } 3248 containerTargets.add(attributeEnum.value.name); 3249 } 3250 } 3251 3252 Set<Name> containedTargets; 3253 Attribute.Array containedTarget = getAttributeTargetAttribute(contained); 3254 if (containedTarget == null) { 3255 containedTargets = getDefaultTargetSet(); 3256 } else { 3257 containedTargets = new HashSet<>(); 3258 for (Attribute app : containedTarget.values) { 3259 if (!(app instanceof Attribute.Enum attributeEnum)) { 3260 continue; // recovery 3261 } 3262 containedTargets.add(attributeEnum.value.name); 3263 } 3264 } 3265 3266 if (!isTargetSubsetOf(containerTargets, containedTargets)) { 3267 log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained)); 3268 } 3269 } 3270 3271 /* get a set of names for the default target */ 3272 private Set<Name> getDefaultTargetSet() { 3273 if (defaultTargets == null) { 3274 defaultTargets = Set.of(defaultTargetMetaInfo()); 3275 } 3276 3277 return defaultTargets; 3278 } 3279 private Set<Name> defaultTargets; 3280 3281 3282 /** Checks that s is a subset of t, with respect to ElementType 3283 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}, 3284 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE, 3285 * TYPE_PARAMETER}. 3286 */ 3287 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) { 3288 // Check that all elements in s are present in t 3289 for (Name n2 : s) { 3290 boolean currentElementOk = false; 3291 for (Name n1 : t) { 3292 if (n1 == n2) { 3293 currentElementOk = true; 3294 break; 3295 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) { 3296 currentElementOk = true; 3297 break; 3298 } else if (n1 == names.TYPE_USE && 3299 (n2 == names.TYPE || 3300 n2 == names.ANNOTATION_TYPE || 3301 n2 == names.TYPE_PARAMETER)) { 3302 currentElementOk = true; 3303 break; 3304 } 3305 } 3306 if (!currentElementOk) 3307 return false; 3308 } 3309 return true; 3310 } 3311 3312 private void validateDefault(Symbol container, DiagnosticPosition pos) { 3313 // validate that all other elements of containing type has defaults 3314 Scope scope = container.members(); 3315 for(Symbol elm : scope.getSymbols()) { 3316 if (elm.name != names.value && 3317 elm.kind == MTH && 3318 ((MethodSymbol)elm).defaultValue == null) { 3319 log.error(pos, 3320 Errors.InvalidRepeatableAnnotationElemNondefault(container, elm)); 3321 } 3322 } 3323 } 3324 3325 /** Is s a method symbol that overrides a method in a superclass? */ 3326 boolean isOverrider(Symbol s) { 3327 if (s.kind != MTH || s.isStatic()) 3328 return false; 3329 MethodSymbol m = (MethodSymbol)s; 3330 TypeSymbol owner = (TypeSymbol)m.owner; 3331 for (Type sup : types.closure(owner.type)) { 3332 if (sup == owner.type) 3333 continue; // skip "this" 3334 Scope scope = sup.tsym.members(); 3335 for (Symbol sym : scope.getSymbolsByName(m.name)) { 3336 if (!sym.isStatic() && m.overrides(sym, owner, types, true)) 3337 return true; 3338 } 3339 } 3340 return false; 3341 } 3342 3343 /** Is the annotation applicable to types? */ 3344 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 3345 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym); 3346 return (targets == null) ? 3347 false : 3348 targets.stream() 3349 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter)); 3350 } 3351 //where 3352 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) { 3353 Attribute.Enum e = (Attribute.Enum)a; 3354 return (e.value.name == names.TYPE_USE || 3355 (isTypeParameter && e.value.name == names.TYPE_PARAMETER)); 3356 } 3357 3358 /** Is the annotation applicable to the symbol? */ 3359 Name[] getTargetNames(JCAnnotation a) { 3360 return getTargetNames(a.annotationType.type.tsym); 3361 } 3362 3363 public Name[] getTargetNames(TypeSymbol annoSym) { 3364 Attribute.Array arr = getAttributeTargetAttribute(annoSym); 3365 Name[] targets; 3366 if (arr == null) { 3367 targets = defaultTargetMetaInfo(); 3368 } else { 3369 // TODO: can we optimize this? 3370 targets = new Name[arr.values.length]; 3371 for (int i=0; i<arr.values.length; ++i) { 3372 Attribute app = arr.values[i]; 3373 if (!(app instanceof Attribute.Enum attributeEnum)) { 3374 return new Name[0]; 3375 } 3376 targets[i] = attributeEnum.value.name; 3377 } 3378 } 3379 return targets; 3380 } 3381 3382 boolean annotationApplicable(JCAnnotation a, Symbol s) { 3383 Optional<Set<Name>> targets = getApplicableTargets(a, s); 3384 /* the optional could be empty if the annotation is unknown in that case 3385 * we return that it is applicable and if it is erroneous that should imply 3386 * an error at the declaration site 3387 */ 3388 return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty(); 3389 } 3390 3391 Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) { 3392 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym); 3393 Name[] targets; 3394 Set<Name> applicableTargets = new HashSet<>(); 3395 3396 if (arr == null) { 3397 targets = defaultTargetMetaInfo(); 3398 } else { 3399 // TODO: can we optimize this? 3400 targets = new Name[arr.values.length]; 3401 for (int i=0; i<arr.values.length; ++i) { 3402 Attribute app = arr.values[i]; 3403 if (!(app instanceof Attribute.Enum attributeEnum)) { 3404 // recovery 3405 return Optional.empty(); 3406 } 3407 targets[i] = attributeEnum.value.name; 3408 } 3409 } 3410 for (Name target : targets) { 3411 if (target == names.TYPE) { 3412 if (s.kind == TYP) 3413 applicableTargets.add(names.TYPE); 3414 } else if (target == names.FIELD) { 3415 if (s.kind == VAR && s.owner.kind != MTH) 3416 applicableTargets.add(names.FIELD); 3417 } else if (target == names.RECORD_COMPONENT) { 3418 if (s.getKind() == ElementKind.RECORD_COMPONENT) { 3419 applicableTargets.add(names.RECORD_COMPONENT); 3420 } 3421 } else if (target == names.METHOD) { 3422 if (s.kind == MTH && !s.isConstructor()) 3423 applicableTargets.add(names.METHOD); 3424 } else if (target == names.PARAMETER) { 3425 if (s.kind == VAR && 3426 (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) { 3427 applicableTargets.add(names.PARAMETER); 3428 } 3429 } else if (target == names.CONSTRUCTOR) { 3430 if (s.kind == MTH && s.isConstructor()) 3431 applicableTargets.add(names.CONSTRUCTOR); 3432 } else if (target == names.LOCAL_VARIABLE) { 3433 if (s.kind == VAR && s.owner.kind == MTH && 3434 (s.flags() & PARAMETER) == 0) { 3435 applicableTargets.add(names.LOCAL_VARIABLE); 3436 } 3437 } else if (target == names.ANNOTATION_TYPE) { 3438 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) { 3439 applicableTargets.add(names.ANNOTATION_TYPE); 3440 } 3441 } else if (target == names.PACKAGE) { 3442 if (s.kind == PCK) 3443 applicableTargets.add(names.PACKAGE); 3444 } else if (target == names.TYPE_USE) { 3445 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) { 3446 //cannot type annotate implicitly typed locals 3447 continue; 3448 } else if (s.kind == TYP || s.kind == VAR || 3449 (s.kind == MTH && !s.isConstructor() && 3450 !s.type.getReturnType().hasTag(VOID)) || 3451 (s.kind == MTH && s.isConstructor())) { 3452 applicableTargets.add(names.TYPE_USE); 3453 } 3454 } else if (target == names.TYPE_PARAMETER) { 3455 if (s.kind == TYP && s.type.hasTag(TYPEVAR)) 3456 applicableTargets.add(names.TYPE_PARAMETER); 3457 } else if (target == names.MODULE) { 3458 if (s.kind == MDL) 3459 applicableTargets.add(names.MODULE); 3460 } else 3461 return Optional.empty(); // Unknown ElementType. This should be an error at declaration site, 3462 // assume applicable. 3463 } 3464 return Optional.of(applicableTargets); 3465 } 3466 3467 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) { 3468 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget(); 3469 if (atTarget == null) return null; // ok, is applicable 3470 Attribute atValue = atTarget.member(names.value); 3471 return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null; 3472 } 3473 3474 private Name[] dfltTargetMeta; 3475 private Name[] defaultTargetMetaInfo() { 3476 if (dfltTargetMeta == null) { 3477 ArrayList<Name> defaultTargets = new ArrayList<>(); 3478 defaultTargets.add(names.PACKAGE); 3479 defaultTargets.add(names.TYPE); 3480 defaultTargets.add(names.FIELD); 3481 defaultTargets.add(names.METHOD); 3482 defaultTargets.add(names.CONSTRUCTOR); 3483 defaultTargets.add(names.ANNOTATION_TYPE); 3484 defaultTargets.add(names.LOCAL_VARIABLE); 3485 defaultTargets.add(names.PARAMETER); 3486 if (allowRecords) { 3487 defaultTargets.add(names.RECORD_COMPONENT); 3488 } 3489 if (allowModules) { 3490 defaultTargets.add(names.MODULE); 3491 } 3492 dfltTargetMeta = defaultTargets.toArray(new Name[0]); 3493 } 3494 return dfltTargetMeta; 3495 } 3496 3497 /** Check an annotation value. 3498 * 3499 * @param a The annotation tree to check 3500 * @return true if this annotation tree is valid, otherwise false 3501 */ 3502 public boolean validateAnnotationDeferErrors(JCAnnotation a) { 3503 boolean res = false; 3504 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log); 3505 try { 3506 res = validateAnnotation(a); 3507 } finally { 3508 log.popDiagnosticHandler(diagHandler); 3509 } 3510 return res; 3511 } 3512 3513 private boolean validateAnnotation(JCAnnotation a) { 3514 boolean isValid = true; 3515 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata(); 3516 3517 // collect an inventory of the annotation elements 3518 Set<MethodSymbol> elements = metadata.getAnnotationElements(); 3519 3520 // remove the ones that are assigned values 3521 for (JCTree arg : a.args) { 3522 if (!arg.hasTag(ASSIGN)) continue; // recovery 3523 JCAssign assign = (JCAssign)arg; 3524 Symbol m = TreeInfo.symbol(assign.lhs); 3525 if (m == null || m.type.isErroneous()) continue; 3526 if (!elements.remove(m)) { 3527 isValid = false; 3528 log.error(assign.lhs.pos(), 3529 Errors.DuplicateAnnotationMemberValue(m.name, a.type)); 3530 } 3531 } 3532 3533 // all the remaining ones better have default values 3534 List<Name> missingDefaults = List.nil(); 3535 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault(); 3536 for (MethodSymbol m : elements) { 3537 if (m.type.isErroneous()) 3538 continue; 3539 3540 if (!membersWithDefault.contains(m)) 3541 missingDefaults = missingDefaults.append(m.name); 3542 } 3543 missingDefaults = missingDefaults.reverse(); 3544 if (missingDefaults.nonEmpty()) { 3545 isValid = false; 3546 Error errorKey = (missingDefaults.size() > 1) 3547 ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults) 3548 : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults); 3549 log.error(a.pos(), errorKey); 3550 } 3551 3552 return isValid && validateTargetAnnotationValue(a); 3553 } 3554 3555 /* Validate the special java.lang.annotation.Target annotation */ 3556 boolean validateTargetAnnotationValue(JCAnnotation a) { 3557 // special case: java.lang.annotation.Target must not have 3558 // repeated values in its value member 3559 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym || 3560 a.args.tail == null) 3561 return true; 3562 3563 boolean isValid = true; 3564 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery 3565 JCAssign assign = (JCAssign) a.args.head; 3566 Symbol m = TreeInfo.symbol(assign.lhs); 3567 if (m.name != names.value) return false; 3568 JCTree rhs = assign.rhs; 3569 if (!rhs.hasTag(NEWARRAY)) return false; 3570 JCNewArray na = (JCNewArray) rhs; 3571 Set<Symbol> targets = new HashSet<>(); 3572 for (JCTree elem : na.elems) { 3573 if (!targets.add(TreeInfo.symbol(elem))) { 3574 isValid = false; 3575 log.error(elem.pos(), Errors.RepeatedAnnotationTarget); 3576 } 3577 } 3578 return isValid; 3579 } 3580 3581 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { 3582 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() && 3583 (s.flags() & DEPRECATED) != 0 && 3584 !syms.deprecatedType.isErroneous() && 3585 s.attribute(syms.deprecatedType.tsym) == null) { 3586 log.warning(LintCategory.DEP_ANN, 3587 pos, Warnings.MissingDeprecatedAnnotation); 3588 } 3589 // Note: @Deprecated has no effect on local variables, parameters and package decls. 3590 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) { 3591 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) { 3592 log.warning(LintCategory.DEPRECATION, pos, 3593 Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s))); 3594 } 3595 } 3596 } 3597 3598 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) { 3599 checkDeprecated(() -> pos, other, s); 3600 } 3601 3602 void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) { 3603 if ( (s.isDeprecatedForRemoval() 3604 || s.isDeprecated() && !other.isDeprecated()) 3605 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null) 3606 && s.kind != Kind.PCK) { 3607 deferredLintHandler.report(() -> warnDeprecated(pos.get(), s)); 3608 } 3609 } 3610 3611 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) { 3612 if ((s.flags() & PROPRIETARY) != 0) { 3613 deferredLintHandler.report(() -> { 3614 log.mandatoryWarning(pos, Warnings.SunProprietary(s)); 3615 }); 3616 } 3617 } 3618 3619 void checkProfile(final DiagnosticPosition pos, final Symbol s) { 3620 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) { 3621 log.error(pos, Errors.NotInProfile(s, profile)); 3622 } 3623 } 3624 3625 void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) { 3626 if ((s.flags() & PREVIEW_API) != 0 && !preview.participatesInPreview(syms, other, s)) { 3627 if ((s.flags() & PREVIEW_REFLECTIVE) == 0) { 3628 if (!preview.isEnabled()) { 3629 log.error(pos, Errors.IsPreview(s)); 3630 } else { 3631 preview.markUsesPreview(pos); 3632 deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreview(s))); 3633 } 3634 } else { 3635 deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreviewReflective(s))); 3636 } 3637 } 3638 if (preview.declaredUsingPreviewFeature(s)) { 3639 if (preview.isEnabled()) { 3640 //for preview disabled do presumably so not need to do anything? 3641 //If "s" is compiled from source, then there was an error for it already; 3642 //if "s" is from classfile, there already was an error for the classfile. 3643 preview.markUsesPreview(pos); 3644 deferredLintHandler.report(() -> warnDeclaredUsingPreview(pos, s)); 3645 } 3646 } 3647 } 3648 3649 /* ************************************************************************* 3650 * Check for recursive annotation elements. 3651 **************************************************************************/ 3652 3653 /** Check for cycles in the graph of annotation elements. 3654 */ 3655 void checkNonCyclicElements(JCClassDecl tree) { 3656 if ((tree.sym.flags_field & ANNOTATION) == 0) return; 3657 Assert.check((tree.sym.flags_field & LOCKED) == 0); 3658 try { 3659 tree.sym.flags_field |= LOCKED; 3660 for (JCTree def : tree.defs) { 3661 if (!def.hasTag(METHODDEF)) continue; 3662 JCMethodDecl meth = (JCMethodDecl)def; 3663 checkAnnotationResType(meth.pos(), meth.restype.type); 3664 } 3665 } finally { 3666 tree.sym.flags_field &= ~LOCKED; 3667 tree.sym.flags_field |= ACYCLIC_ANN; 3668 } 3669 } 3670 3671 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) { 3672 if ((tsym.flags_field & ACYCLIC_ANN) != 0) 3673 return; 3674 if ((tsym.flags_field & LOCKED) != 0) { 3675 log.error(pos, Errors.CyclicAnnotationElement(tsym)); 3676 return; 3677 } 3678 try { 3679 tsym.flags_field |= LOCKED; 3680 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) { 3681 if (s.kind != MTH) 3682 continue; 3683 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType()); 3684 } 3685 } finally { 3686 tsym.flags_field &= ~LOCKED; 3687 tsym.flags_field |= ACYCLIC_ANN; 3688 } 3689 } 3690 3691 void checkAnnotationResType(DiagnosticPosition pos, Type type) { 3692 switch (type.getTag()) { 3693 case CLASS: 3694 if ((type.tsym.flags() & ANNOTATION) != 0) 3695 checkNonCyclicElementsInternal(pos, type.tsym); 3696 break; 3697 case ARRAY: 3698 checkAnnotationResType(pos, types.elemtype(type)); 3699 break; 3700 default: 3701 break; // int etc 3702 } 3703 } 3704 3705 /* ************************************************************************* 3706 * Check for cycles in the constructor call graph. 3707 **************************************************************************/ 3708 3709 /** Check for cycles in the graph of constructors calling other 3710 * constructors. 3711 */ 3712 void checkCyclicConstructors(JCClassDecl tree) { 3713 // use LinkedHashMap so we generate errors deterministically 3714 Map<Symbol,Symbol> callMap = new LinkedHashMap<>(); 3715 3716 // enter each constructor this-call into the map 3717 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 3718 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head); 3719 if (app == null) continue; 3720 JCMethodDecl meth = (JCMethodDecl) l.head; 3721 if (TreeInfo.name(app.meth) == names._this) { 3722 callMap.put(meth.sym, TreeInfo.symbol(app.meth)); 3723 } else { 3724 meth.sym.flags_field |= ACYCLIC; 3725 } 3726 } 3727 3728 // Check for cycles in the map 3729 Symbol[] ctors = new Symbol[0]; 3730 ctors = callMap.keySet().toArray(ctors); 3731 for (Symbol caller : ctors) { 3732 checkCyclicConstructor(tree, caller, callMap); 3733 } 3734 } 3735 3736 /** Look in the map to see if the given constructor is part of a 3737 * call cycle. 3738 */ 3739 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor, 3740 Map<Symbol,Symbol> callMap) { 3741 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) { 3742 if ((ctor.flags_field & LOCKED) != 0) { 3743 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)), 3744 Errors.RecursiveCtorInvocation); 3745 } else { 3746 ctor.flags_field |= LOCKED; 3747 checkCyclicConstructor(tree, callMap.remove(ctor), callMap); 3748 ctor.flags_field &= ~LOCKED; 3749 } 3750 ctor.flags_field |= ACYCLIC; 3751 } 3752 } 3753 3754 /* ************************************************************************* 3755 * Miscellaneous 3756 **************************************************************************/ 3757 3758 /** 3759 * Check for division by integer constant zero 3760 * @param pos Position for error reporting. 3761 * @param operator The operator for the expression 3762 * @param operand The right hand operand for the expression 3763 */ 3764 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { 3765 if (operand.constValue() != null 3766 && operand.getTag().isSubRangeOf(LONG) 3767 && ((Number) (operand.constValue())).longValue() == 0) { 3768 int opc = ((OperatorSymbol)operator).opcode; 3769 if (opc == ByteCodes.idiv || opc == ByteCodes.imod 3770 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) { 3771 deferredLintHandler.report(() -> warnDivZero(pos)); 3772 } 3773 } 3774 } 3775 3776 /** 3777 * Check for possible loss of precission 3778 * @param pos Position for error reporting. 3779 * @param found The computed type of the tree 3780 * @param req The computed type of the tree 3781 */ 3782 void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) { 3783 if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) { 3784 deferredLintHandler.report(() -> { 3785 if (lint.isEnabled(LintCategory.LOSSY_CONVERSIONS)) 3786 log.warning(LintCategory.LOSSY_CONVERSIONS, 3787 pos, Warnings.PossibleLossOfPrecision(found, req)); 3788 }); 3789 } 3790 } 3791 3792 /** 3793 * Check for empty statements after if 3794 */ 3795 void checkEmptyIf(JCIf tree) { 3796 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null && 3797 lint.isEnabled(LintCategory.EMPTY)) 3798 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), Warnings.EmptyIf); 3799 } 3800 3801 /** Check that symbol is unique in given scope. 3802 * @param pos Position for error reporting. 3803 * @param sym The symbol. 3804 * @param s The scope. 3805 */ 3806 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) { 3807 if (sym.type.isErroneous()) 3808 return true; 3809 if (sym.owner.name == names.any) return false; 3810 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) { 3811 if (sym != byName && 3812 (byName.flags() & CLASH) == 0 && 3813 sym.kind == byName.kind && 3814 sym.name != names.error && 3815 (sym.kind != MTH || 3816 types.hasSameArgs(sym.type, byName.type) || 3817 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) { 3818 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) { 3819 sym.flags_field |= CLASH; 3820 varargsDuplicateError(pos, sym, byName); 3821 return true; 3822 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) { 3823 duplicateErasureError(pos, sym, byName); 3824 sym.flags_field |= CLASH; 3825 return true; 3826 } else if ((sym.flags() & MATCH_BINDING) != 0 && 3827 (byName.flags() & MATCH_BINDING) != 0 && 3828 (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) { 3829 if (!sym.type.isErroneous()) { 3830 log.error(pos, Errors.MatchBindingExists); 3831 sym.flags_field |= CLASH; 3832 } 3833 return false; 3834 } else { 3835 duplicateError(pos, byName); 3836 return false; 3837 } 3838 } 3839 } 3840 return true; 3841 } 3842 3843 /** Report duplicate declaration error. 3844 */ 3845 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 3846 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 3847 log.error(pos, Errors.NameClashSameErasure(sym1, sym2)); 3848 } 3849 } 3850 3851 /**Check that types imported through the ordinary imports don't clash with types imported 3852 * by other (static or ordinary) imports. Note that two static imports may import two clashing 3853 * types without an error on the imports. 3854 * @param toplevel The toplevel tree for which the test should be performed. 3855 */ 3856 void checkImportsUnique(JCCompilationUnit toplevel) { 3857 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge); 3858 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge); 3859 WriteableScope topLevelScope = toplevel.toplevelScope; 3860 3861 for (JCTree def : toplevel.defs) { 3862 if (!def.hasTag(IMPORT)) 3863 continue; 3864 3865 JCImport imp = (JCImport) def; 3866 3867 if (imp.importScope == null) 3868 continue; 3869 3870 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) { 3871 if (imp.isStatic()) { 3872 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true); 3873 staticallyImportedSoFar.enter(sym); 3874 } else { 3875 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false); 3876 ordinallyImportedSoFar.enter(sym); 3877 } 3878 } 3879 3880 imp.importScope = null; 3881 } 3882 } 3883 3884 /** Check that single-type import is not already imported or top-level defined, 3885 * but make an exception for two single-type imports which denote the same type. 3886 * @param pos Position for error reporting. 3887 * @param ordinallyImportedSoFar A Scope containing types imported so far through 3888 * ordinary imports. 3889 * @param staticallyImportedSoFar A Scope containing types imported so far through 3890 * static imports. 3891 * @param topLevelScope The current file's top-level Scope 3892 * @param sym The symbol. 3893 * @param staticImport Whether or not this was a static import 3894 */ 3895 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar, 3896 Scope staticallyImportedSoFar, Scope topLevelScope, 3897 Symbol sym, boolean staticImport) { 3898 Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous(); 3899 Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates); 3900 Symbol staticClashing = null; 3901 if (ordinaryClashing == null && !staticImport) { 3902 staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates); 3903 } 3904 if (ordinaryClashing != null || staticClashing != null) { 3905 if (ordinaryClashing != null) 3906 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing)); 3907 else 3908 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing)); 3909 return false; 3910 } 3911 Symbol clashing = topLevelScope.findFirst(sym.name, duplicates); 3912 if (clashing != null) { 3913 log.error(pos, Errors.AlreadyDefinedThisUnit(clashing)); 3914 return false; 3915 } 3916 return true; 3917 } 3918 3919 /** Check that a qualified name is in canonical form (for import decls). 3920 */ 3921 public void checkCanonical(JCTree tree) { 3922 if (!isCanonical(tree)) 3923 log.error(tree.pos(), 3924 Errors.ImportRequiresCanonical(TreeInfo.symbol(tree))); 3925 } 3926 // where 3927 private boolean isCanonical(JCTree tree) { 3928 while (tree.hasTag(SELECT)) { 3929 JCFieldAccess s = (JCFieldAccess) tree; 3930 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName()) 3931 return false; 3932 tree = s.selected; 3933 } 3934 return true; 3935 } 3936 3937 /** Check that an auxiliary class is not accessed from any other file than its own. 3938 */ 3939 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) { 3940 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) && 3941 (c.flags() & AUXILIARY) != 0 && 3942 rs.isAccessible(env, c) && 3943 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile)) 3944 { 3945 log.warning(pos, 3946 Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile)); 3947 } 3948 } 3949 3950 /** 3951 * Check for a default constructor in an exported package. 3952 */ 3953 void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) { 3954 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) && 3955 ((c.flags() & (ENUM | RECORD)) == 0) && 3956 !c.isAnonymous() && 3957 ((c.flags() & (PUBLIC | PROTECTED)) != 0) && 3958 Feature.MODULES.allowedInSource(source)) { 3959 NestingKind nestingKind = c.getNestingKind(); 3960 switch (nestingKind) { 3961 case ANONYMOUS, 3962 LOCAL -> {return;} 3963 case TOP_LEVEL -> {;} // No additional checks needed 3964 case MEMBER -> { 3965 // For nested member classes, all the enclosing 3966 // classes must be public or protected. 3967 Symbol owner = c.owner; 3968 while (owner != null && owner.kind == TYP) { 3969 if ((owner.flags() & (PUBLIC | PROTECTED)) == 0) 3970 return; 3971 owner = owner.owner; 3972 } 3973 } 3974 } 3975 3976 // Only check classes in named packages exported by its module 3977 PackageSymbol pkg = c.packge(); 3978 if (!pkg.isUnnamed()) { 3979 ModuleSymbol modle = pkg.modle; 3980 for (ExportsDirective exportDir : modle.exports) { 3981 // Report warning only if the containing 3982 // package is unconditionally exported 3983 if (exportDir.packge.equals(pkg)) { 3984 if (exportDir.modules == null || exportDir.modules.isEmpty()) { 3985 // Warning may be suppressed by 3986 // annotations; check again for being 3987 // enabled in the deferred context. 3988 deferredLintHandler.report(() -> { 3989 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR)) 3990 log.warning(LintCategory.MISSING_EXPLICIT_CTOR, 3991 pos, Warnings.MissingExplicitCtor(c, pkg, modle)); 3992 }); 3993 } else { 3994 return; 3995 } 3996 } 3997 } 3998 } 3999 } 4000 return; 4001 } 4002 4003 private class ConversionWarner extends Warner { 4004 final String uncheckedKey; 4005 final Type found; 4006 final Type expected; 4007 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) { 4008 super(pos); 4009 this.uncheckedKey = uncheckedKey; 4010 this.found = found; 4011 this.expected = expected; 4012 } 4013 4014 @Override 4015 public void warn(LintCategory lint) { 4016 boolean warned = this.warned; 4017 super.warn(lint); 4018 if (warned) return; // suppress redundant diagnostics 4019 switch (lint) { 4020 case UNCHECKED: 4021 Check.this.warnUnchecked(pos(), Warnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected)); 4022 break; 4023 case VARARGS: 4024 if (method != null && 4025 method.attribute(syms.trustMeType.tsym) != null && 4026 isTrustMeAllowedOnMethod(method) && 4027 !types.isReifiable(method.type.getParameterTypes().last())) { 4028 Check.this.warnUnsafeVararg(pos(), Warnings.VarargsUnsafeUseVarargsParam(method.params.last())); 4029 } 4030 break; 4031 default: 4032 throw new AssertionError("Unexpected lint: " + lint); 4033 } 4034 } 4035 } 4036 4037 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) { 4038 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected); 4039 } 4040 4041 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) { 4042 return new ConversionWarner(pos, "unchecked.assign", found, expected); 4043 } 4044 4045 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) { 4046 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym); 4047 4048 if (functionalType != null) { 4049 try { 4050 types.findDescriptorSymbol((TypeSymbol)cs); 4051 } catch (Types.FunctionDescriptorLookupError ex) { 4052 DiagnosticPosition pos = tree.pos(); 4053 for (JCAnnotation a : tree.getModifiers().annotations) { 4054 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 4055 pos = a.pos(); 4056 break; 4057 } 4058 } 4059 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic())); 4060 } 4061 } 4062 } 4063 4064 public void checkImportsResolvable(final JCCompilationUnit toplevel) { 4065 for (final JCImport imp : toplevel.getImports()) { 4066 if (!imp.staticImport || !imp.qualid.hasTag(SELECT)) 4067 continue; 4068 final JCFieldAccess select = (JCFieldAccess) imp.qualid; 4069 final Symbol origin; 4070 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP) 4071 continue; 4072 4073 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected); 4074 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) { 4075 log.error(imp.pos(), 4076 Errors.CantResolveLocation(KindName.STATIC, 4077 select.name, 4078 null, 4079 null, 4080 Fragments.Location(kindName(site), 4081 site, 4082 null))); 4083 } 4084 } 4085 } 4086 4087 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2) 4088 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) { 4089 OUTER: for (JCImport imp : toplevel.getImports()) { 4090 if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) { 4091 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym; 4092 if (tsym.kind == PCK && tsym.members().isEmpty() && 4093 !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) { 4094 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym)); 4095 } 4096 } 4097 } 4098 } 4099 4100 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) { 4101 if (tsym == null || !processed.add(tsym)) 4102 return false; 4103 4104 // also search through inherited names 4105 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed)) 4106 return true; 4107 4108 for (Type t : types.interfaces(tsym.type)) 4109 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed)) 4110 return true; 4111 4112 for (Symbol sym : tsym.members().getSymbolsByName(name)) { 4113 if (sym.isStatic() && 4114 importAccessible(sym, packge) && 4115 sym.isMemberOf(origin, types)) { 4116 return true; 4117 } 4118 } 4119 4120 return false; 4121 } 4122 4123 // is the sym accessible everywhere in packge? 4124 public boolean importAccessible(Symbol sym, PackageSymbol packge) { 4125 try { 4126 int flags = (int)(sym.flags() & AccessFlags); 4127 switch (flags) { 4128 default: 4129 case PUBLIC: 4130 return true; 4131 case PRIVATE: 4132 return false; 4133 case 0: 4134 case PROTECTED: 4135 return sym.packge() == packge; 4136 } 4137 } catch (ClassFinder.BadClassFile err) { 4138 throw err; 4139 } catch (CompletionFailure ex) { 4140 return false; 4141 } 4142 } 4143 4144 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) { 4145 JCCompilationUnit toplevel = env.toplevel; 4146 4147 if ( toplevel.modle == syms.unnamedModule 4148 || toplevel.modle == syms.noModule 4149 || (check.sym.flags() & COMPOUND) != 0) { 4150 return ; 4151 } 4152 4153 ExportsDirective currentExport = findExport(toplevel.packge); 4154 4155 if ( currentExport == null //not exported 4156 || currentExport.modules != null) //don't check classes in qualified export 4157 return ; 4158 4159 new TreeScanner() { 4160 Lint lint = env.info.lint; 4161 boolean inSuperType; 4162 4163 @Override 4164 public void visitBlock(JCBlock tree) { 4165 } 4166 @Override 4167 public void visitMethodDef(JCMethodDecl tree) { 4168 if (!isAPISymbol(tree.sym)) 4169 return; 4170 Lint prevLint = lint; 4171 try { 4172 lint = lint.augment(tree.sym); 4173 if (lint.isEnabled(LintCategory.EXPORTS)) { 4174 super.visitMethodDef(tree); 4175 } 4176 } finally { 4177 lint = prevLint; 4178 } 4179 } 4180 @Override 4181 public void visitVarDef(JCVariableDecl tree) { 4182 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH) 4183 return; 4184 Lint prevLint = lint; 4185 try { 4186 lint = lint.augment(tree.sym); 4187 if (lint.isEnabled(LintCategory.EXPORTS)) { 4188 scan(tree.mods); 4189 scan(tree.vartype); 4190 } 4191 } finally { 4192 lint = prevLint; 4193 } 4194 } 4195 @Override 4196 public void visitClassDef(JCClassDecl tree) { 4197 if (tree != check) 4198 return ; 4199 4200 if (!isAPISymbol(tree.sym)) 4201 return ; 4202 4203 Lint prevLint = lint; 4204 try { 4205 lint = lint.augment(tree.sym); 4206 if (lint.isEnabled(LintCategory.EXPORTS)) { 4207 scan(tree.mods); 4208 scan(tree.typarams); 4209 try { 4210 inSuperType = true; 4211 scan(tree.extending); 4212 scan(tree.implementing); 4213 } finally { 4214 inSuperType = false; 4215 } 4216 scan(tree.defs); 4217 } 4218 } finally { 4219 lint = prevLint; 4220 } 4221 } 4222 @Override 4223 public void visitTypeApply(JCTypeApply tree) { 4224 scan(tree.clazz); 4225 boolean oldInSuperType = inSuperType; 4226 try { 4227 inSuperType = false; 4228 scan(tree.arguments); 4229 } finally { 4230 inSuperType = oldInSuperType; 4231 } 4232 } 4233 @Override 4234 public void visitIdent(JCIdent tree) { 4235 Symbol sym = TreeInfo.symbol(tree); 4236 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) { 4237 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 4238 } 4239 } 4240 4241 @Override 4242 public void visitSelect(JCFieldAccess tree) { 4243 Symbol sym = TreeInfo.symbol(tree); 4244 Symbol sitesym = TreeInfo.symbol(tree.selected); 4245 if (sym.kind == TYP && sitesym.kind == PCK) { 4246 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 4247 } else { 4248 super.visitSelect(tree); 4249 } 4250 } 4251 4252 @Override 4253 public void visitAnnotation(JCAnnotation tree) { 4254 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null) 4255 super.visitAnnotation(tree); 4256 } 4257 4258 }.scan(check); 4259 } 4260 //where: 4261 private ExportsDirective findExport(PackageSymbol pack) { 4262 for (ExportsDirective d : pack.modle.exports) { 4263 if (d.packge == pack) 4264 return d; 4265 } 4266 4267 return null; 4268 } 4269 private boolean isAPISymbol(Symbol sym) { 4270 while (sym.kind != PCK) { 4271 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) { 4272 return false; 4273 } 4274 sym = sym.owner; 4275 } 4276 return true; 4277 } 4278 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) { 4279 if (!isAPISymbol(what) && !inSuperType) { //package private/private element 4280 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); 4281 return ; 4282 } 4283 4284 PackageSymbol whatPackage = what.packge(); 4285 ExportsDirective whatExport = findExport(whatPackage); 4286 ExportsDirective inExport = findExport(inPackage); 4287 4288 if (whatExport == null) { //package not exported: 4289 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle)); 4290 return ; 4291 } 4292 4293 if (whatExport.modules != null) { 4294 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) { 4295 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); 4296 } 4297 } 4298 4299 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) { 4300 //check that relativeTo.modle requires transitive what.modle, somehow: 4301 List<ModuleSymbol> todo = List.of(inPackage.modle); 4302 4303 while (todo.nonEmpty()) { 4304 ModuleSymbol current = todo.head; 4305 todo = todo.tail; 4306 if (current == whatPackage.modle) 4307 return ; //OK 4308 if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0) 4309 continue; //for automatic modules, don't look into their dependencies 4310 for (RequiresDirective req : current.requires) { 4311 if (req.isTransitive()) { 4312 todo = todo.prepend(req.module); 4313 } 4314 } 4315 } 4316 4317 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle)); 4318 } 4319 } 4320 4321 void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) { 4322 if (msym.kind != MDL) { 4323 deferredLintHandler.report(() -> { 4324 if (lint.isEnabled(LintCategory.MODULE)) 4325 log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym)); 4326 }); 4327 } 4328 } 4329 4330 void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) { 4331 if (packge.members().isEmpty() && 4332 ((packge.flags() & Flags.HAS_RESOURCE) == 0)) { 4333 deferredLintHandler.report(() -> { 4334 if (lint.isEnabled(LintCategory.OPENS)) 4335 log.warning(pos, Warnings.PackageEmptyOrNotFound(packge)); 4336 }); 4337 } 4338 } 4339 4340 void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) { 4341 if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) { 4342 deferredLintHandler.report(() -> { 4343 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) { 4344 log.warning(pos, Warnings.RequiresTransitiveAutomatic); 4345 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) { 4346 log.warning(pos, Warnings.RequiresAutomatic); 4347 } 4348 }); 4349 } 4350 } 4351 4352 /** 4353 * Verify the case labels conform to the constraints. Checks constraints related 4354 * combinations of patterns and other labels. 4355 * 4356 * @param cases the cases that should be checked. 4357 */ 4358 void checkSwitchCaseStructure(List<JCCase> cases) { 4359 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4360 JCCase c = l.head; 4361 if (c.labels.head instanceof JCConstantCaseLabel constLabel) { 4362 if (TreeInfo.isNull(constLabel.expr)) { 4363 if (c.labels.tail.nonEmpty()) { 4364 if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) { 4365 if (c.labels.tail.tail.nonEmpty()) { 4366 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination); 4367 } 4368 } else { 4369 log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination); 4370 } 4371 } 4372 } else { 4373 for (JCCaseLabel label : c.labels.tail) { 4374 if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) { 4375 log.error(label.pos(), Errors.InvalidCaseLabelCombination); 4376 break; 4377 } 4378 } 4379 } 4380 } else { 4381 if (c.labels.tail.nonEmpty()) { 4382 log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern); 4383 } 4384 } 4385 } 4386 4387 boolean isCaseStatementGroup = cases.nonEmpty() && 4388 cases.head.caseKind == CaseTree.CaseKind.STATEMENT; 4389 4390 if (isCaseStatementGroup) { 4391 boolean previousCompletessNormally = false; 4392 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4393 JCCase c = l.head; 4394 if (previousCompletessNormally && 4395 c.stats.nonEmpty() && 4396 c.labels.head instanceof JCPatternCaseLabel patternLabel && 4397 hasBindings(patternLabel.pat)) { 4398 log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern); 4399 } else if (c.stats.isEmpty() && 4400 c.labels.head instanceof JCPatternCaseLabel patternLabel && 4401 hasBindings(patternLabel.pat) && 4402 hasStatements(l.tail)) { 4403 log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern); 4404 } 4405 previousCompletessNormally = c.completesNormally; 4406 } 4407 } 4408 } 4409 4410 boolean hasBindings(JCPattern p) { 4411 boolean[] bindings = new boolean[1]; 4412 4413 new TreeScanner() { 4414 @Override 4415 public void visitBindingPattern(JCBindingPattern tree) { 4416 bindings[0] = true; 4417 super.visitBindingPattern(tree); 4418 } 4419 }.scan(p); 4420 4421 return bindings[0]; 4422 } 4423 4424 boolean hasStatements(List<JCCase> cases) { 4425 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4426 if (l.head.stats.nonEmpty()) { 4427 return true; 4428 } 4429 } 4430 4431 return false; 4432 } 4433 void checkSwitchCaseLabelDominated(List<JCCase> cases) { 4434 List<JCCaseLabel> caseLabels = List.nil(); 4435 boolean seenDefault = false; 4436 boolean seenDefaultLabel = false; 4437 boolean warnDominatedByDefault = false; 4438 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 4439 JCCase c = l.head; 4440 for (JCCaseLabel label : c.labels) { 4441 if (label.hasTag(DEFAULTCASELABEL)) { 4442 seenDefault = true; 4443 seenDefaultLabel |= 4444 TreeInfo.isNullCaseLabel(c.labels.head); 4445 continue; 4446 } 4447 if (TreeInfo.isNullCaseLabel(label)) { 4448 if (seenDefault) { 4449 log.error(label.pos(), Errors.PatternDominated); 4450 } 4451 continue; 4452 } 4453 if (seenDefault && !warnDominatedByDefault) { 4454 if (label.hasTag(PATTERNCASELABEL) || 4455 (label instanceof JCConstantCaseLabel && seenDefaultLabel)) { 4456 log.error(label.pos(), Errors.PatternDominated); 4457 warnDominatedByDefault = true; 4458 } 4459 } 4460 Type currentType = labelType(label); 4461 for (JCCaseLabel testCaseLabel : caseLabels) { 4462 Type testType = labelType(testCaseLabel); 4463 if (types.isSubtype(currentType, testType) && 4464 !currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) { 4465 //the current label is potentially dominated by the existing (test) label, check: 4466 boolean dominated = false; 4467 if (label instanceof JCConstantCaseLabel) { 4468 dominated |= !(testCaseLabel instanceof JCConstantCaseLabel); 4469 } else if (label instanceof JCPatternCaseLabel patternCL && 4470 testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel && 4471 TreeInfo.unguardedCaseLabel(testCaseLabel)) { 4472 dominated = patternDominated(testPatternCaseLabel.pat, 4473 patternCL.pat); 4474 } 4475 if (dominated) { 4476 log.error(label.pos(), Errors.PatternDominated); 4477 } 4478 } 4479 } 4480 caseLabels = caseLabels.prepend(label); 4481 } 4482 } 4483 } 4484 //where: 4485 private Type labelType(JCCaseLabel label) { 4486 return types.erasure(switch (label.getTag()) { 4487 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type; 4488 case CONSTANTCASELABEL -> types.boxedTypeOrType(((JCConstantCaseLabel) label).expr.type); 4489 default -> throw Assert.error("Unexpected tree kind: " + label.getTag()); 4490 }); 4491 } 4492 private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) { 4493 Type existingPatternType = types.erasure(existingPattern.type); 4494 Type currentPatternType = types.erasure(currentPattern.type); 4495 if (existingPatternType.isPrimitive() ^ currentPatternType.isPrimitive()) { 4496 return false; 4497 } 4498 if (existingPatternType.isPrimitive()) { 4499 return types.isSameType(existingPatternType, currentPatternType); 4500 } else { 4501 if (!types.isSubtype(currentPatternType, existingPatternType)) { 4502 return false; 4503 } 4504 } 4505 while (existingPattern instanceof JCParenthesizedPattern parenthesized) { 4506 existingPattern = parenthesized.pattern; 4507 } 4508 while (currentPattern instanceof JCParenthesizedPattern parenthesized) { 4509 currentPattern = parenthesized.pattern; 4510 } 4511 if (currentPattern instanceof JCBindingPattern) { 4512 return existingPattern instanceof JCBindingPattern; 4513 } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) { 4514 if (existingPattern instanceof JCBindingPattern) { 4515 return true; 4516 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) { 4517 List<JCPattern> existingNested = existingRecordPattern.nested; 4518 List<JCPattern> currentNested = currentRecordPattern.nested; 4519 if (existingNested.size() != currentNested.size()) { 4520 return false; 4521 } 4522 while (existingNested.nonEmpty()) { 4523 if (!patternDominated(existingNested.head, currentNested.head)) { 4524 return false; 4525 } 4526 existingNested = existingNested.tail; 4527 currentNested = currentNested.tail; 4528 } 4529 return true; 4530 } else { 4531 Assert.error("Unknown pattern: " + existingPattern.getTag()); 4532 } 4533 } else { 4534 Assert.error("Unknown pattern: " + currentPattern.getTag()); 4535 } 4536 return false; 4537 } 4538 4539 /** check if a type is a subtype of Externalizable, if that is available. */ 4540 boolean isExternalizable(Type t) { 4541 try { 4542 syms.externalizableType.complete(); 4543 } 4544 catch (CompletionFailure e) { 4545 return false; 4546 } 4547 return types.isSubtype(t, syms.externalizableType); 4548 } 4549 4550 /** 4551 * Check structure of serialization declarations. 4552 */ 4553 public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) { 4554 (new SerialTypeVisitor()).visit(c, tree); 4555 } 4556 4557 /** 4558 * This visitor will warn if a serialization-related field or 4559 * method is declared in a suspicious or incorrect way. In 4560 * particular, it will warn for cases where the runtime 4561 * serialization mechanism will silently ignore a mis-declared 4562 * entity. 4563 * 4564 * Distinguished serialization-related fields and methods: 4565 * 4566 * Methods: 4567 * 4568 * private void writeObject(ObjectOutputStream stream) throws IOException 4569 * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException 4570 * 4571 * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException 4572 * private void readObjectNoData() throws ObjectStreamException 4573 * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException 4574 * 4575 * Fields: 4576 * 4577 * private static final long serialVersionUID 4578 * private static final ObjectStreamField[] serialPersistentFields 4579 * 4580 * Externalizable: methods defined on the interface 4581 * public void writeExternal(ObjectOutput) throws IOException 4582 * public void readExternal(ObjectInput) throws IOException 4583 */ 4584 private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> { 4585 SerialTypeVisitor() { 4586 this.lint = Check.this.lint; 4587 } 4588 4589 private static final Set<String> serialMethodNames = 4590 Set.of("writeObject", "writeReplace", 4591 "readObject", "readObjectNoData", 4592 "readResolve"); 4593 4594 private static final Set<String> serialFieldNames = 4595 Set.of("serialVersionUID", "serialPersistentFields"); 4596 4597 // Type of serialPersistentFields 4598 private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass); 4599 4600 Lint lint; 4601 4602 @Override 4603 public Void defaultAction(Element e, JCClassDecl p) { 4604 throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), "")); 4605 } 4606 4607 @Override 4608 public Void visitType(TypeElement e, JCClassDecl p) { 4609 runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param)); 4610 return null; 4611 } 4612 4613 @Override 4614 public Void visitTypeAsClass(TypeElement e, 4615 JCClassDecl p) { 4616 // Anonymous classes filtered out by caller. 4617 4618 ClassSymbol c = (ClassSymbol)e; 4619 4620 checkCtorAccess(p, c); 4621 4622 // Check for missing serialVersionUID; check *not* done 4623 // for enums or records. 4624 VarSymbol svuidSym = null; 4625 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { 4626 if (sym.kind == VAR) { 4627 svuidSym = (VarSymbol)sym; 4628 break; 4629 } 4630 } 4631 4632 if (svuidSym == null) { 4633 log.warning(LintCategory.SERIAL, p.pos(), Warnings.MissingSVUID(c)); 4634 } 4635 4636 // Check for serialPersistentFields to gate checks for 4637 // non-serializable non-transient instance fields 4638 boolean serialPersistentFieldsPresent = 4639 c.members() 4640 .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR) 4641 .iterator() 4642 .hasNext(); 4643 4644 // Check declarations of serialization-related methods and 4645 // fields 4646 for(Symbol el : c.getEnclosedElements()) { 4647 runUnderLint(el, p, (enclosed, tree) -> { 4648 String name = null; 4649 switch(enclosed.getKind()) { 4650 case FIELD -> { 4651 if (!serialPersistentFieldsPresent) { 4652 var flags = enclosed.flags(); 4653 if ( ((flags & TRANSIENT) == 0) && 4654 ((flags & STATIC) == 0)) { 4655 Type varType = enclosed.asType(); 4656 if (!canBeSerialized(varType)) { 4657 // Note per JLS arrays are 4658 // serializable even if the 4659 // component type is not. 4660 log.warning(LintCategory.SERIAL, 4661 TreeInfo.diagnosticPositionFor(enclosed, tree), 4662 Warnings.NonSerializableInstanceField); 4663 } else if (varType.hasTag(ARRAY)) { 4664 ArrayType arrayType = (ArrayType)varType; 4665 Type elementType = arrayType.elemtype; 4666 while (elementType.hasTag(ARRAY)) { 4667 arrayType = (ArrayType)elementType; 4668 elementType = arrayType.elemtype; 4669 } 4670 if (!canBeSerialized(elementType)) { 4671 log.warning(LintCategory.SERIAL, 4672 TreeInfo.diagnosticPositionFor(enclosed, tree), 4673 Warnings.NonSerializableInstanceFieldArray(elementType)); 4674 } 4675 } 4676 } 4677 } 4678 4679 name = enclosed.getSimpleName().toString(); 4680 if (serialFieldNames.contains(name)) { 4681 VarSymbol field = (VarSymbol)enclosed; 4682 switch (name) { 4683 case "serialVersionUID" -> checkSerialVersionUID(tree, e, field); 4684 case "serialPersistentFields" -> checkSerialPersistentFields(tree, e, field); 4685 default -> throw new AssertionError(); 4686 } 4687 } 4688 } 4689 4690 // Correctly checking the serialization-related 4691 // methods is subtle. For the methods declared to be 4692 // private or directly declared in the class, the 4693 // enclosed elements of the class can be checked in 4694 // turn. However, writeReplace and readResolve can be 4695 // declared in a superclass and inherited. Note that 4696 // the runtime lookup walks the superclass chain 4697 // looking for writeReplace/readResolve via 4698 // Class.getDeclaredMethod. This differs from calling 4699 // Elements.getAllMembers(TypeElement) as the latter 4700 // will also pull in default methods from 4701 // superinterfaces. In other words, the runtime checks 4702 // (which long predate default methods on interfaces) 4703 // do not admit the possibility of inheriting methods 4704 // this way, a difference from general inheritance. 4705 4706 // The current implementation just checks the enclosed 4707 // elements and does not directly check the inherited 4708 // methods. If all the types are being checked this is 4709 // less of a concern; however, there are cases that 4710 // could be missed. In particular, readResolve and 4711 // writeReplace could, in principle, by inherited from 4712 // a non-serializable superclass and thus not checked 4713 // even if compiled with a serializable child class. 4714 case METHOD -> { 4715 var method = (MethodSymbol)enclosed; 4716 name = method.getSimpleName().toString(); 4717 if (serialMethodNames.contains(name)) { 4718 switch (name) { 4719 case "writeObject" -> checkWriteObject(tree, e, method); 4720 case "writeReplace" -> checkWriteReplace(tree,e, method); 4721 case "readObject" -> checkReadObject(tree,e, method); 4722 case "readObjectNoData" -> checkReadObjectNoData(tree, e, method); 4723 case "readResolve" -> checkReadResolve(tree, e, method); 4724 default -> throw new AssertionError(); 4725 } 4726 } 4727 } 4728 } 4729 }); 4730 } 4731 4732 return null; 4733 } 4734 4735 boolean canBeSerialized(Type type) { 4736 return type.isPrimitive() || rs.isSerializable(type); 4737 } 4738 4739 /** 4740 * Check that Externalizable class needs a public no-arg 4741 * constructor. 4742 * 4743 * Check that a Serializable class has access to the no-arg 4744 * constructor of its first nonserializable superclass. 4745 */ 4746 private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) { 4747 if (isExternalizable(c.type)) { 4748 for(var sym : c.getEnclosedElements()) { 4749 if (sym.isConstructor() && 4750 ((sym.flags() & PUBLIC) == PUBLIC)) { 4751 if (((MethodSymbol)sym).getParameters().isEmpty()) { 4752 return; 4753 } 4754 } 4755 } 4756 log.warning(LintCategory.SERIAL, tree.pos(), 4757 Warnings.ExternalizableMissingPublicNoArgCtor); 4758 } else { 4759 // Approximate access to the no-arg constructor up in 4760 // the superclass chain by checking that the 4761 // constructor is not private. This may not handle 4762 // some cross-package situations correctly. 4763 Type superClass = c.getSuperclass(); 4764 // java.lang.Object is *not* Serializable so this loop 4765 // should terminate. 4766 while (rs.isSerializable(superClass) ) { 4767 try { 4768 superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass(); 4769 } catch(ClassCastException cce) { 4770 return ; // Don't try to recover 4771 } 4772 } 4773 // Non-Serializable superclass 4774 try { 4775 ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement())); 4776 for(var sym : supertype.getEnclosedElements()) { 4777 if (sym.isConstructor()) { 4778 MethodSymbol ctor = (MethodSymbol)sym; 4779 if (ctor.getParameters().isEmpty()) { 4780 if (((ctor.flags() & PRIVATE) == PRIVATE) || 4781 // Handle nested classes and implicit this$0 4782 (supertype.getNestingKind() == NestingKind.MEMBER && 4783 ((supertype.flags() & STATIC) == 0))) 4784 log.warning(LintCategory.SERIAL, tree.pos(), 4785 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName())); 4786 } 4787 } 4788 } 4789 } catch (ClassCastException cce) { 4790 return ; // Don't try to recover 4791 } 4792 return; 4793 } 4794 } 4795 4796 private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) { 4797 // To be effective, serialVersionUID must be marked static 4798 // and final, but private is recommended. But alas, in 4799 // practice there are many non-private serialVersionUID 4800 // fields. 4801 if ((svuid.flags() & (STATIC | FINAL)) != 4802 (STATIC | FINAL)) { 4803 log.warning(LintCategory.SERIAL, 4804 TreeInfo.diagnosticPositionFor(svuid, tree), 4805 Warnings.ImproperSVUID((Symbol)e)); 4806 } 4807 4808 // check svuid has type long 4809 if (!svuid.type.hasTag(LONG)) { 4810 log.warning(LintCategory.SERIAL, 4811 TreeInfo.diagnosticPositionFor(svuid, tree), 4812 Warnings.LongSVUID((Symbol)e)); 4813 } 4814 4815 if (svuid.getConstValue() == null) 4816 log.warning(LintCategory.SERIAL, 4817 TreeInfo.diagnosticPositionFor(svuid, tree), 4818 Warnings.ConstantSVUID((Symbol)e)); 4819 } 4820 4821 private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) { 4822 // To be effective, serialPersisentFields must be private, static, and final. 4823 if ((spf.flags() & (PRIVATE | STATIC | FINAL)) != 4824 (PRIVATE | STATIC | FINAL)) { 4825 log.warning(LintCategory.SERIAL, 4826 TreeInfo.diagnosticPositionFor(spf, tree), Warnings.ImproperSPF); 4827 } 4828 4829 if (!types.isSameType(spf.type, OSF_TYPE)) { 4830 log.warning(LintCategory.SERIAL, 4831 TreeInfo.diagnosticPositionFor(spf, tree), Warnings.OSFArraySPF); 4832 } 4833 4834 if (isExternalizable((Type)(e.asType()))) { 4835 log.warning(LintCategory.SERIAL, tree.pos(), 4836 Warnings.IneffectualSerialFieldExternalizable); 4837 } 4838 4839 // Warn if serialPersistentFields is initialized to a 4840 // literal null. 4841 JCTree spfDecl = TreeInfo.declarationFor(spf, tree); 4842 if (spfDecl != null && spfDecl.getTag() == VARDEF) { 4843 JCVariableDecl variableDef = (JCVariableDecl) spfDecl; 4844 JCExpression initExpr = variableDef.init; 4845 if (initExpr != null && TreeInfo.isNull(initExpr)) { 4846 log.warning(LintCategory.SERIAL, initExpr.pos(), 4847 Warnings.SPFNullInit); 4848 } 4849 } 4850 } 4851 4852 private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) { 4853 // The "synchronized" modifier is seen in the wild on 4854 // readObject and writeObject methods and is generally 4855 // innocuous. 4856 4857 // private void writeObject(ObjectOutputStream stream) throws IOException 4858 checkPrivateNonStaticMethod(tree, method); 4859 checkReturnType(tree, e, method, syms.voidType); 4860 checkOneArg(tree, e, method, syms.objectOutputStreamType); 4861 checkExceptions(tree, e, method, syms.ioExceptionType); 4862 checkExternalizable(tree, e, method); 4863 } 4864 4865 private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) { 4866 // ANY-ACCESS-MODIFIER Object writeReplace() throws 4867 // ObjectStreamException 4868 4869 // Excluding abstract, could have a more complicated 4870 // rule based on abstract-ness of the class 4871 checkConcreteInstanceMethod(tree, e, method); 4872 checkReturnType(tree, e, method, syms.objectType); 4873 checkNoArgs(tree, e, method); 4874 checkExceptions(tree, e, method, syms.objectStreamExceptionType); 4875 } 4876 4877 private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) { 4878 // The "synchronized" modifier is seen in the wild on 4879 // readObject and writeObject methods and is generally 4880 // innocuous. 4881 4882 // private void readObject(ObjectInputStream stream) 4883 // throws IOException, ClassNotFoundException 4884 checkPrivateNonStaticMethod(tree, method); 4885 checkReturnType(tree, e, method, syms.voidType); 4886 checkOneArg(tree, e, method, syms.objectInputStreamType); 4887 checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType); 4888 checkExternalizable(tree, e, method); 4889 } 4890 4891 private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) { 4892 // private void readObjectNoData() throws ObjectStreamException 4893 checkPrivateNonStaticMethod(tree, method); 4894 checkReturnType(tree, e, method, syms.voidType); 4895 checkNoArgs(tree, e, method); 4896 checkExceptions(tree, e, method, syms.objectStreamExceptionType); 4897 checkExternalizable(tree, e, method); 4898 } 4899 4900 private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) { 4901 // ANY-ACCESS-MODIFIER Object readResolve() 4902 // throws ObjectStreamException 4903 4904 // Excluding abstract, could have a more complicated 4905 // rule based on abstract-ness of the class 4906 checkConcreteInstanceMethod(tree, e, method); 4907 checkReturnType(tree,e, method, syms.objectType); 4908 checkNoArgs(tree, e, method); 4909 checkExceptions(tree, e, method, syms.objectStreamExceptionType); 4910 } 4911 4912 void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) { 4913 var flags = method.flags(); 4914 if ((flags & PRIVATE) == 0) { 4915 log.warning(LintCategory.SERIAL, 4916 TreeInfo.diagnosticPositionFor(method, tree), 4917 Warnings.SerialMethodNotPrivate(method.getSimpleName())); 4918 } 4919 4920 if ((flags & STATIC) != 0) { 4921 log.warning(LintCategory.SERIAL, 4922 TreeInfo.diagnosticPositionFor(method, tree), 4923 Warnings.SerialMethodStatic(method.getSimpleName())); 4924 } 4925 } 4926 4927 /** 4928 * Per section 1.12 "Serialization of Enum Constants" of 4929 * the serialization specification, due to the special 4930 * serialization handling of enums, any writeObject, 4931 * readObject, writeReplace, and readResolve methods are 4932 * ignored as are serialPersistentFields and 4933 * serialVersionUID fields. 4934 */ 4935 @Override 4936 public Void visitTypeAsEnum(TypeElement e, 4937 JCClassDecl p) { 4938 for(Element el : e.getEnclosedElements()) { 4939 runUnderLint(el, p, (enclosed, tree) -> { 4940 String name = enclosed.getSimpleName().toString(); 4941 switch(enclosed.getKind()) { 4942 case FIELD -> { 4943 if (serialFieldNames.contains(name)) { 4944 log.warning(LintCategory.SERIAL, tree.pos(), 4945 Warnings.IneffectualSerialFieldEnum(name)); 4946 } 4947 } 4948 4949 case METHOD -> { 4950 if (serialMethodNames.contains(name)) { 4951 log.warning(LintCategory.SERIAL, tree.pos(), 4952 Warnings.IneffectualSerialMethodEnum(name)); 4953 } 4954 } 4955 } 4956 }); 4957 } 4958 return null; 4959 } 4960 4961 /** 4962 * Most serialization-related fields and methods on interfaces 4963 * are ineffectual or problematic. 4964 */ 4965 @Override 4966 public Void visitTypeAsInterface(TypeElement e, 4967 JCClassDecl p) { 4968 for(Element el : e.getEnclosedElements()) { 4969 runUnderLint(el, p, (enclosed, tree) -> { 4970 String name = null; 4971 switch(enclosed.getKind()) { 4972 case FIELD -> { 4973 var field = (VarSymbol)enclosed; 4974 name = field.getSimpleName().toString(); 4975 switch(name) { 4976 case "serialPersistentFields" -> { 4977 log.warning(LintCategory.SERIAL, 4978 TreeInfo.diagnosticPositionFor(field, tree), 4979 Warnings.IneffectualSerialFieldInterface); 4980 } 4981 4982 case "serialVersionUID" -> { 4983 checkSerialVersionUID(tree, e, field); 4984 } 4985 } 4986 } 4987 4988 case METHOD -> { 4989 var method = (MethodSymbol)enclosed; 4990 name = enclosed.getSimpleName().toString(); 4991 if (serialMethodNames.contains(name)) { 4992 switch (name) { 4993 case 4994 "readObject", 4995 "readObjectNoData", 4996 "writeObject" -> checkPrivateMethod(tree, e, method); 4997 4998 case 4999 "writeReplace", 5000 "readResolve" -> checkDefaultIneffective(tree, e, method); 5001 5002 default -> throw new AssertionError(); 5003 } 5004 5005 } 5006 } 5007 } 5008 }); 5009 } 5010 5011 return null; 5012 } 5013 5014 private void checkPrivateMethod(JCClassDecl tree, 5015 Element e, 5016 MethodSymbol method) { 5017 if ((method.flags() & PRIVATE) == 0) { 5018 log.warning(LintCategory.SERIAL, 5019 TreeInfo.diagnosticPositionFor(method, tree), 5020 Warnings.NonPrivateMethodWeakerAccess); 5021 } 5022 } 5023 5024 private void checkDefaultIneffective(JCClassDecl tree, 5025 Element e, 5026 MethodSymbol method) { 5027 if ((method.flags() & DEFAULT) == DEFAULT) { 5028 log.warning(LintCategory.SERIAL, 5029 TreeInfo.diagnosticPositionFor(method, tree), 5030 Warnings.DefaultIneffective); 5031 5032 } 5033 } 5034 5035 @Override 5036 public Void visitTypeAsAnnotationType(TypeElement e, 5037 JCClassDecl p) { 5038 // Per the JLS, annotation types are not serializeable 5039 return null; 5040 } 5041 5042 /** 5043 * From the Java Object Serialization Specification, 1.13 5044 * Serialization of Records: 5045 * 5046 * "The process by which record objects are serialized or 5047 * externalized cannot be customized; any class-specific 5048 * writeObject, readObject, readObjectNoData, writeExternal, 5049 * and readExternal methods defined by record classes are 5050 * ignored during serialization and deserialization. However, 5051 * a substitute object to be serialized or a designate 5052 * replacement may be specified, by the writeReplace and 5053 * readResolve methods, respectively. Any 5054 * serialPersistentFields field declaration is 5055 * ignored. Documenting serializable fields and data for 5056 * record classes is unnecessary, since there is no variation 5057 * in the serial form, other than whether a substitute or 5058 * replacement object is used. The serialVersionUID of a 5059 * record class is 0L unless explicitly declared. The 5060 * requirement for matching serialVersionUID values is waived 5061 * for record classes." 5062 */ 5063 @Override 5064 public Void visitTypeAsRecord(TypeElement e, 5065 JCClassDecl p) { 5066 for(Element el : e.getEnclosedElements()) { 5067 runUnderLint(el, p, (enclosed, tree) -> { 5068 String name = enclosed.getSimpleName().toString(); 5069 switch(enclosed.getKind()) { 5070 case FIELD -> { 5071 switch(name) { 5072 case "serialPersistentFields" -> { 5073 log.warning(LintCategory.SERIAL, tree.pos(), 5074 Warnings.IneffectualSerialFieldRecord); 5075 } 5076 5077 case "serialVersionUID" -> { 5078 // Could generate additional warning that 5079 // svuid value is not checked to match for 5080 // records. 5081 checkSerialVersionUID(tree, e, (VarSymbol)enclosed); 5082 } 5083 5084 } 5085 } 5086 5087 case METHOD -> { 5088 var method = (MethodSymbol)enclosed; 5089 switch(name) { 5090 case "writeReplace" -> checkWriteReplace(tree, e, method); 5091 case "readResolve" -> checkReadResolve(tree, e, method); 5092 default -> { 5093 if (serialMethodNames.contains(name)) { 5094 log.warning(LintCategory.SERIAL, tree.pos(), 5095 Warnings.IneffectualSerialMethodRecord(name)); 5096 } 5097 } 5098 } 5099 5100 } 5101 } 5102 }); 5103 } 5104 return null; 5105 } 5106 5107 void checkConcreteInstanceMethod(JCClassDecl tree, 5108 Element enclosing, 5109 MethodSymbol method) { 5110 if ((method.flags() & (STATIC | ABSTRACT)) != 0) { 5111 log.warning(LintCategory.SERIAL, 5112 TreeInfo.diagnosticPositionFor(method, tree), 5113 Warnings.SerialConcreteInstanceMethod(method.getSimpleName())); 5114 } 5115 } 5116 5117 private void checkReturnType(JCClassDecl tree, 5118 Element enclosing, 5119 MethodSymbol method, 5120 Type expectedReturnType) { 5121 // Note: there may be complications checking writeReplace 5122 // and readResolve since they return Object and could, in 5123 // principle, have covariant overrides and any synthetic 5124 // bridge method would not be represented here for 5125 // checking. 5126 Type rtype = method.getReturnType(); 5127 if (!types.isSameType(expectedReturnType, rtype)) { 5128 log.warning(LintCategory.SERIAL, 5129 TreeInfo.diagnosticPositionFor(method, tree), 5130 Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(), 5131 rtype, expectedReturnType)); 5132 } 5133 } 5134 5135 private void checkOneArg(JCClassDecl tree, 5136 Element enclosing, 5137 MethodSymbol method, 5138 Type expectedType) { 5139 String name = method.getSimpleName().toString(); 5140 5141 var parameters= method.getParameters(); 5142 5143 if (parameters.size() != 1) { 5144 log.warning(LintCategory.SERIAL, 5145 TreeInfo.diagnosticPositionFor(method, tree), 5146 Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size())); 5147 return; 5148 } 5149 5150 Type parameterType = parameters.get(0).asType(); 5151 if (!types.isSameType(parameterType, expectedType)) { 5152 log.warning(LintCategory.SERIAL, 5153 TreeInfo.diagnosticPositionFor(method, tree), 5154 Warnings.SerialMethodParameterType(method.getSimpleName(), 5155 expectedType, 5156 parameterType)); 5157 } 5158 } 5159 5160 private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) { 5161 var parameters = method.getParameters(); 5162 if (!parameters.isEmpty()) { 5163 log.warning(LintCategory.SERIAL, 5164 TreeInfo.diagnosticPositionFor(parameters.get(0), tree), 5165 Warnings.SerialMethodNoArgs(method.getSimpleName())); 5166 } 5167 } 5168 5169 private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) { 5170 // If the enclosing class is externalizable, warn for the method 5171 if (isExternalizable((Type)enclosing.asType())) { 5172 log.warning(LintCategory.SERIAL, tree.pos(), 5173 Warnings.IneffectualSerialMethodExternalizable(method.getSimpleName())); 5174 } 5175 return; 5176 } 5177 5178 private void checkExceptions(JCClassDecl tree, 5179 Element enclosing, 5180 MethodSymbol method, 5181 Type... declaredExceptions) { 5182 for (Type thrownType: method.getThrownTypes()) { 5183 // For each exception in the throws clause of the 5184 // method, if not an Error and not a RuntimeException, 5185 // check if the exception is a subtype of a declared 5186 // exception from the throws clause of the 5187 // serialization method in question. 5188 if (types.isSubtype(thrownType, syms.runtimeExceptionType) || 5189 types.isSubtype(thrownType, syms.errorType) ) { 5190 continue; 5191 } else { 5192 boolean declared = false; 5193 for (Type declaredException : declaredExceptions) { 5194 if (types.isSubtype(thrownType, declaredException)) { 5195 declared = true; 5196 continue; 5197 } 5198 } 5199 if (!declared) { 5200 log.warning(LintCategory.SERIAL, 5201 TreeInfo.diagnosticPositionFor(method, tree), 5202 Warnings.SerialMethodUnexpectedException(method.getSimpleName(), 5203 thrownType)); 5204 } 5205 } 5206 } 5207 return; 5208 } 5209 5210 private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) { 5211 Lint prevLint = lint; 5212 try { 5213 lint = lint.augment((Symbol) symbol); 5214 5215 if (lint.isEnabled(LintCategory.SERIAL)) { 5216 task.accept(symbol, p); 5217 } 5218 5219 return null; 5220 } finally { 5221 lint = prevLint; 5222 } 5223 } 5224 5225 } 5226 5227 }