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