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