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