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