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.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.CheckUtils;
034import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
035
036/**
037 * <p>
038 * The Check validate abbreviations(consecutive capital letters) length in
039 * identifier name, it also allows to enforce camel case naming. Please read more at
040 * <a href=
041 *  "http://checkstyle.sourceforge.net/reports/google-java-style-20170228.html#s5.3-camel-case">
042 * Google Style Guide</a> to get to know how to avoid long abbreviations in names.
043 * </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 * Option {@code allowedAbbreviationLength} indicates on the allowed amount of capital
056 * letters in abbreviations in the classes, interfaces,
057 * variables and methods names. Default value is '3'.
058 * </p>
059 * <p>
060 * Option {@code allowedAbbreviations} - list of abbreviations that
061 * must be skipped for checking. Abbreviations should be separated by comma,
062 * no spaces are allowed.
063 * </p>
064 * <p>
065 * Option {@code ignoreFinal} allow to skip variables with {@code final} modifier.
066 * Default value is {@code true}.
067 * </p>
068 * <p>
069 * Option {@code ignoreStatic} allow to skip variables with {@code static} modifier.
070 * Default value is {@code true}.
071 * </p>
072 * <p>
073 * Option {@code ignoreOverriddenMethod} - Allows to
074 * ignore methods tagged with {@code @Override} annotation
075 * (that usually mean inherited name). Default value is {@code true}.
076 * </p>
077 * Default configuration
078 * <pre>
079 * &lt;module name="AbbreviationAsWordInName" /&gt;
080 * </pre>
081 * <p>
082 * To configure to check variables and classes identifiers, do not ignore
083 * variables with static modifier
084 * and allow no abbreviations (enforce camel case phrase) but allow XML and URL abbreviations.
085 * </p>
086 * <pre>
087 * &lt;module name="AbbreviationAsWordInName"&gt;
088 *     &lt;property name="tokens" value="VARIABLE_DEF,CLASS_DEF"/&gt;
089 *     &lt;property name="ignoreStatic" value="false"/&gt;
090 *     &lt;property name="allowedAbbreviationLength" value="1"/&gt;
091 *     &lt;property name="allowedAbbreviations" value="XML,URL"/&gt;
092 * &lt;/module&gt;
093 * </pre>
094 *
095 */
096@StatelessCheck
097public class AbbreviationAsWordInNameCheck extends AbstractCheck {
098
099    /**
100     * Warning message key.
101     */
102    public static final String MSG_KEY = "abbreviation.as.word";
103
104    /**
105     * The default value of "allowedAbbreviationLength" option.
106     */
107    private static final int DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH = 3;
108
109    /**
110     * Variable indicates on the allowed amount of capital letters in
111     * abbreviations in the classes, interfaces, variables and methods names.
112     */
113    private int allowedAbbreviationLength =
114            DEFAULT_ALLOWED_ABBREVIATIONS_LENGTH;
115
116    /**
117     * Set of allowed abbreviation to ignore in check.
118     */
119    private Set<String> allowedAbbreviations = new HashSet<>();
120
121    /** Allows to ignore variables with 'final' modifier. */
122    private boolean ignoreFinal = true;
123
124    /** Allows to ignore variables with 'static' modifier. */
125    private boolean ignoreStatic = true;
126
127    /** Allows to ignore methods with '@Override' annotation. */
128    private boolean ignoreOverriddenMethods = true;
129
130    /**
131     * Sets ignore option for variables with 'final' modifier.
132     * @param ignoreFinal
133     *        Defines if ignore variables with 'final' modifier or not.
134     */
135    public void setIgnoreFinal(boolean ignoreFinal) {
136        this.ignoreFinal = ignoreFinal;
137    }
138
139    /**
140     * Sets ignore option for variables with 'static' modifier.
141     * @param ignoreStatic
142     *        Defines if ignore variables with 'static' modifier or not.
143     */
144    public void setIgnoreStatic(boolean ignoreStatic) {
145        this.ignoreStatic = ignoreStatic;
146    }
147
148    /**
149     * Sets ignore option for methods with "@Override" annotation.
150     * @param ignoreOverriddenMethods
151     *        Defines if ignore methods with "@Override" annotation or not.
152     */
153    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
154        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
155    }
156
157    /**
158     * Allowed abbreviation length in names.
159     * @param allowedAbbreviationLength
160     *            amount of allowed capital letters in abbreviation.
161     */
162    public void setAllowedAbbreviationLength(int allowedAbbreviationLength) {
163        this.allowedAbbreviationLength = allowedAbbreviationLength;
164    }
165
166    /**
167     * Set a list of abbreviations that must be skipped for checking.
168     * Abbreviations should be separated by comma, no spaces is allowed.
169     * @param allowedAbbreviations
170     *        an string of abbreviations that must be skipped from checking,
171     *        each abbreviation separated by comma.
172     */
173    public void setAllowedAbbreviations(String... allowedAbbreviations) {
174        if (allowedAbbreviations != null) {
175            this.allowedAbbreviations =
176                Arrays.stream(allowedAbbreviations).collect(Collectors.toSet());
177        }
178    }
179
180    @Override
181    public int[] getDefaultTokens() {
182        return new int[] {
183            TokenTypes.CLASS_DEF,
184            TokenTypes.INTERFACE_DEF,
185            TokenTypes.ENUM_DEF,
186            TokenTypes.ANNOTATION_DEF,
187            TokenTypes.ANNOTATION_FIELD_DEF,
188            TokenTypes.PARAMETER_DEF,
189            TokenTypes.VARIABLE_DEF,
190            TokenTypes.METHOD_DEF,
191        };
192    }
193
194    @Override
195    public int[] getAcceptableTokens() {
196        return new int[] {
197            TokenTypes.CLASS_DEF,
198            TokenTypes.INTERFACE_DEF,
199            TokenTypes.ENUM_DEF,
200            TokenTypes.ANNOTATION_DEF,
201            TokenTypes.ANNOTATION_FIELD_DEF,
202            TokenTypes.PARAMETER_DEF,
203            TokenTypes.VARIABLE_DEF,
204            TokenTypes.METHOD_DEF,
205            TokenTypes.ENUM_CONSTANT_DEF,
206        };
207    }
208
209    @Override
210    public int[] getRequiredTokens() {
211        return CommonUtils.EMPTY_INT_ARRAY;
212    }
213
214    @Override
215    public void visitToken(DetailAST ast) {
216        if (!isIgnoreSituation(ast)) {
217            final DetailAST nameAst = ast.findFirstToken(TokenTypes.IDENT);
218            final String typeName = nameAst.getText();
219
220            final String abbr = getDisallowedAbbreviation(typeName);
221            if (abbr != null) {
222                log(nameAst.getLineNo(), MSG_KEY, typeName, allowedAbbreviationLength + 1);
223            }
224        }
225    }
226
227    /**
228     * Checks if it is an ignore situation.
229     * @param ast input DetailAST node.
230     * @return true if it is an ignore situation found for given input DetailAST
231     *         node.
232     * @noinspection SimplifiableIfStatement
233     */
234    private boolean isIgnoreSituation(DetailAST ast) {
235        final DetailAST modifiers = ast.getFirstChild();
236
237        final boolean result;
238        if (ast.getType() == TokenTypes.VARIABLE_DEF) {
239            if ((ignoreFinal || ignoreStatic)
240                    && isInterfaceDeclaration(ast)) {
241                // field declarations in interface are static/final
242                result = true;
243            }
244            else {
245                result = ignoreFinal
246                          && modifiers.findFirstToken(TokenTypes.FINAL) != null
247                    || ignoreStatic
248                        && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
249            }
250        }
251        else if (ast.getType() == TokenTypes.METHOD_DEF) {
252            result = ignoreOverriddenMethods && hasOverrideAnnotation(modifiers);
253        }
254        else {
255            result = CheckUtils.isReceiverParameter(ast);
256        }
257        return result;
258    }
259
260    /**
261     * Check that variable definition in interface or @interface definition.
262     * @param variableDefAst variable definition.
263     * @return true if variable definition(variableDefAst) is in interface
264     *     or @interface definition.
265     */
266    private static boolean isInterfaceDeclaration(DetailAST variableDefAst) {
267        boolean result = false;
268        final DetailAST astBlock = variableDefAst.getParent();
269        final DetailAST astParent2 = astBlock.getParent();
270
271        if (astParent2.getType() == TokenTypes.INTERFACE_DEF
272                || astParent2.getType() == TokenTypes.ANNOTATION_DEF) {
273            result = true;
274        }
275        return result;
276    }
277
278    /**
279     * Checks that the method has "@Override" annotation.
280     * @param methodModifiersAST
281     *        A DetailAST nod is related to the given method modifiers
282     *        (MODIFIERS type).
283     * @return true if method has "@Override" annotation.
284     */
285    private static boolean hasOverrideAnnotation(DetailAST methodModifiersAST) {
286        boolean result = false;
287        for (DetailAST child : getChildren(methodModifiersAST)) {
288            if (child.getType() == TokenTypes.ANNOTATION) {
289                final DetailAST annotationIdent = child.findFirstToken(TokenTypes.IDENT);
290
291                if (annotationIdent != null && "Override".equals(annotationIdent.getText())) {
292                    result = true;
293                    break;
294                }
295            }
296        }
297        return result;
298    }
299
300    /**
301     * Gets the disallowed abbreviation contained in given String.
302     * @param str
303     *        the given String.
304     * @return the disallowed abbreviation contained in given String as a
305     *         separate String.
306     */
307    private String getDisallowedAbbreviation(String str) {
308        int beginIndex = 0;
309        boolean abbrStarted = false;
310        String result = null;
311
312        for (int index = 0; index < str.length(); index++) {
313            final char symbol = str.charAt(index);
314
315            if (Character.isUpperCase(symbol)) {
316                if (!abbrStarted) {
317                    abbrStarted = true;
318                    beginIndex = index;
319                }
320            }
321            else if (abbrStarted) {
322                abbrStarted = false;
323
324                final int endIndex = index - 1;
325                // -1 as a first capital is usually beginning of next word
326                result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
327                if (result != null) {
328                    break;
329                }
330                beginIndex = -1;
331            }
332        }
333        // if abbreviation at the end of name and it is not single character (example: scaleX)
334        if (abbrStarted && beginIndex != str.length() - 1) {
335            final int endIndex = str.length();
336            result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
337        }
338        return result;
339    }
340
341    /**
342     * Get Abbreviation if it is illegal.
343     * @param str name
344     * @param beginIndex begin index
345     * @param endIndex end index
346     * @return true is abbreviation is bigger that required and not in ignore list
347     */
348    private String getAbbreviationIfIllegal(String str, int beginIndex, int endIndex) {
349        String result = null;
350        final int abbrLength = endIndex - beginIndex;
351        if (abbrLength > allowedAbbreviationLength) {
352            final String abbr = str.substring(beginIndex, endIndex);
353            if (!allowedAbbreviations.contains(abbr)) {
354                result = abbr;
355            }
356        }
357        return result;
358    }
359
360    /**
361     * Gets all the children which are one level below on the current DetailAST
362     * parent node.
363     * @param node
364     *        Current parent node.
365     * @return The list of children one level below on the current parent node.
366     */
367    private static List<DetailAST> getChildren(final DetailAST node) {
368        final List<DetailAST> result = new LinkedList<>();
369        DetailAST curNode = node.getFirstChild();
370        while (curNode != null) {
371            result.add(curNode);
372            curNode = curNode.getNextSibling();
373        }
374        return result;
375    }
376
377}