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.whitespace; 021 022import java.util.Optional; 023 024import com.puppycrawl.tools.checkstyle.StatelessCheck; 025import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 026import com.puppycrawl.tools.checkstyle.api.DetailAST; 027import com.puppycrawl.tools.checkstyle.api.TokenTypes; 028import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 029 030/** 031 * <div> 032 * Checks that there is no whitespace after a token. 033 * More specifically, it checks that it is not followed by whitespace, 034 * or (if linebreaks are allowed) all characters on the line after are 035 * whitespace. To forbid linebreaks after a token, set property 036 * {@code allowLineBreaks} to {@code false}. 037 * </div> 038 * 039 * <p> 040 * The check processes 041 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ARRAY_DECLARATOR"> 042 * ARRAY_DECLARATOR</a> and 043 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INDEX_OP"> 044 * INDEX_OP</a> tokens specially from other tokens. Actually it is checked that 045 * there is no whitespace before these tokens, not after them. Space after the 046 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATIONS"> 047 * ANNOTATIONS</a> before 048 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ARRAY_DECLARATOR"> 049 * ARRAY_DECLARATOR</a> and 050 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INDEX_OP"> 051 * INDEX_OP</a> will be ignored. 052 * </p> 053 * 054 * <p> 055 * If the annotation is between the type and the array, like {@code char @NotNull [] param}, 056 * the check will skip validation for spaces. 057 * </p> 058 * 059 * <p> 060 * Note: This check processes the 061 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LITERAL_SYNCHRONIZED"> 062 * LITERAL_SYNCHRONIZED</a> token only when it appears as a part of a 063 * <a href="https://docs.oracle.com/javase/specs/jls/se19/html/jls-14.html#jls-14.19"> 064 * synchronized statement</a>, i.e. {@code synchronized(this) {}}. 065 * </p> 066 * 067 * @since 3.0 068 */ 069@StatelessCheck 070public class NoWhitespaceAfterCheck extends AbstractCheck { 071 072 /** 073 * A key is pointing to the warning message text in "messages.properties" file. 074 */ 075 public static final String MSG_KEY = "ws.followed"; 076 077 /** Control whether whitespace is allowed if the token is at a linebreak. */ 078 private boolean allowLineBreaks = true; 079 080 /** 081 * Creates a new {@code NoWhitespaceAfterCheck} instance. 082 */ 083 public NoWhitespaceAfterCheck() { 084 // no code by default 085 } 086 087 @Override 088 public int[] getDefaultTokens() { 089 return new int[] { 090 TokenTypes.ARRAY_INIT, 091 TokenTypes.AT, 092 TokenTypes.INC, 093 TokenTypes.DEC, 094 TokenTypes.UNARY_MINUS, 095 TokenTypes.UNARY_PLUS, 096 TokenTypes.BNOT, 097 TokenTypes.LNOT, 098 TokenTypes.DOT, 099 TokenTypes.ARRAY_DECLARATOR, 100 TokenTypes.INDEX_OP, 101 }; 102 } 103 104 @Override 105 public int[] getAcceptableTokens() { 106 return new int[] { 107 TokenTypes.ARRAY_INIT, 108 TokenTypes.AT, 109 TokenTypes.INC, 110 TokenTypes.DEC, 111 TokenTypes.UNARY_MINUS, 112 TokenTypes.UNARY_PLUS, 113 TokenTypes.BNOT, 114 TokenTypes.LNOT, 115 TokenTypes.DOT, 116 TokenTypes.TYPECAST, 117 TokenTypes.ARRAY_DECLARATOR, 118 TokenTypes.INDEX_OP, 119 TokenTypes.DO_WHILE, 120 TokenTypes.LITERAL_IF, 121 TokenTypes.LITERAL_SYNCHRONIZED, 122 TokenTypes.METHOD_REF, 123 TokenTypes.LITERAL_FOR, 124 TokenTypes.LITERAL_WHILE, 125 TokenTypes.LITERAL_CATCH, 126 }; 127 } 128 129 @Override 130 public int[] getRequiredTokens() { 131 return CommonUtil.EMPTY_INT_ARRAY; 132 } 133 134 /** 135 * Setter to control whether whitespace is allowed if the token is at a linebreak. 136 * 137 * @param allowLineBreaks whether whitespace should be flagged at linebreaks. 138 * @since 3.0 139 */ 140 public void setAllowLineBreaks(boolean allowLineBreaks) { 141 this.allowLineBreaks = allowLineBreaks; 142 } 143 144 @Override 145 public void visitToken(DetailAST ast) { 146 if (shouldCheckWhitespaceAfter(ast)) { 147 final DetailAST whitespaceFollowedAst = getWhitespaceFollowedNode(ast); 148 final int whitespaceColumnNo = getPositionAfter(whitespaceFollowedAst); 149 final int whitespaceLineNo = whitespaceFollowedAst.getLineNo(); 150 151 if (hasTrailingWhitespace(ast, whitespaceColumnNo, whitespaceLineNo)) { 152 log(ast, MSG_KEY, whitespaceFollowedAst.getText()); 153 } 154 } 155 } 156 157 /** 158 * For a visited ast node returns node that should be checked 159 * for not being followed by whitespace. 160 * 161 * @param ast 162 * , visited node. 163 * @return node before ast. 164 */ 165 private static DetailAST getWhitespaceFollowedNode(DetailAST ast) { 166 return switch (ast.getType()) { 167 case TokenTypes.TYPECAST -> ast.findFirstToken(TokenTypes.RPAREN); 168 case TokenTypes.ARRAY_DECLARATOR -> getArrayDeclaratorPreviousElement(ast); 169 case TokenTypes.INDEX_OP -> getIndexOpPreviousElement(ast); 170 default -> ast; 171 }; 172 } 173 174 /** 175 * Returns whether whitespace after a visited node should be checked. For example, whitespace 176 * is not allowed between a type and an array declarator (returns true), except when there is 177 * an annotation in between the type and array declarator (returns false). 178 * 179 * @param ast the visited node 180 * @return true if whitespace after ast should be checked 181 */ 182 private static boolean shouldCheckWhitespaceAfter(DetailAST ast) { 183 final DetailAST previousSibling = ast.getPreviousSibling(); 184 final boolean isSynchronizedMethod = ast.getType() == TokenTypes.LITERAL_SYNCHRONIZED 185 && ast.getFirstChild() == null; 186 return !isSynchronizedMethod 187 && (previousSibling == null || previousSibling.getType() != TokenTypes.ANNOTATIONS); 188 } 189 190 /** 191 * Gets position after token (place of possible redundant whitespace). 192 * 193 * @param ast Node representing token. 194 * @return position after token. 195 */ 196 private static int getPositionAfter(DetailAST ast) { 197 final int after; 198 // If target of possible redundant whitespace is in method definition. 199 if (ast.getType() == TokenTypes.IDENT 200 && ast.getNextSibling() != null 201 && ast.getNextSibling().getType() == TokenTypes.LPAREN) { 202 final DetailAST methodDef = ast.getParent(); 203 final DetailAST endOfParams = methodDef.findFirstToken(TokenTypes.RPAREN); 204 after = endOfParams.getColumnNo() + 1; 205 } 206 else { 207 after = ast.getColumnNo() + ast.getText().length(); 208 } 209 return after; 210 } 211 212 /** 213 * Checks if there is unwanted whitespace after the visited node. 214 * 215 * @param ast 216 * , visited node. 217 * @param whitespaceColumnNo 218 * , column number of a possible whitespace. 219 * @param whitespaceLineNo 220 * , line number of a possible whitespace. 221 * @return true if whitespace found. 222 */ 223 private boolean hasTrailingWhitespace(DetailAST ast, 224 int whitespaceColumnNo, int whitespaceLineNo) { 225 final boolean result; 226 final int astLineNo = ast.getLineNo(); 227 final int[] line = getLineCodePoints(astLineNo - 1); 228 if (astLineNo == whitespaceLineNo && whitespaceColumnNo < line.length) { 229 result = CommonUtil.isCodePointWhitespace(line, whitespaceColumnNo); 230 } 231 else { 232 result = !allowLineBreaks; 233 } 234 return result; 235 } 236 237 /** 238 * Returns proper argument for getPositionAfter method, it is a token after 239 * {@link TokenTypes#ARRAY_DECLARATOR ARRAY_DECLARATOR}, in can be {@link TokenTypes#RBRACK 240 * RBRACK}, {@link TokenTypes#IDENT IDENT} or an array type definition (literal). 241 * 242 * @param ast 243 * , {@code TokenTypes#ARRAY_DECLARATOR ARRAY_DECLARATOR} node. 244 * @return previous node by text order. 245 * @throws IllegalStateException if an unexpected token type is encountered. 246 */ 247 private static DetailAST getArrayDeclaratorPreviousElement(DetailAST ast) { 248 final DetailAST previousElement; 249 250 if (ast.getPreviousSibling() != null 251 && ast.getPreviousSibling().getType() == TokenTypes.ARRAY_DECLARATOR) { 252 // Covers higher dimension array declarations and initializations 253 previousElement = getPreviousElementOfMultiDimArray(ast); 254 } 255 else { 256 // First array index, is preceded with identifier or type 257 final DetailAST parent = ast.getParent(); 258 259 previousElement = switch (parent.getType()) { 260 // Generics 261 case TokenTypes.TYPE_UPPER_BOUNDS, TokenTypes.TYPE_LOWER_BOUNDS -> 262 ast.getPreviousSibling(); 263 264 case TokenTypes.LITERAL_NEW, TokenTypes.TYPE_ARGUMENT, TokenTypes.DOT -> 265 getTypeLastNode(ast); 266 267 // Mundane array declaration, can be either Java style or C style 268 case TokenTypes.TYPE -> getPreviousNodeWithParentOfTypeAst(ast, parent); 269 270 // Java 8 method reference 271 case TokenTypes.METHOD_REF -> { 272 final DetailAST ident = getIdentLastToken(ast); 273 if (ident == null) { 274 // i.e. int[]::new 275 yield ast.getParent().getFirstChild(); 276 } 277 yield ident; 278 } 279 280 default -> throw new IllegalStateException("unexpected ast syntax " + parent); 281 }; 282 } 283 284 return previousElement; 285 } 286 287 /** 288 * Gets the previous element of a second or higher dimension of an 289 * array declaration or initialization. 290 * 291 * @param leftBracket the token to get previous element of 292 * @return the previous element 293 */ 294 private static DetailAST getPreviousElementOfMultiDimArray(DetailAST leftBracket) { 295 final DetailAST previousRightBracket = leftBracket.getPreviousSibling().getLastChild(); 296 297 DetailAST ident = null; 298 // This will get us past the type ident, to the actual identifier 299 DetailAST parent = leftBracket.getParent().getParent(); 300 while (ident == null) { 301 ident = parent.findFirstToken(TokenTypes.IDENT); 302 parent = parent.getParent(); 303 } 304 305 final DetailAST previousElement; 306 if (ident.getColumnNo() > previousRightBracket.getColumnNo() 307 && ident.getColumnNo() < leftBracket.getColumnNo()) { 308 // C style and Java style ' int[] arr []' in same construct 309 previousElement = ident; 310 } 311 else { 312 // 'int[][] arr' or 'int arr[][]' 313 previousElement = previousRightBracket; 314 } 315 return previousElement; 316 } 317 318 /** 319 * Gets previous node for {@link TokenTypes#INDEX_OP INDEX_OP} token 320 * for usage in getPositionAfter method, it is a simplified copy of 321 * getArrayDeclaratorPreviousElement method. 322 * 323 * @param ast 324 * , {@code TokenTypes#INDEX_OP INDEX_OP} node. 325 * @return previous node by text order. 326 */ 327 private static DetailAST getIndexOpPreviousElement(DetailAST ast) { 328 final DetailAST result; 329 final DetailAST firstChild = ast.getFirstChild(); 330 if (firstChild.getType() == TokenTypes.INDEX_OP) { 331 // second or higher array index 332 result = firstChild.findFirstToken(TokenTypes.RBRACK); 333 } 334 else if (firstChild.getType() == TokenTypes.IDENT) { 335 result = firstChild; 336 } 337 else { 338 final DetailAST ident = getIdentLastToken(ast); 339 if (ident == null) { 340 final DetailAST rparen = ast.findFirstToken(TokenTypes.RPAREN); 341 // construction like new int[]{1}[0] 342 if (rparen == null) { 343 final DetailAST lastChild = firstChild.getLastChild(); 344 result = lastChild.findFirstToken(TokenTypes.RCURLY); 345 } 346 // construction like ((byte[]) pixels)[0] 347 else { 348 result = rparen; 349 } 350 } 351 else { 352 result = ident; 353 } 354 } 355 return result; 356 } 357 358 /** 359 * Searches parameter node for a type node. 360 * Returns it or its last node if it has an extended structure. 361 * 362 * @param ast 363 * , subject node. 364 * @return type node. 365 */ 366 private static DetailAST getTypeLastNode(DetailAST ast) { 367 final DetailAST typeLastNode; 368 final DetailAST parent = ast.getParent(); 369 final boolean isPrecededByTypeArgs = 370 parent.findFirstToken(TokenTypes.TYPE_ARGUMENTS) != null; 371 372 if (isPrecededByTypeArgs) { 373 typeLastNode = parent.findFirstToken(TokenTypes.TYPE_ARGUMENTS) 374 .findFirstToken(TokenTypes.GENERIC_END); 375 } 376 else { 377 final Optional<DetailAST> objectArrayType = Optional.ofNullable(getIdentLastToken(ast)); 378 typeLastNode = objectArrayType.orElseGet(parent::getFirstChild); 379 } 380 381 return typeLastNode; 382 } 383 384 /** 385 * Finds previous node by text order for an array declarator, 386 * which parent type is {@link TokenTypes#TYPE TYPE}. 387 * 388 * @param ast 389 * , array declarator node. 390 * @param parent 391 * , its parent node. 392 * @return previous node by text order. 393 */ 394 private static DetailAST getPreviousNodeWithParentOfTypeAst(DetailAST ast, DetailAST parent) { 395 final DetailAST previousElement; 396 final DetailAST ident = getIdentLastToken(parent.getParent()); 397 final DetailAST lastTypeNode = getTypeLastNode(ast); 398 // sometimes there are ident-less sentences 399 // i.e. "(Object[]) null", but in casual case should be 400 // checked whether ident or lastTypeNode has preceding position 401 // determining if it is java style or C style 402 403 if (ident == null || ident.getLineNo() > ast.getLineNo()) { 404 previousElement = lastTypeNode; 405 } 406 else if (ident.getLineNo() < ast.getLineNo()) { 407 previousElement = ident; 408 } 409 // ident and lastTypeNode lay on one line 410 else { 411 final int instanceOfSize = 13; 412 // +2 because ast has `[]` after the ident 413 if (ident.getColumnNo() >= ast.getColumnNo() + 2 414 // +13 because ident (at most 1 character) is followed by 415 // ' instanceof ' (12 characters) 416 || lastTypeNode.getColumnNo() >= ident.getColumnNo() + instanceOfSize) { 417 previousElement = lastTypeNode; 418 } 419 else { 420 previousElement = ident; 421 } 422 } 423 return previousElement; 424 } 425 426 /** 427 * Gets leftmost token of identifier. 428 * 429 * @param ast 430 * , token possibly possessing an identifier. 431 * @return leftmost token of identifier. 432 */ 433 private static DetailAST getIdentLastToken(DetailAST ast) { 434 final DetailAST result; 435 final Optional<DetailAST> dot = getPrecedingDot(ast); 436 // method call case 437 if (dot.isEmpty() || ast.getFirstChild().getType() == TokenTypes.METHOD_CALL) { 438 final DetailAST methodCall = ast.findFirstToken(TokenTypes.METHOD_CALL); 439 if (methodCall == null) { 440 result = ast.findFirstToken(TokenTypes.IDENT); 441 } 442 else { 443 result = methodCall.findFirstToken(TokenTypes.RPAREN); 444 } 445 } 446 // qualified name case 447 else { 448 result = dot.orElseThrow().getFirstChild().getNextSibling(); 449 } 450 return result; 451 } 452 453 /** 454 * Gets the dot preceding a class member array index operation or class reference. 455 * 456 * @param leftBracket the ast we are checking 457 * @return dot preceding the left bracket 458 */ 459 private static Optional<DetailAST> getPrecedingDot(DetailAST leftBracket) { 460 final DetailAST referencedMemberDot = leftBracket.findFirstToken(TokenTypes.DOT); 461 final Optional<DetailAST> result = Optional.ofNullable(referencedMemberDot); 462 return result.or(() -> getReferencedClassDot(leftBracket)); 463 } 464 465 /** 466 * Gets the dot preceding a class reference. 467 * 468 * @param leftBracket the ast we are checking 469 * @return dot preceding the left bracket 470 */ 471 private static Optional<DetailAST> getReferencedClassDot(DetailAST leftBracket) { 472 final DetailAST parent = leftBracket.getParent(); 473 Optional<DetailAST> classDot = Optional.empty(); 474 if (parent.getType() != TokenTypes.ASSIGN) { 475 classDot = Optional.ofNullable(parent.findFirstToken(TokenTypes.DOT)); 476 } 477 return classDot; 478 } 479 480}