001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 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.utils; 021 022import java.util.ArrayList; 023import java.util.List; 024import java.util.regex.Pattern; 025 026import antlr.collections.AST; 027import com.puppycrawl.tools.checkstyle.api.DetailAST; 028import com.puppycrawl.tools.checkstyle.api.FullIdent; 029import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030import com.puppycrawl.tools.checkstyle.checks.naming.AccessModifier; 031 032/** 033 * Contains utility methods for the checks. 034 * 035 * @author Oliver Burn 036 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 037 * @author o_sukhodolsky 038 */ 039public final class CheckUtils { 040 // constants for parseDouble() 041 /** Octal radix. */ 042 private static final int BASE_8 = 8; 043 044 /** Decimal radix. */ 045 private static final int BASE_10 = 10; 046 047 /** Hex radix. */ 048 private static final int BASE_16 = 16; 049 050 /** Maximum children allowed in setter/getter. */ 051 private static final int SETTER_GETTER_MAX_CHILDREN = 7; 052 053 /** Maximum nodes allowed in a body of setter. */ 054 private static final int SETTER_BODY_SIZE = 3; 055 056 /** Maximum nodes allowed in a body of getter. */ 057 private static final int GETTER_BODY_SIZE = 2; 058 059 /** Pattern matching underscore characters ('_'). */ 060 private static final Pattern UNDERSCORE_PATTERN = Pattern.compile("_"); 061 062 /** Pattern matching names of setter methods. */ 063 private static final Pattern SETTER_PATTERN = Pattern.compile("^set[A-Z].*"); 064 065 /** Pattern matching names of getter methods. */ 066 private static final Pattern GETTER_PATTERN = Pattern.compile("^(is|get)[A-Z].*"); 067 068 /** Prevent instances. */ 069 private CheckUtils() { 070 } 071 072 /** 073 * Creates {@code FullIdent} for given type node. 074 * @param typeAST a type node. 075 * @return {@code FullIdent} for given type. 076 */ 077 public static FullIdent createFullType(DetailAST typeAST) { 078 final DetailAST arrayDeclaratorAST = 079 typeAST.findFirstToken(TokenTypes.ARRAY_DECLARATOR); 080 final FullIdent fullType; 081 082 if (arrayDeclaratorAST == null) { 083 fullType = createFullTypeNoArrays(typeAST); 084 } 085 else { 086 fullType = createFullTypeNoArrays(arrayDeclaratorAST); 087 } 088 return fullType; 089 } 090 091 /** 092 * Tests whether a method definition AST defines an equals covariant. 093 * @param ast the method definition AST to test. 094 * Precondition: ast is a TokenTypes.METHOD_DEF node. 095 * @return true if ast defines an equals covariant. 096 */ 097 public static boolean isEqualsMethod(DetailAST ast) { 098 boolean equalsMethod = false; 099 100 if (ast.getType() == TokenTypes.METHOD_DEF) { 101 final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); 102 final boolean staticOrAbstract = modifiers.branchContains(TokenTypes.LITERAL_STATIC) 103 || modifiers.branchContains(TokenTypes.ABSTRACT); 104 105 if (!staticOrAbstract) { 106 final DetailAST nameNode = ast.findFirstToken(TokenTypes.IDENT); 107 final String name = nameNode.getText(); 108 109 if ("equals".equals(name)) { 110 // one parameter? 111 final DetailAST paramsNode = ast.findFirstToken(TokenTypes.PARAMETERS); 112 equalsMethod = paramsNode.getChildCount() == 1; 113 } 114 } 115 } 116 return equalsMethod; 117 } 118 119 /** 120 * Returns whether a token represents an ELSE as part of an ELSE / IF set. 121 * @param ast the token to check 122 * @return whether it is 123 */ 124 public static boolean isElseIf(DetailAST ast) { 125 final DetailAST parentAST = ast.getParent(); 126 127 return ast.getType() == TokenTypes.LITERAL_IF 128 && (isElse(parentAST) || isElseWithCurlyBraces(parentAST)); 129 } 130 131 /** 132 * Returns whether a token represents an ELSE. 133 * @param ast the token to check 134 * @return whether the token represents an ELSE 135 */ 136 private static boolean isElse(DetailAST ast) { 137 return ast.getType() == TokenTypes.LITERAL_ELSE; 138 } 139 140 /** 141 * Returns whether a token represents an SLIST as part of an ELSE 142 * statement. 143 * @param ast the token to check 144 * @return whether the toke does represent an SLIST as part of an ELSE 145 */ 146 private static boolean isElseWithCurlyBraces(DetailAST ast) { 147 return ast.getType() == TokenTypes.SLIST 148 && ast.getChildCount() == 2 149 && isElse(ast.getParent()); 150 } 151 152 /** 153 * @param typeAST a type node (no array) 154 * @return {@code FullIdent} for given type. 155 */ 156 private static FullIdent createFullTypeNoArrays(DetailAST typeAST) { 157 return FullIdent.createFullIdent(typeAST.getFirstChild()); 158 } 159 160 /** 161 * Returns the value represented by the specified string of the specified 162 * type. Returns 0 for types other than float, double, int, and long. 163 * @param text the string to be parsed. 164 * @param type the token type of the text. Should be a constant of 165 * {@link TokenTypes}. 166 * @return the double value represented by the string argument. 167 */ 168 public static double parseDouble(String text, int type) { 169 String txt = UNDERSCORE_PATTERN.matcher(text).replaceAll(""); 170 double result = 0; 171 switch (type) { 172 case TokenTypes.NUM_FLOAT: 173 case TokenTypes.NUM_DOUBLE: 174 result = Double.parseDouble(txt); 175 break; 176 case TokenTypes.NUM_INT: 177 case TokenTypes.NUM_LONG: 178 int radix = BASE_10; 179 if (txt.startsWith("0x") || txt.startsWith("0X")) { 180 radix = BASE_16; 181 txt = txt.substring(2); 182 } 183 else if (txt.charAt(0) == '0') { 184 radix = BASE_8; 185 txt = txt.substring(1); 186 } 187 if (CommonUtils.endsWithChar(txt, 'L') || CommonUtils.endsWithChar(txt, 'l')) { 188 txt = txt.substring(0, txt.length() - 1); 189 } 190 if (!txt.isEmpty()) { 191 if (type == TokenTypes.NUM_INT) { 192 result = parseInt(txt, radix); 193 } 194 else { 195 result = parseLong(txt, radix); 196 } 197 } 198 break; 199 default: 200 break; 201 } 202 return result; 203 } 204 205 /** 206 * Parses the string argument as a signed integer in the radix specified by 207 * the second argument. The characters in the string must all be digits of 208 * the specified radix. Handles negative values, which method 209 * java.lang.Integer.parseInt(String, int) does not. 210 * @param text the String containing the integer representation to be 211 * parsed. Precondition: text contains a parsable int. 212 * @param radix the radix to be used while parsing text. 213 * @return the integer represented by the string argument in the specified radix. 214 */ 215 private static int parseInt(String text, int radix) { 216 int result = 0; 217 final int max = text.length(); 218 for (int i = 0; i < max; i++) { 219 final int digit = Character.digit(text.charAt(i), radix); 220 result *= radix; 221 result += digit; 222 } 223 return result; 224 } 225 226 /** 227 * Parses the string argument as a signed long in the radix specified by 228 * the second argument. The characters in the string must all be digits of 229 * the specified radix. Handles negative values, which method 230 * java.lang.Integer.parseInt(String, int) does not. 231 * @param text the String containing the integer representation to be 232 * parsed. Precondition: text contains a parsable int. 233 * @param radix the radix to be used while parsing text. 234 * @return the long represented by the string argument in the specified radix. 235 */ 236 private static long parseLong(String text, int radix) { 237 long result = 0; 238 final int max = text.length(); 239 for (int i = 0; i < max; i++) { 240 final int digit = Character.digit(text.charAt(i), radix); 241 result *= radix; 242 result += digit; 243 } 244 return result; 245 } 246 247 /** 248 * Finds sub-node for given node minimal (line, column) pair. 249 * @param node the root of tree for search. 250 * @return sub-node with minimal (line, column) pair. 251 */ 252 public static DetailAST getFirstNode(final DetailAST node) { 253 DetailAST currentNode = node; 254 DetailAST child = node.getFirstChild(); 255 while (child != null) { 256 final DetailAST newNode = getFirstNode(child); 257 if (newNode.getLineNo() < currentNode.getLineNo() 258 || newNode.getLineNo() == currentNode.getLineNo() 259 && newNode.getColumnNo() < currentNode.getColumnNo()) { 260 currentNode = newNode; 261 } 262 child = child.getNextSibling(); 263 } 264 265 return currentNode; 266 } 267 268 /** 269 * Retrieves the names of the type parameters to the node. 270 * @param node the parameterized AST node 271 * @return a list of type parameter names 272 */ 273 public static List<String> getTypeParameterNames(final DetailAST node) { 274 final DetailAST typeParameters = 275 node.findFirstToken(TokenTypes.TYPE_PARAMETERS); 276 277 final List<String> typeParameterNames = new ArrayList<>(); 278 if (typeParameters != null) { 279 final DetailAST typeParam = 280 typeParameters.findFirstToken(TokenTypes.TYPE_PARAMETER); 281 typeParameterNames.add( 282 typeParam.findFirstToken(TokenTypes.IDENT).getText()); 283 284 DetailAST sibling = typeParam.getNextSibling(); 285 while (sibling != null) { 286 if (sibling.getType() == TokenTypes.TYPE_PARAMETER) { 287 typeParameterNames.add( 288 sibling.findFirstToken(TokenTypes.IDENT).getText()); 289 } 290 sibling = sibling.getNextSibling(); 291 } 292 } 293 294 return typeParameterNames; 295 } 296 297 /** 298 * Retrieves the type parameters to the node. 299 * @param node the parameterized AST node 300 * @return a list of type parameter names 301 */ 302 public static List<DetailAST> getTypeParameters(final DetailAST node) { 303 final DetailAST typeParameters = 304 node.findFirstToken(TokenTypes.TYPE_PARAMETERS); 305 306 final List<DetailAST> typeParams = new ArrayList<>(); 307 if (typeParameters != null) { 308 final DetailAST typeParam = 309 typeParameters.findFirstToken(TokenTypes.TYPE_PARAMETER); 310 typeParams.add(typeParam); 311 312 DetailAST sibling = typeParam.getNextSibling(); 313 while (sibling != null) { 314 if (sibling.getType() == TokenTypes.TYPE_PARAMETER) { 315 typeParams.add(sibling); 316 } 317 sibling = sibling.getNextSibling(); 318 } 319 } 320 321 return typeParams; 322 } 323 324 /** 325 * Returns whether an AST represents a setter method. 326 * @param ast the AST to check with 327 * @return whether the AST represents a setter method 328 */ 329 public static boolean isSetterMethod(final DetailAST ast) { 330 boolean setterMethod = false; 331 332 // Check have a method with exactly 7 children which are all that 333 // is allowed in a proper setter method which does not throw any 334 // exceptions. 335 if (ast.getType() == TokenTypes.METHOD_DEF 336 && ast.getChildCount() == SETTER_GETTER_MAX_CHILDREN) { 337 338 final DetailAST type = ast.findFirstToken(TokenTypes.TYPE); 339 final String name = type.getNextSibling().getText(); 340 final boolean matchesSetterFormat = SETTER_PATTERN.matcher(name).matches(); 341 final boolean voidReturnType = type.getChildCount(TokenTypes.LITERAL_VOID) > 0; 342 343 final DetailAST params = ast.findFirstToken(TokenTypes.PARAMETERS); 344 final boolean singleParam = params.getChildCount(TokenTypes.PARAMETER_DEF) == 1; 345 346 if (matchesSetterFormat && voidReturnType && singleParam) { 347 // Now verify that the body consists of: 348 // SLIST -> EXPR -> ASSIGN 349 // SEMI 350 // RCURLY 351 final DetailAST slist = ast.findFirstToken(TokenTypes.SLIST); 352 353 if (slist != null && slist.getChildCount() == SETTER_BODY_SIZE) { 354 final DetailAST expr = slist.getFirstChild(); 355 setterMethod = expr.getFirstChild().getType() == TokenTypes.ASSIGN; 356 } 357 } 358 } 359 return setterMethod; 360 } 361 362 /** 363 * Returns whether an AST represents a getter method. 364 * @param ast the AST to check with 365 * @return whether the AST represents a getter method 366 */ 367 public static boolean isGetterMethod(final DetailAST ast) { 368 boolean getterMethod = false; 369 370 // Check have a method with exactly 7 children which are all that 371 // is allowed in a proper getter method which does not throw any 372 // exceptions. 373 if (ast.getType() == TokenTypes.METHOD_DEF 374 && ast.getChildCount() == SETTER_GETTER_MAX_CHILDREN) { 375 376 final DetailAST type = ast.findFirstToken(TokenTypes.TYPE); 377 final String name = type.getNextSibling().getText(); 378 final boolean matchesGetterFormat = GETTER_PATTERN.matcher(name).matches(); 379 final boolean noVoidReturnType = type.getChildCount(TokenTypes.LITERAL_VOID) == 0; 380 381 final DetailAST params = ast.findFirstToken(TokenTypes.PARAMETERS); 382 final boolean noParams = params.getChildCount(TokenTypes.PARAMETER_DEF) == 0; 383 384 if (matchesGetterFormat && noVoidReturnType && noParams) { 385 // Now verify that the body consists of: 386 // SLIST -> RETURN 387 // RCURLY 388 final DetailAST slist = ast.findFirstToken(TokenTypes.SLIST); 389 390 if (slist != null && slist.getChildCount() == GETTER_BODY_SIZE) { 391 final DetailAST expr = slist.getFirstChild(); 392 getterMethod = expr.getType() == TokenTypes.LITERAL_RETURN; 393 } 394 } 395 } 396 return getterMethod; 397 } 398 399 /** 400 * Checks whether a method is a not void one. 401 * 402 * @param methodDefAst the method node. 403 * @return true if method is a not void one. 404 */ 405 public static boolean isNonVoidMethod(DetailAST methodDefAst) { 406 boolean returnValue = false; 407 if (methodDefAst.getType() == TokenTypes.METHOD_DEF) { 408 final DetailAST typeAST = methodDefAst.findFirstToken(TokenTypes.TYPE); 409 if (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null) { 410 returnValue = true; 411 } 412 } 413 return returnValue; 414 } 415 416 /** 417 * Checks whether a parameter is a receiver. 418 * 419 * @param parameterDefAst the parameter node. 420 * @return true if the parameter is a receiver. 421 */ 422 public static boolean isReceiverParameter(DetailAST parameterDefAst) { 423 boolean returnValue = false; 424 if (parameterDefAst.getType() == TokenTypes.PARAMETER_DEF 425 && parameterDefAst.findFirstToken(TokenTypes.IDENT) == null) { 426 returnValue = parameterDefAst.branchContains(TokenTypes.LITERAL_THIS); 427 } 428 return returnValue; 429 } 430 431 /** 432 * Returns {@link AccessModifier} based on the information about access modifier 433 * taken from the given token of type {@link TokenTypes#MODIFIERS}. 434 * @param modifiersToken token of type {@link TokenTypes#MODIFIERS}. 435 * @return {@link AccessModifier}. 436 */ 437 public static AccessModifier getAccessModifierFromModifiersToken(DetailAST modifiersToken) { 438 if (modifiersToken == null || modifiersToken.getType() != TokenTypes.MODIFIERS) { 439 throw new IllegalArgumentException("expected non-null AST-token with type 'MODIFIERS'"); 440 } 441 442 // default access modifier 443 AccessModifier accessModifier = AccessModifier.PACKAGE; 444 for (AST token = modifiersToken.getFirstChild(); token != null; 445 token = token.getNextSibling()) { 446 447 final int tokenType = token.getType(); 448 if (tokenType == TokenTypes.LITERAL_PUBLIC) { 449 accessModifier = AccessModifier.PUBLIC; 450 } 451 else if (tokenType == TokenTypes.LITERAL_PROTECTED) { 452 accessModifier = AccessModifier.PROTECTED; 453 } 454 else if (tokenType == TokenTypes.LITERAL_PRIVATE) { 455 accessModifier = AccessModifier.PRIVATE; 456 } 457 } 458 return accessModifier; 459 } 460}