001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 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.Check;
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 Check {
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, 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 definition.
248     * @param variableDefAst variable definition.
249     * @return true if variable definition(variableDefAst) is in interface
250     *     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            result = true;
259        }
260        return result;
261    }
262
263    /**
264     * Checks that the method has "@Override" annotation.
265     * @param methodModifiersAST
266     *        A DetailAST nod is related to the given method modifiers
267     *        (MODIFIERS type).
268     * @return true if method has "@Override" annotation.
269     */
270    private static boolean hasOverrideAnnotation(DetailAST methodModifiersAST) {
271        boolean result = false;
272        for (DetailAST child : getChildren(methodModifiersAST)) {
273            if (child.getType() == TokenTypes.ANNOTATION) {
274                final DetailAST annotationIdent = child.findFirstToken(TokenTypes.IDENT);
275
276                if (annotationIdent != null && "Override".equals(annotationIdent.getText())) {
277                    result = true;
278                    break;
279                }
280            }
281        }
282        return result;
283    }
284
285    /**
286     * Gets the disallowed abbreviation contained in given String.
287     * @param str
288     *        the given String.
289     * @return the disallowed abbreviation contained in given String as a
290     *         separate String.
291     */
292    private String getDisallowedAbbreviation(String str) {
293        int beginIndex = 0;
294        boolean abbrStarted = false;
295        String result = null;
296
297        for (int index = 0; index < str.length(); index++) {
298            final char symbol = str.charAt(index);
299
300            if (Character.isUpperCase(symbol)) {
301                if (!abbrStarted) {
302                    abbrStarted = true;
303                    beginIndex = index;
304                }
305            }
306            else if (abbrStarted) {
307                abbrStarted = false;
308
309                final int endIndex = index - 1;
310                // -1 as a first capital is usually beginning of next word
311                result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
312                if (result != null) {
313                    break;
314                }
315                beginIndex = -1;
316            }
317        }
318        // if abbreviation at the end of name and it is not single character (example: scaleX)
319        if (abbrStarted && beginIndex != str.length() - 1) {
320            final int endIndex = str.length();
321            result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
322        }
323        return result;
324    }
325
326    /**
327     * Get Abbreviation if it is illegal.
328     * @param str name
329     * @param beginIndex begin index
330     * @param endIndex end index
331     * @return true is abbreviation is bigger that required and not in ignore list
332     */
333    private String getAbbreviationIfIllegal(String str, int beginIndex, int endIndex) {
334        String result = null;
335        final int abbrLength = endIndex - beginIndex;
336        if (abbrLength > allowedAbbreviationLength) {
337            final String abbr = str.substring(beginIndex, endIndex);
338            if (!allowedAbbreviations.contains(abbr)) {
339                result = abbr;
340            }
341        }
342        return result;
343    }
344
345    /**
346     * Gets all the children which are one level below on the current DetailAST
347     * parent node.
348     * @param node
349     *        Current parent node.
350     * @return The list of children one level below on the current parent node.
351     */
352    private static List<DetailAST> getChildren(final DetailAST node) {
353        final List<DetailAST> result = new LinkedList<>();
354        DetailAST curNode = node.getFirstChild();
355        while (curNode != null) {
356            result.add(curNode);
357            curNode = curNode.getNextSibling();
358        }
359        return result;
360    }
361
362}