001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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.coding;
021
022import java.util.HashMap;
023import java.util.Map;
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;
030import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
031
032/**
033 * <p>
034 * Checks that classes that either override {@code equals()} or {@code hashCode()} also
035 * overrides the other.
036 * This check only verifies that the method declarations match {@code Object.equals(Object)} and
037 * {@code Object.hashCode()} exactly to be considered an override. This check does not verify
038 * invalid method names, parameters other than {@code Object}, or anything else.
039 * </p>
040 * <p>
041 * Rationale: The contract of {@code equals()} and {@code hashCode()} requires that
042 * equal objects have the same hashCode. Therefore, whenever you override
043 * {@code equals()} you must override {@code hashCode()} to ensure that your class can
044 * be used in hash-based collections.
045 * </p>
046 * <p>
047 * To configure the check:
048 * </p>
049 * <pre>
050 * &lt;module name=&quot;EqualsHashCode&quot;/&gt;
051 * </pre>
052 *
053 * @since 3.0
054 */
055@FileStatefulCheck
056public class EqualsHashCodeCheck
057        extends AbstractCheck {
058
059    // implementation note: we have to use the following members to
060    // keep track of definitions in different inner classes
061
062    /**
063     * A key is pointing to the warning message text in "messages.properties"
064     * file.
065     */
066    public static final String MSG_KEY_HASHCODE = "equals.noHashCode";
067
068    /**
069     * A key is pointing to the warning message text in "messages.properties"
070     * file.
071     */
072    public static final String MSG_KEY_EQUALS = "equals.noEquals";
073
074    /** Maps OBJ_BLOCK to the method definition of equals(). */
075    private final Map<DetailAST, DetailAST> objBlockWithEquals = new HashMap<>();
076
077    /** Maps OBJ_BLOCKs to the method definition of hashCode(). */
078    private final Map<DetailAST, DetailAST> objBlockWithHashCode = new HashMap<>();
079
080    @Override
081    public int[] getDefaultTokens() {
082        return getRequiredTokens();
083    }
084
085    @Override
086    public int[] getAcceptableTokens() {
087        return getRequiredTokens();
088    }
089
090    @Override
091    public int[] getRequiredTokens() {
092        return new int[] {TokenTypes.METHOD_DEF};
093    }
094
095    @Override
096    public void beginTree(DetailAST rootAST) {
097        objBlockWithEquals.clear();
098        objBlockWithHashCode.clear();
099    }
100
101    @Override
102    public void visitToken(DetailAST ast) {
103        if (isEqualsMethod(ast)) {
104            objBlockWithEquals.put(ast.getParent(), ast);
105        }
106        else if (isHashCodeMethod(ast)) {
107            objBlockWithHashCode.put(ast.getParent(), ast);
108        }
109    }
110
111    /**
112     * Determines if an AST is a valid Equals method implementation.
113     *
114     * @param ast the AST to check
115     * @return true if the {code ast} is a Equals method.
116     */
117    private static boolean isEqualsMethod(DetailAST ast) {
118        final DetailAST modifiers = ast.getFirstChild();
119        final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
120
121        return CheckUtil.isEqualsMethod(ast)
122                && isObjectParam(parameters.getFirstChild())
123                && (ast.findFirstToken(TokenTypes.SLIST) != null
124                        || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null);
125    }
126
127    /**
128     * Determines if an AST is a valid HashCode method implementation.
129     *
130     * @param ast the AST to check
131     * @return true if the {code ast} is a HashCode method.
132     */
133    private static boolean isHashCodeMethod(DetailAST ast) {
134        final DetailAST modifiers = ast.getFirstChild();
135        final DetailAST methodName = ast.findFirstToken(TokenTypes.IDENT);
136        final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
137
138        return "hashCode".equals(methodName.getText())
139                && parameters.getFirstChild() == null
140                && (ast.findFirstToken(TokenTypes.SLIST) != null
141                        || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null);
142    }
143
144    /**
145     * Determines if an AST is a formal param of type Object.
146     * @param paramNode the AST to check
147     * @return true if firstChild is a parameter of an Object type.
148     */
149    private static boolean isObjectParam(DetailAST paramNode) {
150        final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
151        final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
152        final String name = fullIdent.getText();
153        return "Object".equals(name) || "java.lang.Object".equals(name);
154    }
155
156    @Override
157    public void finishTree(DetailAST rootAST) {
158        objBlockWithEquals
159            .entrySet().stream().filter(detailASTDetailASTEntry -> {
160                return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null;
161            }).forEach(detailASTDetailASTEntry -> {
162                final DetailAST equalsAST = detailASTDetailASTEntry.getValue();
163                log(equalsAST, MSG_KEY_HASHCODE);
164            });
165        objBlockWithHashCode.forEach((key, equalsAST) -> log(equalsAST, MSG_KEY_EQUALS));
166    }
167
168}