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