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