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