1 /* 2 * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.Set; 30 31 import com.sun.tools.javac.code.*; 32 import com.sun.tools.javac.jvm.*; 33 import com.sun.tools.javac.tree.*; 34 import com.sun.tools.javac.util.*; 35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 36 import com.sun.tools.javac.util.List; 37 38 import com.sun.tools.javac.tree.JCTree.*; 39 import com.sun.tools.javac.code.Lint; 40 import com.sun.tools.javac.code.Lint.LintCategory; 41 import com.sun.tools.javac.code.Type.*; 42 import com.sun.tools.javac.code.Symbol.*; 43 44 import static com.sun.tools.javac.code.Flags.*; 45 import static com.sun.tools.javac.code.Kinds.*; 46 import static com.sun.tools.javac.code.TypeTags.*; 47 48 /** Type checking helper class for the attribution phase. 49 * 50 * <p><b>This is NOT part of any supported API. 51 * If you write code that depends on this, you do so at your own risk. 52 * This code and its internal interfaces are subject to change or 53 * deletion without notice.</b> 54 */ 55 public class Check { 56 protected static final Context.Key<Check> checkKey = 57 new Context.Key<Check>(); 58 59 private final Name.Table names; 60 private final Log log; 61 private final Symtab syms; 62 private final Infer infer; 63 private final Target target; 64 private final Source source; 65 private final Types types; 66 private final boolean skipAnnotations; 67 private final TreeInfo treeinfo; 68 69 // The set of lint options currently in effect. It is initialized 70 // from the context, and then is set/reset as needed by Attr as it 71 // visits all the various parts of the trees during attribution. 72 private Lint lint; 73 74 public static Check instance(Context context) { 75 Check instance = context.get(checkKey); 76 if (instance == null) 77 instance = new Check(context); 78 return instance; 79 } 80 81 protected Check(Context context) { 82 context.put(checkKey, this); 83 84 names = Name.Table.instance(context); 85 log = Log.instance(context); 86 syms = Symtab.instance(context); 87 infer = Infer.instance(context); 88 this.types = Types.instance(context); 89 Options options = Options.instance(context); 90 target = Target.instance(context); 91 source = Source.instance(context); 92 lint = Lint.instance(context); 93 treeinfo = TreeInfo.instance(context); 94 95 Source source = Source.instance(context); 96 allowGenerics = source.allowGenerics(); 97 allowAnnotations = source.allowAnnotations(); 98 complexInference = options.get("-complexinference") != null; 99 skipAnnotations = options.get("skipAnnotations") != null; 100 101 boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION); 102 boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED); 103 boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings(); 104 105 deprecationHandler = new MandatoryWarningHandler(log,verboseDeprecated, 106 enforceMandatoryWarnings, "deprecated"); 107 uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked, 108 enforceMandatoryWarnings, "unchecked"); 109 } 110 111 /** Switch: generics enabled? 112 */ 113 boolean allowGenerics; 114 115 /** Switch: annotations enabled? 116 */ 117 boolean allowAnnotations; 118 119 /** Switch: -complexinference option set? 120 */ 121 boolean complexInference; 122 123 /** A table mapping flat names of all compiled classes in this run to their 124 * symbols; maintained from outside. 125 */ 126 public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>(); 127 128 /** A handler for messages about deprecated usage. 129 */ 130 private MandatoryWarningHandler deprecationHandler; 131 132 /** A handler for messages about unchecked or unsafe usage. 133 */ 134 private MandatoryWarningHandler uncheckedHandler; 135 136 137 /* ************************************************************************* 138 * Errors and Warnings 139 **************************************************************************/ 140 141 Lint setLint(Lint newLint) { 142 Lint prev = lint; 143 lint = newLint; 144 return prev; 145 } 146 147 /** Warn about deprecated symbol. 148 * @param pos Position to be used for error reporting. 149 * @param sym The deprecated symbol. 150 */ 151 void warnDeprecated(DiagnosticPosition pos, Symbol sym) { 152 if (!lint.isSuppressed(LintCategory.DEPRECATION)) 153 deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location()); 154 } 155 156 /** Warn about unchecked operation. 157 * @param pos Position to be used for error reporting. 158 * @param msg A string describing the problem. 159 */ 160 public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) { 161 if (!lint.isSuppressed(LintCategory.UNCHECKED)) 162 uncheckedHandler.report(pos, msg, args); 163 } 164 165 /** 166 * Report any deferred diagnostics. 167 */ 168 public void reportDeferredDiagnostics() { 169 deprecationHandler.reportDeferredDiagnostic(); 170 uncheckedHandler.reportDeferredDiagnostic(); 171 } 172 173 174 /** Report a failure to complete a class. 175 * @param pos Position to be used for error reporting. 176 * @param ex The failure to report. 177 */ 178 public Type completionError(DiagnosticPosition pos, CompletionFailure ex) { 179 log.error(pos, "cant.access", ex.sym, ex.errmsg); 180 if (ex instanceof ClassReader.BadClassFile) throw new Abort(); 181 else return syms.errType; 182 } 183 184 /** Report a type error. 185 * @param pos Position to be used for error reporting. 186 * @param problem A string describing the error. 187 * @param found The type that was found. 188 * @param req The type that was required. 189 */ 190 Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) { 191 log.error(pos, "prob.found.req", 192 problem, found, req); 193 return syms.errType; 194 } 195 196 Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) { 197 log.error(pos, "prob.found.req.1", problem, found, req, explanation); 198 return syms.errType; 199 } 200 201 /** Report an error that wrong type tag was found. 202 * @param pos Position to be used for error reporting. 203 * @param required An internationalized string describing the type tag 204 * required. 205 * @param found The type that was found. 206 */ 207 Type typeTagError(DiagnosticPosition pos, Object required, Object found) { 208 log.error(pos, "type.found.req", found, required); 209 return syms.errType; 210 } 211 212 /** Report an error that symbol cannot be referenced before super 213 * has been called. 214 * @param pos Position to be used for error reporting. 215 * @param sym The referenced symbol. 216 */ 217 void earlyRefError(DiagnosticPosition pos, Symbol sym) { 218 log.error(pos, "cant.ref.before.ctor.called", sym); 219 } 220 221 /** Report duplicate declaration error. 222 */ 223 void duplicateError(DiagnosticPosition pos, Symbol sym) { 224 if (!sym.type.isErroneous()) { 225 log.error(pos, "already.defined", sym, sym.location()); 226 } 227 } 228 229 /** Report array/varargs duplicate declaration 230 */ 231 void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) { 232 if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) { 233 log.error(pos, "array.and.varargs", sym1, sym2, sym2.location()); 234 } 235 } 236 237 /* ************************************************************************ 238 * duplicate declaration checking 239 *************************************************************************/ 240 241 /** Check that variable does not hide variable with same name in 242 * immediately enclosing local scope. 243 * @param pos Position for error reporting. 244 * @param v The symbol. 245 * @param s The scope. 246 */ 247 void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) { 248 if (s.next != null) { 249 for (Scope.Entry e = s.next.lookup(v.name); 250 e.scope != null && e.sym.owner == v.owner; 251 e = e.next()) { 252 if (e.sym.kind == VAR && 253 (e.sym.owner.kind & (VAR | MTH)) != 0 && 254 v.name != names.error) { 255 duplicateError(pos, e.sym); 256 return; 257 } 258 } 259 } 260 } 261 262 /** Check that a class or interface does not hide a class or 263 * interface with same name in immediately enclosing local scope. 264 * @param pos Position for error reporting. 265 * @param c The symbol. 266 * @param s The scope. 267 */ 268 void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) { 269 if (s.next != null) { 270 for (Scope.Entry e = s.next.lookup(c.name); 271 e.scope != null && e.sym.owner == c.owner; 272 e = e.next()) { 273 if (e.sym.kind == TYP && 274 (e.sym.owner.kind & (VAR | MTH)) != 0 && 275 c.name != names.error) { 276 duplicateError(pos, e.sym); 277 return; 278 } 279 } 280 } 281 } 282 283 /** Check that class does not have the same name as one of 284 * its enclosing classes, or as a class defined in its enclosing scope. 285 * return true if class is unique in its enclosing scope. 286 * @param pos Position for error reporting. 287 * @param name The class name. 288 * @param s The enclosing scope. 289 */ 290 boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) { 291 for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) { 292 if (e.sym.kind == TYP && e.sym.name != names.error) { 293 duplicateError(pos, e.sym); 294 return false; 295 } 296 } 297 for (Symbol sym = s.owner; sym != null; sym = sym.owner) { 298 if (sym.kind == TYP && sym.name == name && sym.name != names.error) { 299 duplicateError(pos, sym); 300 return true; 301 } 302 } 303 return true; 304 } 305 306 /* ************************************************************************* 307 * Class name generation 308 **************************************************************************/ 309 310 /** Return name of local class. 311 * This is of the form <enclClass> $ n <classname> 312 * where 313 * enclClass is the flat name of the enclosing class, 314 * classname is the simple name of the local class 315 */ 316 Name localClassName(ClassSymbol c) { 317 for (int i=1; ; i++) { 318 Name flatname = names. 319 fromString("" + c.owner.enclClass().flatname + 320 target.syntheticNameChar() + i + 321 c.name); 322 if (compiled.get(flatname) == null) return flatname; 323 } 324 } 325 326 /* ************************************************************************* 327 * Type Checking 328 **************************************************************************/ 329 330 /** Check that a given type is assignable to a given proto-type. 331 * If it is, return the type, otherwise return errType. 332 * @param pos Position to be used for error reporting. 333 * @param found The type that was found. 334 * @param req The type that was required. 335 */ 336 Type checkType(DiagnosticPosition pos, Type found, Type req) { 337 if (req.tag == ERROR) 338 return req; 339 if (found.tag == FORALL) 340 return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req)); 341 if (req.tag == NONE) 342 return found; 343 if (types.isAssignable(found, req, convertWarner(pos, found, req))) 344 return found; 345 if (found.tag <= DOUBLE && req.tag <= DOUBLE) 346 return typeError(pos, JCDiagnostic.fragment("possible.loss.of.precision"), found, req); 347 if (found.isSuperBound()) { 348 log.error(pos, "assignment.from.super-bound", found); 349 return syms.errType; 350 } 351 if (req.isExtendsBound()) { 352 log.error(pos, "assignment.to.extends-bound", req); 353 return syms.errType; 354 } 355 return typeError(pos, JCDiagnostic.fragment("incompatible.types"), found, req); 356 } 357 358 /** Instantiate polymorphic type to some prototype, unless 359 * prototype is `anyPoly' in which case polymorphic type 360 * is returned unchanged. 361 */ 362 Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) { 363 if (pt == Infer.anyPoly && complexInference) { 364 return t; 365 } else if (pt == Infer.anyPoly || pt.tag == NONE) { 366 Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType; 367 return instantiatePoly(pos, t, newpt, warn); 368 } else if (pt.tag == ERROR) { 369 return pt; 370 } else { 371 try { 372 return infer.instantiateExpr(t, pt, warn); 373 } catch (Infer.NoInstanceException ex) { 374 if (ex.isAmbiguous) { 375 JCDiagnostic d = ex.getDiagnostic(); 376 log.error(pos, 377 "undetermined.type" + (d!=null ? ".1" : ""), 378 t, d); 379 return syms.errType; 380 } else { 381 JCDiagnostic d = ex.getDiagnostic(); 382 return typeError(pos, 383 JCDiagnostic.fragment("incompatible.types" + (d!=null ? ".1" : ""), d), 384 t, pt); 385 } 386 } 387 } 388 } 389 390 /** Check that a given type can be cast to a given target type. 391 * Return the result of the cast. 392 * @param pos Position to be used for error reporting. 393 * @param found The type that is being cast. 394 * @param req The target type of the cast. 395 */ 396 Type checkCastable(DiagnosticPosition pos, Type found, Type req) { 397 if (found.tag == FORALL) { 398 instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req)); 399 return req; 400 } else if (types.isCastable(found, req, castWarner(pos, found, req))) { 401 return req; 402 } else { 403 return typeError(pos, 404 JCDiagnostic.fragment("inconvertible.types"), 405 found, req); 406 } 407 } 408 //where 409 /** Is type a type variable, or a (possibly multi-dimensional) array of 410 * type variables? 411 */ 412 boolean isTypeVar(Type t) { 413 return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t)); 414 } 415 416 /** Check that a type is within some bounds. 417 * 418 * Used in TypeApply to verify that, e.g., X in V<X> is a valid 419 * type argument. 420 * @param pos Position to be used for error reporting. 421 * @param a The type that should be bounded by bs. 422 * @param bs The bound. 423 */ 424 private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) { 425 if (a.isUnbound()) { 426 return; 427 } else if (a.tag != WILDCARD) { 428 a = types.upperBound(a); 429 for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) { 430 if (!types.isSubtype(a, l.head)) { 431 log.error(pos, "not.within.bounds", a); 432 return; 433 } 434 } 435 } else if (a.isExtendsBound()) { 436 if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings)) 437 log.error(pos, "not.within.bounds", a); 438 } else if (a.isSuperBound()) { 439 if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound())) 440 log.error(pos, "not.within.bounds", a); 441 } 442 } 443 444 /** Check that type is different from 'void'. 445 * @param pos Position to be used for error reporting. 446 * @param t The type to be checked. 447 */ 448 Type checkNonVoid(DiagnosticPosition pos, Type t) { 449 if (t.tag == VOID) { 450 log.error(pos, "void.not.allowed.here"); 451 return syms.errType; 452 } else { 453 return t; 454 } 455 } 456 457 /** Check that type is a class or interface type. 458 * @param pos Position to be used for error reporting. 459 * @param t The type to be checked. 460 */ 461 Type checkClassType(DiagnosticPosition pos, Type t) { 462 if (t.tag != CLASS && t.tag != ERROR) 463 return typeTagError(pos, 464 JCDiagnostic.fragment("type.req.class"), 465 (t.tag == TYPEVAR) 466 ? JCDiagnostic.fragment("type.parameter", t) 467 : t); 468 else 469 return t; 470 } 471 472 /** Check that type is a class or interface type. 473 * @param pos Position to be used for error reporting. 474 * @param t The type to be checked. 475 * @param noBounds True if type bounds are illegal here. 476 */ 477 Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) { 478 t = checkClassType(pos, t); 479 if (noBounds && t.isParameterized()) { 480 List<Type> args = t.getTypeArguments(); 481 while (args.nonEmpty()) { 482 if (args.head.tag == WILDCARD) 483 return typeTagError(pos, 484 log.getLocalizedString("type.req.exact"), 485 args.head); 486 args = args.tail; 487 } 488 } 489 return t; 490 } 491 492 /** Check that type is a reifiable class, interface or array type. 493 * @param pos Position to be used for error reporting. 494 * @param t The type to be checked. 495 */ 496 Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) { 497 if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) { 498 return typeTagError(pos, 499 JCDiagnostic.fragment("type.req.class.array"), 500 t); 501 } else if (!types.isReifiable(t)) { 502 log.error(pos, "illegal.generic.type.for.instof"); 503 return syms.errType; 504 } else { 505 return t; 506 } 507 } 508 509 /** Check that type is a reference type, i.e. a class, interface or array type 510 * or a type variable. 511 * @param pos Position to be used for error reporting. 512 * @param t The type to be checked. 513 */ 514 Type checkRefType(DiagnosticPosition pos, Type t) { 515 switch (t.tag) { 516 case CLASS: 517 case ARRAY: 518 case TYPEVAR: 519 case WILDCARD: 520 case ERROR: 521 return t; 522 default: 523 return typeTagError(pos, 524 JCDiagnostic.fragment("type.req.ref"), 525 t); 526 } 527 } 528 529 /** Check that type is a null or reference type. 530 * @param pos Position to be used for error reporting. 531 * @param t The type to be checked. 532 */ 533 Type checkNullOrRefType(DiagnosticPosition pos, Type t) { 534 switch (t.tag) { 535 case CLASS: 536 case ARRAY: 537 case TYPEVAR: 538 case WILDCARD: 539 case BOT: 540 case ERROR: 541 return t; 542 default: 543 return typeTagError(pos, 544 JCDiagnostic.fragment("type.req.ref"), 545 t); 546 } 547 } 548 549 /** Check that flag set does not contain elements of two conflicting sets. s 550 * Return true if it doesn't. 551 * @param pos Position to be used for error reporting. 552 * @param flags The set of flags to be checked. 553 * @param set1 Conflicting flags set #1. 554 * @param set2 Conflicting flags set #2. 555 */ 556 boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) { 557 if ((flags & set1) != 0 && (flags & set2) != 0) { 558 log.error(pos, 559 "illegal.combination.of.modifiers", 560 TreeInfo.flagNames(TreeInfo.firstFlag(flags & set1)), 561 TreeInfo.flagNames(TreeInfo.firstFlag(flags & set2))); 562 return false; 563 } else 564 return true; 565 } 566 567 /** Check that given modifiers are legal for given symbol and 568 * return modifiers together with any implicit modififiers for that symbol. 569 * Warning: we can't use flags() here since this method 570 * is called during class enter, when flags() would cause a premature 571 * completion. 572 * @param pos Position to be used for error reporting. 573 * @param flags The set of modifiers given in a definition. 574 * @param sym The defined symbol. 575 */ 576 long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) { 577 long mask; 578 long implicit = 0; 579 switch (sym.kind) { 580 case VAR: 581 if (sym.owner.kind != TYP) 582 mask = LocalVarFlags; 583 else if ((sym.owner.flags_field & INTERFACE) != 0) 584 mask = implicit = InterfaceVarFlags; 585 else 586 mask = VarFlags; 587 break; 588 case MTH: 589 if (sym.name == names.init) { 590 if ((sym.owner.flags_field & ENUM) != 0) { 591 // enum constructors cannot be declared public or 592 // protected and must be implicitly or explicitly 593 // private 594 implicit = PRIVATE; 595 mask = PRIVATE; 596 } else 597 mask = ConstructorFlags; 598 } else if ((sym.owner.flags_field & INTERFACE) != 0) 599 mask = implicit = InterfaceMethodFlags; 600 else { 601 mask = MethodFlags; 602 } 603 // Imply STRICTFP if owner has STRICTFP set. 604 if (((flags|implicit) & Flags.ABSTRACT) == 0) 605 implicit |= sym.owner.flags_field & STRICTFP; 606 break; 607 case TYP: 608 if (sym.isLocal()) { 609 mask = LocalClassFlags; 610 if (sym.name.len == 0) { // Anonymous class 611 // Anonymous classes in static methods are themselves static; 612 // that's why we admit STATIC here. 613 mask |= STATIC; 614 // JLS: Anonymous classes are final. 615 implicit |= FINAL; 616 } 617 if ((sym.owner.flags_field & STATIC) == 0 && 618 (flags & ENUM) != 0) 619 log.error(pos, "enums.must.be.static"); 620 } else if (sym.owner.kind == TYP) { 621 mask = MemberClassFlags; 622 if (sym.owner.owner.kind == PCK || 623 (sym.owner.flags_field & STATIC) != 0) 624 mask |= STATIC; 625 else if ((flags & ENUM) != 0) 626 log.error(pos, "enums.must.be.static"); 627 // Nested interfaces and enums are always STATIC (Spec ???) 628 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC; 629 } else { 630 mask = ClassFlags; 631 } 632 // Interfaces are always ABSTRACT 633 if ((flags & INTERFACE) != 0) implicit |= ABSTRACT; 634 635 if ((flags & ENUM) != 0) { 636 // enums can't be declared abstract or final 637 mask &= ~(ABSTRACT | FINAL); 638 implicit |= implicitEnumFinalFlag(tree); 639 } 640 // Imply STRICTFP if owner has STRICTFP set. 641 implicit |= sym.owner.flags_field & STRICTFP; 642 break; 643 default: 644 throw new AssertionError(); 645 } 646 long illegal = flags & StandardFlags & ~mask; 647 if (illegal != 0) { 648 if ((illegal & INTERFACE) != 0) { 649 log.error(pos, "intf.not.allowed.here"); 650 mask |= INTERFACE; 651 } 652 else { 653 log.error(pos, 654 "mod.not.allowed.here", TreeInfo.flagNames(illegal)); 655 } 656 } 657 else if ((sym.kind == TYP || 658 // ISSUE: Disallowing abstract&private is no longer appropriate 659 // in the presence of inner classes. Should it be deleted here? 660 checkDisjoint(pos, flags, 661 ABSTRACT, 662 PRIVATE | STATIC)) 663 && 664 checkDisjoint(pos, flags, 665 ABSTRACT | INTERFACE, 666 FINAL | NATIVE | SYNCHRONIZED) 667 && 668 checkDisjoint(pos, flags, 669 PUBLIC, 670 PRIVATE | PROTECTED) 671 && 672 checkDisjoint(pos, flags, 673 PRIVATE, 674 PUBLIC | PROTECTED) 675 && 676 checkDisjoint(pos, flags, 677 FINAL, 678 VOLATILE) 679 && 680 (sym.kind == TYP || 681 checkDisjoint(pos, flags, 682 ABSTRACT | NATIVE, 683 STRICTFP))) { 684 // skip 685 } 686 return flags & (mask | ~StandardFlags) | implicit; 687 } 688 689 690 /** Determine if this enum should be implicitly final. 691 * 692 * If the enum has no specialized enum contants, it is final. 693 * 694 * If the enum does have specialized enum contants, it is 695 * <i>not</i> final. 696 */ 697 private long implicitEnumFinalFlag(JCTree tree) { 698 if (tree.getTag() != JCTree.CLASSDEF) return 0; 699 class SpecialTreeVisitor extends JCTree.Visitor { 700 boolean specialized; 701 SpecialTreeVisitor() { 702 this.specialized = false; 703 }; 704 705 public void visitTree(JCTree tree) { /* no-op */ } 706 707 public void visitVarDef(JCVariableDecl tree) { 708 if ((tree.mods.flags & ENUM) != 0) { 709 if (tree.init instanceof JCNewClass && 710 ((JCNewClass) tree.init).def != null) { 711 specialized = true; 712 } 713 } 714 } 715 } 716 717 SpecialTreeVisitor sts = new SpecialTreeVisitor(); 718 JCClassDecl cdef = (JCClassDecl) tree; 719 for (JCTree defs: cdef.defs) { 720 defs.accept(sts); 721 if (sts.specialized) return 0; 722 } 723 return FINAL; 724 } 725 726 /* ************************************************************************* 727 * Type Validation 728 **************************************************************************/ 729 730 /** Validate a type expression. That is, 731 * check that all type arguments of a parametric type are within 732 * their bounds. This must be done in a second phase after type attributon 733 * since a class might have a subclass as type parameter bound. E.g: 734 * 735 * class B<A extends C> { ... } 736 * class C extends B<C> { ... } 737 * 738 * and we can't make sure that the bound is already attributed because 739 * of possible cycles. 740 */ 741 private Validator validator = new Validator(); 742 743 /** Visitor method: Validate a type expression, if it is not null, catching 744 * and reporting any completion failures. 745 */ 746 void validate(JCTree tree) { 747 try { 748 if (tree != null) tree.accept(validator); 749 } catch (CompletionFailure ex) { 750 completionError(tree.pos(), ex); 751 } 752 } 753 754 /** Visitor method: Validate a list of type expressions. 755 */ 756 void validate(List<? extends JCTree> trees) { 757 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 758 validate(l.head); 759 } 760 761 /** Visitor method: Validate a list of type parameters. 762 */ 763 void validateTypeParams(List<JCTypeParameter> trees) { 764 for (List<JCTypeParameter> l = trees; l.nonEmpty(); l = l.tail) 765 validate(l.head); 766 } 767 768 /** A visitor class for type validation. 769 */ 770 class Validator extends JCTree.Visitor { 771 772 public void visitTypeArray(JCArrayTypeTree tree) { 773 validate(tree.elemtype); 774 } 775 776 public void visitTypeApply(JCTypeApply tree) { 777 if (tree.type.tag == CLASS) { 778 List<Type> formals = tree.type.tsym.type.getTypeArguments(); 779 List<Type> actuals = tree.type.getTypeArguments(); 780 List<JCExpression> args = tree.arguments; 781 List<Type> forms = formals; 782 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>(); 783 784 // For matching pairs of actual argument types `a' and 785 // formal type parameters with declared bound `b' ... 786 while (args.nonEmpty() && forms.nonEmpty()) { 787 validate(args.head); 788 789 // exact type arguments needs to know their 790 // bounds (for upper and lower bound 791 // calculations). So we create new TypeVars with 792 // bounds substed with actuals. 793 tvars_buf.append(types.substBound(((TypeVar)forms.head), 794 formals, 795 Type.removeBounds(actuals))); 796 797 args = args.tail; 798 forms = forms.tail; 799 } 800 801 args = tree.arguments; 802 List<TypeVar> tvars = tvars_buf.toList(); 803 while (args.nonEmpty() && tvars.nonEmpty()) { 804 // Let the actual arguments know their bound 805 args.head.type.withTypeVar(tvars.head); 806 args = args.tail; 807 tvars = tvars.tail; 808 } 809 810 args = tree.arguments; 811 tvars = tvars_buf.toList(); 812 while (args.nonEmpty() && tvars.nonEmpty()) { 813 checkExtends(args.head.pos(), 814 args.head.type, 815 tvars.head); 816 args = args.tail; 817 tvars = tvars.tail; 818 } 819 820 // Check that this type is either fully parameterized, or 821 // not parameterized at all. 822 if (tree.type.getEnclosingType().isRaw()) 823 log.error(tree.pos(), "improperly.formed.type.inner.raw.param"); 824 if (tree.clazz.getTag() == JCTree.SELECT) 825 visitSelectInternal((JCFieldAccess)tree.clazz); 826 } 827 } 828 829 public void visitTypeParameter(JCTypeParameter tree) { 830 validate(tree.bounds); 831 checkClassBounds(tree.pos(), tree.type); 832 } 833 834 @Override 835 public void visitWildcard(JCWildcard tree) { 836 if (tree.inner != null) 837 validate(tree.inner); 838 } 839 840 public void visitSelect(JCFieldAccess tree) { 841 if (tree.type.tag == CLASS) { 842 visitSelectInternal(tree); 843 844 // Check that this type is either fully parameterized, or 845 // not parameterized at all. 846 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty()) 847 log.error(tree.pos(), "improperly.formed.type.param.missing"); 848 } 849 } 850 public void visitSelectInternal(JCFieldAccess tree) { 851 if (tree.type.getEnclosingType().tag != CLASS && 852 tree.selected.type.isParameterized()) { 853 // The enclosing type is not a class, so we are 854 // looking at a static member type. However, the 855 // qualifying expression is parameterized. 856 log.error(tree.pos(), "cant.select.static.class.from.param.type"); 857 } else { 858 // otherwise validate the rest of the expression 859 validate(tree.selected); 860 } 861 } 862 863 /** Default visitor method: do nothing. 864 */ 865 public void visitTree(JCTree tree) { 866 } 867 } 868 869 /* ************************************************************************* 870 * Exception checking 871 **************************************************************************/ 872 873 /* The following methods treat classes as sets that contain 874 * the class itself and all their subclasses 875 */ 876 877 /** Is given type a subtype of some of the types in given list? 878 */ 879 boolean subset(Type t, List<Type> ts) { 880 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 881 if (types.isSubtype(t, l.head)) return true; 882 return false; 883 } 884 885 /** Is given type a subtype or supertype of 886 * some of the types in given list? 887 */ 888 boolean intersects(Type t, List<Type> ts) { 889 for (List<Type> l = ts; l.nonEmpty(); l = l.tail) 890 if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true; 891 return false; 892 } 893 894 /** Add type set to given type list, unless it is a subclass of some class 895 * in the list. 896 */ 897 List<Type> incl(Type t, List<Type> ts) { 898 return subset(t, ts) ? ts : excl(t, ts).prepend(t); 899 } 900 901 /** Remove type set from type set list. 902 */ 903 List<Type> excl(Type t, List<Type> ts) { 904 if (ts.isEmpty()) { 905 return ts; 906 } else { 907 List<Type> ts1 = excl(t, ts.tail); 908 if (types.isSubtype(ts.head, t)) return ts1; 909 else if (ts1 == ts.tail) return ts; 910 else return ts1.prepend(ts.head); 911 } 912 } 913 914 /** Form the union of two type set lists. 915 */ 916 List<Type> union(List<Type> ts1, List<Type> ts2) { 917 List<Type> ts = ts1; 918 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 919 ts = incl(l.head, ts); 920 return ts; 921 } 922 923 /** Form the difference of two type lists. 924 */ 925 List<Type> diff(List<Type> ts1, List<Type> ts2) { 926 List<Type> ts = ts1; 927 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 928 ts = excl(l.head, ts); 929 return ts; 930 } 931 932 /** Form the intersection of two type lists. 933 */ 934 public List<Type> intersect(List<Type> ts1, List<Type> ts2) { 935 List<Type> ts = List.nil(); 936 for (List<Type> l = ts1; l.nonEmpty(); l = l.tail) 937 if (subset(l.head, ts2)) ts = incl(l.head, ts); 938 for (List<Type> l = ts2; l.nonEmpty(); l = l.tail) 939 if (subset(l.head, ts1)) ts = incl(l.head, ts); 940 return ts; 941 } 942 943 /** Is exc an exception symbol that need not be declared? 944 */ 945 boolean isUnchecked(ClassSymbol exc) { 946 return 947 exc.kind == ERR || 948 exc.isSubClass(syms.errorType.tsym, types) || 949 exc.isSubClass(syms.runtimeExceptionType.tsym, types); 950 } 951 952 /** Is exc an exception type that need not be declared? 953 */ 954 boolean isUnchecked(Type exc) { 955 return 956 (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) : 957 (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) : 958 exc.tag == BOT; 959 } 960 961 /** Same, but handling completion failures. 962 */ 963 boolean isUnchecked(DiagnosticPosition pos, Type exc) { 964 try { 965 return isUnchecked(exc); 966 } catch (CompletionFailure ex) { 967 completionError(pos, ex); 968 return true; 969 } 970 } 971 972 /** Is exc handled by given exception list? 973 */ 974 boolean isHandled(Type exc, List<Type> handled) { 975 return isUnchecked(exc) || subset(exc, handled); 976 } 977 978 /** Return all exceptions in thrown list that are not in handled list. 979 * @param thrown The list of thrown exceptions. 980 * @param handled The list of handled exceptions. 981 */ 982 List<Type> unHandled(List<Type> thrown, List<Type> handled) { 983 List<Type> unhandled = List.nil(); 984 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 985 if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head); 986 return unhandled; 987 } 988 989 /* ************************************************************************* 990 * Overriding/Implementation checking 991 **************************************************************************/ 992 993 /** The level of access protection given by a flag set, 994 * where PRIVATE is highest and PUBLIC is lowest. 995 */ 996 static int protection(long flags) { 997 switch ((short)(flags & AccessFlags)) { 998 case PRIVATE: return 3; 999 case PROTECTED: return 1; 1000 default: 1001 case PUBLIC: return 0; 1002 case 0: return 2; 1003 } 1004 } 1005 1006 /** A string describing the access permission given by a flag set. 1007 * This always returns a space-separated list of Java Keywords. 1008 */ 1009 private static String protectionString(long flags) { 1010 long flags1 = flags & AccessFlags; 1011 return (flags1 == 0) ? "package" : TreeInfo.flagNames(flags1); 1012 } 1013 1014 /** A customized "cannot override" error message. 1015 * @param m The overriding method. 1016 * @param other The overridden method. 1017 * @return An internationalized string. 1018 */ 1019 static Object cannotOverride(MethodSymbol m, MethodSymbol other) { 1020 String key; 1021 if ((other.owner.flags() & INTERFACE) == 0) 1022 key = "cant.override"; 1023 else if ((m.owner.flags() & INTERFACE) == 0) 1024 key = "cant.implement"; 1025 else 1026 key = "clashes.with"; 1027 return JCDiagnostic.fragment(key, m, m.location(), other, other.location()); 1028 } 1029 1030 /** A customized "override" warning message. 1031 * @param m The overriding method. 1032 * @param other The overridden method. 1033 * @return An internationalized string. 1034 */ 1035 static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) { 1036 String key; 1037 if ((other.owner.flags() & INTERFACE) == 0) 1038 key = "unchecked.override"; 1039 else if ((m.owner.flags() & INTERFACE) == 0) 1040 key = "unchecked.implement"; 1041 else 1042 key = "unchecked.clash.with"; 1043 return JCDiagnostic.fragment(key, m, m.location(), other, other.location()); 1044 } 1045 1046 /** A customized "override" warning message. 1047 * @param m The overriding method. 1048 * @param other The overridden method. 1049 * @return An internationalized string. 1050 */ 1051 static Object varargsOverrides(MethodSymbol m, MethodSymbol other) { 1052 String key; 1053 if ((other.owner.flags() & INTERFACE) == 0) 1054 key = "varargs.override"; 1055 else if ((m.owner.flags() & INTERFACE) == 0) 1056 key = "varargs.implement"; 1057 else 1058 key = "varargs.clash.with"; 1059 return JCDiagnostic.fragment(key, m, m.location(), other, other.location()); 1060 } 1061 1062 /** Check that this method conforms with overridden method 'other'. 1063 * where `origin' is the class where checking started. 1064 * Complications: 1065 * (1) Do not check overriding of synthetic methods 1066 * (reason: they might be final). 1067 * todo: check whether this is still necessary. 1068 * (2) Admit the case where an interface proxy throws fewer exceptions 1069 * than the method it implements. Augment the proxy methods with the 1070 * undeclared exceptions in this case. 1071 * (3) When generics are enabled, admit the case where an interface proxy 1072 * has a result type 1073 * extended by the result type of the method it implements. 1074 * Change the proxies result type to the smaller type in this case. 1075 * 1076 * @param tree The tree from which positions 1077 * are extracted for errors. 1078 * @param m The overriding method. 1079 * @param other The overridden method. 1080 * @param origin The class of which the overriding method 1081 * is a member. 1082 */ 1083 void checkOverride(JCTree tree, 1084 MethodSymbol m, 1085 MethodSymbol other, 1086 ClassSymbol origin) { 1087 // Don't check overriding of synthetic methods or by bridge methods. 1088 if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) { 1089 return; 1090 } 1091 1092 // Error if static method overrides instance method (JLS 8.4.6.2). 1093 if ((m.flags() & STATIC) != 0 && 1094 (other.flags() & STATIC) == 0) { 1095 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static", 1096 cannotOverride(m, other)); 1097 return; 1098 } 1099 1100 // Error if instance method overrides static or final 1101 // method (JLS 8.4.6.1). 1102 if ((other.flags() & FINAL) != 0 || 1103 (m.flags() & STATIC) == 0 && 1104 (other.flags() & STATIC) != 0) { 1105 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth", 1106 cannotOverride(m, other), 1107 TreeInfo.flagNames(other.flags() & (FINAL | STATIC))); 1108 return; 1109 } 1110 1111 if ((m.owner.flags() & ANNOTATION) != 0) { 1112 // handled in validateAnnotationMethod 1113 return; 1114 } 1115 1116 // Error if overriding method has weaker access (JLS 8.4.6.3). 1117 if ((origin.flags() & INTERFACE) == 0 && 1118 protection(m.flags()) > protection(other.flags())) { 1119 log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access", 1120 cannotOverride(m, other), 1121 protectionString(other.flags())); 1122 return; 1123 1124 } 1125 1126 Type mt = types.memberType(origin.type, m); 1127 Type ot = types.memberType(origin.type, other); 1128 // Error if overriding result type is different 1129 // (or, in the case of generics mode, not a subtype) of 1130 // overridden result type. We have to rename any type parameters 1131 // before comparing types. 1132 List<Type> mtvars = mt.getTypeArguments(); 1133 List<Type> otvars = ot.getTypeArguments(); 1134 Type mtres = mt.getReturnType(); 1135 Type otres = types.subst(ot.getReturnType(), otvars, mtvars); 1136 1137 overrideWarner.warned = false; 1138 boolean resultTypesOK = 1139 types.returnTypeSubstitutable(mt, ot, otres, overrideWarner); 1140 if (!resultTypesOK) { 1141 if (!source.allowCovariantReturns() && 1142 m.owner != origin && 1143 m.owner.isSubClass(other.owner, types)) { 1144 // allow limited interoperability with covariant returns 1145 } else { 1146 typeError(TreeInfo.diagnosticPositionFor(m, tree), 1147 JCDiagnostic.fragment("override.incompatible.ret", 1148 cannotOverride(m, other)), 1149 mtres, otres); 1150 return; 1151 } 1152 } else if (overrideWarner.warned) { 1153 warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree), 1154 "prob.found.req", 1155 JCDiagnostic.fragment("override.unchecked.ret", 1156 uncheckedOverrides(m, other)), 1157 mtres, otres); 1158 } 1159 1160 // Error if overriding method throws an exception not reported 1161 // by overridden method. 1162 List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars); 1163 List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown); 1164 if (unhandled.nonEmpty()) { 1165 log.error(TreeInfo.diagnosticPositionFor(m, tree), 1166 "override.meth.doesnt.throw", 1167 cannotOverride(m, other), 1168 unhandled.head); 1169 return; 1170 } 1171 1172 // Optional warning if varargs don't agree 1173 if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0) 1174 && lint.isEnabled(Lint.LintCategory.OVERRIDES)) { 1175 log.warning(TreeInfo.diagnosticPositionFor(m, tree), 1176 ((m.flags() & Flags.VARARGS) != 0) 1177 ? "override.varargs.missing" 1178 : "override.varargs.extra", 1179 varargsOverrides(m, other)); 1180 } 1181 1182 // Warn if instance method overrides bridge method (compiler spec ??) 1183 if ((other.flags() & BRIDGE) != 0) { 1184 log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge", 1185 uncheckedOverrides(m, other)); 1186 } 1187 1188 // Warn if a deprecated method overridden by a non-deprecated one. 1189 if ((other.flags() & DEPRECATED) != 0 1190 && (m.flags() & DEPRECATED) == 0 1191 && m.outermostClass() != other.outermostClass() 1192 && !isDeprecatedOverrideIgnorable(other, origin)) { 1193 warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other); 1194 } 1195 } 1196 // where 1197 private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) { 1198 // If the method, m, is defined in an interface, then ignore the issue if the method 1199 // is only inherited via a supertype and also implemented in the supertype, 1200 // because in that case, we will rediscover the issue when examining the method 1201 // in the supertype. 1202 // If the method, m, is not defined in an interface, then the only time we need to 1203 // address the issue is when the method is the supertype implemementation: any other 1204 // case, we will have dealt with when examining the supertype classes 1205 ClassSymbol mc = m.enclClass(); 1206 Type st = types.supertype(origin.type); 1207 if (st.tag != CLASS) 1208 return true; 1209 MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false); 1210 1211 if (mc != null && ((mc.flags() & INTERFACE) != 0)) { 1212 List<Type> intfs = types.interfaces(origin.type); 1213 return (intfs.contains(mc.type) ? false : (stimpl != null)); 1214 } 1215 else 1216 return (stimpl != m); 1217 } 1218 1219 1220 // used to check if there were any unchecked conversions 1221 Warner overrideWarner = new Warner(); 1222 1223 /** Check that a class does not inherit two concrete methods 1224 * with the same signature. 1225 * @param pos Position to be used for error reporting. 1226 * @param site The class type to be checked. 1227 */ 1228 public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) { 1229 Type sup = types.supertype(site); 1230 if (sup.tag != CLASS) return; 1231 1232 for (Type t1 = sup; 1233 t1.tsym.type.isParameterized(); 1234 t1 = types.supertype(t1)) { 1235 for (Scope.Entry e1 = t1.tsym.members().elems; 1236 e1 != null; 1237 e1 = e1.sibling) { 1238 Symbol s1 = e1.sym; 1239 if (s1.kind != MTH || 1240 (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1241 !s1.isInheritedIn(site.tsym, types) || 1242 ((MethodSymbol)s1).implementation(site.tsym, 1243 types, 1244 true) != s1) 1245 continue; 1246 Type st1 = types.memberType(t1, s1); 1247 int s1ArgsLength = st1.getParameterTypes().length(); 1248 if (st1 == s1.type) continue; 1249 1250 for (Type t2 = sup; 1251 t2.tag == CLASS; 1252 t2 = types.supertype(t2)) { 1253 for (Scope.Entry e2 = t1.tsym.members().lookup(s1.name); 1254 e2.scope != null; 1255 e2 = e2.next()) { 1256 Symbol s2 = e2.sym; 1257 if (s2 == s1 || 1258 s2.kind != MTH || 1259 (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 || 1260 s2.type.getParameterTypes().length() != s1ArgsLength || 1261 !s2.isInheritedIn(site.tsym, types) || 1262 ((MethodSymbol)s2).implementation(site.tsym, 1263 types, 1264 true) != s2) 1265 continue; 1266 Type st2 = types.memberType(t2, s2); 1267 if (types.overrideEquivalent(st1, st2)) 1268 log.error(pos, "concrete.inheritance.conflict", 1269 s1, t1, s2, t2, sup); 1270 } 1271 } 1272 } 1273 } 1274 } 1275 1276 /** Check that classes (or interfaces) do not each define an abstract 1277 * method with same name and arguments but incompatible return types. 1278 * @param pos Position to be used for error reporting. 1279 * @param t1 The first argument type. 1280 * @param t2 The second argument type. 1281 */ 1282 public boolean checkCompatibleAbstracts(DiagnosticPosition pos, 1283 Type t1, 1284 Type t2) { 1285 return checkCompatibleAbstracts(pos, t1, t2, 1286 types.makeCompoundType(t1, t2)); 1287 } 1288 1289 public boolean checkCompatibleAbstracts(DiagnosticPosition pos, 1290 Type t1, 1291 Type t2, 1292 Type site) { 1293 Symbol sym = firstIncompatibility(t1, t2, site); 1294 if (sym != null) { 1295 log.error(pos, "types.incompatible.diff.ret", 1296 t1, t2, sym.name + 1297 "(" + types.memberType(t2, sym).getParameterTypes() + ")"); 1298 return false; 1299 } 1300 return true; 1301 } 1302 1303 /** Return the first method which is defined with same args 1304 * but different return types in two given interfaces, or null if none 1305 * exists. 1306 * @param t1 The first type. 1307 * @param t2 The second type. 1308 * @param site The most derived type. 1309 * @returns symbol from t2 that conflicts with one in t1. 1310 */ 1311 private Symbol firstIncompatibility(Type t1, Type t2, Type site) { 1312 Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>(); 1313 closure(t1, interfaces1); 1314 Map<TypeSymbol,Type> interfaces2; 1315 if (t1 == t2) 1316 interfaces2 = interfaces1; 1317 else 1318 closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>()); 1319 1320 for (Type t3 : interfaces1.values()) { 1321 for (Type t4 : interfaces2.values()) { 1322 Symbol s = firstDirectIncompatibility(t3, t4, site); 1323 if (s != null) return s; 1324 } 1325 } 1326 return null; 1327 } 1328 1329 /** Compute all the supertypes of t, indexed by type symbol. */ 1330 private void closure(Type t, Map<TypeSymbol,Type> typeMap) { 1331 if (t.tag != CLASS) return; 1332 if (typeMap.put(t.tsym, t) == null) { 1333 closure(types.supertype(t), typeMap); 1334 for (Type i : types.interfaces(t)) 1335 closure(i, typeMap); 1336 } 1337 } 1338 1339 /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */ 1340 private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) { 1341 if (t.tag != CLASS) return; 1342 if (typesSkip.get(t.tsym) != null) return; 1343 if (typeMap.put(t.tsym, t) == null) { 1344 closure(types.supertype(t), typesSkip, typeMap); 1345 for (Type i : types.interfaces(t)) 1346 closure(i, typesSkip, typeMap); 1347 } 1348 } 1349 1350 /** Return the first method in t2 that conflicts with a method from t1. */ 1351 private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) { 1352 for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) { 1353 Symbol s1 = e1.sym; 1354 Type st1 = null; 1355 if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue; 1356 Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false); 1357 if (impl != null && (impl.flags() & ABSTRACT) == 0) continue; 1358 for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) { 1359 Symbol s2 = e2.sym; 1360 if (s1 == s2) continue; 1361 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue; 1362 if (st1 == null) st1 = types.memberType(t1, s1); 1363 Type st2 = types.memberType(t2, s2); 1364 if (types.overrideEquivalent(st1, st2)) { 1365 List<Type> tvars1 = st1.getTypeArguments(); 1366 List<Type> tvars2 = st2.getTypeArguments(); 1367 Type rt1 = st1.getReturnType(); 1368 Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1); 1369 boolean compat = 1370 types.isSameType(rt1, rt2) || 1371 rt1.tag >= CLASS && rt2.tag >= CLASS && 1372 (types.covariantReturnType(rt1, rt2, Warner.noWarnings) || 1373 types.covariantReturnType(rt2, rt1, Warner.noWarnings)); 1374 if (!compat) return s2; 1375 } 1376 } 1377 } 1378 return null; 1379 } 1380 1381 /** Check that a given method conforms with any method it overrides. 1382 * @param tree The tree from which positions are extracted 1383 * for errors. 1384 * @param m The overriding method. 1385 */ 1386 void checkOverride(JCTree tree, MethodSymbol m) { 1387 ClassSymbol origin = (ClassSymbol)m.owner; 1388 if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) 1389 if (m.overrides(syms.enumFinalFinalize, origin, types, false)) { 1390 log.error(tree.pos(), "enum.no.finalize"); 1391 return; 1392 } 1393 for (Type t = types.supertype(origin.type); t.tag == CLASS; 1394 t = types.supertype(t)) { 1395 TypeSymbol c = t.tsym; 1396 Scope.Entry e = c.members().lookup(m.name); 1397 while (e.scope != null) { 1398 if (m.overrides(e.sym, origin, types, false)) 1399 checkOverride(tree, m, (MethodSymbol)e.sym, origin); 1400 e = e.next(); 1401 } 1402 } 1403 } 1404 1405 /** Check that all abstract members of given class have definitions. 1406 * @param pos Position to be used for error reporting. 1407 * @param c The class. 1408 */ 1409 void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) { 1410 try { 1411 MethodSymbol undef = firstUndef(c, c); 1412 if (undef != null) { 1413 if ((c.flags() & ENUM) != 0 && 1414 types.supertype(c.type).tsym == syms.enumSym && 1415 (c.flags() & FINAL) == 0) { 1416 // add the ABSTRACT flag to an enum 1417 c.flags_field |= ABSTRACT; 1418 } else { 1419 MethodSymbol undef1 = 1420 new MethodSymbol(undef.flags(), undef.name, 1421 types.memberType(c.type, undef), undef.owner); 1422 log.error(pos, "does.not.override.abstract", 1423 c, undef1, undef1.location()); 1424 } 1425 } 1426 } catch (CompletionFailure ex) { 1427 completionError(pos, ex); 1428 } 1429 } 1430 //where 1431 /** Return first abstract member of class `c' that is not defined 1432 * in `impl', null if there is none. 1433 */ 1434 private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) { 1435 MethodSymbol undef = null; 1436 // Do not bother to search in classes that are not abstract, 1437 // since they cannot have abstract members. 1438 if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) { 1439 Scope s = c.members(); 1440 for (Scope.Entry e = s.elems; 1441 undef == null && e != null; 1442 e = e.sibling) { 1443 if (e.sym.kind == MTH && 1444 (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) { 1445 MethodSymbol absmeth = (MethodSymbol)e.sym; 1446 MethodSymbol implmeth = absmeth.implementation(impl, types, true); 1447 if (implmeth == null || implmeth == absmeth) 1448 undef = absmeth; 1449 } 1450 } 1451 if (undef == null) { 1452 Type st = types.supertype(c.type); 1453 if (st.tag == CLASS) 1454 undef = firstUndef(impl, (ClassSymbol)st.tsym); 1455 } 1456 for (List<Type> l = types.interfaces(c.type); 1457 undef == null && l.nonEmpty(); 1458 l = l.tail) { 1459 undef = firstUndef(impl, (ClassSymbol)l.head.tsym); 1460 } 1461 } 1462 return undef; 1463 } 1464 1465 /** Check for cyclic references. Issue an error if the 1466 * symbol of the type referred to has a LOCKED flag set. 1467 * 1468 * @param pos Position to be used for error reporting. 1469 * @param t The type referred to. 1470 */ 1471 void checkNonCyclic(DiagnosticPosition pos, Type t) { 1472 checkNonCyclicInternal(pos, t); 1473 } 1474 1475 1476 void checkNonCyclic(DiagnosticPosition pos, TypeVar t) { 1477 checkNonCyclic1(pos, t, new HashSet<TypeVar>()); 1478 } 1479 1480 private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) { 1481 final TypeVar tv; 1482 if (seen.contains(t)) { 1483 tv = (TypeVar)t; 1484 tv.bound = new ErrorType(); 1485 log.error(pos, "cyclic.inheritance", t); 1486 } else if (t.tag == TYPEVAR) { 1487 tv = (TypeVar)t; 1488 seen.add(tv); 1489 for (Type b : types.getBounds(tv)) 1490 checkNonCyclic1(pos, b, seen); 1491 } 1492 } 1493 1494 /** Check for cyclic references. Issue an error if the 1495 * symbol of the type referred to has a LOCKED flag set. 1496 * 1497 * @param pos Position to be used for error reporting. 1498 * @param t The type referred to. 1499 * @returns True if the check completed on all attributed classes 1500 */ 1501 private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) { 1502 boolean complete = true; // was the check complete? 1503 //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG 1504 Symbol c = t.tsym; 1505 if ((c.flags_field & ACYCLIC) != 0) return true; 1506 1507 if ((c.flags_field & LOCKED) != 0) { 1508 noteCyclic(pos, (ClassSymbol)c); 1509 } else if (!c.type.isErroneous()) { 1510 try { 1511 c.flags_field |= LOCKED; 1512 if (c.type.tag == CLASS) { 1513 ClassType clazz = (ClassType)c.type; 1514 if (clazz.interfaces_field != null) 1515 for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail) 1516 complete &= checkNonCyclicInternal(pos, l.head); 1517 if (clazz.supertype_field != null) { 1518 Type st = clazz.supertype_field; 1519 if (st != null && st.tag == CLASS) 1520 complete &= checkNonCyclicInternal(pos, st); 1521 } 1522 if (c.owner.kind == TYP) 1523 complete &= checkNonCyclicInternal(pos, c.owner.type); 1524 } 1525 } finally { 1526 c.flags_field &= ~LOCKED; 1527 } 1528 } 1529 if (complete) 1530 complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null; 1531 if (complete) c.flags_field |= ACYCLIC; 1532 return complete; 1533 } 1534 1535 /** Note that we found an inheritance cycle. */ 1536 private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) { 1537 log.error(pos, "cyclic.inheritance", c); 1538 for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail) 1539 l.head = new ErrorType((ClassSymbol)l.head.tsym); 1540 Type st = types.supertype(c.type); 1541 if (st.tag == CLASS) 1542 ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym); 1543 c.type = new ErrorType(c); 1544 c.flags_field |= ACYCLIC; 1545 } 1546 1547 /** Check that all methods which implement some 1548 * method conform to the method they implement. 1549 * @param tree The class definition whose members are checked. 1550 */ 1551 void checkImplementations(JCClassDecl tree) { 1552 checkImplementations(tree, tree.sym); 1553 } 1554 //where 1555 /** Check that all methods which implement some 1556 * method in `ic' conform to the method they implement. 1557 */ 1558 void checkImplementations(JCClassDecl tree, ClassSymbol ic) { 1559 ClassSymbol origin = tree.sym; 1560 for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) { 1561 ClassSymbol lc = (ClassSymbol)l.head.tsym; 1562 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) { 1563 for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) { 1564 if (e.sym.kind == MTH && 1565 (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) { 1566 MethodSymbol absmeth = (MethodSymbol)e.sym; 1567 MethodSymbol implmeth = absmeth.implementation(origin, types, false); 1568 if (implmeth != null && implmeth != absmeth && 1569 (implmeth.owner.flags() & INTERFACE) == 1570 (origin.flags() & INTERFACE)) { 1571 // don't check if implmeth is in a class, yet 1572 // origin is an interface. This case arises only 1573 // if implmeth is declared in Object. The reason is 1574 // that interfaces really don't inherit from 1575 // Object it's just that the compiler represents 1576 // things that way. 1577 checkOverride(tree, implmeth, absmeth, origin); 1578 } 1579 } 1580 } 1581 } 1582 } 1583 } 1584 1585 /** Check that all abstract methods implemented by a class are 1586 * mutually compatible. 1587 * @param pos Position to be used for error reporting. 1588 * @param c The class whose interfaces are checked. 1589 */ 1590 void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) { 1591 List<Type> supertypes = types.interfaces(c); 1592 Type supertype = types.supertype(c); 1593 if (supertype.tag == CLASS && 1594 (supertype.tsym.flags() & ABSTRACT) != 0) 1595 supertypes = supertypes.prepend(supertype); 1596 for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) { 1597 if (allowGenerics && !l.head.getTypeArguments().isEmpty() && 1598 !checkCompatibleAbstracts(pos, l.head, l.head, c)) 1599 return; 1600 for (List<Type> m = supertypes; m != l; m = m.tail) 1601 if (!checkCompatibleAbstracts(pos, l.head, m.head, c)) 1602 return; 1603 } 1604 checkCompatibleConcretes(pos, c); 1605 } 1606 1607 /** Check that class c does not implement directly or indirectly 1608 * the same parameterized interface with two different argument lists. 1609 * @param pos Position to be used for error reporting. 1610 * @param type The type whose interfaces are checked. 1611 */ 1612 void checkClassBounds(DiagnosticPosition pos, Type type) { 1613 checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type); 1614 } 1615 //where 1616 /** Enter all interfaces of type `type' into the hash table `seensofar' 1617 * with their class symbol as key and their type as value. Make 1618 * sure no class is entered with two different types. 1619 */ 1620 void checkClassBounds(DiagnosticPosition pos, 1621 Map<TypeSymbol,Type> seensofar, 1622 Type type) { 1623 if (type.isErroneous()) return; 1624 for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) { 1625 Type it = l.head; 1626 Type oldit = seensofar.put(it.tsym, it); 1627 if (oldit != null) { 1628 List<Type> oldparams = oldit.allparams(); 1629 List<Type> newparams = it.allparams(); 1630 if (!types.containsTypeEquivalent(oldparams, newparams)) 1631 log.error(pos, "cant.inherit.diff.arg", 1632 it.tsym, Type.toString(oldparams), 1633 Type.toString(newparams)); 1634 } 1635 checkClassBounds(pos, seensofar, it); 1636 } 1637 Type st = types.supertype(type); 1638 if (st != null) checkClassBounds(pos, seensofar, st); 1639 } 1640 1641 /** Enter interface into into set. 1642 * If it existed already, issue a "repeated interface" error. 1643 */ 1644 void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) { 1645 if (its.contains(it)) 1646 log.error(pos, "repeated.interface"); 1647 else { 1648 its.add(it); 1649 } 1650 } 1651 1652 /* ************************************************************************* 1653 * Check annotations 1654 **************************************************************************/ 1655 1656 /** Annotation types are restricted to primitives, String, an 1657 * enum, an annotation, Class, Class<?>, Class<? extends 1658 * Anything>, arrays of the preceding. 1659 */ 1660 void validateAnnotationType(JCTree restype) { 1661 // restype may be null if an error occurred, so don't bother validating it 1662 if (restype != null) { 1663 validateAnnotationType(restype.pos(), restype.type); 1664 } 1665 } 1666 1667 void validateAnnotationType(DiagnosticPosition pos, Type type) { 1668 if (type.isPrimitive()) return; 1669 if (types.isSameType(type, syms.stringType)) return; 1670 if ((type.tsym.flags() & Flags.ENUM) != 0) return; 1671 if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return; 1672 if (types.lowerBound(type).tsym == syms.classType.tsym) return; 1673 if (types.isArray(type) && !types.isArray(types.elemtype(type))) { 1674 validateAnnotationType(pos, types.elemtype(type)); 1675 return; 1676 } 1677 log.error(pos, "invalid.annotation.member.type"); 1678 } 1679 1680 /** 1681 * "It is also a compile-time error if any method declared in an 1682 * annotation type has a signature that is override-equivalent to 1683 * that of any public or protected method declared in class Object 1684 * or in the interface annotation.Annotation." 1685 * 1686 * @jls3 9.6 Annotation Types 1687 */ 1688 void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) { 1689 for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) { 1690 Scope s = sup.tsym.members(); 1691 for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) { 1692 if (e.sym.kind == MTH && 1693 (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 && 1694 types.overrideEquivalent(m.type, e.sym.type)) 1695 log.error(pos, "intf.annotation.member.clash", e.sym, sup); 1696 } 1697 } 1698 } 1699 1700 /** Check the annotations of a symbol. 1701 */ 1702 public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) { 1703 if (skipAnnotations) return; 1704 for (JCAnnotation a : annotations) 1705 validateAnnotation(a, s); 1706 } 1707 1708 /** Check an annotation of a symbol. 1709 */ 1710 public void validateAnnotation(JCAnnotation a, Symbol s) { 1711 validateAnnotation(a); 1712 1713 if (!annotationApplicable(a, s)) 1714 log.error(a.pos(), "annotation.type.not.applicable"); 1715 1716 if (a.annotationType.type.tsym == syms.overrideType.tsym) { 1717 if (!isOverrider(s)) 1718 log.error(a.pos(), "method.does.not.override.superclass"); 1719 } 1720 } 1721 1722 /** Is s a method symbol that overrides a method in a superclass? */ 1723 boolean isOverrider(Symbol s) { 1724 if (s.kind != MTH || s.isStatic()) 1725 return false; 1726 MethodSymbol m = (MethodSymbol)s; 1727 TypeSymbol owner = (TypeSymbol)m.owner; 1728 for (Type sup : types.closure(owner.type)) { 1729 if (sup == owner.type) 1730 continue; // skip "this" 1731 Scope scope = sup.tsym.members(); 1732 for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) { 1733 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true)) 1734 return true; 1735 } 1736 } 1737 return false; 1738 } 1739 1740 /** Is the annotation applicable to the symbol? */ 1741 boolean annotationApplicable(JCAnnotation a, Symbol s) { 1742 Attribute.Compound atTarget = 1743 a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym); 1744 if (atTarget == null) return true; 1745 Attribute atValue = atTarget.member(names.value); 1746 if (!(atValue instanceof Attribute.Array)) return true; // error recovery 1747 Attribute.Array arr = (Attribute.Array) atValue; 1748 for (Attribute app : arr.values) { 1749 if (!(app instanceof Attribute.Enum)) return true; // recovery 1750 Attribute.Enum e = (Attribute.Enum) app; 1751 if (e.value.name == names.TYPE) 1752 { if (s.kind == TYP) return true; } 1753 else if (e.value.name == names.FIELD) 1754 { if (s.kind == VAR && s.owner.kind != MTH) return true; } 1755 else if (e.value.name == names.METHOD) 1756 { if (s.kind == MTH && !s.isConstructor()) return true; } 1757 else if (e.value.name == names.PARAMETER) 1758 { if (s.kind == VAR && 1759 s.owner.kind == MTH && 1760 (s.flags() & PARAMETER) != 0) 1761 return true; 1762 } 1763 else if (e.value.name == names.CONSTRUCTOR) 1764 { if (s.kind == MTH && s.isConstructor()) return true; } 1765 else if (e.value.name == names.LOCAL_VARIABLE) 1766 { if (s.kind == VAR && s.owner.kind == MTH && 1767 (s.flags() & PARAMETER) == 0) 1768 return true; 1769 } 1770 else if (e.value.name == names.ANNOTATION_TYPE) 1771 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) 1772 return true; 1773 } 1774 else if (e.value.name == names.PACKAGE) 1775 { if (s.kind == PCK) return true; } 1776 else 1777 return true; // recovery 1778 } 1779 return false; 1780 } 1781 1782 /** Check an annotation value. 1783 */ 1784 public void validateAnnotation(JCAnnotation a) { 1785 if (a.type.isErroneous()) return; 1786 1787 // collect an inventory of the members 1788 Set<MethodSymbol> members = new HashSet<MethodSymbol>(); 1789 for (Scope.Entry e = a.annotationType.type.tsym.members().elems; 1790 e != null; 1791 e = e.sibling) 1792 if (e.sym.kind == MTH) 1793 members.add((MethodSymbol) e.sym); 1794 1795 // count them off as they're annotated 1796 for (JCTree arg : a.args) { 1797 if (arg.getTag() != JCTree.ASSIGN) continue; // recovery 1798 JCAssign assign = (JCAssign) arg; 1799 Symbol m = TreeInfo.symbol(assign.lhs); 1800 if (m == null || m.type.isErroneous()) continue; 1801 if (!members.remove(m)) 1802 log.error(arg.pos(), "duplicate.annotation.member.value", 1803 m.name, a.type); 1804 if (assign.rhs.getTag() == ANNOTATION) 1805 validateAnnotation((JCAnnotation)assign.rhs); 1806 } 1807 1808 // all the remaining ones better have default values 1809 for (MethodSymbol m : members) 1810 if (m.defaultValue == null && !m.type.isErroneous()) 1811 log.error(a.pos(), "annotation.missing.default.value", 1812 a.type, m.name); 1813 1814 // special case: java.lang.annotation.Target must not have 1815 // repeated values in its value member 1816 if (a.annotationType.type.tsym != syms.annotationTargetType.tsym || 1817 a.args.tail == null) 1818 return; 1819 1820 if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery 1821 JCAssign assign = (JCAssign) a.args.head; 1822 Symbol m = TreeInfo.symbol(assign.lhs); 1823 if (m.name != names.value) return; 1824 JCTree rhs = assign.rhs; 1825 if (rhs.getTag() != JCTree.NEWARRAY) return; 1826 JCNewArray na = (JCNewArray) rhs; 1827 Set<Symbol> targets = new HashSet<Symbol>(); 1828 for (JCTree elem : na.elems) { 1829 if (!targets.add(TreeInfo.symbol(elem))) { 1830 log.error(elem.pos(), "repeated.annotation.target"); 1831 } 1832 } 1833 } 1834 1835 void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) { 1836 if (allowAnnotations && 1837 lint.isEnabled(Lint.LintCategory.DEP_ANN) && 1838 (s.flags() & DEPRECATED) != 0 && 1839 !syms.deprecatedType.isErroneous() && 1840 s.attribute(syms.deprecatedType.tsym) == null) { 1841 log.warning(pos, "missing.deprecated.annotation"); 1842 } 1843 } 1844 1845 /* ************************************************************************* 1846 * Check for recursive annotation elements. 1847 **************************************************************************/ 1848 1849 /** Check for cycles in the graph of annotation elements. 1850 */ 1851 void checkNonCyclicElements(JCClassDecl tree) { 1852 if ((tree.sym.flags_field & ANNOTATION) == 0) return; 1853 assert (tree.sym.flags_field & LOCKED) == 0; 1854 try { 1855 tree.sym.flags_field |= LOCKED; 1856 for (JCTree def : tree.defs) { 1857 if (def.getTag() != JCTree.METHODDEF) continue; 1858 JCMethodDecl meth = (JCMethodDecl)def; 1859 checkAnnotationResType(meth.pos(), meth.restype.type); 1860 } 1861 } finally { 1862 tree.sym.flags_field &= ~LOCKED; 1863 tree.sym.flags_field |= ACYCLIC_ANN; 1864 } 1865 } 1866 1867 void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) { 1868 if ((tsym.flags_field & ACYCLIC_ANN) != 0) 1869 return; 1870 if ((tsym.flags_field & LOCKED) != 0) { 1871 log.error(pos, "cyclic.annotation.element"); 1872 return; 1873 } 1874 try { 1875 tsym.flags_field |= LOCKED; 1876 for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) { 1877 Symbol s = e.sym; 1878 if (s.kind != Kinds.MTH) 1879 continue; 1880 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType()); 1881 } 1882 } finally { 1883 tsym.flags_field &= ~LOCKED; 1884 tsym.flags_field |= ACYCLIC_ANN; 1885 } 1886 } 1887 1888 void checkAnnotationResType(DiagnosticPosition pos, Type type) { 1889 switch (type.tag) { 1890 case TypeTags.CLASS: 1891 if ((type.tsym.flags() & ANNOTATION) != 0) 1892 checkNonCyclicElementsInternal(pos, type.tsym); 1893 break; 1894 case TypeTags.ARRAY: 1895 checkAnnotationResType(pos, types.elemtype(type)); 1896 break; 1897 default: 1898 break; // int etc 1899 } 1900 } 1901 1902 /* ************************************************************************* 1903 * Check for cycles in the constructor call graph. 1904 **************************************************************************/ 1905 1906 /** Check for cycles in the graph of constructors calling other 1907 * constructors. 1908 */ 1909 void checkCyclicConstructors(JCClassDecl tree) { 1910 Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>(); 1911 1912 // enter each constructor this-call into the map 1913 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 1914 JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head); 1915 if (app == null) continue; 1916 JCMethodDecl meth = (JCMethodDecl) l.head; 1917 if (TreeInfo.name(app.meth) == names._this) { 1918 callMap.put(meth.sym, TreeInfo.symbol(app.meth)); 1919 } else { 1920 meth.sym.flags_field |= ACYCLIC; 1921 } 1922 } 1923 1924 // Check for cycles in the map 1925 Symbol[] ctors = new Symbol[0]; 1926 ctors = callMap.keySet().toArray(ctors); 1927 for (Symbol caller : ctors) { 1928 checkCyclicConstructor(tree, caller, callMap); 1929 } 1930 } 1931 1932 /** Look in the map to see if the given constructor is part of a 1933 * call cycle. 1934 */ 1935 private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor, 1936 Map<Symbol,Symbol> callMap) { 1937 if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) { 1938 if ((ctor.flags_field & LOCKED) != 0) { 1939 log.error(TreeInfo.diagnosticPositionFor(ctor, tree), 1940 "recursive.ctor.invocation"); 1941 } else { 1942 ctor.flags_field |= LOCKED; 1943 checkCyclicConstructor(tree, callMap.remove(ctor), callMap); 1944 ctor.flags_field &= ~LOCKED; 1945 } 1946 ctor.flags_field |= ACYCLIC; 1947 } 1948 } 1949 1950 /* ************************************************************************* 1951 * Miscellaneous 1952 **************************************************************************/ 1953 1954 /** 1955 * Return the opcode of the operator but emit an error if it is an 1956 * error. 1957 * @param pos position for error reporting. 1958 * @param operator an operator 1959 * @param tag a tree tag 1960 * @param left type of left hand side 1961 * @param right type of right hand side 1962 */ 1963 int checkOperator(DiagnosticPosition pos, 1964 OperatorSymbol operator, 1965 int tag, 1966 Type left, 1967 Type right) { 1968 if (operator.opcode == ByteCodes.error) { 1969 log.error(pos, 1970 "operator.cant.be.applied", 1971 treeinfo.operatorName(tag), 1972 left + "," + right); 1973 } 1974 return operator.opcode; 1975 } 1976 1977 1978 /** 1979 * Check for division by integer constant zero 1980 * @param pos Position for error reporting. 1981 * @param operator The operator for the expression 1982 * @param operand The right hand operand for the expression 1983 */ 1984 void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) { 1985 if (operand.constValue() != null 1986 && lint.isEnabled(Lint.LintCategory.DIVZERO) 1987 && operand.tag <= LONG 1988 && ((Number) (operand.constValue())).longValue() == 0) { 1989 int opc = ((OperatorSymbol)operator).opcode; 1990 if (opc == ByteCodes.idiv || opc == ByteCodes.imod 1991 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) { 1992 log.warning(pos, "div.zero"); 1993 } 1994 } 1995 } 1996 1997 /** 1998 * Check for empty statements after if 1999 */ 2000 void checkEmptyIf(JCIf tree) { 2001 if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY)) 2002 log.warning(tree.thenpart.pos(), "empty.if"); 2003 } 2004 2005 /** Check that symbol is unique in given scope. 2006 * @param pos Position for error reporting. 2007 * @param sym The symbol. 2008 * @param s The scope. 2009 */ 2010 boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) { 2011 if (sym.type.isErroneous()) 2012 return true; 2013 if (sym.owner.name == names.any) return false; 2014 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) { 2015 if (sym != e.sym && 2016 sym.kind == e.sym.kind && 2017 sym.name != names.error && 2018 (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) { 2019 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) 2020 varargsDuplicateError(pos, sym, e.sym); 2021 else 2022 duplicateError(pos, e.sym); 2023 return false; 2024 } 2025 } 2026 return true; 2027 } 2028 2029 /** Check that single-type import is not already imported or top-level defined, 2030 * but make an exception for two single-type imports which denote the same type. 2031 * @param pos Position for error reporting. 2032 * @param sym The symbol. 2033 * @param s The scope 2034 */ 2035 boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) { 2036 return checkUniqueImport(pos, sym, s, false); 2037 } 2038 2039 /** Check that static single-type import is not already imported or top-level defined, 2040 * but make an exception for two single-type imports which denote the same type. 2041 * @param pos Position for error reporting. 2042 * @param sym The symbol. 2043 * @param s The scope 2044 * @param staticImport Whether or not this was a static import 2045 */ 2046 boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) { 2047 return checkUniqueImport(pos, sym, s, true); 2048 } 2049 2050 /** Check that single-type import is not already imported or top-level defined, 2051 * but make an exception for two single-type imports which denote the same type. 2052 * @param pos Position for error reporting. 2053 * @param sym The symbol. 2054 * @param s The scope. 2055 * @param staticImport Whether or not this was a static import 2056 */ 2057 private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) { 2058 for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) { 2059 // is encountered class entered via a class declaration? 2060 boolean isClassDecl = e.scope == s; 2061 if ((isClassDecl || sym != e.sym) && 2062 sym.kind == e.sym.kind && 2063 sym.name != names.error) { 2064 if (!e.sym.type.isErroneous()) { 2065 String what = e.sym.toString(); 2066 if (!isClassDecl) { 2067 if (staticImport) 2068 log.error(pos, "already.defined.static.single.import", what); 2069 else 2070 log.error(pos, "already.defined.single.import", what); 2071 } 2072 else if (sym != e.sym) 2073 log.error(pos, "already.defined.this.unit", what); 2074 } 2075 return false; 2076 } 2077 } 2078 return true; 2079 } 2080 2081 /** Check that a qualified name is in canonical form (for import decls). 2082 */ 2083 public void checkCanonical(JCTree tree) { 2084 if (!isCanonical(tree)) 2085 log.error(tree.pos(), "import.requires.canonical", 2086 TreeInfo.symbol(tree)); 2087 } 2088 // where 2089 private boolean isCanonical(JCTree tree) { 2090 while (tree.getTag() == JCTree.SELECT) { 2091 JCFieldAccess s = (JCFieldAccess) tree; 2092 if (s.sym.owner != TreeInfo.symbol(s.selected)) 2093 return false; 2094 tree = s.selected; 2095 } 2096 return true; 2097 } 2098 2099 private class ConversionWarner extends Warner { 2100 final String key; 2101 final Type found; 2102 final Type expected; 2103 public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) { 2104 super(pos); 2105 this.key = key; 2106 this.found = found; 2107 this.expected = expected; 2108 } 2109 2110 public void warnUnchecked() { 2111 boolean warned = this.warned; 2112 super.warnUnchecked(); 2113 if (warned) return; // suppress redundant diagnostics 2114 Object problem = JCDiagnostic.fragment(key); 2115 Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected); 2116 } 2117 } 2118 2119 public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) { 2120 return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected); 2121 } 2122 2123 public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) { 2124 return new ConversionWarner(pos, "unchecked.assign", found, expected); 2125 } 2126 }