View Javadoc
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  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      private final Map<DetailAST, DetailAST> objBlockWithEquals = new HashMap<>();
75  
76      /** Maps OBJ_BLOCKs to the method definition of hashCode(). */
77      private final Map<DetailAST, DetailAST> objBlockWithHashCode = new HashMap<>();
78  
79      @Override
80      public int[] getDefaultTokens() {
81          return getRequiredTokens();
82      }
83  
84      @Override
85      public int[] getAcceptableTokens() {
86          return getRequiredTokens();
87      }
88  
89      @Override
90      public int[] getRequiredTokens() {
91          return new int[] {TokenTypes.METHOD_DEF};
92      }
93  
94      @Override
95      public void beginTree(DetailAST rootAST) {
96          objBlockWithEquals.clear();
97          objBlockWithHashCode.clear();
98      }
99  
100     @Override
101     public void visitToken(DetailAST ast) {
102         if (isEqualsMethod(ast)) {
103             objBlockWithEquals.put(ast.getParent(), ast);
104         }
105         else if (isHashCodeMethod(ast)) {
106             objBlockWithHashCode.put(ast.getParent(), ast);
107         }
108     }
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         final DetailAST modifiers = ast.getFirstChild();
118         final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
119 
120         return CheckUtils.isEqualsMethod(ast)
121                 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
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 AST type = ast.findFirstToken(TokenTypes.TYPE);
136         final AST methodName = ast.findFirstToken(TokenTypes.IDENT);
137         final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
138 
139         return type.getFirstChild().getType() == TokenTypes.LITERAL_INT
140                 && "hashCode".equals(methodName.getText())
141                 && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
142                 && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null
143                 && parameters.getFirstChild() == null
144                 && (ast.findFirstToken(TokenTypes.SLIST) != null
145                         || 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         final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
155         final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
156         final String name = fullIdent.getText();
157         return "Object".equals(name) || "java.lang.Object".equals(name);
158     }
159 
160     @Override
161     public void finishTree(DetailAST rootAST) {
162         objBlockWithEquals
163             .entrySet().stream().filter(detailASTDetailASTEntry -> {
164                 return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null;
165             }).forEach(detailASTDetailASTEntry -> {
166                 final DetailAST equalsAST = detailASTDetailASTEntry.getValue();
167                 log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_HASHCODE);
168             });
169         objBlockWithHashCode.forEach((key, equalsAST) -> {
170             log(equalsAST.getLineNo(), equalsAST.getColumnNo(), MSG_KEY_EQUALS);
171         });
172     }
173 }