View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 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   * <p>
33   * Checks for redundant import statements. An import statement is
34   * considered redundant if:
35   * </p>
36   * <ul>
37   *   <li>It is a duplicate of another import. This is, when a class is imported
38   *   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   * <p>
45   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
46   * </p>
47   * <p>
48   * Violation Message Keys:
49   * </p>
50   * <ul>
51   * <li>
52   * {@code import.duplicate}
53   * </li>
54   * <li>
55   * {@code import.lang}
56   * </li>
57   * <li>
58   * {@code import.same}
59   * </li>
60   * </ul>
61   *
62   * @since 3.0
63   */
64  @FileStatefulCheck
65  public class RedundantImportCheck
66      extends AbstractCheck {
67  
68      /**
69       * A key is pointing to the warning message text in "messages.properties"
70       * file.
71       */
72      public static final String MSG_LANG = "import.lang";
73  
74      /**
75       * A key is pointing to the warning message text in "messages.properties"
76       * file.
77       */
78      public static final String MSG_SAME = "import.same";
79  
80      /**
81       * A key is pointing to the warning message text in "messages.properties"
82       * file.
83       */
84      public static final String MSG_DUPLICATE = "import.duplicate";
85  
86      /** Set of the imports. */
87      private final Set<FullIdent> imports = new HashSet<>();
88      /** Set of static imports. */
89      private final Set<FullIdent> staticImports = new HashSet<>();
90  
91      /** Name of package in file. */
92      private String pkgName;
93  
94      @Override
95      public void beginTree(DetailAST aRootAST) {
96          pkgName = null;
97          imports.clear();
98          staticImports.clear();
99      }
100 
101     @Override
102     public int[] getDefaultTokens() {
103         return getRequiredTokens();
104     }
105 
106     @Override
107     public int[] getAcceptableTokens() {
108         return getRequiredTokens();
109     }
110 
111     @Override
112     public int[] getRequiredTokens() {
113         return new int[] {
114             TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF,
115         };
116     }
117 
118     @Override
119     public void visitToken(DetailAST ast) {
120         if (ast.getType() == TokenTypes.PACKAGE_DEF) {
121             pkgName = FullIdent.createFullIdent(
122                     ast.getLastChild().getPreviousSibling()).getText();
123         }
124         else if (ast.getType() == TokenTypes.IMPORT) {
125             final FullIdent imp = FullIdent.createFullIdentBelow(ast);
126             final String importText = imp.getText();
127             if (isFromPackage(importText, "java.lang")) {
128                 log(ast, MSG_LANG, importText);
129             }
130             // imports from unnamed package are not allowed,
131             // so we are checking SAME rule only for named packages
132             else if (pkgName != null && isFromPackage(importText, pkgName)) {
133                 log(ast, MSG_SAME, importText);
134             }
135             // Check for a duplicate import
136             imports.stream().filter(full -> importText.equals(full.getText()))
137                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
138 
139             imports.add(imp);
140         }
141         else {
142             // Check for a duplicate static import
143             final FullIdent imp =
144                 FullIdent.createFullIdent(
145                     ast.getLastChild().getPreviousSibling());
146             staticImports.stream().filter(full -> imp.getText().equals(full.getText()))
147                 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), imp.getText()));
148 
149             staticImports.add(imp);
150         }
151     }
152 
153     /**
154      * Determines if an import statement is for types from a specified package.
155      *
156      * @param importName the import name
157      * @param pkg the package name
158      * @return whether from the package
159      */
160     private static boolean isFromPackage(String importName, String pkg) {
161         // imports from unnamed package are not allowed:
162         // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
163         // So '.' must be present in member name and we are not checking for it
164         final int index = importName.lastIndexOf('.');
165         final String front = importName.substring(0, index);
166         return pkg.equals(front);
167     }
168 
169 }