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