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