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