001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2018 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 antlr.collections.AST; 026import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 027import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 028import com.puppycrawl.tools.checkstyle.api.DetailAST; 029import com.puppycrawl.tools.checkstyle.api.FullIdent; 030import com.puppycrawl.tools.checkstyle.api.TokenTypes; 031import com.puppycrawl.tools.checkstyle.utils.CheckUtils; 032 033/** 034 * <p> 035 * Checks that classes that either override {@code equals()} or {@code hashCode()} also 036 * overrides the other. 037 * This checks only verifies that the method declarations match {@link Object#equals(Object)} and 038 * {@link Object#hashCode()} exactly to be considered an override. This check does not verify 039 * invalid method names, parameters other than {@code Object}, or anything else. 040 * </p> 041 * <p> 042 * Rationale: The contract of equals() and hashCode() requires that 043 * equal objects have the same hashCode. Hence, whenever you override 044 * equals() you must override hashCode() to ensure that your class can 045 * be used in collections that are hash based. 046 * </p> 047 * <p> 048 * An example of how to configure the check is: 049 * </p> 050 * <pre> 051 * <module name="EqualsHashCode"/> 052 * </pre> 053 * @author lkuehne 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 CheckUtils.isEqualsMethod(ast) 122 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null 123 && isObjectParam(parameters.getFirstChild()) 124 && (ast.findFirstToken(TokenTypes.SLIST) != null 125 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null); 126 } 127 128 /** 129 * Determines if an AST is a valid HashCode method implementation. 130 * 131 * @param ast the AST to check 132 * @return true if the {code ast} is a HashCode method. 133 */ 134 private static boolean isHashCodeMethod(DetailAST ast) { 135 final DetailAST modifiers = ast.getFirstChild(); 136 final AST type = ast.findFirstToken(TokenTypes.TYPE); 137 final AST methodName = ast.findFirstToken(TokenTypes.IDENT); 138 final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS); 139 140 return type.getFirstChild().getType() == TokenTypes.LITERAL_INT 141 && "hashCode".equals(methodName.getText()) 142 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null 143 && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null 144 && parameters.getFirstChild() == null 145 && (ast.findFirstToken(TokenTypes.SLIST) != null 146 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null); 147 } 148 149 /** 150 * Determines if an AST is a formal param of type Object. 151 * @param paramNode the AST to check 152 * @return true if firstChild is a parameter of an Object type. 153 */ 154 private static boolean isObjectParam(DetailAST paramNode) { 155 final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE); 156 final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); 157 final String name = fullIdent.getText(); 158 return "Object".equals(name) || "java.lang.Object".equals(name); 159 } 160 161 @Override 162 public void finishTree(DetailAST rootAST) { 163 objBlockWithEquals 164 .entrySet().stream().filter(detailASTDetailASTEntry -> { 165 return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null; 166 }).forEach(detailASTDetailASTEntry -> { 167 final DetailAST equalsAST = detailASTDetailASTEntry.getValue(); 168 log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_HASHCODE); 169 }); 170 objBlockWithHashCode.forEach((key, equalsAST) -> { 171 log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_EQUALS); 172 }); 173 } 174 175}