001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018/////////////////////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import java.util.HashSet; 023import java.util.Locale; 024import java.util.Objects; 025import java.util.Set; 026import java.util.regex.Pattern; 027 028import javax.annotation.Nullable; 029 030import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 031import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 032import com.puppycrawl.tools.checkstyle.api.DetailAST; 033import com.puppycrawl.tools.checkstyle.api.Scope; 034import com.puppycrawl.tools.checkstyle.api.TokenTypes; 035import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 036import com.puppycrawl.tools.checkstyle.utils.ScopeUtil; 037import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 038 039/** 040 * <div> 041 * Checks that a local variable or a parameter does not shadow 042 * a field that is defined in the same class. 043 * </div> 044 * 045 * <p> 046 * Notes: 047 * It is possible to configure the check to ignore all property setter methods. 048 * </p> 049 * 050 * <p> 051 * A method is recognized as a setter if it is in the following form 052 * </p> 053 * {@snippet lang="text" : 054 * ${returnType} set${Name}(${anyType} ${name}) { ... } 055 * } 056 * 057 * <p> 058 * where ${anyType} is any primitive type, class or interface name; 059 * ${name} is name of the variable that is being set and ${Name} its 060 * capitalized form that appears in the method name. By default, it is expected 061 * that setter returns void, i.e. ${returnType} is 'void'. For example 062 * </p> 063 * {@snippet lang="text" : 064 * void setTime(long time) { } 065 * } 066 * 067 * <p> 068 * Any other return types will not let method match a setter pattern. However, 069 * by setting <em>setterCanReturnItsClass</em> property to <em>true</em> 070 * definition of a setter is expanded, so that setter return type can also be 071 * a class in which setter is declared. For example 072 * </p> 073 * {@snippet lang="text" : 074 * class PageBuilder { 075 * PageBuilder setName(String name) { } 076 * } 077 * } 078 * 079 * <p> 080 * Such methods are known as chain-setters and a common when Builder-pattern 081 * is used. Property <em>setterCanReturnItsClass</em> has effect only if 082 * <em>ignoreSetter</em> is set to true. 083 * </p> 084 * 085 * @since 3.0 086 */ 087@FileStatefulCheck 088public class HiddenFieldCheck extends AbstractCheck { 089 090 /** 091 * A key is pointing to the warning message text in "messages.properties" file. 092 */ 093 public static final String MSG_KEY = "hidden.field"; 094 095 /** 096 * Stack of sets of field names, 097 * one for each class of a set of nested classes. 098 */ 099 private FieldFrame frame; 100 101 /** Define the RegExp for names of variables and parameters to ignore. */ 102 private Pattern ignoreFormat; 103 104 /** 105 * Allow to ignore the parameter of a property setter method. 106 */ 107 private boolean ignoreSetter; 108 109 /** 110 * Allow to expand the definition of a setter method to include methods 111 * that return the class' instance. 112 */ 113 private boolean setterCanReturnItsClass; 114 115 /** Control whether to ignore constructor parameters. */ 116 private boolean ignoreConstructorParameter; 117 118 /** Control whether to ignore parameters of abstract methods. */ 119 private boolean ignoreAbstractMethods; 120 121 /** 122 * Creates a new {@code HiddenFieldCheck} instance. 123 */ 124 public HiddenFieldCheck() { 125 // no code by default 126 } 127 128 @Override 129 public int[] getDefaultTokens() { 130 return getAcceptableTokens(); 131 } 132 133 @Override 134 public int[] getAcceptableTokens() { 135 return new int[] { 136 TokenTypes.VARIABLE_DEF, 137 TokenTypes.PARAMETER_DEF, 138 TokenTypes.CLASS_DEF, 139 TokenTypes.ENUM_DEF, 140 TokenTypes.ENUM_CONSTANT_DEF, 141 TokenTypes.PATTERN_VARIABLE_DEF, 142 TokenTypes.LAMBDA, 143 TokenTypes.RECORD_DEF, 144 TokenTypes.RECORD_COMPONENT_DEF, 145 TokenTypes.COMPACT_COMPILATION_UNIT, 146 }; 147 } 148 149 @Override 150 public int[] getRequiredTokens() { 151 return new int[] { 152 TokenTypes.CLASS_DEF, 153 TokenTypes.ENUM_DEF, 154 TokenTypes.ENUM_CONSTANT_DEF, 155 TokenTypes.RECORD_DEF, 156 TokenTypes.COMPACT_COMPILATION_UNIT, 157 }; 158 } 159 160 @Override 161 public void beginTree(DetailAST rootAST) { 162 frame = new FieldFrame(null, true, null); 163 } 164 165 @Override 166 public void visitToken(DetailAST ast) { 167 final int type = ast.getType(); 168 switch (type) { 169 case TokenTypes.VARIABLE_DEF, 170 TokenTypes.PARAMETER_DEF, 171 TokenTypes.PATTERN_VARIABLE_DEF, 172 TokenTypes.RECORD_COMPONENT_DEF -> processVariable(ast); 173 case TokenTypes.LAMBDA -> processLambda(ast); 174 default -> visitOtherTokens(ast, type); 175 } 176 } 177 178 /** 179 * Process a lambda token. 180 * Checks whether a lambda parameter shadows a field. 181 * Note, that when parameter of lambda expression is untyped, 182 * ANTLR parses the parameter as an identifier. 183 * 184 * @param ast the lambda token. 185 */ 186 private void processLambda(DetailAST ast) { 187 final DetailAST firstChild = ast.getFirstChild(); 188 if (TokenUtil.isOfType(firstChild, TokenTypes.IDENT)) { 189 final String untypedLambdaParameterName = firstChild.getText(); 190 if (frame.containsStaticField(untypedLambdaParameterName) 191 || isInstanceField(firstChild, untypedLambdaParameterName)) { 192 log(firstChild, MSG_KEY, untypedLambdaParameterName); 193 } 194 } 195 } 196 197 /** 198 * Called to process tokens other than {@link TokenTypes#VARIABLE_DEF} 199 * and {@link TokenTypes#PARAMETER_DEF}. 200 * 201 * @param ast token to process 202 * @param type type of the token 203 */ 204 private void visitOtherTokens(DetailAST ast, int type) { 205 // A more thorough check of enum constant class bodies is 206 // possible (checking for hidden fields against the enum 207 // class body in addition to enum constant class bodies) 208 // but not attempted as it seems out of the scope of this 209 // check. 210 final boolean isStaticInnerType = isStaticInnerType(ast); 211 final String frameName; 212 213 if (type == TokenTypes.CLASS_DEF 214 || type == TokenTypes.ENUM_DEF) { 215 frameName = ast.findFirstToken(TokenTypes.IDENT).getText(); 216 } 217 else { 218 frameName = null; 219 } 220 final FieldFrame newFrame = new FieldFrame(frame, isStaticInnerType, frameName); 221 222 // add fields to container 223 final DetailAST objBlock = getFieldContainer(ast); 224 // enum constants may not have bodies 225 if (objBlock != null) { 226 DetailAST child = objBlock.getFirstChild(); 227 while (child != null) { 228 if (child.getType() == TokenTypes.VARIABLE_DEF) { 229 final String name = 230 child.findFirstToken(TokenTypes.IDENT).getText(); 231 final DetailAST mods = 232 child.findFirstToken(TokenTypes.MODIFIERS); 233 if (mods.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { 234 newFrame.addInstanceField(name); 235 } 236 else { 237 newFrame.addStaticField(name); 238 } 239 } 240 child = child.getNextSibling(); 241 } 242 } 243 if (ast.getType() == TokenTypes.RECORD_DEF) { 244 final DetailAST recordComponents = 245 ast.findFirstToken(TokenTypes.RECORD_COMPONENTS); 246 247 // For each record component definition, we will add it to this frame. 248 TokenUtil.forEachChild(recordComponents, 249 TokenTypes.RECORD_COMPONENT_DEF, node -> { 250 final String name = node.findFirstToken(TokenTypes.IDENT).getText(); 251 newFrame.addInstanceField(name); 252 }); 253 } 254 // push container 255 frame = newFrame; 256 } 257 258 /** 259 * Checks whether a type definition is static, explicitly or implicitly. 260 * 261 * @param ast the type definition node. 262 * @return true if the type is static. 263 */ 264 private static boolean isStaticInnerType(DetailAST ast) { 265 final DetailAST typeMods = ast.findFirstToken(TokenTypes.MODIFIERS); 266 return typeMods != null 267 && typeMods.findFirstToken(TokenTypes.LITERAL_STATIC) != null 268 // inner record and enum are implicitly static 269 || ast.getType() == TokenTypes.RECORD_DEF 270 || ast.getType() == TokenTypes.ENUM_DEF 271 // member type of interface or annotation is implicitly static 272 || ScopeUtil.isInInterfaceOrAnnotationBlock(ast); 273 } 274 275 /** 276 * Gets the member container for field declaration harvesting. 277 * 278 * @param ast the type definition node. 279 * @return the member container, either the compact compilation unit 280 * itself or the OBJBLOCK child of a standard type definition. 281 */ 282 @Nullable 283 private static DetailAST getFieldContainer(DetailAST ast) { 284 final DetailAST result; 285 if (ast.getType() == TokenTypes.COMPACT_COMPILATION_UNIT) { 286 result = ast; 287 } 288 else { 289 result = ast.findFirstToken(TokenTypes.OBJBLOCK); 290 } 291 return result; 292 } 293 294 @Override 295 public void leaveToken(DetailAST ast) { 296 if (ast.getType() == TokenTypes.CLASS_DEF 297 || ast.getType() == TokenTypes.ENUM_DEF 298 || ast.getType() == TokenTypes.ENUM_CONSTANT_DEF 299 || ast.getType() == TokenTypes.RECORD_DEF) { 300 // pop 301 frame = frame.getParent(); 302 } 303 } 304 305 /** 306 * Process a variable token. 307 * Check whether a local variable or parameter shadows a field. 308 * Store a field for later comparison with local variables and parameters. 309 * 310 * @param ast the variable token. 311 */ 312 private void processVariable(DetailAST ast) { 313 if (!ScopeUtil.isInInterfaceOrAnnotationBlock(ast) 314 && !CheckUtil.isReceiverParameter(ast) 315 && (ScopeUtil.isLocalVariableDef(ast) 316 || ast.getType() == TokenTypes.PARAMETER_DEF 317 || ast.getType() == TokenTypes.PATTERN_VARIABLE_DEF)) { 318 // local variable or parameter. Does it shadow a field? 319 final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT); 320 final String name = nameAST.getText(); 321 322 if ((frame.containsStaticField(name) || isInstanceField(ast, name)) 323 && !isMatchingRegexp(name) 324 && !isIgnoredParam(ast, name)) { 325 log(nameAST, MSG_KEY, name); 326 } 327 } 328 } 329 330 /** 331 * Checks whether method or constructor parameter is ignored. 332 * 333 * @param ast the parameter token. 334 * @param name the parameter name. 335 * @return true if parameter is ignored. 336 */ 337 private boolean isIgnoredParam(DetailAST ast, String name) { 338 return isIgnoredSetterParam(ast, name) 339 || isIgnoredConstructorParam(ast) 340 || isIgnoredParamOfAbstractMethod(ast); 341 } 342 343 /** 344 * Check for instance field. 345 * 346 * @param ast token 347 * @param name identifier of token 348 * @return true if instance field 349 */ 350 private boolean isInstanceField(DetailAST ast, String name) { 351 return !isInStatic(ast) && frame.containsInstanceField(name); 352 } 353 354 /** 355 * Check name by regExp. 356 * 357 * @param name string value to check 358 * @return true is regexp is matching 359 */ 360 private boolean isMatchingRegexp(String name) { 361 return ignoreFormat != null && ignoreFormat.matcher(name).find(); 362 } 363 364 /** 365 * Determines whether an AST node is in a static method or static initializer. 366 * 367 * @param ast the node to check. 368 * @return true if ast is in a static method or a static block; 369 */ 370 private static boolean isInStatic(DetailAST ast) { 371 DetailAST parent = ast.getParent(); 372 boolean inStatic = false; 373 374 while (parent != null && !inStatic) { 375 if (parent.getType() == TokenTypes.STATIC_INIT) { 376 inStatic = true; 377 } 378 else if (parent.getType() == TokenTypes.METHOD_DEF 379 && !ScopeUtil.isInScope(parent, Scope.ANONINNER) 380 || parent.getType() == TokenTypes.VARIABLE_DEF) { 381 final DetailAST mods = 382 parent.findFirstToken(TokenTypes.MODIFIERS); 383 inStatic = mods.findFirstToken(TokenTypes.LITERAL_STATIC) != null; 384 break; 385 } 386 else { 387 parent = parent.getParent(); 388 } 389 } 390 return inStatic; 391 } 392 393 /** 394 * Decides whether to ignore an AST node that is the parameter of a 395 * setter method, where the property setter method for field 'xyz' has 396 * name 'setXyz', one parameter named 'xyz', and return type void 397 * (default behavior) or return type is name of the class in which 398 * such method is declared (allowed only if 399 * {@link #setSetterCanReturnItsClass(boolean)} is called with value <em>true</em>). 400 * 401 * @param ast the AST to check. 402 * @param name the name of ast. 403 * @return true if ast should be ignored because check property 404 * ignoreSetter is true and ast is the parameter of a setter method. 405 */ 406 private boolean isIgnoredSetterParam(DetailAST ast, String name) { 407 boolean isIgnoredSetterParam = false; 408 if (ignoreSetter) { 409 final DetailAST parametersAST = ast.getParent(); 410 final DetailAST methodAST = parametersAST.getParent(); 411 if (parametersAST.getChildCount() == 1 412 && methodAST.getType() == TokenTypes.METHOD_DEF 413 && isSetterMethod(methodAST, name)) { 414 isIgnoredSetterParam = true; 415 } 416 } 417 return isIgnoredSetterParam; 418 } 419 420 /** 421 * Determine if a specific method identified by methodAST and a single 422 * variable name parameterName is a setter. This recognition partially depends 423 * on setterCanReturnItsClass property. 424 * 425 * @param methodAST AST corresponding to a method call 426 * @param parameterName name of single parameter of this method. 427 * @return true of false indicating of method is a setter or not. 428 */ 429 private boolean isSetterMethod(DetailAST methodAST, String parameterName) { 430 final String methodName = 431 methodAST.findFirstToken(TokenTypes.IDENT).getText(); 432 boolean isSetterMethod = false; 433 434 if (("set" + capitalize(parameterName)).equals(methodName)) { 435 // method name did match set${Name}(${anyType} ${parameterName}) 436 // where ${Name} is capitalized version of ${parameterName} 437 // therefore this method is potentially a setter 438 final DetailAST typeAST = methodAST.findFirstToken(TokenTypes.TYPE); 439 final String returnType = typeAST.getFirstChild().getText(); 440 if (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) != null 441 || setterCanReturnItsClass && frame.isEmbeddedIn(returnType)) { 442 // this method has signature 443 // 444 // void set${Name}(${anyType} ${name}) 445 // 446 // and therefore considered to be a setter 447 // 448 // or 449 // 450 // return type is not void, but it is the same as the class 451 // where method is declared and setterCanReturnItsClass 452 // is set to true 453 isSetterMethod = true; 454 } 455 } 456 457 return isSetterMethod; 458 } 459 460 /** 461 * Capitalizes a given property name the way we expect to see it in a setter name. 462 * 463 * @param name a property name 464 * @return capitalized property name 465 */ 466 private static String capitalize(final String name) { 467 String setterName = name; 468 // we should not capitalize the first character if the second 469 // one is a capital one, since according to JavaBeans spec 470 // setFooBar() is a setter for FooBar property, not for fooBar one. 471 if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) { 472 setterName = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); 473 } 474 return setterName; 475 } 476 477 /** 478 * Decides whether to ignore an AST node that is the parameter of a constructor. 479 * 480 * @param ast the AST to check. 481 * @return true if ast should be ignored because check property 482 * ignoreConstructorParameter is true and ast is a constructor parameter. 483 */ 484 private boolean isIgnoredConstructorParam(DetailAST ast) { 485 boolean result = false; 486 if (ignoreConstructorParameter 487 && ast.getType() == TokenTypes.PARAMETER_DEF) { 488 final DetailAST parametersAST = ast.getParent(); 489 final DetailAST constructorAST = parametersAST.getParent(); 490 result = constructorAST.getType() == TokenTypes.CTOR_DEF; 491 } 492 return result; 493 } 494 495 /** 496 * Decides whether to ignore an AST node that is the parameter of an abstract method. 497 * 498 * @param ast the AST to check. 499 * @return true if ast should be ignored because check property 500 * ignoreAbstractMethods is true and ast is a parameter of abstract methods. 501 */ 502 private boolean isIgnoredParamOfAbstractMethod(DetailAST ast) { 503 boolean result = false; 504 if (ignoreAbstractMethods) { 505 final DetailAST method = ast.getParent().getParent(); 506 if (method.getType() == TokenTypes.METHOD_DEF) { 507 final DetailAST mods = method.findFirstToken(TokenTypes.MODIFIERS); 508 result = mods.findFirstToken(TokenTypes.ABSTRACT) != null; 509 } 510 } 511 return result; 512 } 513 514 /** 515 * Setter to define the RegExp for names of variables and parameters to ignore. 516 * 517 * @param pattern a pattern. 518 * @since 3.2 519 */ 520 public void setIgnoreFormat(Pattern pattern) { 521 ignoreFormat = pattern; 522 } 523 524 /** 525 * Setter to allow to ignore the parameter of a property setter method. 526 * 527 * @param ignoreSetter decide whether to ignore the parameter of a property setter method. 528 * @since 3.2 529 */ 530 public void setIgnoreSetter(boolean ignoreSetter) { 531 this.ignoreSetter = ignoreSetter; 532 } 533 534 /** 535 * Setter to allow to expand the definition of a setter method to include methods 536 * that return the class' instance. 537 * 538 * @param setterCanReturnItsClass if true then setter can return 539 * either void or class in which it is declared. If false then 540 * in order to be recognized as setter method (otherwise 541 * already recognized as a setter) must return void. Later is the default behavior. 542 * @since 6.3 543 */ 544 public void setSetterCanReturnItsClass( 545 boolean setterCanReturnItsClass) { 546 this.setterCanReturnItsClass = setterCanReturnItsClass; 547 } 548 549 /** 550 * Setter to control whether to ignore constructor parameters. 551 * 552 * @param ignoreConstructorParameter decide whether to ignore constructor parameters. 553 * @since 3.2 554 */ 555 public void setIgnoreConstructorParameter( 556 boolean ignoreConstructorParameter) { 557 this.ignoreConstructorParameter = ignoreConstructorParameter; 558 } 559 560 /** 561 * Setter to control whether to ignore parameters of abstract methods. 562 * 563 * @param ignoreAbstractMethods decide whether to ignore parameters of abstract methods. 564 * @since 4.0 565 */ 566 public void setIgnoreAbstractMethods( 567 boolean ignoreAbstractMethods) { 568 this.ignoreAbstractMethods = ignoreAbstractMethods; 569 } 570 571 /** 572 * Holds the names of static and instance fields of a type. 573 */ 574 private static final class FieldFrame { 575 576 /** Name of the frame, such name of the class or enum declaration. */ 577 private final String frameName; 578 579 /** Is this a static inner type. */ 580 private final boolean staticType; 581 582 /** Parent frame. */ 583 private final FieldFrame parent; 584 585 /** Set of instance field names. */ 586 private final Set<String> instanceFields = new HashSet<>(); 587 588 /** Set of static field names. */ 589 private final Set<String> staticFields = new HashSet<>(); 590 591 /** 592 * Creates new frame. 593 * 594 * @param parent parent frame. 595 * @param staticType is this a static inner type (class or enum). 596 * @param frameName name associated with the frame, which can be a 597 */ 598 private FieldFrame(FieldFrame parent, boolean staticType, String frameName) { 599 this.parent = parent; 600 this.staticType = staticType; 601 this.frameName = frameName; 602 } 603 604 /** 605 * Adds an instance field to this FieldFrame. 606 * 607 * @param field the name of the instance field. 608 */ 609 /* package */ void addInstanceField(String field) { 610 instanceFields.add(field); 611 } 612 613 /** 614 * Adds a static field to this FieldFrame. 615 * 616 * @param field the name of the instance field. 617 */ 618 /* package */ void addStaticField(String field) { 619 staticFields.add(field); 620 } 621 622 /** 623 * Determines whether this FieldFrame contains an instance field. 624 * 625 * @param field the field to check 626 * @return true if this FieldFrame contains instance field 627 */ 628 /* package */ boolean containsInstanceField(String field) { 629 FieldFrame currentParent = parent; 630 boolean contains = instanceFields.contains(field); 631 boolean isStaticType = staticType; 632 while (!isStaticType && !contains) { 633 contains = currentParent.instanceFields.contains(field); 634 isStaticType = currentParent.staticType; 635 currentParent = currentParent.parent; 636 } 637 return contains; 638 } 639 640 /** 641 * Determines whether this FieldFrame contains a static field. 642 * 643 * @param field the field to check 644 * @return true if this FieldFrame contains static field 645 */ 646 /* package */ boolean containsStaticField(String field) { 647 FieldFrame currentParent = parent; 648 boolean contains = staticFields.contains(field); 649 while (currentParent != null && !contains) { 650 contains = currentParent.staticFields.contains(field); 651 currentParent = currentParent.parent; 652 } 653 return contains; 654 } 655 656 /** 657 * Getter for parent frame. 658 * 659 * @return parent frame. 660 */ 661 /* package */ FieldFrame getParent() { 662 return parent; 663 } 664 665 /** 666 * Check if current frame is embedded in class or enum with specific name. 667 * 668 * @param classOrEnumName name of class or enum that we are looking 669 * for in the chain of field frames. 670 * 671 * @return true if current frame is embedded in class or enum with name classOrNameName 672 */ 673 private boolean isEmbeddedIn(String classOrEnumName) { 674 FieldFrame currentFrame = this; 675 boolean isEmbeddedIn = false; 676 while (currentFrame != null) { 677 if (Objects.equals(currentFrame.frameName, classOrEnumName)) { 678 isEmbeddedIn = true; 679 break; 680 } 681 currentFrame = currentFrame.parent; 682 } 683 return isEmbeddedIn; 684 } 685 686 } 687 688}