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