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