Coverage Report - com.puppycrawl.tools.checkstyle.checks.coding.EqualsHashCodeCheck
 
Classes in this File Line Coverage Branch Coverage Complexity
EqualsHashCodeCheck
100%
47/47
100%
34/34
0
 
 1  
 ////////////////////////////////////////////////////////////////////////////////
 2  
 // checkstyle: Checks Java source code for adherence to a set of rules.
 3  
 // Copyright (C) 2001-2017 the original author or authors.
 4  
 //
 5  
 // This library is free software; you can redistribute it and/or
 6  
 // modify it under the terms of the GNU Lesser General Public
 7  
 // License as published by the Free Software Foundation; either
 8  
 // version 2.1 of the License, or (at your option) any later version.
 9  
 //
 10  
 // This library is distributed in the hope that it will be useful,
 11  
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12  
 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 13  
 // Lesser General Public License for more details.
 14  
 //
 15  
 // You should have received a copy of the GNU Lesser General Public
 16  
 // License along with this library; if not, write to the Free Software
 17  
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 18  
 ////////////////////////////////////////////////////////////////////////////////
 19  
 
 20  
 package com.puppycrawl.tools.checkstyle.checks.coding;
 21  
 
 22  
 import java.util.HashMap;
 23  
 import java.util.Map;
 24  
 
 25  
 import antlr.collections.AST;
 26  
 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
 27  
 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
 28  
 import com.puppycrawl.tools.checkstyle.api.DetailAST;
 29  
 import com.puppycrawl.tools.checkstyle.api.FullIdent;
 30  
 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
 31  
 import com.puppycrawl.tools.checkstyle.utils.CheckUtils;
 32  
 
 33  
 /**
 34  
  * <p>
 35  
  * Checks that classes that either override {@code equals()} or {@code hashCode()} also
 36  
  * overrides the other.
 37  
  * This checks only verifies that the method declarations match {@link Object#equals(Object)} and
 38  
  * {@link Object#hashCode()} exactly to be considered an override. This check does not verify
 39  
  * invalid method names, parameters other than {@code Object}, or anything else.
 40  
  * </p>
 41  
  * <p>
 42  
  * Rationale: The contract of equals() and hashCode() requires that
 43  
  * equal objects have the same hashCode. Hence, whenever you override
 44  
  * equals() you must override hashCode() to ensure that your class can
 45  
  * be used in collections that are hash based.
 46  
  * </p>
 47  
  * <p>
 48  
  * An example of how to configure the check is:
 49  
  * </p>
 50  
  * <pre>
 51  
  * &lt;module name="EqualsHashCode"/&gt;
 52  
  * </pre>
 53  
  * @author lkuehne
 54  
  */
 55  
 @FileStatefulCheck
 56  13
 public class EqualsHashCodeCheck
 57  
         extends AbstractCheck {
 58  
     // implementation note: we have to use the following members to
 59  
     // keep track of definitions in different inner classes
 60  
 
 61  
     /**
 62  
      * A key is pointing to the warning message text in "messages.properties"
 63  
      * file.
 64  
      */
 65  
     public static final String MSG_KEY_HASHCODE = "equals.noHashCode";
 66  
 
 67  
     /**
 68  
      * A key is pointing to the warning message text in "messages.properties"
 69  
      * file.
 70  
      */
 71  
     public static final String MSG_KEY_EQUALS = "equals.noEquals";
 72  
 
 73  
     /** Maps OBJ_BLOCK to the method definition of equals(). */
 74  13
     private final Map<DetailAST, DetailAST> objBlockWithEquals = new HashMap<>();
 75  
 
 76  
     /** Maps OBJ_BLOCKs to the method definition of hashCode(). */
 77  13
     private final Map<DetailAST, DetailAST> objBlockWithHashCode = new HashMap<>();
 78  
 
 79  
     @Override
 80  
     public int[] getDefaultTokens() {
 81  19
         return getRequiredTokens();
 82  
     }
 83  
 
 84  
     @Override
 85  
     public int[] getAcceptableTokens() {
 86  5
         return getRequiredTokens();
 87  
     }
 88  
 
 89  
     @Override
 90  
     public int[] getRequiredTokens() {
 91  43
         return new int[] {TokenTypes.METHOD_DEF};
 92  
     }
 93  
 
 94  
     @Override
 95  
     public void beginTree(DetailAST rootAST) {
 96  8
         objBlockWithEquals.clear();
 97  8
         objBlockWithHashCode.clear();
 98  8
     }
 99  
 
 100  
     @Override
 101  
     public void visitToken(DetailAST ast) {
 102  72
         if (isEqualsMethod(ast)) {
 103  15
             objBlockWithEquals.put(ast.getParent(), ast);
 104  
         }
 105  57
         else if (isHashCodeMethod(ast)) {
 106  15
             objBlockWithHashCode.put(ast.getParent(), ast);
 107  
         }
 108  72
     }
 109  
 
 110  
     /**
 111  
      * Determines if an AST is a valid Equals method implementation.
 112  
      *
 113  
      * @param ast the AST to check
 114  
      * @return true if the {code ast} is a Equals method.
 115  
      */
 116  
     private static boolean isEqualsMethod(DetailAST ast) {
 117  72
         final DetailAST modifiers = ast.getFirstChild();
 118  72
         final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
 119  
 
 120  144
         return CheckUtils.isEqualsMethod(ast)
 121  31
                 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
 122  29
                 && isObjectParam(parameters.getFirstChild())
 123  17
                 && (ast.findFirstToken(TokenTypes.SLIST) != null
 124  4
                         || 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  57
         final DetailAST modifiers = ast.getFirstChild();
 135  57
         final AST type = ast.findFirstToken(TokenTypes.TYPE);
 136  57
         final AST methodName = ast.findFirstToken(TokenTypes.IDENT);
 137  57
         final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
 138  
 
 139  114
         return type.getFirstChild().getType() == TokenTypes.LITERAL_INT
 140  26
                 && "hashCode".equals(methodName.getText())
 141  24
                 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
 142  22
                 && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null
 143  21
                 && parameters.getFirstChild() == null
 144  19
                 && (ast.findFirstToken(TokenTypes.SLIST) != null
 145  6
                         || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null);
 146  
     }
 147  
 
 148  
     /**
 149  
      * Determines if an AST is a formal param of type Object.
 150  
      * @param paramNode the AST to check
 151  
      * @return true if firstChild is a parameter of an Object type.
 152  
      */
 153  
     private static boolean isObjectParam(DetailAST paramNode) {
 154  29
         final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
 155  29
         final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
 156  29
         final String name = fullIdent.getText();
 157  29
         return "Object".equals(name) || "java.lang.Object".equals(name);
 158  
     }
 159  
 
 160  
     @Override
 161  
     public void finishTree(DetailAST rootAST) {
 162  8
         objBlockWithEquals
 163  8
             .entrySet().stream().filter(detailASTDetailASTEntry -> {
 164  15
                 return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null;
 165  8
             }).forEach(detailASTDetailASTEntry -> {
 166  6
                 final DetailAST equalsAST = detailASTDetailASTEntry.getValue();
 167  6
                 log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_HASHCODE);
 168  6
             });
 169  8
         objBlockWithHashCode.forEach((key, equalsAST) -> {
 170  6
             log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_EQUALS);
 171  6
         });
 172  8
     }
 173  
 }