001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.imports;
021
022import java.util.HashSet;
023import java.util.Set;
024
025import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.FullIdent;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030
031/**
032 * <div>
033 * Checks for redundant import statements. An import statement is
034 * considered redundant if:
035 * </div>
036 * <ul>
037 *   <li>It is a duplicate of another import. This is, when a class or a module
038 *   is imported more than once.</li>
039 *   <li>The class non-statically imported is from the {@code java.lang}
040 *   package, e.g. importing {@code java.lang.String}.</li>
041 *   <li>The class non-statically imported is from the same package as the
042 *   current package.</li>
043 * </ul>
044 *
045 * @since 3.0
046 */
047@FileStatefulCheck
048public class RedundantImportCheck extends AbstractCheck {
049
050    /**
051     * A key is pointing to the warning message text in "messages.properties" file.
052     */
053    public static final String MSG_LANG = "import.lang";
054
055    /**
056     * A key is pointing to the warning message text in "messages.properties" file.
057     */
058    public static final String MSG_SAME = "import.same";
059
060    /**
061     * A key is pointing to the warning message text in "messages.properties" file.
062     */
063    public static final String MSG_DUPLICATE = "import.duplicate";
064
065    /** Set of the imports. */
066    private final Set<FullIdent> imports = new HashSet<>();
067    /** Set of static and module imports. */
068    private final Set<FullIdent> staticAndModuleImports = new HashSet<>();
069
070    /** Name of package in file. */
071    private String pkgName;
072
073    /**
074     * Creates a new {@code RedundantImportCheck} instance.
075     */
076    public RedundantImportCheck() {
077        // no code by default
078    }
079
080    @Override
081    public void beginTree(DetailAST aRootAST) {
082        pkgName = null;
083        imports.clear();
084        staticAndModuleImports.clear();
085    }
086
087    @Override
088    public int[] getDefaultTokens() {
089        return getRequiredTokens();
090    }
091
092    @Override
093    public int[] getAcceptableTokens() {
094        return getRequiredTokens();
095    }
096
097    @Override
098    public int[] getRequiredTokens() {
099        return new int[] {
100            TokenTypes.IMPORT,
101            TokenTypes.STATIC_IMPORT,
102            TokenTypes.PACKAGE_DEF,
103            TokenTypes.MODULE_IMPORT,
104        };
105    }
106
107    @Override
108    public void visitToken(DetailAST ast) {
109        if (ast.getType() == TokenTypes.PACKAGE_DEF) {
110            pkgName = FullIdent.createFullIdent(
111                    ast.getLastChild().getPreviousSibling()).getText();
112        }
113        else if (ast.getType() == TokenTypes.IMPORT) {
114            final FullIdent imp = FullIdent.createFullIdentBelow(ast);
115            final String importText = imp.getText();
116            if (isFromPackage(importText, "java.lang")) {
117                log(ast, MSG_LANG, importText);
118            }
119            // imports from unnamed package are not allowed,
120            // so we are checking SAME rule only for named packages
121            else if (pkgName != null && isFromPackage(importText, pkgName)) {
122                log(ast, MSG_SAME, importText);
123            }
124            // Check for a duplicate import
125            imports.stream().filter(full -> importText.equals(full.getText()))
126                .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
127
128            imports.add(imp);
129        }
130        else {
131            // Check for a duplicate static or module import
132            final DetailAST identNode = ast.getLastChild().getPreviousSibling();
133            final FullIdent importFullIdent = FullIdent.createFullIdent(identNode);
134            final String importText = importFullIdent.getText();
135
136            staticAndModuleImports
137                    .stream()
138                    .filter(existingImport -> importText.equals(existingImport.getText()))
139                    .forEach(existingImport -> {
140                        log(ast, MSG_DUPLICATE, existingImport.getLineNo(), importText);
141                    });
142
143            staticAndModuleImports.add(importFullIdent);
144        }
145    }
146
147    /**
148     * Determines if an import statement is for types from a specified package.
149     *
150     * @param importName the import name
151     * @param pkg the package name
152     * @return whether from the package
153     */
154    private static boolean isFromPackage(String importName, String pkg) {
155        // imports from unnamed package are not allowed:
156        // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
157        // So '.' must be present in member name and we are not checking for it
158        final int index = importName.lastIndexOf('.');
159        final String front = importName.substring(0, index);
160        return pkg.equals(front);
161    }
162
163}