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