1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2026 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.HashSet;
23 import java.util.Set;
24
25 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27 import com.puppycrawl.tools.checkstyle.api.DetailAST;
28 import com.puppycrawl.tools.checkstyle.api.FullIdent;
29 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30 import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
31
32 /**
33 * <div>
34 * Checks that classes and records which define a covariant {@code equals()} method
35 * also override method {@code equals(Object)}.
36 * </div>
37 *
38 * <p>
39 * Covariant {@code equals()} - method that is similar to {@code equals(Object)},
40 * but with a covariant parameter type (any subtype of Object).
41 * </p>
42 *
43 * <p>
44 * <strong>Notice</strong>: the enums are also checked,
45 * even though they cannot override {@code equals(Object)}.
46 * The reason is to point out that implementing {@code equals()} in enums
47 * is considered an awful practice: it may cause having two different enum values
48 * that are equal using covariant enum method, and not equal when compared normally.
49 * </p>
50 *
51 * <p>
52 * Note: Compact source files
53 * (<a href="https://openjdk.org/jeps/512">JEP 512</a>)
54 * are skipped by design. Implicit classes in compact source files are not
55 * reusable types and cannot be referenced by name, so they cannot participate
56 * in the polymorphic contexts and collections where covariant {@code equals()}
57 * silently falls back to identity comparison. The rationale for this check
58 * does not extend to compact source files.
59 * </p>
60 *
61 * <p>
62 * Inspired by <a href="https://www.cs.jhu.edu/~daveho/pubs/oopsla2004.pdf">
63 * Finding Bugs is Easy, chapter '4.5 Bad Covariant Definition of Equals (Eq)'</a>:
64 * </p>
65 *
66 * <p>
67 * Java classes and records may override the {@code equals(Object)} method to define
68 * a predicate for object equality. This method is used by many of the Java
69 * runtime library classes; for example, to implement generic containers.
70 * </p>
71 *
72 * <p>
73 * Programmers sometimes mistakenly use the type of their class {@code Foo}
74 * as the type of the parameter to {@code equals()}:
75 * </p>
76 * {@snippet lang="text" :
77 * public boolean equals(Foo obj) { }
78 * }
79 *
80 * <p>
81 * This covariant version of {@code equals()} does not override the version in
82 * the {@code Object} class, and it may lead to unexpected behavior at runtime,
83 * especially if the class is used with one of the standard collection classes
84 * which expect that the standard {@code equals(Object)} method is overridden.
85 * </p>
86 *
87 * <p>
88 * This kind of bug is not obvious because it looks correct, and in circumstances
89 * where the class is accessed through the references of the class type (rather
90 * than a supertype), it will work correctly. However, the first time it is used
91 * in a container, the behavior might be mysterious. For these reasons, this type
92 * of bug can elude testing and code inspections.
93 * </p>
94 *
95 * @since 3.2
96 */
97 @FileStatefulCheck
98 public class CovariantEqualsCheck extends AbstractCheck {
99
100 /**
101 * A key is pointing to the warning message text in "messages.properties"
102 * file.
103 */
104 public static final String MSG_KEY = "covariant.equals";
105
106 /** Set of equals method definitions. */
107 private final Set<DetailAST> equalsMethods = new HashSet<>();
108
109 /**
110 * Creates a new {@code CovariantEqualsCheck} instance.
111 */
112 public CovariantEqualsCheck() {
113 // no code by default
114 }
115
116 @Override
117 public int[] getDefaultTokens() {
118 return getRequiredTokens();
119 }
120
121 @Override
122 public int[] getRequiredTokens() {
123 return new int[] {
124 TokenTypes.CLASS_DEF,
125 TokenTypes.LITERAL_NEW,
126 TokenTypes.ENUM_DEF,
127 TokenTypes.RECORD_DEF,
128 };
129 }
130
131 @Override
132 public int[] getAcceptableTokens() {
133 return getRequiredTokens();
134 }
135
136 @Override
137 public void visitToken(DetailAST ast) {
138 equalsMethods.clear();
139
140 // examine method definitions for equals methods
141 final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
142 if (objBlock != null) {
143 DetailAST child = objBlock.getFirstChild();
144 boolean hasEqualsObject = false;
145 while (child != null) {
146 if (CheckUtil.isEqualsMethod(child)) {
147 if (isFirstParameterObject(child)) {
148 hasEqualsObject = true;
149 }
150 else {
151 equalsMethods.add(child);
152 }
153 }
154 child = child.getNextSibling();
155 }
156
157 // report equals method definitions
158 if (!hasEqualsObject) {
159 for (DetailAST equalsAST : equalsMethods) {
160 final DetailAST nameNode = equalsAST
161 .findFirstToken(TokenTypes.IDENT);
162 log(nameNode, MSG_KEY);
163 }
164 }
165 }
166 }
167
168 /**
169 * Tests whether a method's first parameter is an Object.
170 *
171 * @param methodDefAst the method definition AST to test.
172 * Precondition: ast is a TokenTypes.METHOD_DEF node.
173 * @return true if ast has first parameter of type Object.
174 */
175 private static boolean isFirstParameterObject(DetailAST methodDefAst) {
176 final DetailAST paramsNode = methodDefAst.findFirstToken(TokenTypes.PARAMETERS);
177
178 // parameter type "Object"?
179 final DetailAST paramNode =
180 paramsNode.findFirstToken(TokenTypes.PARAMETER_DEF);
181 final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
182 final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
183 final String name = fullIdent.getText();
184 return "Object".equals(name) || "java.lang.Object".equals(name);
185 }
186
187 }