001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2025 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 is imported
038 *   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
049    extends AbstractCheck {
050
051    /**
052     * A key is pointing to the warning message text in "messages.properties"
053     * file.
054     */
055    public static final String MSG_LANG = "import.lang";
056
057    /**
058     * A key is pointing to the warning message text in "messages.properties"
059     * file.
060     */
061    public static final String MSG_SAME = "import.same";
062
063    /**
064     * A key is pointing to the warning message text in "messages.properties"
065     * file.
066     */
067    public static final String MSG_DUPLICATE = "import.duplicate";
068
069    /** Set of the imports. */
070    private final Set<FullIdent> imports = new HashSet<>();
071    /** Set of static imports. */
072    private final Set<FullIdent> staticImports = new HashSet<>();
073
074    /** Name of package in file. */
075    private String pkgName;
076
077    @Override
078    public void beginTree(DetailAST aRootAST) {
079        pkgName = null;
080        imports.clear();
081        staticImports.clear();
082    }
083
084    @Override
085    public int[] getDefaultTokens() {
086        return getRequiredTokens();
087    }
088
089    @Override
090    public int[] getAcceptableTokens() {
091        return getRequiredTokens();
092    }
093
094    @Override
095    public int[] getRequiredTokens() {
096        return new int[] {
097            TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF,
098        };
099    }
100
101    @Override
102    public void visitToken(DetailAST ast) {
103        if (ast.getType() == TokenTypes.PACKAGE_DEF) {
104            pkgName = FullIdent.createFullIdent(
105                    ast.getLastChild().getPreviousSibling()).getText();
106        }
107        else if (ast.getType() == TokenTypes.IMPORT) {
108            final FullIdent imp = FullIdent.createFullIdentBelow(ast);
109            final String importText = imp.getText();
110            if (isFromPackage(importText, "java.lang")) {
111                log(ast, MSG_LANG, importText);
112            }
113            // imports from unnamed package are not allowed,
114            // so we are checking SAME rule only for named packages
115            else if (pkgName != null && isFromPackage(importText, pkgName)) {
116                log(ast, MSG_SAME, importText);
117            }
118            // Check for a duplicate import
119            imports.stream().filter(full -> importText.equals(full.getText()))
120                .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
121
122            imports.add(imp);
123        }
124        else {
125            // Check for a duplicate static import
126            final FullIdent imp =
127                FullIdent.createFullIdent(
128                    ast.getLastChild().getPreviousSibling());
129            staticImports.stream().filter(full -> imp.getText().equals(full.getText()))
130                .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), imp.getText()));
131
132            staticImports.add(imp);
133        }
134    }
135
136    /**
137     * Determines if an import statement is for types from a specified package.
138     *
139     * @param importName the import name
140     * @param pkg the package name
141     * @return whether from the package
142     */
143    private static boolean isFromPackage(String importName, String pkg) {
144        // imports from unnamed package are not allowed:
145        // https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5
146        // So '.' must be present in member name and we are not checking for it
147        final int index = importName.lastIndexOf('.');
148        final String front = importName.substring(0, index);
149        return pkg.equals(front);
150    }
151
152}