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