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