001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2021 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.lang.reflect.Field; 023import java.lang.reflect.Modifier; 024import java.util.Arrays; 025import java.util.Collections; 026import java.util.Locale; 027import java.util.Map; 028import java.util.Optional; 029import java.util.ResourceBundle; 030import java.util.function.Consumer; 031import java.util.function.Predicate; 032import java.util.stream.Collectors; 033 034import com.puppycrawl.tools.checkstyle.api.DetailAST; 035import com.puppycrawl.tools.checkstyle.api.TokenTypes; 036 037/** 038 * Contains utility methods for tokens. 039 * 040 */ 041public final class TokenUtil { 042 043 /** Maps from a token name to value. */ 044 private static final Map<String, Integer> TOKEN_NAME_TO_VALUE; 045 /** Maps from a token value to name. */ 046 private static final String[] TOKEN_VALUE_TO_NAME; 047 048 /** Array of all token IDs. */ 049 private static final int[] TOKEN_IDS; 050 051 /** Format for exception message when getting token by given id. */ 052 private static final String TOKEN_ID_EXCEPTION_FORMAT = "unknown TokenTypes id '%s'"; 053 054 /** Format for exception message when getting token by given name. */ 055 private static final String TOKEN_NAME_EXCEPTION_FORMAT = "unknown TokenTypes value '%s'"; 056 057 // initialise the constants 058 static { 059 TOKEN_NAME_TO_VALUE = nameToValueMapFromPublicIntFields(TokenTypes.class); 060 TOKEN_VALUE_TO_NAME = valueToNameArrayFromNameToValueMap(TOKEN_NAME_TO_VALUE); 061 TOKEN_IDS = TOKEN_NAME_TO_VALUE.values().stream().mapToInt(Integer::intValue).toArray(); 062 } 063 064 /** Stop instances being created. **/ 065 private TokenUtil() { 066 } 067 068 /** 069 * Gets the value of a static or instance field of type int or of another primitive type 070 * convertible to type int via a widening conversion. Does not throw any checked exceptions. 071 * 072 * @param field from which the int should be extracted 073 * @param object to extract the int value from 074 * @return the value of the field converted to type int 075 * @throws IllegalStateException if this Field object is enforcing Java language access control 076 * and the underlying field is inaccessible 077 * @see Field#getInt(Object) 078 */ 079 public static int getIntFromField(Field field, Object object) { 080 try { 081 return field.getInt(object); 082 } 083 catch (final IllegalAccessException exception) { 084 throw new IllegalStateException(exception); 085 } 086 } 087 088 /** 089 * Creates a map of 'field name' to 'field value' from all {@code public} {@code int} fields 090 * of a class. 091 * 092 * @param cls source class 093 * @return unmodifiable name to value map 094 */ 095 public static Map<String, Integer> nameToValueMapFromPublicIntFields(Class<?> cls) { 096 final Map<String, Integer> map = Arrays.stream(cls.getDeclaredFields()) 097 .filter(fld -> Modifier.isPublic(fld.getModifiers()) && fld.getType() == Integer.TYPE) 098 .collect(Collectors.toMap(Field::getName, fld -> getIntFromField(fld, fld.getName()))); 099 return Collections.unmodifiableMap(map); 100 } 101 102 /** 103 * Creates an array of map keys for quick value-to-name lookup for the map. 104 * 105 * @param map source map 106 * @return array of map keys 107 */ 108 public static String[] valueToNameArrayFromNameToValueMap(Map<String, Integer> map) { 109 String[] valueToNameArray = CommonUtil.EMPTY_STRING_ARRAY; 110 111 for (Map.Entry<String, Integer> entry : map.entrySet()) { 112 final int value = entry.getValue(); 113 // JavadocTokenTypes.EOF has value '-1' and is handled explicitly. 114 if (value >= 0) { 115 if (value >= valueToNameArray.length) { 116 final String[] temp = new String[value + 1]; 117 System.arraycopy(valueToNameArray, 0, temp, 0, valueToNameArray.length); 118 valueToNameArray = temp; 119 } 120 valueToNameArray[value] = entry.getKey(); 121 } 122 } 123 return valueToNameArray; 124 } 125 126 /** 127 * Get total number of TokenTypes. 128 * 129 * @return total number of TokenTypes. 130 */ 131 public static int getTokenTypesTotalNumber() { 132 return TOKEN_IDS.length; 133 } 134 135 /** 136 * Get all token IDs that are available in TokenTypes. 137 * 138 * @return array of token IDs 139 */ 140 public static int[] getAllTokenIds() { 141 final int[] safeCopy = new int[TOKEN_IDS.length]; 142 System.arraycopy(TOKEN_IDS, 0, safeCopy, 0, TOKEN_IDS.length); 143 return safeCopy; 144 } 145 146 /** 147 * Returns the name of a token for a given ID. 148 * 149 * @param id the ID of the token name to get 150 * @return a token name 151 * @throws IllegalArgumentException when id is not valid 152 */ 153 public static String getTokenName(int id) { 154 if (id > TOKEN_VALUE_TO_NAME.length - 1) { 155 throw new IllegalArgumentException( 156 String.format(Locale.ROOT, TOKEN_ID_EXCEPTION_FORMAT, id)); 157 } 158 final String name = TOKEN_VALUE_TO_NAME[id]; 159 if (name == null) { 160 throw new IllegalArgumentException( 161 String.format(Locale.ROOT, TOKEN_ID_EXCEPTION_FORMAT, id)); 162 } 163 return name; 164 } 165 166 /** 167 * Returns the ID of a token for a given name. 168 * 169 * @param name the name of the token ID to get 170 * @return a token ID 171 * @throws IllegalArgumentException when id is null 172 */ 173 public static int getTokenId(String name) { 174 final Integer id = TOKEN_NAME_TO_VALUE.get(name); 175 if (id == null) { 176 throw new IllegalArgumentException( 177 String.format(Locale.ROOT, TOKEN_NAME_EXCEPTION_FORMAT, name)); 178 } 179 return id; 180 } 181 182 /** 183 * Returns the short description of a token for a given name. 184 * 185 * @param name the name of the token ID to get 186 * @return a short description 187 * @throws IllegalArgumentException when name is unknown 188 */ 189 public static String getShortDescription(String name) { 190 if (!TOKEN_NAME_TO_VALUE.containsKey(name)) { 191 throw new IllegalArgumentException( 192 String.format(Locale.ROOT, TOKEN_NAME_EXCEPTION_FORMAT, name)); 193 } 194 195 final String tokenTypes = 196 "com.puppycrawl.tools.checkstyle.api.tokentypes"; 197 final ResourceBundle bundle = ResourceBundle.getBundle(tokenTypes, Locale.ROOT); 198 return bundle.getString(name); 199 } 200 201 /** 202 * Is argument comment-related type (SINGLE_LINE_COMMENT, 203 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 204 * 205 * @param type 206 * token type. 207 * @return true if type is comment-related type. 208 */ 209 public static boolean isCommentType(int type) { 210 return type == TokenTypes.SINGLE_LINE_COMMENT 211 || type == TokenTypes.BLOCK_COMMENT_BEGIN 212 || type == TokenTypes.BLOCK_COMMENT_END 213 || type == TokenTypes.COMMENT_CONTENT; 214 } 215 216 /** 217 * Is argument comment-related type name (SINGLE_LINE_COMMENT, 218 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 219 * 220 * @param type 221 * token type name. 222 * @return true if type is comment-related type name. 223 */ 224 public static boolean isCommentType(String type) { 225 return isCommentType(getTokenId(type)); 226 } 227 228 /** 229 * Finds the first {@link Optional} child token of {@link DetailAST} root node 230 * which matches the given predicate. 231 * 232 * @param root root node. 233 * @param predicate predicate. 234 * @return {@link Optional} of {@link DetailAST} node which matches the predicate. 235 */ 236 public static Optional<DetailAST> findFirstTokenByPredicate(DetailAST root, 237 Predicate<DetailAST> predicate) { 238 Optional<DetailAST> result = Optional.empty(); 239 for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) { 240 if (predicate.test(ast)) { 241 result = Optional.of(ast); 242 break; 243 } 244 } 245 return result; 246 } 247 248 /** 249 * Performs an action for each child of {@link DetailAST} root node 250 * which matches the given token type. 251 * 252 * @param root root node. 253 * @param type token type to match. 254 * @param action action to perform on the nodes. 255 */ 256 public static void forEachChild(DetailAST root, int type, Consumer<DetailAST> action) { 257 for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) { 258 if (ast.getType() == type) { 259 action.accept(ast); 260 } 261 } 262 } 263 264 /** 265 * Determines if two ASTs are on the same line. 266 * 267 * @param ast1 the first AST 268 * @param ast2 the second AST 269 * 270 * @return true if they are on the same line. 271 */ 272 public static boolean areOnSameLine(DetailAST ast1, DetailAST ast2) { 273 return ast1.getLineNo() == ast2.getLineNo(); 274 } 275 276 /** 277 * Is type declaration token type (CLASS_DEF, INTERFACE_DEF, 278 * ANNOTATION_DEF, ENUM_DEF, RECORD_DEF). 279 * 280 * @param type 281 * token type. 282 * @return true if type is type declaration token type. 283 */ 284 public static boolean isTypeDeclaration(int type) { 285 return type == TokenTypes.CLASS_DEF 286 || type == TokenTypes.INTERFACE_DEF 287 || type == TokenTypes.ANNOTATION_DEF 288 || type == TokenTypes.ENUM_DEF 289 || type == TokenTypes.RECORD_DEF; 290 } 291 292 /** 293 * Determines if the token type belongs to the given types. 294 * 295 * @param type the Token Type to check 296 * @param types the acceptable types 297 * 298 * @return true if type matches one of the given types. 299 */ 300 public static boolean isOfType(int type, int... types) { 301 return Arrays.stream(types).anyMatch(tokenType -> tokenType == type); 302 } 303 304 /** 305 * Determines if the AST belongs to the given types. 306 * 307 * @param ast the AST node to check 308 * @param types the acceptable types 309 * 310 * @return true if type matches one of the given types. 311 */ 312 public static boolean isOfType(DetailAST ast, int... types) { 313 return ast != null && isOfType(ast.getType(), types); 314 } 315 316}