View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.imports;
21  
22  import java.util.HashSet;
23  import java.util.Set;
24  
25  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27  import com.puppycrawl.tools.checkstyle.api.DetailAST;
28  import com.puppycrawl.tools.checkstyle.api.FullIdent;
29  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30  
31  /**
32   * <div>
33   * Checks for redundant import statements. An import statement is
34   * considered redundant if:
35   * </div>
36   * <ul>
37   *   <li>It is a duplicate of another import. This is, when a class or a module
38   *   is imported more than once.</li>
39   *   <li>The class non-statically imported is from the {@code java.lang}
40   *   package, e.g. importing {@code java.lang.String}.</li>
41   *   <li>The class non-statically imported is from the same package as the
42   *   current package.</li>
43   * </ul>
44   *
45   * @since 3.0
46   */
47  @FileStatefulCheck
48  public class RedundantImportCheck
49      extends AbstractCheck {
50  
51      /**
52       * A key is pointing to the warning message text in "messages.properties"
53       * file.
54       */
55      public static final String MSG_LANG = "import.lang";
56  
57      /**
58       * A key is pointing to the warning message text in "messages.properties"
59       * file.
60       */
61      public static final String MSG_SAME = "import.same";
62  
63      /**
64       * A key is pointing to the warning message text in "messages.properties"
65       * file.
66       */
67      public static final String MSG_DUPLICATE = "import.duplicate";
68  
69      /** Set of the imports. */
70      private final Set<FullIdent> imports = new HashSet<>();
71      /** Set of static and module imports. */
72      private final Set<FullIdent> staticAndModuleImports = new HashSet<>();
73  
74      /** Name of package in file. */
75      private String pkgName;
76  
77      @Override
78      public void beginTree(DetailAST aRootAST) {
79          pkgName = null;
80          imports.clear();
81          staticAndModuleImports.clear();
82      }
83  
84      @Override
85      public int[] getDefaultTokens() {
86          return getRequiredTokens();
87      }
88  
89      @Override
90      public int[] getAcceptableTokens() {
91          return getRequiredTokens();
92      }
93  
94      @Override
95      public int[] getRequiredTokens() {
96          return new int[] {
97              TokenTypes.IMPORT,
98              TokenTypes.STATIC_IMPORT,
99              TokenTypes.PACKAGE_DEF,
100             TokenTypes.MODULE_IMPORT,
101         };
102     }
103 
104     @Override
105     public void visitToken(DetailAST ast) {
106         if (ast.getType() == TokenTypes.PACKAGE_DEF) {
107             pkgName = FullIdent.createFullIdent(
108                     ast.getLastChild().getPreviousSibling()).getText();
109         }
110         else if (ast.getType() == TokenTypes.IMPORT) {
111             final FullIdent imp = FullIdent.createFullIdentBelow(ast);
112             final String importText = imp.getText();
113             if (isFromPackage(importText, "java.lang")) {
114                 log(ast, MSG_LANG, importText);
115             }
116             // imports from unnamed package are not allowed,
117             // so we are checking SAME rule only for named packages
118             else if (pkgName != null && isFromPackage(importText, pkgName)) {
119                 log(ast, MSG_SAME, importText);
120             }
121             // Check for a duplicate import
122             imports.stream().filter(full -> importText.equals(full.getText()))
123                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
124 
125             imports.add(imp);
126         }
127         else {
128             // Check for a duplicate static or module import
129             final DetailAST identNode = ast.getLastChild().getPreviousSibling();
130             final FullIdent importFullIdent = FullIdent.createFullIdent(identNode);
131             final String importText = importFullIdent.getText();
132 
133             staticAndModuleImports
134                     .stream()
135                     .filter(existingImport -> importText.equals(existingImport.getText()))
136                     .forEach(existingImport -> {
137                         log(ast, MSG_DUPLICATE, existingImport.getLineNo(), importText);
138                     });
139 
140             staticAndModuleImports.add(importFullIdent);
141         }
142     }
143 
144     /**
145      * Determines if an import statement is for types from a specified package.
146      *
147      * @param importName the import name
148      * @param pkg the package name
149      * @return whether from the package
150      */
151     private static boolean isFromPackage(String importName, String pkg) {
152         // imports from unnamed package are not allowed:
153         // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
154         // So '.' must be present in member name and we are not checking for it
155         final int index = importName.lastIndexOf('.');
156         final String front = importName.substring(0, index);
157         return pkg.equals(front);
158     }
159 
160 }