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.modifier;
021
022import java.util.ArrayList;
023import java.util.List;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
030
031/**
032 * Checks for redundant modifiers in interface and annotation definitions,
033 * final modifier on methods of final classes, inner {@code interface}
034 * declarations that are declared as {@code static}, non public class
035 * constructors and enum constructors, nested enum definitions that are declared
036 * as {@code static}.
037 *
038 * <p>Interfaces by definition are abstract so the {@code abstract}
039 * modifier on the interface is redundant.
040 *
041 * <p>Classes inside of interfaces by definition are public and static,
042 * so the {@code public} and {@code static} modifiers
043 * on the inner classes are redundant. On the other hand, classes
044 * inside of interfaces can be abstract or non abstract.
045 * So, {@code abstract} modifier is allowed.
046 *
047 * <p>Fields in interfaces and annotations are automatically
048 * public, static and final, so these modifiers are redundant as
049 * well.</p>
050 *
051 * <p>As annotations are a form of interface, their fields are also
052 * automatically public, static and final just as their
053 * annotation fields are automatically public and abstract.</p>
054 *
055 * <p>Enums by definition are static implicit subclasses of java.lang.Enum&#60;E&#62;.
056 * So, the {@code static} modifier on the enums is redundant. In addition,
057 * if enum is inside of interface, {@code public} modifier is also redundant.</p>
058 *
059 * <p>Enums can also contain abstract methods and methods which can be overridden by the declared
060 * enumeration fields.
061 * See the following example:</p>
062 * <pre>
063 * public enum EnumClass {
064 *    FIELD_1,
065 *    FIELD_2 {
066 *        &#64;Override
067 *        public final void method1() {} // violation expected
068 *    };
069 *
070 *    public void method1() {}
071 *    public final void method2() {} // no violation expected
072 * }
073 * </pre>
074 *
075 * <p>Since these methods can be overridden in these situations, the final methods are not
076 * marked as redundant even though they can't be extended by other classes/enums.</p>
077 *
078 * <p>Final classes by definition cannot be extended so the {@code final}
079 * modifier on the method of a final class is redundant.
080 *
081 * <p>Public modifier for constructors in non-public non-protected classes
082 * is always obsolete: </p>
083 *
084 * <pre>
085 * public class PublicClass {
086 *     public PublicClass() {} // OK
087 * }
088 *
089 * class PackagePrivateClass {
090 *     public PackagePrivateClass() {} // violation expected
091 * }
092 * </pre>
093 *
094 * <p>There is no violation in the following example,
095 * because removing public modifier from ProtectedInnerClass
096 * constructor will make this code not compiling: </p>
097 *
098 * <pre>
099 * package a;
100 * public class ClassExample {
101 *     protected class ProtectedInnerClass {
102 *         public ProtectedInnerClass () {}
103 *     }
104 * }
105 *
106 * package b;
107 * import a.ClassExample;
108 * public class ClassExtending extends ClassExample {
109 *     ProtectedInnerClass pc = new ProtectedInnerClass();
110 * }
111 * </pre>
112 *
113 */
114@StatelessCheck
115public class RedundantModifierCheck
116    extends AbstractCheck {
117
118    /**
119     * A key is pointing to the warning message text in "messages.properties"
120     * file.
121     */
122    public static final String MSG_KEY = "redundantModifier";
123
124    /**
125     * An array of tokens for interface modifiers.
126     */
127    private static final int[] TOKENS_FOR_INTERFACE_MODIFIERS = {
128        TokenTypes.LITERAL_STATIC,
129        TokenTypes.ABSTRACT,
130    };
131
132    @Override
133    public int[] getDefaultTokens() {
134        return getAcceptableTokens();
135    }
136
137    @Override
138    public int[] getRequiredTokens() {
139        return CommonUtils.EMPTY_INT_ARRAY;
140    }
141
142    @Override
143    public int[] getAcceptableTokens() {
144        return new int[] {
145            TokenTypes.METHOD_DEF,
146            TokenTypes.VARIABLE_DEF,
147            TokenTypes.ANNOTATION_FIELD_DEF,
148            TokenTypes.INTERFACE_DEF,
149            TokenTypes.CTOR_DEF,
150            TokenTypes.CLASS_DEF,
151            TokenTypes.ENUM_DEF,
152            TokenTypes.RESOURCE,
153        };
154    }
155
156    @Override
157    public void visitToken(DetailAST ast) {
158        if (ast.getType() == TokenTypes.INTERFACE_DEF) {
159            checkInterfaceModifiers(ast);
160        }
161        else if (ast.getType() == TokenTypes.ENUM_DEF) {
162            checkEnumDef(ast);
163        }
164        else {
165            if (ast.getType() == TokenTypes.CTOR_DEF) {
166                if (isEnumMember(ast)) {
167                    checkEnumConstructorModifiers(ast);
168                }
169                else {
170                    checkClassConstructorModifiers(ast);
171                }
172            }
173            else if (ast.getType() == TokenTypes.METHOD_DEF) {
174                processMethods(ast);
175            }
176            else if (ast.getType() == TokenTypes.RESOURCE) {
177                processResources(ast);
178            }
179
180            if (isInterfaceOrAnnotationMember(ast)) {
181                processInterfaceOrAnnotation(ast);
182            }
183        }
184    }
185
186    /**
187     * Checks if interface has proper modifiers.
188     * @param ast interface to check
189     */
190    private void checkInterfaceModifiers(DetailAST ast) {
191        final DetailAST modifiers =
192            ast.findFirstToken(TokenTypes.MODIFIERS);
193
194        for (final int tokenType : TOKENS_FOR_INTERFACE_MODIFIERS) {
195            final DetailAST modifier =
196                    modifiers.findFirstToken(tokenType);
197            if (modifier != null) {
198                log(modifier.getLineNo(), modifier.getColumnNo(),
199                        MSG_KEY, modifier.getText());
200            }
201        }
202    }
203
204    /**
205     * Check if enum constructor has proper modifiers.
206     * @param ast constructor of enum
207     */
208    private void checkEnumConstructorModifiers(DetailAST ast) {
209        final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
210        final DetailAST modifier = getFirstModifierAst(modifiers);
211
212        if (modifier != null) {
213            log(modifier.getLineNo(), modifier.getColumnNo(),
214                    MSG_KEY, modifier.getText());
215        }
216    }
217
218    /**
219     * Retrieves the first modifier that is not an annotation.
220     * @param modifiers The ast to examine.
221     * @return The first modifier or {@code null} if none found.
222     */
223    private static DetailAST getFirstModifierAst(DetailAST modifiers) {
224        DetailAST modifier = modifiers.getFirstChild();
225
226        while (modifier != null && modifier.getType() == TokenTypes.ANNOTATION) {
227            modifier = modifier.getNextSibling();
228        }
229
230        return modifier;
231    }
232
233    /**
234     * Checks whether enum has proper modifiers.
235     * @param ast enum definition.
236     */
237    private void checkEnumDef(DetailAST ast) {
238        if (isInterfaceOrAnnotationMember(ast)) {
239            processInterfaceOrAnnotation(ast);
240        }
241        else if (ast.getParent() != null) {
242            checkForRedundantModifier(ast, TokenTypes.LITERAL_STATIC);
243        }
244    }
245
246    /**
247     * Do validation of interface of annotation.
248     * @param ast token AST
249     */
250    private void processInterfaceOrAnnotation(DetailAST ast) {
251        final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
252        DetailAST modifier = modifiers.getFirstChild();
253        while (modifier != null) {
254            // javac does not allow final or static in interface methods
255            // order annotation fields hence no need to check that this
256            // is not a method or annotation field
257
258            final int type = modifier.getType();
259            if (type == TokenTypes.LITERAL_PUBLIC
260                || type == TokenTypes.LITERAL_STATIC
261                        && ast.getType() != TokenTypes.METHOD_DEF
262                || type == TokenTypes.ABSTRACT
263                        && ast.getType() != TokenTypes.CLASS_DEF
264                || type == TokenTypes.FINAL
265                        && ast.getType() != TokenTypes.CLASS_DEF) {
266                log(modifier.getLineNo(), modifier.getColumnNo(),
267                        MSG_KEY, modifier.getText());
268                break;
269            }
270
271            modifier = modifier.getNextSibling();
272        }
273    }
274
275    /**
276     * Process validation of Methods.
277     * @param ast method AST
278     */
279    private void processMethods(DetailAST ast) {
280        final DetailAST modifiers =
281                        ast.findFirstToken(TokenTypes.MODIFIERS);
282        // private method?
283        boolean checkFinal =
284            modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null;
285        // declared in a final class?
286        DetailAST parent = ast.getParent();
287        while (parent != null && !checkFinal) {
288            if (parent.getType() == TokenTypes.CLASS_DEF) {
289                final DetailAST classModifiers =
290                    parent.findFirstToken(TokenTypes.MODIFIERS);
291                checkFinal = classModifiers.findFirstToken(TokenTypes.FINAL) != null;
292                parent = null;
293            }
294            else if (parent.getType() == TokenTypes.LITERAL_NEW
295                    || parent.getType() == TokenTypes.ENUM_CONSTANT_DEF) {
296                checkFinal = true;
297                parent = null;
298            }
299            else if (parent.getType() == TokenTypes.ENUM_DEF) {
300                checkFinal = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
301                parent = null;
302            }
303            else {
304                parent = parent.getParent();
305            }
306        }
307        if (checkFinal && !isAnnotatedWithSafeVarargs(ast)) {
308            checkForRedundantModifier(ast, TokenTypes.FINAL);
309        }
310
311        if (ast.findFirstToken(TokenTypes.SLIST) == null) {
312            processAbstractMethodParameters(ast);
313        }
314    }
315
316    /**
317     * Process validation of parameters for Methods with no definition.
318     * @param ast method AST
319     */
320    private void processAbstractMethodParameters(DetailAST ast) {
321        final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
322
323        for (DetailAST child = parameters.getFirstChild(); child != null; child = child
324                .getNextSibling()) {
325            if (child.getType() == TokenTypes.PARAMETER_DEF) {
326                checkForRedundantModifier(child, TokenTypes.FINAL);
327            }
328        }
329    }
330
331    /**
332     * Check if class constructor has proper modifiers.
333     * @param classCtorAst class constructor ast
334     */
335    private void checkClassConstructorModifiers(DetailAST classCtorAst) {
336        final DetailAST classDef = classCtorAst.getParent().getParent();
337        if (!isClassPublic(classDef) && !isClassProtected(classDef)) {
338            checkForRedundantModifier(classCtorAst, TokenTypes.LITERAL_PUBLIC);
339        }
340    }
341
342    /**
343     * Checks if given resource has redundant modifiers.
344     * @param ast ast
345     */
346    private void processResources(DetailAST ast) {
347        checkForRedundantModifier(ast, TokenTypes.FINAL);
348    }
349
350    /**
351     * Checks if given ast has a redundant modifier.
352     * @param ast ast
353     * @param modifierType The modifier to check for.
354     */
355    private void checkForRedundantModifier(DetailAST ast, int modifierType) {
356        final DetailAST astModifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
357        DetailAST astModifier = astModifiers.getFirstChild();
358        while (astModifier != null) {
359            if (astModifier.getType() == modifierType) {
360                log(astModifier.getLineNo(), astModifier.getColumnNo(),
361                        MSG_KEY, astModifier.getText());
362            }
363
364            astModifier = astModifier.getNextSibling();
365        }
366    }
367
368    /**
369     * Checks if given class ast has protected modifier.
370     * @param classDef class ast
371     * @return true if class is protected, false otherwise
372     */
373    private static boolean isClassProtected(DetailAST classDef) {
374        final DetailAST classModifiers =
375                classDef.findFirstToken(TokenTypes.MODIFIERS);
376        return classModifiers.findFirstToken(TokenTypes.LITERAL_PROTECTED) != null;
377    }
378
379    /**
380     * Checks if given class is accessible from "public" scope.
381     * @param ast class def to check
382     * @return true if class is accessible from public scope,false otherwise
383     */
384    private static boolean isClassPublic(DetailAST ast) {
385        boolean isAccessibleFromPublic = false;
386        final boolean isMostOuterScope = ast.getParent() == null;
387        final DetailAST modifiersAst = ast.findFirstToken(TokenTypes.MODIFIERS);
388        final boolean hasPublicModifier =
389                modifiersAst.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null;
390
391        if (isMostOuterScope) {
392            isAccessibleFromPublic = hasPublicModifier;
393        }
394        else {
395            final DetailAST parentClassAst = ast.getParent().getParent();
396
397            if (hasPublicModifier || parentClassAst.getType() == TokenTypes.INTERFACE_DEF) {
398                isAccessibleFromPublic = isClassPublic(parentClassAst);
399            }
400        }
401
402        return isAccessibleFromPublic;
403    }
404
405    /**
406     * Checks if current AST node is member of Enum.
407     * @param ast AST node
408     * @return true if it is an enum member
409     */
410    private static boolean isEnumMember(DetailAST ast) {
411        final DetailAST parentTypeDef = ast.getParent().getParent();
412        return parentTypeDef.getType() == TokenTypes.ENUM_DEF;
413    }
414
415    /**
416     * Checks if current AST node is member of Interface or Annotation, not of their subnodes.
417     * @param ast AST node
418     * @return true or false
419     */
420    private static boolean isInterfaceOrAnnotationMember(DetailAST ast) {
421        DetailAST parentTypeDef = ast.getParent();
422
423        if (parentTypeDef != null) {
424            parentTypeDef = parentTypeDef.getParent();
425        }
426        return parentTypeDef != null
427                && (parentTypeDef.getType() == TokenTypes.INTERFACE_DEF
428                    || parentTypeDef.getType() == TokenTypes.ANNOTATION_DEF);
429    }
430
431    /**
432     * Checks if method definition is annotated with.
433     * <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/SafeVarargs.html">
434     * SafeVarargs</a> annotation
435     * @param methodDef method definition node
436     * @return true or false
437     */
438    private static boolean isAnnotatedWithSafeVarargs(DetailAST methodDef) {
439        boolean result = false;
440        final List<DetailAST> methodAnnotationsList = getMethodAnnotationsList(methodDef);
441        for (DetailAST annotationNode : methodAnnotationsList) {
442            if ("SafeVarargs".equals(annotationNode.getLastChild().getText())) {
443                result = true;
444                break;
445            }
446        }
447        return result;
448    }
449
450    /**
451     * Gets the list of annotations on method definition.
452     * @param methodDef method definition node
453     * @return List of annotations
454     */
455    private static List<DetailAST> getMethodAnnotationsList(DetailAST methodDef) {
456        final List<DetailAST> annotationsList = new ArrayList<>();
457        final DetailAST modifiers = methodDef.findFirstToken(TokenTypes.MODIFIERS);
458        DetailAST modifier = modifiers.getFirstChild();
459        while (modifier != null) {
460            if (modifier.getType() == TokenTypes.ANNOTATION) {
461                annotationsList.add(modifier);
462            }
463            modifier = modifier.getNextSibling();
464        }
465        return annotationsList;
466    }
467
468}