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.HashSet;
023import java.util.LinkedList;
024import java.util.List;
025import java.util.Set;
026
027import com.google.common.collect.Sets;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.TokenTypes;
031import com.puppycrawl.tools.checkstyle.utils.CheckUtils;
032import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
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 = Sets.newHashSet(allowedAbbreviations);
163        }
164    }
165
166    @Override
167    public int[] getDefaultTokens() {
168        return new int[] {
169            TokenTypes.CLASS_DEF,
170            TokenTypes.INTERFACE_DEF,
171            TokenTypes.ENUM_DEF,
172            TokenTypes.ANNOTATION_DEF,
173            TokenTypes.ANNOTATION_FIELD_DEF,
174            TokenTypes.PARAMETER_DEF,
175            TokenTypes.VARIABLE_DEF,
176            TokenTypes.METHOD_DEF,
177        };
178    }
179
180    @Override
181    public int[] getAcceptableTokens() {
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            TokenTypes.ENUM_CONSTANT_DEF,
192        };
193    }
194
195    @Override
196    public int[] getRequiredTokens() {
197        return CommonUtils.EMPTY_INT_ARRAY;
198    }
199
200    @Override
201    public void visitToken(DetailAST ast) {
202
203        if (!isIgnoreSituation(ast)) {
204
205            final DetailAST nameAst = ast.findFirstToken(TokenTypes.IDENT);
206            final String typeName = nameAst.getText();
207
208            final String abbr = getDisallowedAbbreviation(typeName);
209            if (abbr != null) {
210                log(nameAst.getLineNo(), MSG_KEY, typeName, allowedAbbreviationLength);
211            }
212        }
213    }
214
215    /**
216     * Checks if it is an ignore situation.
217     * @param ast input DetailAST node.
218     * @return true if it is an ignore situation found for given input DetailAST
219     *         node.
220     */
221    private boolean isIgnoreSituation(DetailAST ast) {
222        final DetailAST modifiers = ast.getFirstChild();
223
224        final boolean result;
225        if (ast.getType() == TokenTypes.VARIABLE_DEF) {
226            if ((ignoreFinal || ignoreStatic)
227                    && isInterfaceDeclaration(ast)) {
228                // field declarations in interface are static/final
229                result = true;
230            }
231            else {
232                result = ignoreFinal
233                          && modifiers.branchContains(TokenTypes.FINAL)
234                    || ignoreStatic
235                        && modifiers.branchContains(TokenTypes.LITERAL_STATIC);
236            }
237        }
238        else if (ast.getType() == TokenTypes.METHOD_DEF) {
239            result = ignoreOverriddenMethods
240                    && hasOverrideAnnotation(modifiers);
241        }
242        else {
243            result = CheckUtils.isReceiverParameter(ast);
244        }
245        return result;
246    }
247
248    /**
249     * Check that variable definition in interface or @interface definition.
250     * @param variableDefAst variable definition.
251     * @return true if variable definition(variableDefAst) is in interface
252     *     or @interface definition.
253     */
254    private static boolean isInterfaceDeclaration(DetailAST variableDefAst) {
255        boolean result = false;
256        final DetailAST astBlock = variableDefAst.getParent();
257        final DetailAST astParent2 = astBlock.getParent();
258
259        if (astParent2.getType() == TokenTypes.INTERFACE_DEF
260                || astParent2.getType() == TokenTypes.ANNOTATION_DEF) {
261            result = true;
262        }
263        return result;
264    }
265
266    /**
267     * Checks that the method has "@Override" annotation.
268     * @param methodModifiersAST
269     *        A DetailAST nod is related to the given method modifiers
270     *        (MODIFIERS type).
271     * @return true if method has "@Override" annotation.
272     */
273    private static boolean hasOverrideAnnotation(DetailAST methodModifiersAST) {
274        boolean result = false;
275        for (DetailAST child : getChildren(methodModifiersAST)) {
276            if (child.getType() == TokenTypes.ANNOTATION) {
277                final DetailAST annotationIdent = child.findFirstToken(TokenTypes.IDENT);
278
279                if (annotationIdent != null && "Override".equals(annotationIdent.getText())) {
280                    result = true;
281                    break;
282                }
283            }
284        }
285        return result;
286    }
287
288    /**
289     * Gets the disallowed abbreviation contained in given String.
290     * @param str
291     *        the given String.
292     * @return the disallowed abbreviation contained in given String as a
293     *         separate String.
294     */
295    private String getDisallowedAbbreviation(String str) {
296        int beginIndex = 0;
297        boolean abbrStarted = false;
298        String result = null;
299
300        for (int index = 0; index < str.length(); index++) {
301            final char symbol = str.charAt(index);
302
303            if (Character.isUpperCase(symbol)) {
304                if (!abbrStarted) {
305                    abbrStarted = true;
306                    beginIndex = index;
307                }
308            }
309            else if (abbrStarted) {
310                abbrStarted = false;
311
312                final int endIndex = index - 1;
313                // -1 as a first capital is usually beginning of next word
314                result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
315                if (result != null) {
316                    break;
317                }
318                beginIndex = -1;
319            }
320        }
321        // if abbreviation at the end of name and it is not single character (example: scaleX)
322        if (abbrStarted && beginIndex != str.length() - 1) {
323            final int endIndex = str.length();
324            result = getAbbreviationIfIllegal(str, beginIndex, endIndex);
325        }
326        return result;
327    }
328
329    /**
330     * Get Abbreviation if it is illegal.
331     * @param str name
332     * @param beginIndex begin index
333     * @param endIndex end index
334     * @return true is abbreviation is bigger that required and not in ignore list
335     */
336    private String getAbbreviationIfIllegal(String str, int beginIndex, int endIndex) {
337        String result = null;
338        final int abbrLength = endIndex - beginIndex;
339        if (abbrLength > allowedAbbreviationLength) {
340            final String abbr = str.substring(beginIndex, endIndex);
341            if (!allowedAbbreviations.contains(abbr)) {
342                result = abbr;
343            }
344        }
345        return result;
346    }
347
348    /**
349     * Gets all the children which are one level below on the current DetailAST
350     * parent node.
351     * @param node
352     *        Current parent node.
353     * @return The list of children one level below on the current parent node.
354     */
355    private static List<DetailAST> getChildren(final DetailAST node) {
356        final List<DetailAST> result = new LinkedList<>();
357        DetailAST curNode = node.getFirstChild();
358        while (curNode != null) {
359            result.add(curNode);
360            curNode = curNode.getNextSibling();
361        }
362        return result;
363    }
364
365}