-
Notifications
You must be signed in to change notification settings - Fork 134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
DangerousIdentityKey identifies unsafe map and set keys #1731
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
197b3ee
PatternAsKeyOfSetOrMap identifies regex Pattern used as map or set key
schlosna fa2acff
Add generated changelog entries
schlosna 7abce60
review comments
schlosna db23b27
Broaden the check to catch all final types which don't override equal…
carterkozak 7b2ef88
Update changelog/@unreleased/pr-1731.v2.yml
carterkozak 641c734
Add stream map collector tests
schlosna 167f645
Handle additional hashing cases (#1733)
carterkozak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
...line-error-prone/src/main/java/com/palantir/baseline/errorprone/DangerousIdentityKey.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/* | ||
* (c) Copyright 2021 Palantir Technologies Inc. All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.palantir.baseline.errorprone; | ||
|
||
import com.google.common.collect.Iterables; | ||
import com.google.errorprone.BugPattern; | ||
import com.google.errorprone.BugPattern.SeverityLevel; | ||
import com.google.errorprone.VisitorState; | ||
import com.google.errorprone.bugpatterns.AbstractAsKeyOfSetOrMap; | ||
import com.sun.tools.javac.code.Symbol.MethodSymbol; | ||
import com.sun.tools.javac.code.Type; | ||
import com.sun.tools.javac.code.Types; | ||
import com.sun.tools.javac.util.Name; | ||
|
||
/** | ||
* Warns that users should not have a {@link java.util.regex.Pattern} as a key to a Set or Map. | ||
*/ | ||
@BugPattern( | ||
name = "DangerousIdentityKey", | ||
summary = "Key type does not override equals() and hashCode, so comparisons will be done on" | ||
+ " reference equality only. If neither deduplication nor lookup are needed," | ||
+ " consider using a List instead. Otherwise, use IdentityHashMap/Set," | ||
+ " or an Iterable/List of pairs.", | ||
severity = SeverityLevel.WARNING) | ||
public final class DangerousIdentityKey extends AbstractAsKeyOfSetOrMap { | ||
|
||
@Override | ||
protected boolean isBadType(Type type, VisitorState state) { | ||
// Only flag final types, otherwise we'll encounter false positives when presented with overrides. | ||
if (type == null || !type.isFinal()) { | ||
return false; | ||
} | ||
return !implementsMethod(state.getTypes(), type, state.getNames().equals, state) | ||
|| !implementsMethod(state.getTypes(), type, state.getNames().hashCode, state); | ||
} | ||
|
||
private static boolean implementsMethod(Types types, Type type, Name methodName, VisitorState state) { | ||
MethodSymbol equals = | ||
(MethodSymbol) state.getSymtab().objectType.tsym.members().findFirst(methodName); | ||
return !Iterables.isEmpty(types.membersClosure(type, false) | ||
.getSymbolsByName(methodName, m -> m != equals && m.overrides(equals, type.tsym, types, false))); | ||
} | ||
} |
241 changes: 241 additions & 0 deletions
241
...-error-prone/src/test/java/com/palantir/baseline/errorprone/DangerousIdentityKeyTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,241 @@ | ||
/* | ||
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.palantir.baseline.errorprone; | ||
|
||
import com.google.errorprone.CompilationTestHelper; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
|
||
public final class DangerousIdentityKeyTest { | ||
|
||
private CompilationTestHelper compilationHelper; | ||
|
||
@BeforeEach | ||
public void before() { | ||
compilationHelper = CompilationTestHelper.newInstance(DangerousIdentityKey.class, getClass()); | ||
} | ||
|
||
@Test | ||
public void testInvalidMapKey() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"import java.util.regex.Pattern;", | ||
"class Test {", | ||
" private Object test() {", | ||
" // BUG: Diagnostic contains: does not override equals", | ||
" return new HashMap<Pattern, String>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testInvalidSetKey() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"import java.util.regex.Pattern;", | ||
"class Test {", | ||
" private Object test() {", | ||
" // BUG: Diagnostic contains: does not override equals", | ||
" return new HashSet<Pattern>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testValidMap() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"import java.util.regex.Pattern;", | ||
"class Test {", | ||
" private Object test() {", | ||
" return new IdentityHashMap<Pattern, String>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testValidSetKey() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" private Object test() {", | ||
" return new HashSet<String>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testValidNonFinal() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" static class Impl {}", | ||
" private Object test() {", | ||
" return new HashSet<Impl>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testValidEnum() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" enum Impl {", | ||
" INSTANCE", | ||
" }", | ||
" private Object test() {", | ||
" return new HashSet<Impl>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testInvalidNoEquals() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" static final class Impl {", | ||
" @Override public boolean equals(Object o) {", | ||
" return true;", | ||
" }", | ||
" }", | ||
" private Object test() {", | ||
" // BUG: Diagnostic contains: does not override", | ||
" return new HashSet<Impl>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testInvalidNoHash() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" static final class Impl {", | ||
" @Override public int hashCode() {", | ||
" return 1;", | ||
" }", | ||
" }", | ||
" private Object test() {", | ||
" // BUG: Diagnostic contains: does not override", | ||
" return new HashSet<Impl>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testObjectAllowed() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" private Object test() {", | ||
" return new HashSet<Object>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testRawTypeAllowed() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" private Object test() {", | ||
" return new HashSet();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void testWildcardAllowed() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"class Test {", | ||
" private HashSet<?> test() {", | ||
" return new HashSet<>();", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
void testCollectMapInvalidKey() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"import java.util.regex.Pattern;", | ||
"import java.util.stream.*;", | ||
"class Test {", | ||
" private Map<Pattern, String> test() {", | ||
" // BUG: Diagnostic contains: does not override", | ||
" return Stream.of(\".\").collect(", | ||
" Collectors.toMap(Pattern::compile, s -> s));", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. right now we don't actually catch this case There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. #1733 will handle this |
||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
void testCollectMapValidKey() { | ||
compilationHelper | ||
.addSourceLines( | ||
"Test.java", | ||
"import java.util.*;", | ||
"import java.util.regex.Pattern;", | ||
"import java.util.stream.*;", | ||
"class Test {", | ||
" private Map<String, Pattern> test() {", | ||
" return Stream.of(\".\").collect(", | ||
" Collectors.toMap(s -> s, Pattern::compile));", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
type: improvement | ||
improvement: | ||
description: DangerousIdentityKey identifies key types which do not override equals or hashCode thus rely on reference comparison. | ||
links: | ||
- https://github.com/palantir/gradle-baseline/pull/1731 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we try to push this upstream to error-prone proper? I'm curious if there is a reason they haven't added something of this shape (though this is the type of thing drilled fairly well by
Effective Java
, I'd like to have 🤖 compiler assistance).I can add a test case to confirm that this catches the construction in places like stream collectors, as that's where I noticed one example.
Also worth noting that since we're building on
AbstractAsKeyOfSetOrMap
it is specific to the actual constructed map/set type (not the apparent type of sayMap<Pattern, String>
) and analyzes the typical JDK & Guava (minusWeakHash(Map|Set)
) hash based maps & sets wherehashCode
andequals
are relevant. Not sure if we need/want a similar check for Caffeine caches & sorted/navigable map & set types. Reminds me of some places I've seenjava.net.URL
as keys 😢 .https://github.com/google/error-prone/blob/c601758e81723a8efc4671726b8363be7a306dce/core/src/main/java/com/google/errorprone/bugpatterns/AbstractAsKeyOfSetOrMap.java#L43-L91
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a good point, this should be a strong candidate for an upstream contribution, although I've never had much luck with error-prone contributions, I can reach out again.
We could extend AbstractAsKeyOfSetOrMap to include caches (guava + caffeine) as well as collectors. I can PR something here shortly, and make a similar contribution to the abstract class upstream.