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