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