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