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