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