001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2021 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.HashSet;
023import java.util.Set;
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 and records which define a covariant {@code equals()} method
035 * also override method {@code equals(Object)}.
036 * </p>
037 * <p>
038 * Covariant {@code equals()} - method that is similar to {@code equals(Object)},
039 * but with a covariant parameter type (any subtype of Object).
040 * </p>
041 * <p>
042 * <strong>Notice</strong>: the enums are also checked,
043 * even though they cannot override {@code equals(Object)}.
044 * The reason is to point out that implementing {@code equals()} in enums
045 * is considered an awful practice: it may cause having two different enum values
046 * that are equal using covariant enum method, and not equal when compared normally.
047 * </p>
048 * <p>
049 * Inspired by <a href="https://www.cs.jhu.edu/~daveho/pubs/oopsla2004.pdf">
050 * Finding Bugs is Easy, chapter '4.5 Bad Covariant Definition of Equals (Eq)'</a>:
051 * </p>
052 * <p>
053 * Java classes and records may override the {@code equals(Object)} method to define
054 * a predicate for object equality. This method is used by many of the Java
055 * runtime library classes; for example, to implement generic containers.
056 * </p>
057 * <p>
058 * Programmers sometimes mistakenly use the type of their class {@code Foo}
059 * as the type of the parameter to {@code equals()}:
060 * </p>
061 * <pre>
062 * public boolean equals(Foo obj) {...}
063 * </pre>
064 * <p>
065 * This covariant version of {@code equals()} does not override the version in
066 * the {@code Object} class, and it may lead to unexpected behavior at runtime,
067 * especially if the class is used with one of the standard collection classes
068 * which expect that the standard {@code equals(Object)} method is overridden.
069 * </p>
070 * <p>
071 * This kind of bug is not obvious because it looks correct, and in circumstances
072 * where the class is accessed through the references of the class type (rather
073 * than a supertype), it will work correctly. However, the first time it is used
074 * in a container, the behavior might be mysterious. For these reasons, this type
075 * of bug can elude testing and code inspections.
076 * </p>
077 * <p>
078 * To configure the check:
079 * </p>
080 * <pre>
081 * &lt;module name=&quot;CovariantEquals&quot;/&gt;
082 * </pre>
083 * <p>
084 * For example:
085 * </p>
086 * <pre>
087 * class Test {
088 *   public boolean equals(Test i) {  // violation
089 *     return false;
090 *   }
091 * }
092 * </pre>
093 * <p>
094 * The same class without violations:
095 * </p>
096 * <pre>
097 * class Test {
098 *   public boolean equals(Test i) {  // no violation
099 *     return false;
100 *   }
101 *
102 *   public boolean equals(Object i) {
103 *     return false;
104 *   }
105 * }
106 * </pre>
107 * <p>
108 * Another example:
109 * </p>
110 * <pre>
111 * record Test(String str) {
112 *   public boolean equals(Test r) {  // violation
113 *     return false;
114 *   }
115 * }
116 * </pre>
117 * <p>
118 * The same record without violations:
119 * </p>
120 * <pre>
121 * record Test(String str) {
122 *   public boolean equals(Test r) {  // no violation
123 *     return false;
124 *   }
125 *
126 *   public boolean equals(Object r) {
127 *     return false;
128 *   }
129 * }
130 * </pre>
131 * <p>
132 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
133 * </p>
134 * <p>
135 * Violation Message Keys:
136 * </p>
137 * <ul>
138 * <li>
139 * {@code covariant.equals}
140 * </li>
141 * </ul>
142 *
143 * @since 3.2
144 */
145@FileStatefulCheck
146public class CovariantEqualsCheck extends AbstractCheck {
147
148    /**
149     * A key is pointing to the warning message text in "messages.properties"
150     * file.
151     */
152    public static final String MSG_KEY = "covariant.equals";
153
154    /** Set of equals method definitions. */
155    private final Set<DetailAST> equalsMethods = new HashSet<>();
156
157    @Override
158    public int[] getDefaultTokens() {
159        return getRequiredTokens();
160    }
161
162    @Override
163    public int[] getRequiredTokens() {
164        return new int[] {
165            TokenTypes.CLASS_DEF,
166            TokenTypes.LITERAL_NEW,
167            TokenTypes.ENUM_DEF,
168            TokenTypes.RECORD_DEF,
169        };
170    }
171
172    @Override
173    public int[] getAcceptableTokens() {
174        return getRequiredTokens();
175    }
176
177    @Override
178    public void visitToken(DetailAST ast) {
179        equalsMethods.clear();
180
181        // examine method definitions for equals methods
182        final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
183        if (objBlock != null) {
184            DetailAST child = objBlock.getFirstChild();
185            boolean hasEqualsObject = false;
186            while (child != null) {
187                if (CheckUtil.isEqualsMethod(child)) {
188                    if (isFirstParameterObject(child)) {
189                        hasEqualsObject = true;
190                    }
191                    else {
192                        equalsMethods.add(child);
193                    }
194                }
195                child = child.getNextSibling();
196            }
197
198            // report equals method definitions
199            if (!hasEqualsObject) {
200                for (DetailAST equalsAST : equalsMethods) {
201                    final DetailAST nameNode = equalsAST
202                            .findFirstToken(TokenTypes.IDENT);
203                    log(nameNode, MSG_KEY);
204                }
205            }
206        }
207    }
208
209    /**
210     * Tests whether a method's first parameter is an Object.
211     *
212     * @param methodDefAst the method definition AST to test.
213     *     Precondition: ast is a TokenTypes.METHOD_DEF node.
214     * @return true if ast has first parameter of type Object.
215     */
216    private static boolean isFirstParameterObject(DetailAST methodDefAst) {
217        final DetailAST paramsNode = methodDefAst.findFirstToken(TokenTypes.PARAMETERS);
218
219        // parameter type "Object"?
220        final DetailAST paramNode =
221            paramsNode.findFirstToken(TokenTypes.PARAMETER_DEF);
222        final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
223        final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
224        final String name = fullIdent.getText();
225        return "Object".equals(name) || "java.lang.Object".equals(name);
226    }
227
228}