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