001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2020 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 /** Prefix for exception when getting token by given id. */ 052 private static final String TOKEN_ID_EXCEPTION_PREFIX = "given id "; 053 054 /** Prefix for exception when getting token by given name. */ 055 private static final String TOKEN_NAME_EXCEPTION_PREFIX = "given name "; 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 * @param field from which the int should be extracted 072 * @param object to extract the int value from 073 * @return the value of the field converted to type int 074 * @throws IllegalStateException if this Field object is enforcing Java language access control 075 * and the underlying field is inaccessible 076 * @see Field#getInt(Object) 077 */ 078 public static int getIntFromField(Field field, Object object) { 079 try { 080 return field.getInt(object); 081 } 082 catch (final IllegalAccessException exception) { 083 throw new IllegalStateException(exception); 084 } 085 } 086 087 /** 088 * Creates a map of 'field name' to 'field value' from all {@code public} {@code int} fields 089 * of a class. 090 * @param cls source class 091 * @return unmodifiable name to value map 092 */ 093 public static Map<String, Integer> nameToValueMapFromPublicIntFields(Class<?> cls) { 094 final Map<String, Integer> map = Arrays.stream(cls.getDeclaredFields()) 095 .filter(fld -> Modifier.isPublic(fld.getModifiers()) && fld.getType() == Integer.TYPE) 096 .collect(Collectors.toMap(Field::getName, fld -> getIntFromField(fld, fld.getName()))); 097 return Collections.unmodifiableMap(map); 098 } 099 100 /** 101 * Creates an array of map keys for quick value-to-name lookup for the map. 102 * @param map source map 103 * @return array of map keys 104 */ 105 public static String[] valueToNameArrayFromNameToValueMap(Map<String, Integer> map) { 106 String[] valueToNameArray = CommonUtil.EMPTY_STRING_ARRAY; 107 108 for (Map.Entry<String, Integer> entry : map.entrySet()) { 109 final int value = entry.getValue(); 110 // JavadocTokenTypes.EOF has value '-1' and is handled explicitly. 111 if (value >= 0) { 112 if (value >= valueToNameArray.length) { 113 final String[] temp = new String[value + 1]; 114 System.arraycopy(valueToNameArray, 0, temp, 0, valueToNameArray.length); 115 valueToNameArray = temp; 116 } 117 valueToNameArray[value] = entry.getKey(); 118 } 119 } 120 return valueToNameArray; 121 } 122 123 /** 124 * Get total number of TokenTypes. 125 * @return total number of TokenTypes. 126 */ 127 public static int getTokenTypesTotalNumber() { 128 return TOKEN_IDS.length; 129 } 130 131 /** 132 * Get all token IDs that are available in TokenTypes. 133 * @return array of token IDs 134 */ 135 public static int[] getAllTokenIds() { 136 final int[] safeCopy = new int[TOKEN_IDS.length]; 137 System.arraycopy(TOKEN_IDS, 0, safeCopy, 0, TOKEN_IDS.length); 138 return safeCopy; 139 } 140 141 /** 142 * Returns the name of a token for a given ID. 143 * @param id the ID of the token name to get 144 * @return a token name 145 * @throws IllegalArgumentException when id is not valid 146 */ 147 public static String getTokenName(int id) { 148 if (id > TOKEN_VALUE_TO_NAME.length - 1) { 149 throw new IllegalArgumentException(TOKEN_ID_EXCEPTION_PREFIX + id); 150 } 151 final String name = TOKEN_VALUE_TO_NAME[id]; 152 if (name == null) { 153 throw new IllegalArgumentException(TOKEN_ID_EXCEPTION_PREFIX + id); 154 } 155 return name; 156 } 157 158 /** 159 * Returns the ID of a token for a given name. 160 * @param name the name of the token ID to get 161 * @return a token ID 162 * @throws IllegalArgumentException when id is null 163 */ 164 public static int getTokenId(String name) { 165 final Integer id = TOKEN_NAME_TO_VALUE.get(name); 166 if (id == null) { 167 throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name); 168 } 169 return id; 170 } 171 172 /** 173 * Returns the short description of a token for a given name. 174 * @param name the name of the token ID to get 175 * @return a short description 176 * @throws IllegalArgumentException when name is unknown 177 */ 178 public static String getShortDescription(String name) { 179 if (!TOKEN_NAME_TO_VALUE.containsKey(name)) { 180 throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name); 181 } 182 183 final String tokenTypes = 184 "com.puppycrawl.tools.checkstyle.api.tokentypes"; 185 final ResourceBundle bundle = ResourceBundle.getBundle(tokenTypes, Locale.ROOT); 186 return bundle.getString(name); 187 } 188 189 /** 190 * Is argument comment-related type (SINGLE_LINE_COMMENT, 191 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 192 * @param type 193 * token type. 194 * @return true if type is comment-related type. 195 */ 196 public static boolean isCommentType(int type) { 197 return type == TokenTypes.SINGLE_LINE_COMMENT 198 || type == TokenTypes.BLOCK_COMMENT_BEGIN 199 || type == TokenTypes.BLOCK_COMMENT_END 200 || type == TokenTypes.COMMENT_CONTENT; 201 } 202 203 /** 204 * Is argument comment-related type name (SINGLE_LINE_COMMENT, 205 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 206 * @param type 207 * token type name. 208 * @return true if type is comment-related type name. 209 */ 210 public static boolean isCommentType(String type) { 211 return isCommentType(getTokenId(type)); 212 } 213 214 /** 215 * Finds the first {@link Optional} child token of {@link DetailAST} root node 216 * which matches the given predicate. 217 * @param root root node. 218 * @param predicate predicate. 219 * @return {@link Optional} of {@link DetailAST} node which matches the predicate. 220 */ 221 public static Optional<DetailAST> findFirstTokenByPredicate(DetailAST root, 222 Predicate<DetailAST> predicate) { 223 Optional<DetailAST> result = Optional.empty(); 224 for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) { 225 if (predicate.test(ast)) { 226 result = Optional.of(ast); 227 break; 228 } 229 } 230 return result; 231 } 232 233 /** 234 * Performs an action for each child of {@link DetailAST} root node 235 * which matches the given token type. 236 * @param root root node. 237 * @param type token type to match. 238 * @param action action to perform on the nodes. 239 */ 240 public static void forEachChild(DetailAST root, int type, Consumer<DetailAST> action) { 241 for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) { 242 if (ast.getType() == type) { 243 action.accept(ast); 244 } 245 } 246 } 247 248}