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