Check.java revision 3684:53dd5c5efac3
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 warnOnAccessToSensitiveMembers; 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 warnOnAccessToSensitiveMembers = options.isSet("warnOnAccessToSensitiveMembers"); 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 checkElemAccessFromSerializableLambda(final JCTree tree) { 2609 if (warnOnAccessToSensitiveMembers) { 2610 Symbol sym = TreeInfo.symbol(tree); 2611 if (!sym.kind.matches(KindSelector.VAL_MTH)) { 2612 return; 2613 } 2614 2615 if (sym.kind == VAR) { 2616 if ((sym.flags() & PARAMETER) != 0 || 2617 sym.isLocal() || 2618 sym.name == names._this || 2619 sym.name == names._super) { 2620 return; 2621 } 2622 } 2623 2624 if (!types.isSubtype(sym.owner.type, syms.serializableType) && 2625 isEffectivelyNonPublic(sym)) { 2626 log.warning(tree.pos(), 2627 "access.to.sensitive.member.from.serializable.element", sym); 2628 } 2629 } 2630 } 2631 2632 private boolean isEffectivelyNonPublic(Symbol sym) { 2633 if (sym.packge() == syms.rootPackage) { 2634 return false; 2635 } 2636 2637 while (sym.kind != PCK) { 2638 if ((sym.flags() & PUBLIC) == 0) { 2639 return true; 2640 } 2641 sym = sym.owner; 2642 } 2643 return false; 2644 } 2645 2646 /** Report a conflict between a user symbol and a synthetic symbol. 2647 */ 2648 private void syntheticError(DiagnosticPosition pos, Symbol sym) { 2649 if (!sym.type.isErroneous()) { 2650 log.error(pos, "synthetic.name.conflict", sym, sym.location()); 2651 } 2652 } 2653 2654 /** Check that class c does not implement directly or indirectly 2655 * the same parameterized interface with two different argument lists. 2656 * @param pos Position to be used for error reporting. 2657 * @param type The type whose interfaces are checked. 2658 */ 2659 void checkClassBounds(DiagnosticPosition pos, Type type) { 2660 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type); 2661 } 2662//where 2663 /** Enter all interfaces of type `type' into the hash table `seensofar' 2664 * with their class symbol as key and their type as value. Make 2665 * sure no class is entered with two different types. 2666 */ 2667 void checkClassBounds(DiagnosticPosition pos, 2668 Map<TypeSymbol,Type> seensofar, 2669 Type type) { 2670 if (type.isErroneous()) return; 2671 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) { 2672 Type it = l.head; 2673 Type oldit = seensofar.put(it.tsym, it); 2674 if (oldit != null) { 2675 List<Type> oldparams = oldit.allparams(); 2676 List<Type> newparams = it.allparams(); 2677 if (!types.containsTypeEquivalent(oldparams, newparams)) 2678 log.error(pos, "cant.inherit.diff.arg", 2679 it.tsym, Type.toString(oldparams), 2680 Type.toString(newparams)); 2681 } 2682 checkClassBounds(pos, seensofar, it); 2683 } 2684 Type st = types.supertype(type); 2685 if (st != Type.noType) checkClassBounds(pos, seensofar, st); 2686 } 2687 2688 /** Enter interface into into set. 2689 * If it existed already, issue a "repeated interface" error. 2690 */ 2691 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) { 2692 if (its.contains(it)) 2693 log.error(pos, "repeated.interface"); 2694 else { 2695 its.add(it); 2696 } 2697 } 2698 2699/* ************************************************************************* 2700 * Check annotations 2701 **************************************************************************/ 2702 2703 /** 2704 * Recursively validate annotations values 2705 */ 2706 void validateAnnotationTree(JCTree tree) { 2707 class AnnotationValidator extends TreeScanner { 2708 @Override 2709 public void visitAnnotation(JCAnnotation tree) { 2710 if (!tree.type.isErroneous()) { 2711 super.visitAnnotation(tree); 2712 validateAnnotation(tree); 2713 } 2714 } 2715 } 2716 tree.accept(new AnnotationValidator()); 2717 } 2718 2719 /** 2720 * {@literal 2721 * Annotation types are restricted to primitives, String, an 2722 * enum, an annotation, Class, Class<?>, Class<? extends 2723 * Anything>, arrays of the preceding. 2724 * } 2725 */ 2726 void validateAnnotationType(JCTree restype) { 2727 // restype may be null if an error occurred, so don't bother validating it 2728 if (restype != null) { 2729 validateAnnotationType(restype.pos(), restype.type); 2730 } 2731 } 2732 2733 void validateAnnotationType(DiagnosticPosition pos, Type type) { 2734 if (type.isPrimitive()) return; 2735 if (types.isSameType(type, syms.stringType)) return; 2736 if ((type.tsym.flags() & Flags.ENUM) != 0) return; 2737 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return; 2738 if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return; 2739 if (types.isArray(type) && !types.isArray(types.elemtype(type))) { 2740 validateAnnotationType(pos, types.elemtype(type)); 2741 return; 2742 } 2743 log.error(pos, "invalid.annotation.member.type"); 2744 } 2745 2746 /** 2747 * "It is also a compile-time error if any method declared in an 2748 * annotation type has a signature that is override-equivalent to 2749 * that of any public or protected method declared in class Object 2750 * or in the interface annotation.Annotation." 2751 * 2752 * @jls 9.6 Annotation Types 2753 */ 2754 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) { 2755 for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) { 2756 Scope s = sup.tsym.members(); 2757 for (Symbol sym : s.getSymbolsByName(m.name)) { 2758 if (sym.kind == MTH && 2759 (sym.flags() & (PUBLIC | PROTECTED)) != 0 && 2760 types.overrideEquivalent(m.type, sym.type)) 2761 log.error(pos, "intf.annotation.member.clash", sym, sup); 2762 } 2763 } 2764 } 2765 2766 /** Check the annotations of a symbol. 2767 */ 2768 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) { 2769 for (JCAnnotation a : annotations) 2770 validateAnnotation(a, s); 2771 } 2772 2773 /** Check the type annotations. 2774 */ 2775 public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) { 2776 for (JCAnnotation a : annotations) 2777 validateTypeAnnotation(a, isTypeParameter); 2778 } 2779 2780 /** Check an annotation of a symbol. 2781 */ 2782 private void validateAnnotation(JCAnnotation a, Symbol s) { 2783 validateAnnotationTree(a); 2784 2785 if (!annotationApplicable(a, s)) 2786 log.error(a.pos(), "annotation.type.not.applicable"); 2787 2788 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 2789 if (s.kind != TYP) { 2790 log.error(a.pos(), "bad.functional.intf.anno"); 2791 } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) { 2792 log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s)); 2793 } 2794 } 2795 } 2796 2797 public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 2798 Assert.checkNonNull(a.type); 2799 validateAnnotationTree(a); 2800 2801 if (a.hasTag(TYPE_ANNOTATION) && 2802 !a.annotationType.type.isErroneous() && 2803 !isTypeAnnotation(a, isTypeParameter)) { 2804 log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type)); 2805 } 2806 } 2807 2808 /** 2809 * Validate the proposed container 'repeatable' on the 2810 * annotation type symbol 's'. Report errors at position 2811 * 'pos'. 2812 * 2813 * @param s The (annotation)type declaration annotated with a @Repeatable 2814 * @param repeatable the @Repeatable on 's' 2815 * @param pos where to report errors 2816 */ 2817 public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) { 2818 Assert.check(types.isSameType(repeatable.type, syms.repeatableType)); 2819 2820 Type t = null; 2821 List<Pair<MethodSymbol,Attribute>> l = repeatable.values; 2822 if (!l.isEmpty()) { 2823 Assert.check(l.head.fst.name == names.value); 2824 t = ((Attribute.Class)l.head.snd).getValue(); 2825 } 2826 2827 if (t == null) { 2828 // errors should already have been reported during Annotate 2829 return; 2830 } 2831 2832 validateValue(t.tsym, s, pos); 2833 validateRetention(t.tsym, s, pos); 2834 validateDocumented(t.tsym, s, pos); 2835 validateInherited(t.tsym, s, pos); 2836 validateTarget(t.tsym, s, pos); 2837 validateDefault(t.tsym, pos); 2838 } 2839 2840 private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2841 Symbol sym = container.members().findFirst(names.value); 2842 if (sym != null && sym.kind == MTH) { 2843 MethodSymbol m = (MethodSymbol) sym; 2844 Type ret = m.getReturnType(); 2845 if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) { 2846 log.error(pos, "invalid.repeatable.annotation.value.return", 2847 container, ret, types.makeArrayType(contained.type)); 2848 } 2849 } else { 2850 log.error(pos, "invalid.repeatable.annotation.no.value", container); 2851 } 2852 } 2853 2854 private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2855 Attribute.RetentionPolicy containerRetention = types.getRetention(container); 2856 Attribute.RetentionPolicy containedRetention = types.getRetention(contained); 2857 2858 boolean error = false; 2859 switch (containedRetention) { 2860 case RUNTIME: 2861 if (containerRetention != Attribute.RetentionPolicy.RUNTIME) { 2862 error = true; 2863 } 2864 break; 2865 case CLASS: 2866 if (containerRetention == Attribute.RetentionPolicy.SOURCE) { 2867 error = true; 2868 } 2869 } 2870 if (error ) { 2871 log.error(pos, "invalid.repeatable.annotation.retention", 2872 container, containerRetention, 2873 contained, containedRetention); 2874 } 2875 } 2876 2877 private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) { 2878 if (contained.attribute(syms.documentedType.tsym) != null) { 2879 if (container.attribute(syms.documentedType.tsym) == null) { 2880 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained); 2881 } 2882 } 2883 } 2884 2885 private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) { 2886 if (contained.attribute(syms.inheritedType.tsym) != null) { 2887 if (container.attribute(syms.inheritedType.tsym) == null) { 2888 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained); 2889 } 2890 } 2891 } 2892 2893 private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) { 2894 // The set of targets the container is applicable to must be a subset 2895 // (with respect to annotation target semantics) of the set of targets 2896 // the contained is applicable to. The target sets may be implicit or 2897 // explicit. 2898 2899 Set<Name> containerTargets; 2900 Attribute.Array containerTarget = getAttributeTargetAttribute(container); 2901 if (containerTarget == null) { 2902 containerTargets = getDefaultTargetSet(); 2903 } else { 2904 containerTargets = new HashSet<>(); 2905 for (Attribute app : containerTarget.values) { 2906 if (!(app instanceof Attribute.Enum)) { 2907 continue; // recovery 2908 } 2909 Attribute.Enum e = (Attribute.Enum)app; 2910 containerTargets.add(e.value.name); 2911 } 2912 } 2913 2914 Set<Name> containedTargets; 2915 Attribute.Array containedTarget = getAttributeTargetAttribute(contained); 2916 if (containedTarget == null) { 2917 containedTargets = getDefaultTargetSet(); 2918 } else { 2919 containedTargets = new HashSet<>(); 2920 for (Attribute app : containedTarget.values) { 2921 if (!(app instanceof Attribute.Enum)) { 2922 continue; // recovery 2923 } 2924 Attribute.Enum e = (Attribute.Enum)app; 2925 containedTargets.add(e.value.name); 2926 } 2927 } 2928 2929 if (!isTargetSubsetOf(containerTargets, containedTargets)) { 2930 log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained); 2931 } 2932 } 2933 2934 /* get a set of names for the default target */ 2935 private Set<Name> getDefaultTargetSet() { 2936 if (defaultTargets == null) { 2937 Set<Name> targets = new HashSet<>(); 2938 targets.add(names.ANNOTATION_TYPE); 2939 targets.add(names.CONSTRUCTOR); 2940 targets.add(names.FIELD); 2941 targets.add(names.LOCAL_VARIABLE); 2942 targets.add(names.METHOD); 2943 targets.add(names.PACKAGE); 2944 targets.add(names.PARAMETER); 2945 targets.add(names.TYPE); 2946 2947 defaultTargets = java.util.Collections.unmodifiableSet(targets); 2948 } 2949 2950 return defaultTargets; 2951 } 2952 private Set<Name> defaultTargets; 2953 2954 2955 /** Checks that s is a subset of t, with respect to ElementType 2956 * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}, 2957 * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE, 2958 * TYPE_PARAMETER}. 2959 */ 2960 private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) { 2961 // Check that all elements in s are present in t 2962 for (Name n2 : s) { 2963 boolean currentElementOk = false; 2964 for (Name n1 : t) { 2965 if (n1 == n2) { 2966 currentElementOk = true; 2967 break; 2968 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) { 2969 currentElementOk = true; 2970 break; 2971 } else if (n1 == names.TYPE_USE && 2972 (n2 == names.TYPE || 2973 n2 == names.ANNOTATION_TYPE || 2974 n2 == names.TYPE_PARAMETER)) { 2975 currentElementOk = true; 2976 break; 2977 } 2978 } 2979 if (!currentElementOk) 2980 return false; 2981 } 2982 return true; 2983 } 2984 2985 private void validateDefault(Symbol container, DiagnosticPosition pos) { 2986 // validate that all other elements of containing type has defaults 2987 Scope scope = container.members(); 2988 for(Symbol elm : scope.getSymbols()) { 2989 if (elm.name != names.value && 2990 elm.kind == MTH && 2991 ((MethodSymbol)elm).defaultValue == null) { 2992 log.error(pos, 2993 "invalid.repeatable.annotation.elem.nondefault", 2994 container, 2995 elm); 2996 } 2997 } 2998 } 2999 3000 /** Is s a method symbol that overrides a method in a superclass? */ 3001 boolean isOverrider(Symbol s) { 3002 if (s.kind != MTH || s.isStatic()) 3003 return false; 3004 MethodSymbol m = (MethodSymbol)s; 3005 TypeSymbol owner = (TypeSymbol)m.owner; 3006 for (Type sup : types.closure(owner.type)) { 3007 if (sup == owner.type) 3008 continue; // skip "this" 3009 Scope scope = sup.tsym.members(); 3010 for (Symbol sym : scope.getSymbolsByName(m.name)) { 3011 if (!sym.isStatic() && m.overrides(sym, owner, types, true)) 3012 return true; 3013 } 3014 } 3015 return false; 3016 } 3017 3018 /** Is the annotation applicable to types? */ 3019 protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) { 3020 List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym); 3021 return (targets == null) ? 3022 false : 3023 targets.stream() 3024 .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter)); 3025 } 3026 //where 3027 boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) { 3028 Attribute.Enum e = (Attribute.Enum)a; 3029 return (e.value.name == names.TYPE_USE || 3030 (isTypeParameter && e.value.name == names.TYPE_PARAMETER)); 3031 } 3032 3033 /** Is the annotation applicable to the symbol? */ 3034 boolean annotationApplicable(JCAnnotation a, Symbol s) { 3035 Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym); 3036 Name[] targets; 3037 3038 if (arr == null) { 3039 targets = defaultTargetMetaInfo(a, s); 3040 } else { 3041 // TODO: can we optimize this? 3042 targets = new Name[arr.values.length]; 3043 for (int i=0; i<arr.values.length; ++i) { 3044 Attribute app = arr.values[i]; 3045 if (!(app instanceof Attribute.Enum)) { 3046 return true; // recovery 3047 } 3048 Attribute.Enum e = (Attribute.Enum) app; 3049 targets[i] = e.value.name; 3050 } 3051 } 3052 for (Name target : targets) { 3053 if (target == names.TYPE) { 3054 if (s.kind == TYP) 3055 return true; 3056 } else if (target == names.FIELD) { 3057 if (s.kind == VAR && s.owner.kind != MTH) 3058 return true; 3059 } else if (target == names.METHOD) { 3060 if (s.kind == MTH && !s.isConstructor()) 3061 return true; 3062 } else if (target == names.PARAMETER) { 3063 if (s.kind == VAR && s.owner.kind == MTH && 3064 (s.flags() & PARAMETER) != 0) { 3065 return true; 3066 } 3067 } else if (target == names.CONSTRUCTOR) { 3068 if (s.kind == MTH && s.isConstructor()) 3069 return true; 3070 } else if (target == names.LOCAL_VARIABLE) { 3071 if (s.kind == VAR && s.owner.kind == MTH && 3072 (s.flags() & PARAMETER) == 0) { 3073 return true; 3074 } 3075 } else if (target == names.ANNOTATION_TYPE) { 3076 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) { 3077 return true; 3078 } 3079 } else if (target == names.PACKAGE) { 3080 if (s.kind == PCK) 3081 return true; 3082 } else if (target == names.TYPE_USE) { 3083 if (s.kind == TYP || s.kind == VAR || 3084 (s.kind == MTH && !s.isConstructor() && 3085 !s.type.getReturnType().hasTag(VOID)) || 3086 (s.kind == MTH && s.isConstructor())) { 3087 return true; 3088 } 3089 } else if (target == names.TYPE_PARAMETER) { 3090 if (s.kind == TYP && s.type.hasTag(TYPEVAR)) 3091 return true; 3092 } else 3093 return true; // Unknown ElementType. This should be an error at declaration site, 3094 // assume applicable. 3095 } 3096 return false; 3097 } 3098 3099 3100 Attribute.Array getAttributeTargetAttribute(TypeSymbol s) { 3101 Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget(); 3102 if (atTarget == null) return null; // ok, is applicable 3103 Attribute atValue = atTarget.member(names.value); 3104 if (!(atValue instanceof Attribute.Array)) return null; // error recovery 3105 return (Attribute.Array) atValue; 3106 } 3107 3108 private final Name[] dfltTargetMeta; 3109 private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) { 3110 return dfltTargetMeta; 3111 } 3112 3113 /** Check an annotation value. 3114 * 3115 * @param a The annotation tree to check 3116 * @return true if this annotation tree is valid, otherwise false 3117 */ 3118 public boolean validateAnnotationDeferErrors(JCAnnotation a) { 3119 boolean res = false; 3120 final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log); 3121 try { 3122 res = validateAnnotation(a); 3123 } finally { 3124 log.popDiagnosticHandler(diagHandler); 3125 } 3126 return res; 3127 } 3128 3129 private boolean validateAnnotation(JCAnnotation a) { 3130 boolean isValid = true; 3131 AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata(); 3132 3133 // collect an inventory of the annotation elements 3134 Set<MethodSymbol> elements = metadata.getAnnotationElements(); 3135 3136 // remove the ones that are assigned values 3137 for (JCTree arg : a.args) { 3138 if (!arg.hasTag(ASSIGN)) continue; // recovery 3139 JCAssign assign = (JCAssign)arg; 3140 Symbol m = TreeInfo.symbol(assign.lhs); 3141 if (m == null || m.type.isErroneous()) continue; 3142 if (!elements.remove(m)) { 3143 isValid = false; 3144 log.error(assign.lhs.pos(), "duplicate.annotation.member.value", 3145 m.name, a.type); 3146 } 3147 } 3148 3149 // all the remaining ones better have default values 3150 List<Name> missingDefaults = List.nil(); 3151 Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault(); 3152 for (MethodSymbol m : elements) { 3153 if (m.type.isErroneous()) 3154 continue; 3155 3156 if (!membersWithDefault.contains(m)) 3157 missingDefaults = missingDefaults.append(m.name); 3158 } 3159 missingDefaults = missingDefaults.reverse(); 3160 if (missingDefaults.nonEmpty()) { 3161 isValid = false; 3162 String key = (missingDefaults.size() > 1) 3163 ? "annotation.missing.default.value.1" 3164 : "annotation.missing.default.value"; 3165 log.error(a.pos(), key, a.type, missingDefaults); 3166 } 3167 3168 return isValid && validateTargetAnnotationValue(a); 3169 } 3170 3171 /* Validate the special java.lang.annotation.Target annotation */ 3172 boolean validateTargetAnnotationValue(JCAnnotation a) { 3173 // special case: java.lang.annotation.Target must not have 3174 // repeated values in its value member 3175 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym || 3176 a.args.tail == null) 3177 return true; 3178 3179 boolean isValid = true; 3180 if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery 3181 JCAssign assign = (JCAssign) a.args.head; 3182 Symbol m = TreeInfo.symbol(assign.lhs); 3183 if (m.name != names.value) return false; 3184 JCTree rhs = assign.rhs; 3185 if (!rhs.hasTag(NEWARRAY)) return false; 3186 JCNewArray na = (JCNewArray) rhs; 3187 Set<Symbol> targets = new HashSet<>(); 3188 for (JCTree elem : na.elems) { 3189 if (!targets.add(TreeInfo.symbol(elem))) { 3190 isValid = false; 3191 log.error(elem.pos(), "repeated.annotation.target"); 3192 } 3193 } 3194 return isValid; 3195 } 3196 3197 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { 3198 if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() && 3199 (s.flags() & DEPRECATED) != 0 && 3200 !syms.deprecatedType.isErroneous() && 3201 s.attribute(syms.deprecatedType.tsym) == null) { 3202 log.warning(LintCategory.DEP_ANN, 3203 pos, "missing.deprecated.annotation"); 3204 } 3205 // Note: @Deprecated has no effect on local variables, parameters and package decls. 3206 if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) { 3207 if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) { 3208 log.warning(LintCategory.DEPRECATION, pos, 3209 "deprecated.annotation.has.no.effect", Kinds.kindName(s)); 3210 } 3211 } 3212 } 3213 3214 void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) { 3215 if ((s.flags() & DEPRECATED) != 0 && 3216 (other.flags() & DEPRECATED) == 0 && 3217 s.outermostClass() != other.outermostClass()) { 3218 deferredLintHandler.report(new DeferredLintHandler.LintLogger() { 3219 @Override 3220 public void report() { 3221 warnDeprecated(pos, s); 3222 } 3223 }); 3224 } 3225 } 3226 3227 void checkSunAPI(final DiagnosticPosition pos, final Symbol s) { 3228 if ((s.flags() & PROPRIETARY) != 0) { 3229 deferredLintHandler.report(() -> { 3230 log.mandatoryWarning(pos, "sun.proprietary", s); 3231 }); 3232 } 3233 } 3234 3235 void checkProfile(final DiagnosticPosition pos, final Symbol s) { 3236 if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) { 3237 log.error(pos, "not.in.profile", s, profile); 3238 } 3239 } 3240 3241/* ************************************************************************* 3242 * Check for recursive annotation elements. 3243 **************************************************************************/ 3244 3245 /** Check for cycles in the graph of annotation elements. 3246 */ 3247 void checkNonCyclicElements(JCClassDecl tree) { 3248 if ((tree.sym.flags_field & ANNOTATION) == 0) return; 3249 Assert.check((tree.sym.flags_field & LOCKED) == 0); 3250 try { 3251 tree.sym.flags_field |= LOCKED; 3252 for (JCTree def : tree.defs) { 3253 if (!def.hasTag(METHODDEF)) continue; 3254 JCMethodDecl meth = (JCMethodDecl)def; 3255 checkAnnotationResType(meth.pos(), meth.restype.type); 3256 } 3257 } finally { 3258 tree.sym.flags_field &= ~LOCKED; 3259 tree.sym.flags_field |= ACYCLIC_ANN; 3260 } 3261 } 3262 3263 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) { 3264 if ((tsym.flags_field & ACYCLIC_ANN) != 0) 3265 return; 3266 if ((tsym.flags_field & LOCKED) != 0) { 3267 log.error(pos, "cyclic.annotation.element"); 3268 return; 3269 } 3270 try { 3271 tsym.flags_field |= LOCKED; 3272 for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) { 3273 if (s.kind != MTH) 3274 continue; 3275 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType()); 3276 } 3277 } finally { 3278 tsym.flags_field &= ~LOCKED; 3279 tsym.flags_field |= ACYCLIC_ANN; 3280 } 3281 } 3282 3283 void checkAnnotationResType(DiagnosticPosition pos, Type type) { 3284 switch (type.getTag()) { 3285 case CLASS: 3286 if ((type.tsym.flags() & ANNOTATION) != 0) 3287 checkNonCyclicElementsInternal(pos, type.tsym); 3288 break; 3289 case ARRAY: 3290 checkAnnotationResType(pos, types.elemtype(type)); 3291 break; 3292 default: 3293 break; // int etc 3294 } 3295 } 3296 3297/* ************************************************************************* 3298 * Check for cycles in the constructor call graph. 3299 **************************************************************************/ 3300 3301 /** Check for cycles in the graph of constructors calling other 3302 * constructors. 3303 */ 3304 void checkCyclicConstructors(JCClassDecl tree) { 3305 Map<Symbol,Symbol> callMap = new HashMap<>(); 3306 3307 // enter each constructor this-call into the map 3308 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 3309 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head); 3310 if (app == null) continue; 3311 JCMethodDecl meth = (JCMethodDecl) l.head; 3312 if (TreeInfo.name(app.meth) == names._this) { 3313 callMap.put(meth.sym, TreeInfo.symbol(app.meth)); 3314 } else { 3315 meth.sym.flags_field |= ACYCLIC; 3316 } 3317 } 3318 3319 // Check for cycles in the map 3320 Symbol[] ctors = new Symbol[0]; 3321 ctors = callMap.keySet().toArray(ctors); 3322 for (Symbol caller : ctors) { 3323 checkCyclicConstructor(tree, caller, callMap); 3324 } 3325 } 3326 3327 /** Look in the map to see if the given constructor is part of a 3328 * call cycle. 3329 */ 3330 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor, 3331 Map<Symbol,Symbol> callMap) { 3332 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) { 3333 if ((ctor.flags_field & LOCKED) != 0) { 3334 log.error(TreeInfo.diagnosticPositionFor(ctor, tree), 3335 "recursive.ctor.invocation"); 3336 } else { 3337 ctor.flags_field |= LOCKED; 3338 checkCyclicConstructor(tree, callMap.remove(ctor), callMap); 3339 ctor.flags_field &= ~LOCKED; 3340 } 3341 ctor.flags_field |= ACYCLIC; 3342 } 3343 } 3344 3345/* ************************************************************************* 3346 * Miscellaneous 3347 **************************************************************************/ 3348 3349 /** 3350 * Check for division by integer constant zero 3351 * @param pos Position for error reporting. 3352 * @param operator The operator for the expression 3353 * @param operand The right hand operand for the expression 3354 */ 3355 void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) { 3356 if (operand.constValue() != null 3357 && operand.getTag().isSubRangeOf(LONG) 3358 && ((Number) (operand.constValue())).longValue() == 0) { 3359 int opc = ((OperatorSymbol)operator).opcode; 3360 if (opc == ByteCodes.idiv || opc == ByteCodes.imod 3361 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) { 3362 deferredLintHandler.report(new DeferredLintHandler.LintLogger() { 3363 @Override 3364 public void report() { 3365 warnDivZero(pos); 3366 } 3367 }); 3368 } 3369 } 3370 } 3371 3372 /** 3373 * Check for empty statements after if 3374 */ 3375 void checkEmptyIf(JCIf tree) { 3376 if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null && 3377 lint.isEnabled(LintCategory.EMPTY)) 3378 log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if"); 3379 } 3380 3381 /** Check that symbol is unique in given scope. 3382 * @param pos Position for error reporting. 3383 * @param sym The symbol. 3384 * @param s The scope. 3385 */ 3386 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) { 3387 if (sym.type.isErroneous()) 3388 return true; 3389 if (sym.owner.name == names.any) return false; 3390 for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) { 3391 if (sym != byName && 3392 (byName.flags() & CLASH) == 0 && 3393 sym.kind == byName.kind && 3394 sym.name != names.error && 3395 (sym.kind != MTH || 3396 types.hasSameArgs(sym.type, byName.type) || 3397 types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) { 3398 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) { 3399 varargsDuplicateError(pos, sym, byName); 3400 return true; 3401 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) { 3402 duplicateErasureError(pos, sym, byName); 3403 sym.flags_field |= CLASH; 3404 return true; 3405 } else { 3406 duplicateError(pos, byName); 3407 return false; 3408 } 3409 } 3410 } 3411 return true; 3412 } 3413 3414 /** Report duplicate declaration error. 3415 */ 3416 void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 3417 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 3418 log.error(pos, "name.clash.same.erasure", sym1, sym2); 3419 } 3420 } 3421 3422 /**Check that types imported through the ordinary imports don't clash with types imported 3423 * by other (static or ordinary) imports. Note that two static imports may import two clashing 3424 * types without an error on the imports. 3425 * @param toplevel The toplevel tree for which the test should be performed. 3426 */ 3427 void checkImportsUnique(JCCompilationUnit toplevel) { 3428 WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge); 3429 WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge); 3430 WriteableScope topLevelScope = toplevel.toplevelScope; 3431 3432 for (JCTree def : toplevel.defs) { 3433 if (!def.hasTag(IMPORT)) 3434 continue; 3435 3436 JCImport imp = (JCImport) def; 3437 3438 if (imp.importScope == null) 3439 continue; 3440 3441 for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) { 3442 if (imp.isStatic()) { 3443 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true); 3444 staticallyImportedSoFar.enter(sym); 3445 } else { 3446 checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false); 3447 ordinallyImportedSoFar.enter(sym); 3448 } 3449 } 3450 3451 imp.importScope = null; 3452 } 3453 } 3454 3455 /** Check that single-type import is not already imported or top-level defined, 3456 * but make an exception for two single-type imports which denote the same type. 3457 * @param pos Position for error reporting. 3458 * @param ordinallyImportedSoFar A Scope containing types imported so far through 3459 * ordinary imports. 3460 * @param staticallyImportedSoFar A Scope containing types imported so far through 3461 * static imports. 3462 * @param topLevelScope The current file's top-level Scope 3463 * @param sym The symbol. 3464 * @param staticImport Whether or not this was a static import 3465 */ 3466 private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar, 3467 Scope staticallyImportedSoFar, Scope topLevelScope, 3468 Symbol sym, boolean staticImport) { 3469 Filter<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous(); 3470 Symbol clashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates); 3471 if (clashing == null && !staticImport) { 3472 clashing = staticallyImportedSoFar.findFirst(sym.name, duplicates); 3473 } 3474 if (clashing != null) { 3475 if (staticImport) 3476 log.error(pos, "already.defined.static.single.import", clashing); 3477 else 3478 log.error(pos, "already.defined.single.import", clashing); 3479 return false; 3480 } 3481 clashing = topLevelScope.findFirst(sym.name, duplicates); 3482 if (clashing != null) { 3483 log.error(pos, "already.defined.this.unit", clashing); 3484 return false; 3485 } 3486 return true; 3487 } 3488 3489 /** Check that a qualified name is in canonical form (for import decls). 3490 */ 3491 public void checkCanonical(JCTree tree) { 3492 if (!isCanonical(tree)) 3493 log.error(tree.pos(), "import.requires.canonical", 3494 TreeInfo.symbol(tree)); 3495 } 3496 // where 3497 private boolean isCanonical(JCTree tree) { 3498 while (tree.hasTag(SELECT)) { 3499 JCFieldAccess s = (JCFieldAccess) tree; 3500 if (s.sym.owner.name != TreeInfo.symbol(s.selected).name) 3501 return false; 3502 tree = s.selected; 3503 } 3504 return true; 3505 } 3506 3507 /** Check that an auxiliary class is not accessed from any other file than its own. 3508 */ 3509 void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) { 3510 if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) && 3511 (c.flags() & AUXILIARY) != 0 && 3512 rs.isAccessible(env, c) && 3513 !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile)) 3514 { 3515 log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file", 3516 c, c.sourcefile); 3517 } 3518 } 3519 3520 private class ConversionWarner extends Warner { 3521 final String uncheckedKey; 3522 final Type found; 3523 final Type expected; 3524 public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) { 3525 super(pos); 3526 this.uncheckedKey = uncheckedKey; 3527 this.found = found; 3528 this.expected = expected; 3529 } 3530 3531 @Override 3532 public void warn(LintCategory lint) { 3533 boolean warned = this.warned; 3534 super.warn(lint); 3535 if (warned) return; // suppress redundant diagnostics 3536 switch (lint) { 3537 case UNCHECKED: 3538 Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected); 3539 break; 3540 case VARARGS: 3541 if (method != null && 3542 method.attribute(syms.trustMeType.tsym) != null && 3543 isTrustMeAllowedOnMethod(method) && 3544 !types.isReifiable(method.type.getParameterTypes().last())) { 3545 Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last()); 3546 } 3547 break; 3548 default: 3549 throw new AssertionError("Unexpected lint: " + lint); 3550 } 3551 } 3552 } 3553 3554 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) { 3555 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected); 3556 } 3557 3558 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) { 3559 return new ConversionWarner(pos, "unchecked.assign", found, expected); 3560 } 3561 3562 public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) { 3563 Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym); 3564 3565 if (functionalType != null) { 3566 try { 3567 types.findDescriptorSymbol((TypeSymbol)cs); 3568 } catch (Types.FunctionDescriptorLookupError ex) { 3569 DiagnosticPosition pos = tree.pos(); 3570 for (JCAnnotation a : tree.getModifiers().annotations) { 3571 if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) { 3572 pos = a.pos(); 3573 break; 3574 } 3575 } 3576 log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic()); 3577 } 3578 } 3579 } 3580 3581 public void checkImportsResolvable(final JCCompilationUnit toplevel) { 3582 for (final JCImport imp : toplevel.getImports()) { 3583 if (!imp.staticImport || !imp.qualid.hasTag(SELECT)) 3584 continue; 3585 final JCFieldAccess select = (JCFieldAccess) imp.qualid; 3586 final Symbol origin; 3587 if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP) 3588 continue; 3589 3590 TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected); 3591 if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) { 3592 log.error(imp.pos(), "cant.resolve.location", 3593 KindName.STATIC, 3594 select.name, List.<Type>nil(), List.<Type>nil(), 3595 Kinds.typeKindName(TreeInfo.symbol(select.selected).type), 3596 TreeInfo.symbol(select.selected).type); 3597 } 3598 } 3599 } 3600 3601 // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2) 3602 public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) { 3603 OUTER: for (JCImport imp : toplevel.getImports()) { 3604 if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) { 3605 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym; 3606 if (toplevel.modle.visiblePackages != null) { 3607 //TODO - unclear: selects like javax.* will get resolved from the current module 3608 //(as javax is not an exported package from any module). And as javax in the current 3609 //module typically does not contain any classes or subpackages, we need to go through 3610 //the visible packages to find a sub-package: 3611 for (PackageSymbol known : toplevel.modle.visiblePackages.values()) { 3612 if (Convert.packagePart(known.fullname) == tsym.flatName()) 3613 continue OUTER; 3614 } 3615 } 3616 if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) { 3617 log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, "doesnt.exist", tsym); 3618 } 3619 } 3620 } 3621 } 3622 3623 private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) { 3624 if (tsym == null || !processed.add(tsym)) 3625 return false; 3626 3627 // also search through inherited names 3628 if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed)) 3629 return true; 3630 3631 for (Type t : types.interfaces(tsym.type)) 3632 if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed)) 3633 return true; 3634 3635 for (Symbol sym : tsym.members().getSymbolsByName(name)) { 3636 if (sym.isStatic() && 3637 importAccessible(sym, packge) && 3638 sym.isMemberOf(origin, types)) { 3639 return true; 3640 } 3641 } 3642 3643 return false; 3644 } 3645 3646 // is the sym accessible everywhere in packge? 3647 public boolean importAccessible(Symbol sym, PackageSymbol packge) { 3648 try { 3649 int flags = (int)(sym.flags() & AccessFlags); 3650 switch (flags) { 3651 default: 3652 case PUBLIC: 3653 return true; 3654 case PRIVATE: 3655 return false; 3656 case 0: 3657 case PROTECTED: 3658 return sym.packge() == packge; 3659 } 3660 } catch (ClassFinder.BadClassFile err) { 3661 throw err; 3662 } catch (CompletionFailure ex) { 3663 return false; 3664 } 3665 } 3666 3667 public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) { 3668 JCCompilationUnit toplevel = env.toplevel; 3669 3670 if ( toplevel.modle == syms.unnamedModule 3671 || toplevel.modle == syms.noModule 3672 || (check.sym.flags() & COMPOUND) != 0) { 3673 return ; 3674 } 3675 3676 ExportsDirective currentExport = findExport(toplevel.packge); 3677 3678 if ( currentExport == null //not exported 3679 || currentExport.modules != null) //don't check classes in qualified export 3680 return ; 3681 3682 new TreeScanner() { 3683 Lint lint = env.info.lint; 3684 boolean inSuperType; 3685 3686 @Override 3687 public void visitBlock(JCBlock tree) { 3688 } 3689 @Override 3690 public void visitMethodDef(JCMethodDecl tree) { 3691 if (!isAPISymbol(tree.sym)) 3692 return; 3693 Lint prevLint = lint; 3694 try { 3695 lint = lint.augment(tree.sym); 3696 if (lint.isEnabled(LintCategory.EXPORTS)) { 3697 super.visitMethodDef(tree); 3698 } 3699 } finally { 3700 lint = prevLint; 3701 } 3702 } 3703 @Override 3704 public void visitVarDef(JCVariableDecl tree) { 3705 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH) 3706 return; 3707 Lint prevLint = lint; 3708 try { 3709 lint = lint.augment(tree.sym); 3710 if (lint.isEnabled(LintCategory.EXPORTS)) { 3711 scan(tree.mods); 3712 scan(tree.vartype); 3713 } 3714 } finally { 3715 lint = prevLint; 3716 } 3717 } 3718 @Override 3719 public void visitClassDef(JCClassDecl tree) { 3720 if (tree != check) 3721 return ; 3722 3723 if (!isAPISymbol(tree.sym)) 3724 return ; 3725 3726 Lint prevLint = lint; 3727 try { 3728 lint = lint.augment(tree.sym); 3729 if (lint.isEnabled(LintCategory.EXPORTS)) { 3730 scan(tree.mods); 3731 scan(tree.typarams); 3732 try { 3733 inSuperType = true; 3734 scan(tree.extending); 3735 scan(tree.implementing); 3736 } finally { 3737 inSuperType = false; 3738 } 3739 scan(tree.defs); 3740 } 3741 } finally { 3742 lint = prevLint; 3743 } 3744 } 3745 @Override 3746 public void visitTypeApply(JCTypeApply tree) { 3747 scan(tree.clazz); 3748 boolean oldInSuperType = inSuperType; 3749 try { 3750 inSuperType = false; 3751 scan(tree.arguments); 3752 } finally { 3753 inSuperType = oldInSuperType; 3754 } 3755 } 3756 @Override 3757 public void visitIdent(JCIdent tree) { 3758 Symbol sym = TreeInfo.symbol(tree); 3759 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) { 3760 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 3761 } 3762 } 3763 3764 @Override 3765 public void visitSelect(JCFieldAccess tree) { 3766 Symbol sym = TreeInfo.symbol(tree); 3767 Symbol sitesym = TreeInfo.symbol(tree.selected); 3768 if (sym.kind == TYP && sitesym.kind == PCK) { 3769 checkVisible(tree.pos(), sym, toplevel.packge, inSuperType); 3770 } else { 3771 super.visitSelect(tree); 3772 } 3773 } 3774 3775 @Override 3776 public void visitAnnotation(JCAnnotation tree) { 3777 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null) 3778 super.visitAnnotation(tree); 3779 } 3780 3781 }.scan(check); 3782 } 3783 //where: 3784 private ExportsDirective findExport(PackageSymbol pack) { 3785 for (ExportsDirective d : pack.modle.exports) { 3786 if (d.packge == pack) 3787 return d; 3788 } 3789 3790 return null; 3791 } 3792 private boolean isAPISymbol(Symbol sym) { 3793 while (sym.kind != PCK) { 3794 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) { 3795 return false; 3796 } 3797 sym = sym.owner; 3798 } 3799 return true; 3800 } 3801 private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) { 3802 if (!isAPISymbol(what) && !inSuperType) { //package private/private element 3803 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle)); 3804 return ; 3805 } 3806 3807 PackageSymbol whatPackage = what.packge(); 3808 ExportsDirective whatExport = findExport(whatPackage); 3809 ExportsDirective inExport = findExport(inPackage); 3810 3811 if (whatExport == null) { //package not exported: 3812 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle)); 3813 return ; 3814 } 3815 3816 if (whatExport.modules != null) { 3817 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) { 3818 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle)); 3819 } 3820 } 3821 3822 if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) { 3823 //check that relativeTo.modle requires public what.modle, somehow: 3824 List<ModuleSymbol> todo = List.of(inPackage.modle); 3825 3826 while (todo.nonEmpty()) { 3827 ModuleSymbol current = todo.head; 3828 todo = todo.tail; 3829 if (current == whatPackage.modle) 3830 return ; //OK 3831 for (RequiresDirective req : current.requires) { 3832 if (req.isPublic()) { 3833 todo = todo.prepend(req.module); 3834 } 3835 } 3836 } 3837 3838 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredPublic(kindName(what), what, what.packge().modle)); 3839 } 3840 } 3841} 3842