001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2025 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.stream.IntStream; 023 024import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 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.CodePointUtil; 029import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 030 031/** 032 * <div> 033 * Checks that the whitespace around the Generic tokens (angle brackets) 034 * "<" and ">" are correct to the <i>typical</i> convention. 035 * The convention is not configurable. 036 * </div> 037 * 038 * <p> 039 * Left angle bracket ("<"): 040 * </p> 041 * <ul> 042 * <li> should be preceded with whitespace only 043 * in generic methods definitions.</li> 044 * <li> should not be preceded with whitespace 045 * when it is preceded method name or constructor.</li> 046 * <li> should not be preceded with whitespace when following type name.</li> 047 * <li> should not be followed with whitespace in all cases.</li> 048 * </ul> 049 * 050 * <p> 051 * Right angle bracket (">"): 052 * </p> 053 * <ul> 054 * <li> should not be preceded with whitespace in all cases.</li> 055 * <li> should be followed with whitespace in almost all cases, 056 * except diamond operators and when preceding a method name, constructor, or record header.</li> 057 * </ul> 058 * 059 * <p> 060 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 061 * </p> 062 * 063 * <p> 064 * Violation Message Keys: 065 * </p> 066 * <ul> 067 * <li> 068 * {@code ws.followed} 069 * </li> 070 * <li> 071 * {@code ws.illegalFollow} 072 * </li> 073 * <li> 074 * {@code ws.notPreceded} 075 * </li> 076 * <li> 077 * {@code ws.preceded} 078 * </li> 079 * </ul> 080 * 081 * @since 5.0 082 */ 083@FileStatefulCheck 084public class GenericWhitespaceCheck extends AbstractCheck { 085 086 /** 087 * A key is pointing to the warning message text in "messages.properties" 088 * file. 089 */ 090 public static final String MSG_WS_PRECEDED = "ws.preceded"; 091 092 /** 093 * A key is pointing to the warning message text in "messages.properties" 094 * file. 095 */ 096 public static final String MSG_WS_FOLLOWED = "ws.followed"; 097 098 /** 099 * A key is pointing to the warning message text in "messages.properties" 100 * file. 101 */ 102 public static final String MSG_WS_NOT_PRECEDED = "ws.notPreceded"; 103 104 /** 105 * A key is pointing to the warning message text in "messages.properties" 106 * file. 107 */ 108 public static final String MSG_WS_ILLEGAL_FOLLOW = "ws.illegalFollow"; 109 110 /** Open angle bracket literal. */ 111 private static final String OPEN_ANGLE_BRACKET = "<"; 112 113 /** Close angle bracket literal. */ 114 private static final String CLOSE_ANGLE_BRACKET = ">"; 115 116 /** Used to count the depth of a Generic expression. */ 117 private int depth; 118 119 @Override 120 public int[] getDefaultTokens() { 121 return getRequiredTokens(); 122 } 123 124 @Override 125 public int[] getAcceptableTokens() { 126 return getRequiredTokens(); 127 } 128 129 @Override 130 public int[] getRequiredTokens() { 131 return new int[] {TokenTypes.GENERIC_START, TokenTypes.GENERIC_END}; 132 } 133 134 @Override 135 public void beginTree(DetailAST rootAST) { 136 // Reset for each tree, just increase there are violations in preceding 137 // trees. 138 depth = 0; 139 } 140 141 @Override 142 public void visitToken(DetailAST ast) { 143 switch (ast.getType()) { 144 case TokenTypes.GENERIC_START -> { 145 processStart(ast); 146 depth++; 147 } 148 case TokenTypes.GENERIC_END -> { 149 processEnd(ast); 150 depth--; 151 } 152 default -> throw new IllegalArgumentException("Unknown type " + ast); 153 } 154 } 155 156 /** 157 * Checks the token for the end of Generics. 158 * 159 * @param ast the token to check 160 */ 161 private void processEnd(DetailAST ast) { 162 final int[] line = getLineCodePoints(ast.getLineNo() - 1); 163 final int before = ast.getColumnNo() - 1; 164 final int after = ast.getColumnNo() + 1; 165 166 if (before >= 0 && CommonUtil.isCodePointWhitespace(line, before) 167 && !containsWhitespaceBefore(before, line)) { 168 log(ast, MSG_WS_PRECEDED, CLOSE_ANGLE_BRACKET); 169 } 170 171 if (after < line.length) { 172 // Check if the last Generic, in which case must be a whitespace 173 // or a '(),[.'. 174 if (depth == 1) { 175 processSingleGeneric(ast, line, after); 176 } 177 else { 178 processNestedGenerics(ast, line, after); 179 } 180 } 181 } 182 183 /** 184 * Process Nested generics. 185 * 186 * @param ast token 187 * @param line unicode code points array of line 188 * @param after position after 189 */ 190 private void processNestedGenerics(DetailAST ast, int[] line, int after) { 191 // In a nested Generic type, so can only be a '>' or ',' or '&' 192 193 // In case of several extends definitions: 194 // 195 // class IntEnumValueType<E extends Enum<E> & IntEnum> 196 // ^ 197 // should be whitespace if followed by & -+ 198 // 199 final int indexOfAmp = IntStream.range(after, line.length) 200 .filter(index -> line[index] == '&') 201 .findFirst() 202 .orElse(-1); 203 if (indexOfAmp >= 1 204 && containsWhitespaceBetween(after, indexOfAmp, line)) { 205 if (indexOfAmp - after == 0) { 206 log(ast, MSG_WS_NOT_PRECEDED, "&"); 207 } 208 else if (indexOfAmp - after != 1) { 209 log(ast, MSG_WS_FOLLOWED, CLOSE_ANGLE_BRACKET); 210 } 211 } 212 else if (line[after] == ' ') { 213 log(ast, MSG_WS_FOLLOWED, CLOSE_ANGLE_BRACKET); 214 } 215 } 216 217 /** 218 * Process Single-generic. 219 * 220 * @param ast token 221 * @param line unicode code points array of line 222 * @param after position after 223 */ 224 private void processSingleGeneric(DetailAST ast, int[] line, int after) { 225 final char charAfter = Character.toChars(line[after])[0]; 226 if (isGenericBeforeMethod(ast) 227 || isGenericBeforeCtorInvocation(ast) 228 || isGenericBeforeRecordHeader(ast)) { 229 if (Character.isWhitespace(charAfter)) { 230 log(ast, MSG_WS_FOLLOWED, CLOSE_ANGLE_BRACKET); 231 } 232 } 233 else if (!isCharacterValidAfterGenericEnd(charAfter)) { 234 log(ast, MSG_WS_ILLEGAL_FOLLOW, CLOSE_ANGLE_BRACKET); 235 } 236 } 237 238 /** 239 * Checks if generic is before record header. Identifies two cases: 240 * <ol> 241 * <li>In record def, eg: {@code record Session<T>()}</li> 242 * <li>In record pattern def, eg: {@code o instanceof Session<String>(var s)}</li> 243 * </ol> 244 * 245 * @param ast ast 246 * @return true if generic is before record header 247 */ 248 private static boolean isGenericBeforeRecordHeader(DetailAST ast) { 249 final DetailAST grandParent = ast.getParent().getParent(); 250 return grandParent.getType() == TokenTypes.RECORD_DEF 251 || grandParent.getParent().getType() == TokenTypes.RECORD_PATTERN_DEF; 252 } 253 254 /** 255 * Checks if generic is before constructor invocation. Identifies two cases: 256 * <ol> 257 * <li>{@code new ArrayList<>();}</li> 258 * <li>{@code new Outer.Inner<>();}</li> 259 * </ol> 260 * 261 * @param ast ast 262 * @return true if generic is before constructor invocation 263 */ 264 private static boolean isGenericBeforeCtorInvocation(DetailAST ast) { 265 final DetailAST grandParent = ast.getParent().getParent(); 266 return grandParent.getType() == TokenTypes.LITERAL_NEW 267 || grandParent.getParent().getType() == TokenTypes.LITERAL_NEW; 268 } 269 270 /** 271 * Checks if generic is after {@code LITERAL_NEW}. Identifies three cases: 272 * <ol> 273 * <li>{@code new <String>Object();}</li> 274 * <li>{@code new <String>Outer.Inner();}</li> 275 * <li>{@code new <@A Outer>@B Inner();}</li> 276 * </ol> 277 * 278 * @param ast ast 279 * @return true if generic after {@code LITERAL_NEW} 280 */ 281 private static boolean isGenericAfterNew(DetailAST ast) { 282 final DetailAST parent = ast.getParent(); 283 return parent.getParent().getType() == TokenTypes.LITERAL_NEW 284 && (parent.getNextSibling().getType() == TokenTypes.IDENT 285 || parent.getNextSibling().getType() == TokenTypes.DOT 286 || parent.getNextSibling().getType() == TokenTypes.ANNOTATIONS); 287 } 288 289 /** 290 * Is generic before method reference. 291 * 292 * @param ast ast 293 * @return true if generic before a method ref 294 */ 295 private static boolean isGenericBeforeMethod(DetailAST ast) { 296 return ast.getParent().getParent().getParent().getType() == TokenTypes.METHOD_CALL 297 || isAfterMethodReference(ast); 298 } 299 300 /** 301 * Checks if current generic end ('>') is located after 302 * {@link TokenTypes#METHOD_REF method reference operator}. 303 * 304 * @param genericEnd {@link TokenTypes#GENERIC_END} 305 * @return true if '>' follows after method reference. 306 */ 307 private static boolean isAfterMethodReference(DetailAST genericEnd) { 308 return genericEnd.getParent().getParent().getType() == TokenTypes.METHOD_REF; 309 } 310 311 /** 312 * Checks the token for the start of Generics. 313 * 314 * @param ast the token to check 315 */ 316 private void processStart(DetailAST ast) { 317 final int[] line = getLineCodePoints(ast.getLineNo() - 1); 318 final int before = ast.getColumnNo() - 1; 319 final int after = ast.getColumnNo() + 1; 320 321 // Checks if generic needs to be preceded by a whitespace or not. 322 // Handles 3 cases as in: 323 // 324 // public static <T> Callable<T> callable(Runnable task, T result) 325 // ^ ^ 326 // 1. ws reqd ---+ 2. +--- whitespace NOT required 327 // 328 // new <String>Object() 329 // ^ 330 // 3. +--- ws required 331 if (before >= 0) { 332 final DetailAST parent = ast.getParent(); 333 final DetailAST grandparent = parent.getParent(); 334 // cases (1, 3) where whitespace is required: 335 if (grandparent.getType() == TokenTypes.CTOR_DEF 336 || grandparent.getType() == TokenTypes.METHOD_DEF 337 || isGenericAfterNew(ast)) { 338 339 if (!CommonUtil.isCodePointWhitespace(line, before)) { 340 log(ast, MSG_WS_NOT_PRECEDED, OPEN_ANGLE_BRACKET); 341 } 342 } 343 // case 2 where whitespace is not required: 344 else if (CommonUtil.isCodePointWhitespace(line, before) 345 && !containsWhitespaceBefore(before, line)) { 346 log(ast, MSG_WS_PRECEDED, OPEN_ANGLE_BRACKET); 347 } 348 } 349 350 if (after < line.length 351 && CommonUtil.isCodePointWhitespace(line, after)) { 352 log(ast, MSG_WS_FOLLOWED, OPEN_ANGLE_BRACKET); 353 } 354 } 355 356 /** 357 * Returns whether the specified string contains only whitespace between 358 * specified indices. 359 * 360 * @param fromIndex the index to start the search from. Inclusive 361 * @param toIndex the index to finish the search. Exclusive 362 * @param line the unicode code points array of line to check 363 * @return whether there are only whitespaces (or nothing) 364 */ 365 private static boolean containsWhitespaceBetween(int fromIndex, int toIndex, int... line) { 366 boolean result = true; 367 for (int i = fromIndex; i < toIndex; i++) { 368 if (!CommonUtil.isCodePointWhitespace(line, i)) { 369 result = false; 370 break; 371 } 372 } 373 return result; 374 } 375 376 /** 377 * Returns whether the specified string contains only whitespace up to specified index. 378 * 379 * @param before the index to finish the search. Exclusive 380 * @param line the unicode code points array of line to check 381 * @return {@code true} if there are only whitespaces, 382 * false if there is nothing before or some other characters 383 */ 384 private static boolean containsWhitespaceBefore(int before, int... line) { 385 return before != 0 && CodePointUtil.hasWhitespaceBefore(before, line); 386 } 387 388 /** 389 * Checks whether given character is valid to be right after generic ends. 390 * 391 * @param charAfter character to check 392 * @return checks if given character is valid 393 */ 394 private static boolean isCharacterValidAfterGenericEnd(char charAfter) { 395 return charAfter == ')' || charAfter == ',' 396 || charAfter == '[' || charAfter == '.' 397 || charAfter == ':' || charAfter == ';' 398 || Character.isWhitespace(charAfter); 399 } 400 401}