1 /////////////////////////////////////////////////////////////////////////////////////////////// 2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules. 3 // Copyright (C) 2001-2024 the original author or authors. 4 // 5 // This library is free software; you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 2.1 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library; if not, write to the Free Software 17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 18 /////////////////////////////////////////////////////////////////////////////////////////////// 19 20 package com.puppycrawl.tools.checkstyle.checks.naming; 21 22 import java.util.Arrays; 23 import java.util.HashSet; 24 import java.util.LinkedList; 25 import java.util.List; 26 import java.util.Set; 27 import java.util.stream.Collectors; 28 29 import com.puppycrawl.tools.checkstyle.StatelessCheck; 30 import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 31 import com.puppycrawl.tools.checkstyle.api.DetailAST; 32 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 33 import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 34 import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 35 36 /** 37 * <p> 38 * Validates abbreviations (consecutive capital letters) length in 39 * identifier name, it also allows to enforce camel case naming. Please read more at 40 * <a href="https://checkstyle.org/styleguides/google-java-style-20220203/javaguide.html#s5.3-camel-case"> 41 * Google Style Guide</a> to get to know how to avoid long abbreviations in names. 42 * </p> 43 * <p>'_' is considered as word separator in identifier name.</p> 44 * <p> 45 * {@code allowedAbbreviationLength} specifies how many consecutive capital letters are 46 * allowed in the identifier. 47 * A value of <i>3</i> indicates that up to 4 consecutive capital letters are allowed, 48 * one after the other, before a violation is printed. The identifier 'MyTEST' would be 49 * allowed, but 'MyTESTS' would not be. 50 * A value of <i>0</i> indicates that only 1 consecutive capital letter is allowed. This 51 * is what should be used to enforce strict camel casing. The identifier 'MyTest' would 52 * be allowed, but 'MyTEst' would not be. 53 * </p> 54 * <p> 55 * {@code ignoreFinal}, {@code ignoreStatic}, and {@code ignoreStaticFinal} 56 * control whether variables with the respective modifiers are to be ignored. 57 * Note that a variable that is both static and final will always be considered under 58 * {@code ignoreStaticFinal} only, regardless of the values of {@code ignoreFinal} 59 * and {@code ignoreStatic}. So for example if {@code ignoreStatic} is true but 60 * {@code ignoreStaticFinal} is false, then static final variables will not be ignored. 61 * </p> 62 * <ul> 63 * <li> 64 * Property {@code allowedAbbreviationLength} - Indicate the number of consecutive capital 65 * letters allowed in targeted identifiers (abbreviations in the classes, interfaces, variables 66 * and methods names, ... ). 67 * Type is {@code int}. 68 * Default value is {@code 3}. 69 * </li> 70 * <li> 71 * Property {@code allowedAbbreviations} - Specify abbreviations that must be skipped for checking. 72 * Type is {@code java.lang.String[]}. 73 * Default value is {@code ""}. 74 * </li> 75 * <li> 76 * Property {@code ignoreFinal} - Allow to skip variables with {@code final} modifier. 77 * Type is {@code boolean}. 78 * Default value is {@code true}. 79 * </li> 80 * <li> 81 * Property {@code ignoreOverriddenMethods} - Allow to ignore methods tagged with {@code @Override} 82 * annotation (that usually mean inherited name). 83 * Type is {@code boolean}. 84 * Default value is {@code true}. 85 * </li> 86 * <li> 87 * Property {@code ignoreStatic} - Allow to skip variables with {@code static} modifier. 88 * Type is {@code boolean}. 89 * Default value is {@code true}. 90 * </li> 91 * <li> 92 * Property {@code ignoreStaticFinal} - Allow to skip variables with both {@code static} and 93 * {@code final} modifiers. 94 * Type is {@code boolean}. 95 * Default value is {@code true}. 96 * </li> 97 * <li> 98 * Property {@code tokens} - tokens to check 99 * Type is {@code java.lang.String[]}. 100 * Validation type is {@code tokenSet}. 101 * Default value is: 102 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CLASS_DEF"> 103 * CLASS_DEF</a>, 104 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INTERFACE_DEF"> 105 * INTERFACE_DEF</a>, 106 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_DEF"> 107 * ENUM_DEF</a>, 108 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_DEF"> 109 * ANNOTATION_DEF</a>, 110 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_FIELD_DEF"> 111 * ANNOTATION_FIELD_DEF</a>, 112 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PARAMETER_DEF"> 113 * PARAMETER_DEF</a>, 114 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF"> 115 * VARIABLE_DEF</a>, 116 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#METHOD_DEF"> 117 * METHOD_DEF</a>, 118 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PATTERN_VARIABLE_DEF"> 119 * PATTERN_VARIABLE_DEF</a>, 120 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#RECORD_DEF"> 121 * RECORD_DEF</a>, 122 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#RECORD_COMPONENT_DEF"> 123 * RECORD_COMPONENT_DEF</a>. 124 * </li> 125 * </ul> 126 * <p> 127 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 128 * </p> 129 * <p> 130 * Violation Message Keys: 131 * </p> 132 * <ul> 133 * <li> 134 * {@code abbreviation.as.word} 135 * </li> 136 * </ul> 137 * 138 * @since 5.8 139 */ 140 @StatelessCheck 141 public class AbbreviationAsWordInNameCheck extends AbstractCheck { 142 143 /** 144 * Warning message key. 145 */ 146 public static final String MSG_KEY = "abbreviation.as.word"; 147 148 /** 149 * The default value of "allowedAbbreviationLength" option. 150 */ 151 private static final int DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH = 3; 152 153 /** 154 * Indicate the number of consecutive capital letters allowed in 155 * targeted identifiers (abbreviations in the classes, interfaces, variables 156 * and methods names, ... ). 157 */ 158 private int allowedAbbreviationLength = 159 DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH; 160 161 /** 162 * Specify abbreviations that must be skipped for checking. 163 */ 164 private Set<String> allowedAbbreviations = new HashSet<>(); 165 166 /** Allow to skip variables with {@code final} modifier. */ 167 private boolean ignoreFinal = true; 168 169 /** Allow to skip variables with {@code static} modifier. */ 170 private boolean ignoreStatic = true; 171 172 /** Allow to skip variables with both {@code static} and {@code final} modifiers. */ 173 private boolean ignoreStaticFinal = true; 174 175 /** 176 * Allow to ignore methods tagged with {@code @Override} annotation (that 177 * usually mean inherited name). 178 */ 179 private boolean ignoreOverriddenMethods = true; 180 181 /** 182 * Setter to allow to skip variables with {@code final} modifier. 183 * 184 * @param ignoreFinal 185 * Defines if ignore variables with 'final' modifier or not. 186 * @since 5.8 187 */ 188 public void setIgnoreFinal(boolean ignoreFinal) { 189 this.ignoreFinal = ignoreFinal; 190 } 191 192 /** 193 * Setter to allow to skip variables with {@code static} modifier. 194 * 195 * @param ignoreStatic 196 * Defines if ignore variables with 'static' modifier or not. 197 * @since 5.8 198 */ 199 public void setIgnoreStatic(boolean ignoreStatic) { 200 this.ignoreStatic = ignoreStatic; 201 } 202 203 /** 204 * Setter to allow to skip variables with both {@code static} and {@code final} modifiers. 205 * 206 * @param ignoreStaticFinal 207 * Defines if ignore variables with both 'static' and 'final' modifiers or not. 208 * @since 8.32 209 */ 210 public void setIgnoreStaticFinal(boolean ignoreStaticFinal) { 211 this.ignoreStaticFinal = ignoreStaticFinal; 212 } 213 214 /** 215 * Setter to allow to ignore methods tagged with {@code @Override} 216 * annotation (that usually mean inherited name). 217 * 218 * @param ignoreOverriddenMethods 219 * Defines if ignore methods with "@Override" annotation or not. 220 * @since 5.8 221 */ 222 public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) { 223 this.ignoreOverriddenMethods = ignoreOverriddenMethods; 224 } 225 226 /** 227 * Setter to indicate the number of consecutive capital letters allowed 228 * in targeted identifiers (abbreviations in the classes, interfaces, 229 * variables and methods names, ... ). 230 * 231 * @param allowedAbbreviationLength amount of allowed capital letters in 232 * abbreviation. 233 * @since 5.8 234 */ 235 public void setAllowedAbbreviationLength(int allowedAbbreviationLength) { 236 this.allowedAbbreviationLength = allowedAbbreviationLength; 237 } 238 239 /** 240 * Setter to specify abbreviations that must be skipped for checking. 241 * 242 * @param allowedAbbreviations abbreviations that must be 243 * skipped from checking. 244 * @since 5.8 245 */ 246 public void setAllowedAbbreviations(String... allowedAbbreviations) { 247 if (allowedAbbreviations != null) { 248 this.allowedAbbreviations = 249 Arrays.stream(allowedAbbreviations).collect(Collectors.toUnmodifiableSet()); 250 } 251 } 252 253 @Override 254 public int[] getDefaultTokens() { 255 return new int[] { 256 TokenTypes.CLASS_DEF, 257 TokenTypes.INTERFACE_DEF, 258 TokenTypes.ENUM_DEF, 259 TokenTypes.ANNOTATION_DEF, 260 TokenTypes.ANNOTATION_FIELD_DEF, 261 TokenTypes.PARAMETER_DEF, 262 TokenTypes.VARIABLE_DEF, 263 TokenTypes.METHOD_DEF, 264 TokenTypes.PATTERN_VARIABLE_DEF, 265 TokenTypes.RECORD_DEF, 266 TokenTypes.RECORD_COMPONENT_DEF, 267 }; 268 } 269 270 @Override 271 public int[] getAcceptableTokens() { 272 return new int[] { 273 TokenTypes.CLASS_DEF, 274 TokenTypes.INTERFACE_DEF, 275 TokenTypes.ENUM_DEF, 276 TokenTypes.ANNOTATION_DEF, 277 TokenTypes.ANNOTATION_FIELD_DEF, 278 TokenTypes.PARAMETER_DEF, 279 TokenTypes.VARIABLE_DEF, 280 TokenTypes.METHOD_DEF, 281 TokenTypes.ENUM_CONSTANT_DEF, 282 TokenTypes.PATTERN_VARIABLE_DEF, 283 TokenTypes.RECORD_DEF, 284 TokenTypes.RECORD_COMPONENT_DEF, 285 }; 286 } 287 288 @Override 289 public int[] getRequiredTokens() { 290 return CommonUtil.EMPTY_INT_ARRAY; 291 } 292 293 @Override 294 public void visitToken(DetailAST ast) { 295 if (!isIgnoreSituation(ast)) { 296 final DetailAST nameAst = ast.findFirstToken(TokenTypes.IDENT); 297 final String typeName = nameAst.getText(); 298 299 final String abbr = getDisallowedAbbreviation(typeName); 300 if (abbr != null) { 301 log(nameAst, MSG_KEY, typeName, allowedAbbreviationLength + 1); 302 } 303 } 304 } 305 306 /** 307 * Checks if it is an ignore situation. 308 * 309 * @param ast input DetailAST node. 310 * @return true if it is an ignore situation found for given input DetailAST 311 * node. 312 */ 313 private boolean isIgnoreSituation(DetailAST ast) { 314 final DetailAST modifiers = ast.getFirstChild(); 315 316 final boolean result; 317 if (ast.getType() == TokenTypes.VARIABLE_DEF) { 318 if (isInterfaceDeclaration(ast)) { 319 // field declarations in interface are static/final 320 result = ignoreStaticFinal; 321 } 322 else { 323 result = hasIgnoredModifiers(modifiers); 324 } 325 } 326 else if (ast.getType() == TokenTypes.METHOD_DEF) { 327 result = ignoreOverriddenMethods && hasOverrideAnnotation(modifiers); 328 } 329 else { 330 result = CheckUtil.isReceiverParameter(ast); 331 } 332 return result; 333 } 334 335 /** 336 * Checks if a variable is to be ignored based on its modifiers. 337 * 338 * @param modifiers modifiers of the variable to be checked 339 * @return true if there is a modifier to be ignored 340 */ 341 private boolean hasIgnoredModifiers(DetailAST modifiers) { 342 final boolean isStatic = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; 343 final boolean isFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null; 344 final boolean result; 345 if (isStatic && isFinal) { 346 result = ignoreStaticFinal; 347 } 348 else { 349 result = ignoreStatic && isStatic || ignoreFinal && isFinal; 350 } 351 return result; 352 } 353 354 /** 355 * Check that variable definition in interface or @interface definition. 356 * 357 * @param variableDefAst variable definition. 358 * @return true if variable definition(variableDefAst) is in interface 359 * or @interface definition. 360 */ 361 private static boolean isInterfaceDeclaration(DetailAST variableDefAst) { 362 boolean result = false; 363 final DetailAST astBlock = variableDefAst.getParent(); 364 final DetailAST astParent2 = astBlock.getParent(); 365 366 if (astParent2.getType() == TokenTypes.INTERFACE_DEF 367 || astParent2.getType() == TokenTypes.ANNOTATION_DEF) { 368 result = true; 369 } 370 return result; 371 } 372 373 /** 374 * Checks that the method has "@Override" annotation. 375 * 376 * @param methodModifiersAST 377 * A DetailAST nod is related to the given method modifiers 378 * (MODIFIERS type). 379 * @return true if method has "@Override" annotation. 380 */ 381 private static boolean hasOverrideAnnotation(DetailAST methodModifiersAST) { 382 boolean result = false; 383 for (DetailAST child : getChildren(methodModifiersAST)) { 384 final DetailAST annotationIdent = child.findFirstToken(TokenTypes.IDENT); 385 386 if (annotationIdent != null && "Override".equals(annotationIdent.getText())) { 387 result = true; 388 break; 389 } 390 } 391 return result; 392 } 393 394 /** 395 * Gets the disallowed abbreviation contained in given String. 396 * 397 * @param str 398 * the given String. 399 * @return the disallowed abbreviation contained in given String as a 400 * separate String. 401 */ 402 private String getDisallowedAbbreviation(String str) { 403 int beginIndex = 0; 404 boolean abbrStarted = false; 405 String result = null; 406 407 for (int index = 0; index < str.length(); index++) { 408 final char symbol = str.charAt(index); 409 410 if (Character.isUpperCase(symbol)) { 411 if (!abbrStarted) { 412 abbrStarted = true; 413 beginIndex = index; 414 } 415 } 416 else if (abbrStarted) { 417 abbrStarted = false; 418 419 final int endIndex; 420 final int allowedLength; 421 if (symbol == '_') { 422 endIndex = index; 423 allowedLength = allowedAbbreviationLength + 1; 424 } 425 else { 426 endIndex = index - 1; 427 allowedLength = allowedAbbreviationLength; 428 } 429 result = getAbbreviationIfIllegal(str, beginIndex, endIndex, allowedLength); 430 if (result != null) { 431 break; 432 } 433 beginIndex = -1; 434 } 435 } 436 // if abbreviation at the end of name (example: scaleX) 437 if (abbrStarted) { 438 final int endIndex = str.length() - 1; 439 result = getAbbreviationIfIllegal(str, beginIndex, endIndex, allowedAbbreviationLength); 440 } 441 return result; 442 } 443 444 /** 445 * Get Abbreviation if it is illegal, where {@code beginIndex} and {@code endIndex} are 446 * inclusive indexes of a sequence of consecutive upper-case characters. 447 * 448 * @param str name 449 * @param beginIndex begin index 450 * @param endIndex end index 451 * @param allowedLength maximum allowed length for Abbreviation 452 * @return the abbreviation if it is bigger than required and not in the 453 * ignore list, otherwise {@code null} 454 */ 455 private String getAbbreviationIfIllegal(String str, int beginIndex, int endIndex, 456 int allowedLength) { 457 String result = null; 458 final int abbrLength = endIndex - beginIndex; 459 if (abbrLength > allowedLength) { 460 final String abbr = getAbbreviation(str, beginIndex, endIndex); 461 if (!allowedAbbreviations.contains(abbr)) { 462 result = abbr; 463 } 464 } 465 return result; 466 } 467 468 /** 469 * Gets the abbreviation, where {@code beginIndex} and {@code endIndex} are 470 * inclusive indexes of a sequence of consecutive upper-case characters. 471 * <p> 472 * The character at {@code endIndex} is only included in the abbreviation if 473 * it is the last character in the string; otherwise it is usually the first 474 * capital in the next word. 475 * </p> 476 * <p> 477 * For example, {@code getAbbreviation("getXMLParser", 3, 6)} returns "XML" 478 * (not "XMLP"), and so does {@code getAbbreviation("parseXML", 5, 7)}. 479 * </p> 480 * 481 * @param str name 482 * @param beginIndex begin index 483 * @param endIndex end index 484 * @return the specified abbreviation 485 */ 486 private static String getAbbreviation(String str, int beginIndex, int endIndex) { 487 final String result; 488 if (endIndex == str.length() - 1) { 489 result = str.substring(beginIndex); 490 } 491 else { 492 result = str.substring(beginIndex, endIndex); 493 } 494 return result; 495 } 496 497 /** 498 * Gets all the children which are one level below on the current DetailAST 499 * parent node. 500 * 501 * @param node 502 * Current parent node. 503 * @return The list of children one level below on the current parent node. 504 */ 505 private static List<DetailAST> getChildren(final DetailAST node) { 506 final List<DetailAST> result = new LinkedList<>(); 507 DetailAST curNode = node.getFirstChild(); 508 while (curNode != null) { 509 result.add(curNode); 510 curNode = curNode.getNextSibling(); 511 } 512 return result; 513 } 514 515 }