001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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.naming;
021
022import java.util.Arrays;
023import java.util.HashSet;
024import java.util.LinkedList;
025import java.util.List;
026import java.util.Set;
027import java.util.stream.Collectors;
028
029import com.puppycrawl.tools.checkstyle.StatelessCheck;
030import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
031import com.puppycrawl.tools.checkstyle.api.DetailAST;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
034import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
035
036/**
037 * <p>
038 * Validates abbreviations (consecutive capital letters) length in
039 * identifier name, it also allows to enforce camel case naming. Please read more at
040 * <a href="https://checkstyle.org/styleguides/google-java-style-20180523/javaguide.html#s5.3-camel-case">
041 * Google Style Guide</a> to get to know how to avoid long abbreviations in names.
042 * </p>
043 * <p>'_' is considered as word separator in identifier name.</p>
044 * <p>
045 * {@code allowedAbbreviationLength} specifies how many consecutive capital letters are
046 * allowed in the identifier.
047 * A value of <i>3</i> indicates that up to 4 consecutive capital letters are allowed,
048 * one after the other, before a violation is printed. The identifier 'MyTEST' would be
049 * allowed, but 'MyTESTS' would not be.
050 * A value of <i>0</i> indicates that only 1 consecutive capital letter is allowed. This
051 * is what should be used to enforce strict camel casing. The identifier 'MyTest' would
052 * be allowed, but 'MyTEst' would not be.
053 * </p>
054 * <p>
055 * {@code ignoreFinal}, {@code ignoreStatic}, and {@code ignoreStaticFinal}
056 * control whether variables with the respective modifiers are to be ignored.
057 * Note that a variable that is both static and final will always be considered under
058 * {@code ignoreStaticFinal} only, regardless of the values of {@code ignoreFinal}
059 * and {@code ignoreStatic}. So for example if {@code ignoreStatic} is true but
060 * {@code ignoreStaticFinal} is false, then static final variables will not be ignored.
061 * </p>
062 * <ul>
063 * <li>
064 * Property {@code allowedAbbreviationLength} - Indicate the number of consecutive capital
065 * letters allowed in targeted identifiers (abbreviations in the classes, interfaces, variables
066 * and methods names, ... ).
067 * Type is {@code int}.
068 * Default value is {@code 3}.
069 * </li>
070 * <li>
071 * Property {@code allowedAbbreviations} - Specify abbreviations that must be skipped for checking.
072 * Type is {@code java.lang.String[]}.
073 * Default value is {@code ""}.
074 * </li>
075 * <li>
076 * Property {@code ignoreFinal} - Allow to skip variables with {@code final} modifier.
077 * Type is {@code boolean}.
078 * Default value is {@code true}.
079 * </li>
080 * <li>
081 * Property {@code ignoreOverriddenMethods} - Allow to ignore methods tagged with {@code @Override}
082 * annotation (that usually mean inherited name).
083 * Type is {@code boolean}.
084 * Default value is {@code true}.
085 * </li>
086 * <li>
087 * Property {@code ignoreStatic} - Allow to skip variables with {@code static} modifier.
088 * Type is {@code boolean}.
089 * Default value is {@code true}.
090 * </li>
091 * <li>
092 * Property {@code ignoreStaticFinal} - Allow to skip variables with both {@code static} and
093 * {@code final} modifiers.
094 * Type is {@code boolean}.
095 * Default value is {@code true}.
096 * </li>
097 * <li>
098 * Property {@code tokens} - tokens to check
099 * Type is {@code java.lang.String[]}.
100 * Validation type is {@code tokenSet}.
101 * Default value is:
102 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CLASS_DEF">
103 * CLASS_DEF</a>,
104 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INTERFACE_DEF">
105 * INTERFACE_DEF</a>,
106 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_DEF">
107 * ENUM_DEF</a>,
108 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_DEF">
109 * ANNOTATION_DEF</a>,
110 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_FIELD_DEF">
111 * ANNOTATION_FIELD_DEF</a>,
112 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PARAMETER_DEF">
113 * PARAMETER_DEF</a>,
114 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF">
115 * VARIABLE_DEF</a>,
116 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#METHOD_DEF">
117 * METHOD_DEF</a>,
118 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PATTERN_VARIABLE_DEF">
119 * PATTERN_VARIABLE_DEF</a>,
120 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#RECORD_DEF">
121 * RECORD_DEF</a>,
122 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#RECORD_COMPONENT_DEF">
123 * RECORD_COMPONENT_DEF</a>.
124 * </li>
125 * </ul>
126 * <p>
127 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
128 * </p>
129 * <p>
130 * Violation Message Keys:
131 * </p>
132 * <ul>
133 * <li>
134 * {@code abbreviation.as.word}
135 * </li>
136 * </ul>
137 *
138 * @since 5.8
139 */
140@StatelessCheck
141public class AbbreviationAsWordInNameCheck extends AbstractCheck {
142
143    /**
144     * Warning message key.
145     */
146    public static final String MSG_KEY = "abbreviation.as.word";
147
148    /**
149     * The default value of "allowedAbbreviationLength" option.
150     */
151    private static final int DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH = 3;
152
153    /**
154     * Indicate the number of consecutive capital letters allowed in
155     * targeted identifiers (abbreviations in the classes, interfaces, variables
156     * and methods names, ... ).
157     */
158    private int allowedAbbreviationLength =
159            DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH;
160
161    /**
162     * Specify abbreviations that must be skipped for checking.
163     */
164    private Set<String> allowedAbbreviations = new HashSet<>();
165
166    /** Allow to skip variables with {@code final} modifier. */
167    private boolean ignoreFinal = true;
168
169    /** Allow to skip variables with {@code static} modifier. */
170    private boolean ignoreStatic = true;
171
172    /** Allow to skip variables with both {@code static} and {@code final} modifiers. */
173    private boolean ignoreStaticFinal = true;
174
175    /**
176     * Allow to ignore methods tagged with {@code @Override} annotation (that
177     * usually mean inherited name).
178     */
179    private boolean ignoreOverriddenMethods = true;
180
181    /**
182     * Setter to allow to skip variables with {@code final} modifier.
183     *
184     * @param ignoreFinal
185     *        Defines if ignore variables with 'final' modifier or not.
186     * @since 5.8
187     */
188    public void setIgnoreFinal(boolean ignoreFinal) {
189        this.ignoreFinal = ignoreFinal;
190    }
191
192    /**
193     * Setter to allow to skip variables with {@code static} modifier.
194     *
195     * @param ignoreStatic
196     *        Defines if ignore variables with 'static' modifier or not.
197     * @since 5.8
198     */
199    public void setIgnoreStatic(boolean ignoreStatic) {
200        this.ignoreStatic = ignoreStatic;
201    }
202
203    /**
204     * Setter to allow to skip variables with both {@code static} and {@code final} modifiers.
205     *
206     * @param ignoreStaticFinal
207     *        Defines if ignore variables with both 'static' and 'final' modifiers or not.
208     * @since 8.32
209     */
210    public void setIgnoreStaticFinal(boolean ignoreStaticFinal) {
211        this.ignoreStaticFinal = ignoreStaticFinal;
212    }
213
214    /**
215     * Setter to allow to ignore methods tagged with {@code @Override}
216     * annotation (that usually mean inherited name).
217     *
218     * @param ignoreOverriddenMethods
219     *        Defines if ignore methods with "@Override" annotation or not.
220     * @since 5.8
221     */
222    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
223        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
224    }
225
226    /**
227     * Setter to indicate the number of consecutive capital letters allowed
228     * in targeted identifiers (abbreviations in the classes, interfaces,
229     * variables and methods names, ... ).
230     *
231     * @param allowedAbbreviationLength amount of allowed capital letters in
232     *        abbreviation.
233     * @since 5.8
234     */
235    public void setAllowedAbbreviationLength(int allowedAbbreviationLength) {
236        this.allowedAbbreviationLength = allowedAbbreviationLength;
237    }
238
239    /**
240     * Setter to specify abbreviations that must be skipped for checking.
241     *
242     * @param allowedAbbreviations abbreviations that must be
243     *        skipped from checking.
244     * @since 5.8
245     */
246    public void setAllowedAbbreviations(String... allowedAbbreviations) {
247        if (allowedAbbreviations != null) {
248            this.allowedAbbreviations =
249                Arrays.stream(allowedAbbreviations).collect(Collectors.toUnmodifiableSet());
250        }
251    }
252
253    @Override
254    public int[] getDefaultTokens() {
255        return new int[] {
256            TokenTypes.CLASS_DEF,
257            TokenTypes.INTERFACE_DEF,
258            TokenTypes.ENUM_DEF,
259            TokenTypes.ANNOTATION_DEF,
260            TokenTypes.ANNOTATION_FIELD_DEF,
261            TokenTypes.PARAMETER_DEF,
262            TokenTypes.VARIABLE_DEF,
263            TokenTypes.METHOD_DEF,
264            TokenTypes.PATTERN_VARIABLE_DEF,
265            TokenTypes.RECORD_DEF,
266            TokenTypes.RECORD_COMPONENT_DEF,
267        };
268    }
269
270    @Override
271    public int[] getAcceptableTokens() {
272        return new int[] {
273            TokenTypes.CLASS_DEF,
274            TokenTypes.INTERFACE_DEF,
275            TokenTypes.ENUM_DEF,
276            TokenTypes.ANNOTATION_DEF,
277            TokenTypes.ANNOTATION_FIELD_DEF,
278            TokenTypes.PARAMETER_DEF,
279            TokenTypes.VARIABLE_DEF,
280            TokenTypes.METHOD_DEF,
281            TokenTypes.ENUM_CONSTANT_DEF,
282            TokenTypes.PATTERN_VARIABLE_DEF,
283            TokenTypes.RECORD_DEF,
284            TokenTypes.RECORD_COMPONENT_DEF,
285        };
286    }
287
288    @Override
289    public int[] getRequiredTokens() {
290        return CommonUtil.EMPTY_INT_ARRAY;
291    }
292
293    @Override
294    public void visitToken(DetailAST ast) {
295        if (!isIgnoreSituation(ast)) {
296            final DetailAST nameAst = ast.findFirstToken(TokenTypes.IDENT);
297            final String typeName = nameAst.getText();
298
299            final String abbr = getDisallowedAbbreviation(typeName);
300            if (abbr != null) {
301                log(nameAst, MSG_KEY, typeName, allowedAbbreviationLength + 1);
302            }
303        }
304    }
305
306    /**
307     * Checks if it is an ignore situation.
308     *
309     * @param ast input DetailAST node.
310     * @return true if it is an ignore situation found for given input DetailAST
311     *         node.
312     */
313    private boolean isIgnoreSituation(DetailAST ast) {
314        final DetailAST modifiers = ast.getFirstChild();
315
316        final boolean result;
317        if (ast.getType() == TokenTypes.VARIABLE_DEF) {
318            if (isInterfaceDeclaration(ast)) {
319                // field declarations in interface are static/final
320                result = ignoreStaticFinal;
321            }
322            else {
323                result = hasIgnoredModifiers(modifiers);
324            }
325        }
326        else if (ast.getType() == TokenTypes.METHOD_DEF) {
327            result = ignoreOverriddenMethods && hasOverrideAnnotation(modifiers);
328        }
329        else {
330            result = CheckUtil.isReceiverParameter(ast);
331        }
332        return result;
333    }
334
335    /**
336     * Checks if a variable is to be ignored based on its modifiers.
337     *
338     * @param modifiers modifiers of the variable to be checked
339     * @return true if there is a modifier to be ignored
340     */
341    private boolean hasIgnoredModifiers(DetailAST modifiers) {
342        final boolean isStatic = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
343        final boolean isFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null;
344        final boolean result;
345        if (isStatic && isFinal) {
346            result = ignoreStaticFinal;
347        }
348        else {
349            result = ignoreStatic && isStatic || ignoreFinal && isFinal;
350        }
351        return result;
352    }
353
354    /**
355     * Check that variable definition in interface or @interface definition.
356     *
357     * @param variableDefAst variable definition.
358     * @return true if variable definition(variableDefAst) is in interface
359     *     or @interface definition.
360     */
361    private static boolean isInterfaceDeclaration(DetailAST variableDefAst) {
362        boolean result = false;
363        final DetailAST astBlock = variableDefAst.getParent();
364        final DetailAST astParent2 = astBlock.getParent();
365
366        if (astParent2.getType() == TokenTypes.INTERFACE_DEF
367                || astParent2.getType() == TokenTypes.ANNOTATION_DEF) {
368            result = true;
369        }
370        return result;
371    }
372
373    /**
374     * Checks that the method has "@Override" annotation.
375     *
376     * @param methodModifiersAST
377     *        A DetailAST nod is related to the given method modifiers
378     *        (MODIFIERS type).
379     * @return true if method has "@Override" annotation.
380     */
381    private static boolean hasOverrideAnnotation(DetailAST methodModifiersAST) {
382        boolean result = false;
383        for (DetailAST child : getChildren(methodModifiersAST)) {
384            final DetailAST annotationIdent = child.findFirstToken(TokenTypes.IDENT);
385
386            if (annotationIdent != null && "Override".equals(annotationIdent.getText())) {
387                result = true;
388                break;
389            }
390        }
391        return result;
392    }
393
394    /**
395     * Gets the disallowed abbreviation contained in given String.
396     *
397     * @param str
398     *        the given String.
399     * @return the disallowed abbreviation contained in given String as a
400     *         separate String.
401     */
402    private String getDisallowedAbbreviation(String str) {
403        int beginIndex = 0;
404        boolean abbrStarted = false;
405        String result = null;
406
407        for (int index = 0; index < str.length(); index++) {
408            final char symbol = str.charAt(index);
409
410            if (Character.isUpperCase(symbol)) {
411                if (!abbrStarted) {
412                    abbrStarted = true;
413                    beginIndex = index;
414                }
415            }
416            else if (abbrStarted) {
417                abbrStarted = false;
418
419                final int endIndex;
420                final int allowedLength;
421                if (symbol == '_') {
422                    endIndex = index;
423                    allowedLength = allowedAbbreviationLength + 1;
424                }
425                else {
426                    endIndex = index - 1;
427                    allowedLength = allowedAbbreviationLength;
428                }
429                result = getAbbreviationIfIllegal(str, beginIndex, endIndex, allowedLength);
430                if (result != null) {
431                    break;
432                }
433                beginIndex = -1;
434            }
435        }
436        // if abbreviation at the end of name (example: scaleX)
437        if (abbrStarted) {
438            final int endIndex = str.length() - 1;
439            result = getAbbreviationIfIllegal(str, beginIndex, endIndex, allowedAbbreviationLength);
440        }
441        return result;
442    }
443
444    /**
445     * Get Abbreviation if it is illegal, where {@code beginIndex} and {@code endIndex} are
446     * inclusive indexes of a sequence of consecutive upper-case characters.
447     *
448     * @param str name
449     * @param beginIndex begin index
450     * @param endIndex end index
451     * @param allowedLength maximum allowed length for Abbreviation
452     * @return the abbreviation if it is bigger than required and not in the
453     *         ignore list, otherwise {@code null}
454     */
455    private String getAbbreviationIfIllegal(String str, int beginIndex, int endIndex,
456                                            int allowedLength) {
457        String result = null;
458        final int abbrLength = endIndex - beginIndex;
459        if (abbrLength > allowedLength) {
460            final String abbr = getAbbreviation(str, beginIndex, endIndex);
461            if (!allowedAbbreviations.contains(abbr)) {
462                result = abbr;
463            }
464        }
465        return result;
466    }
467
468    /**
469     * Gets the abbreviation, where {@code beginIndex} and {@code endIndex} are
470     * inclusive indexes of a sequence of consecutive upper-case characters.
471     * <p>
472     * The character at {@code endIndex} is only included in the abbreviation if
473     * it is the last character in the string; otherwise it is usually the first
474     * capital in the next word.
475     * </p>
476     * <p>
477     * For example, {@code getAbbreviation("getXMLParser", 3, 6)} returns "XML"
478     * (not "XMLP"), and so does {@code getAbbreviation("parseXML", 5, 7)}.
479     * </p>
480     *
481     * @param str name
482     * @param beginIndex begin index
483     * @param endIndex end index
484     * @return the specified abbreviation
485     */
486    private static String getAbbreviation(String str, int beginIndex, int endIndex) {
487        final String result;
488        if (endIndex == str.length() - 1) {
489            result = str.substring(beginIndex);
490        }
491        else {
492            result = str.substring(beginIndex, endIndex);
493        }
494        return result;
495    }
496
497    /**
498     * Gets all the children which are one level below on the current DetailAST
499     * parent node.
500     *
501     * @param node
502     *        Current parent node.
503     * @return The list of children one level below on the current parent node.
504     */
505    private static List<DetailAST> getChildren(final DetailAST node) {
506        final List<DetailAST> result = new LinkedList<>();
507        DetailAST curNode = node.getFirstChild();
508        while (curNode != null) {
509            result.add(curNode);
510            curNode = curNode.getNextSibling();
511        }
512        return result;
513    }
514
515}