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     *
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(TOKEN_ID_EXCEPTION_PREFIX + id);
156        }
157        final String name = TOKEN_VALUE_TO_NAME[id];
158        if (name == null) {
159            throw new IllegalArgumentException(TOKEN_ID_EXCEPTION_PREFIX + id);
160        }
161        return name;
162    }
163
164    /**
165     * Returns the ID of a token for a given name.
166     *
167     * @param name the name of the token ID to get
168     * @return a token ID
169     * @throws IllegalArgumentException when id is null
170     */
171    public static int getTokenId(String name) {
172        final Integer id = TOKEN_NAME_TO_VALUE.get(name);
173        if (id == null) {
174            throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name);
175        }
176        return id;
177    }
178
179    /**
180     * Returns the short description of a token for a given name.
181     *
182     * @param name the name of the token ID to get
183     * @return a short description
184     * @throws IllegalArgumentException when name is unknown
185     */
186    public static String getShortDescription(String name) {
187        if (!TOKEN_NAME_TO_VALUE.containsKey(name)) {
188            throw new IllegalArgumentException(TOKEN_NAME_EXCEPTION_PREFIX + name);
189        }
190
191        final String tokenTypes =
192            "com.puppycrawl.tools.checkstyle.api.tokentypes";
193        final ResourceBundle bundle = ResourceBundle.getBundle(tokenTypes, Locale.ROOT);
194        return bundle.getString(name);
195    }
196
197    /**
198     * Is argument comment-related type (SINGLE_LINE_COMMENT,
199     * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT).
200     *
201     * @param type
202     *        token type.
203     * @return true if type is comment-related type.
204     */
205    public static boolean isCommentType(int type) {
206        return type == TokenTypes.SINGLE_LINE_COMMENT
207                || type == TokenTypes.BLOCK_COMMENT_BEGIN
208                || type == TokenTypes.BLOCK_COMMENT_END
209                || type == TokenTypes.COMMENT_CONTENT;
210    }
211
212    /**
213     * Is argument comment-related type name (SINGLE_LINE_COMMENT,
214     * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT).
215     *
216     * @param type
217     *        token type name.
218     * @return true if type is comment-related type name.
219     */
220    public static boolean isCommentType(String type) {
221        return isCommentType(getTokenId(type));
222    }
223
224    /**
225     * Finds the first {@link Optional} child token of {@link DetailAST} root node
226     * which matches the given predicate.
227     *
228     * @param root root node.
229     * @param predicate predicate.
230     * @return {@link Optional} of {@link DetailAST} node which matches the predicate.
231     */
232    public static Optional<DetailAST> findFirstTokenByPredicate(DetailAST root,
233                                                                Predicate<DetailAST> predicate) {
234        Optional<DetailAST> result = Optional.empty();
235        for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
236            if (predicate.test(ast)) {
237                result = Optional.of(ast);
238                break;
239            }
240        }
241        return result;
242    }
243
244    /**
245     * Performs an action for each child of {@link DetailAST} root node
246     * which matches the given token type.
247     *
248     * @param root root node.
249     * @param type token type to match.
250     * @param action action to perform on the nodes.
251     */
252    public static void forEachChild(DetailAST root, int type, Consumer<DetailAST> action) {
253        for (DetailAST ast = root.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
254            if (ast.getType() == type) {
255                action.accept(ast);
256            }
257        }
258    }
259
260    /**
261     * Determines if two ASTs are on the same line.
262     *
263     * @param ast1   the first AST
264     * @param ast2   the second AST
265     *
266     * @return true if they are on the same line.
267     */
268    public static boolean areOnSameLine(DetailAST ast1, DetailAST ast2) {
269        return ast1.getLineNo() == ast2.getLineNo();
270    }
271
272}