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