001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2018 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.util.Locale; 024import java.util.Optional; 025import java.util.ResourceBundle; 026import java.util.function.Predicate; 027 028import com.google.common.collect.ImmutableMap; 029import com.puppycrawl.tools.checkstyle.api.DetailAST; 030import com.puppycrawl.tools.checkstyle.api.TokenTypes; 031 032/** 033 * Contains utility methods for tokens. 034 * 035 * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a> 036 */ 037public final class TokenUtils { 038 039 /** Maps from a token name to value. */ 040 private static final ImmutableMap<String, Integer> TOKEN_NAME_TO_VALUE; 041 /** Maps from a token value to name. */ 042 private static final String[] TOKEN_VALUE_TO_NAME; 043 044 /** Array of all token IDs. */ 045 private static final int[] TOKEN_IDS; 046 047 /** Prefix for exception when getting token by given id. */ 048 private static final String TOKEN_ID_EXCEPTION_PREFIX = "given id "; 049 050 /** Prefix for exception when getting token by given name. */ 051 private static final String TOKEN_NAME_EXCEPTION_PREFIX = "given name "; 052 053 // initialise the constants 054 static { 055 final ImmutableMap.Builder<String, Integer> builder = 056 ImmutableMap.builder(); 057 final Field[] fields = TokenTypes.class.getDeclaredFields(); 058 String[] tempTokenValueToName = CommonUtils.EMPTY_STRING_ARRAY; 059 for (final Field field : fields) { 060 // Only process the int declarations. 061 if (field.getType() != Integer.TYPE) { 062 continue; 063 } 064 065 final String name = field.getName(); 066 final int tokenValue = getIntFromField(field, name); 067 builder.put(name, tokenValue); 068 if (tokenValue > tempTokenValueToName.length - 1) { 069 final String[] temp = new String[tokenValue + 1]; 070 System.arraycopy(tempTokenValueToName, 0, 071 temp, 0, tempTokenValueToName.length); 072 tempTokenValueToName = temp; 073 } 074 tempTokenValueToName[tokenValue] = name; 075 } 076 077 TOKEN_NAME_TO_VALUE = builder.build(); 078 TOKEN_VALUE_TO_NAME = tempTokenValueToName; 079 TOKEN_IDS = TOKEN_NAME_TO_VALUE.values().stream().mapToInt(Integer::intValue).toArray(); 080 } 081 082 /** Stop instances being created. **/ 083 private TokenUtils() { 084 } 085 086 /** 087 * Gets the value of a static or instance field of type int or of another primitive type 088 * convertible to type int via a widening conversion. Does not throw any checked exceptions. 089 * @param field from which the int should be extracted 090 * @param object to extract the int value from 091 * @return the value of the field converted to type int 092 * @throws IllegalStateException if this Field object is enforcing Java language access control 093 * and the underlying field is inaccessible 094 * @see Field#getInt(Object) 095 */ 096 public static int getIntFromField(Field field, Object object) { 097 try { 098 return field.getInt(object); 099 } 100 catch (final IllegalAccessException exception) { 101 throw new IllegalStateException(exception); 102 } 103 } 104 105 /** 106 * Get total number of TokenTypes. 107 * @return total number of TokenTypes. 108 */ 109 public static int getTokenTypesTotalNumber() { 110 return TOKEN_IDS.length; 111 } 112 113 /** 114 * Get all token IDs that are available in TokenTypes. 115 * @return array of token IDs 116 */ 117 public static int[] getAllTokenIds() { 118 final int[] safeCopy = new int[TOKEN_IDS.length]; 119 System.arraycopy(TOKEN_IDS, 0, safeCopy, 0, TOKEN_IDS.length); 120 return safeCopy; 121 } 122 123 /** 124 * Returns the name of a token for a given ID. 125 * @param id the ID of the token name to get 126 * @return a token name 127 */ 128 public static String getTokenName(int id) { 129 if (id > TOKEN_VALUE_TO_NAME.length - 1) { 130 throw new IllegalArgumentException(TOKEN_ID_EXCEPTION_PREFIX + id); 131 } 132 final String name = TOKEN_VALUE_TO_NAME[id]; 133 if (name == null) { 134 throw new IllegalArgumentException(TOKEN_ID_EXCEPTION_PREFIX + id); 135 } 136 return name; 137 } 138 139 /** 140 * Returns the ID of a token for a given name. 141 * @param name the name of the token ID to get 142 * @return a token ID 143 */ 144 public static int getTokenId(String name) { 145 final Integer id = TOKEN_NAME_TO_VALUE.get(name); 146 if (id == null) { 147 throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name); 148 } 149 return id; 150 } 151 152 /** 153 * Returns the short description of a token for a given name. 154 * @param name the name of the token ID to get 155 * @return a short description 156 */ 157 public static String getShortDescription(String name) { 158 if (!TOKEN_NAME_TO_VALUE.containsKey(name)) { 159 throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name); 160 } 161 162 final String tokenTypes = 163 "com.puppycrawl.tools.checkstyle.api.tokentypes"; 164 final ResourceBundle bundle = ResourceBundle.getBundle(tokenTypes, Locale.ROOT); 165 return bundle.getString(name); 166 } 167 168 /** 169 * Is argument comment-related type (SINGLE_LINE_COMMENT, 170 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 171 * @param type 172 * token type. 173 * @return true if type is comment-related type. 174 */ 175 public static boolean isCommentType(int type) { 176 return type == TokenTypes.SINGLE_LINE_COMMENT 177 || type == TokenTypes.BLOCK_COMMENT_BEGIN 178 || type == TokenTypes.BLOCK_COMMENT_END 179 || type == TokenTypes.COMMENT_CONTENT; 180 } 181 182 /** 183 * Is argument comment-related type name (SINGLE_LINE_COMMENT, 184 * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). 185 * @param type 186 * token type name. 187 * @return true if type is comment-related type name. 188 */ 189 public static boolean isCommentType(String type) { 190 return isCommentType(getTokenId(type)); 191 } 192 193 /** 194 * Finds the first {@link Optional} child token of {@link DetailAST} root node 195 * which matches the given predicate. 196 * @param root root node. 197 * @param predicate predicate. 198 * @return {@link Optional} of {@link DetailAST} node which matches the predicate. 199 */ 200 public static Optional<DetailAST> findFirstTokenByPredicate(DetailAST root, 201 Predicate<DetailAST> predicate) { 202 Optional<DetailAST> result = Optional.empty(); 203 for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) { 204 if (predicate.test(ast)) { 205 result = Optional.of(ast); 206 break; 207 } 208 } 209 return result; 210 } 211 212}