Repository navigation
SONARJAVA-6777: Implement S9401: IdentityHashMap keys should not be boxed primitive types #6152
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
Merged
+252
−0
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
29 changes: 29 additions & 0 deletions
29
...ks-test-sources/default/src/main/java/checks/IdentityHashMapBoxedKeyCheckGuavaSample.java
This file contains hidden or 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,29 @@ | ||
| package checks; | ||
|
|
||
| import com.google.common.collect.Maps; | ||
| import java.util.Map; | ||
|
|
||
| class IdentityHashMapBoxedKeyCheckGuavaSample { | ||
|
|
||
| void boxedKeys() { | ||
| Map<Boolean, String> booleans = Maps.newIdentityHashMap(); // Noncompliant {{Use a map that compares keys by value because IdentityHashMap compares keys by reference.}} | ||
| // ^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| Map<Byte, String> bytes = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Character, String> characters = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Short, String> shorts = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Integer, String> integers = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Long, String> longs = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Float, String> floats = Maps.newIdentityHashMap(); // Noncompliant | ||
| Map<Double, String> doubles = Maps.newIdentityHashMap(); // Noncompliant | ||
| } | ||
|
|
||
| void compliant() { | ||
| Map<String, Boolean> boxedValue = Maps.newIdentityHashMap(); | ||
| Map<String, String> strings = Maps.newIdentityHashMap(); | ||
| Map<Object, String> objects = Maps.newIdentityHashMap(); | ||
| } | ||
|
|
||
| <T> void genericKey() { | ||
| Map<T, String> generic = Maps.newIdentityHashMap(); | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
...-checks-test-sources/default/src/main/java/checks/IdentityHashMapBoxedKeyCheckSample.java
This file contains hidden or 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,35 @@ | ||
| package checks; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.IdentityHashMap; | ||
| import java.util.Map; | ||
|
|
||
| class IdentityHashMapBoxedKeyCheckSample { | ||
|
|
||
| void boxedKeys(Map<Integer, String> source) { | ||
| Map<Boolean, String> booleans = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Byte, String> bytes = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Character, String> characters = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Short, String> shorts = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Integer, String> integers = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Long, String> longs = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Float, String> floats = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Double, String> doubles = new IdentityHashMap<>(); // Noncompliant | ||
| Map<Integer, String> explicit = new IdentityHashMap<Integer, String>(); // Noncompliant | ||
| Map<Integer, String> copied = new IdentityHashMap<>(source); // Noncompliant | ||
| var inferred = new IdentityHashMap<Integer, String>(); // Noncompliant {{Use a map that compares keys by value because IdentityHashMap compares keys by reference.}} | ||
| // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| } | ||
|
|
||
| void compliant() { | ||
| Map<String, Boolean> boxedValue = new IdentityHashMap<>(); | ||
| Map<String, String> strings = new IdentityHashMap<>(); | ||
| Map<Object, String> objects = new IdentityHashMap<>(); | ||
| Map<Integer, String> hashMap = new HashMap<>(); | ||
| IdentityHashMap raw = new IdentityHashMap(); | ||
| } | ||
|
|
||
| <T> void genericKey() { | ||
| Map<T, String> generic = new IdentityHashMap<>(); | ||
| } | ||
| } |
72 changes: 72 additions & 0 deletions
72
java-checks/src/main/java/org/sonar/java/checks/IdentityHashMapBoxedKeyCheck.java
This file contains hidden or 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,72 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Set; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.semantic.MethodMatchers; | ||
| import org.sonar.plugins.java.api.semantic.Type; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MethodInvocationTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
|
|
||
| @Rule(key = "S9401") | ||
| public class IdentityHashMapBoxedKeyCheck extends IssuableSubscriptionVisitor { | ||
|
|
||
| private static final String IDENTITY_HASH_MAP = "java.util.IdentityHashMap"; | ||
| private static final String MESSAGE = "Use a map that compares keys by value because IdentityHashMap compares keys by reference."; | ||
| private static final Set<String> BOXED_TYPES = Set.of( | ||
| "java.lang.Boolean", | ||
| "java.lang.Byte", | ||
| "java.lang.Character", | ||
| "java.lang.Short", | ||
| "java.lang.Integer", | ||
| "java.lang.Long", | ||
| "java.lang.Float", | ||
| "java.lang.Double"); | ||
| private static final MethodMatchers GUAVA_IDENTITY_HASH_MAP_FACTORY = MethodMatchers.create() | ||
| .ofTypes("com.google.common.collect.Maps") | ||
| .names("newIdentityHashMap") | ||
| .addWithoutParametersMatcher() | ||
| .build(); | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return List.of(Tree.Kind.NEW_CLASS, Tree.Kind.METHOD_INVOCATION); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| ExpressionTree expression = (ExpressionTree) tree; | ||
| if (isIdentityHashMapCreation(tree, expression.symbolType()) && hasBoxedKey(expression.symbolType())) { | ||
| reportIssue(tree, MESSAGE); | ||
| } | ||
| } | ||
|
|
||
| private static boolean isIdentityHashMapCreation(Tree tree, Type resultType) { | ||
| return tree.is(Tree.Kind.NEW_CLASS) | ||
| ? resultType.is(IDENTITY_HASH_MAP) | ||
| : GUAVA_IDENTITY_HASH_MAP_FACTORY.matches((MethodInvocationTree) tree); | ||
| } | ||
|
|
||
| private static boolean hasBoxedKey(Type resultType) { | ||
| List<Type> typeArguments = resultType.typeArguments(); | ||
| return typeArguments.size() == 2 && BOXED_TYPES.contains(typeArguments.get(0).fullyQualifiedName()); | ||
| } | ||
| } |
59 changes: 59 additions & 0 deletions
59
java-checks/src/test/java/org/sonar/java/checks/IdentityHashMapBoxedKeyCheckTest.java
This file contains hidden or 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,59 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class IdentityHashMapBoxedKeyCheckTest { | ||
|
|
||
| @Test | ||
| void test() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckSample.java")) | ||
| .withCheck(new IdentityHashMapBoxedKeyCheck()) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void test_without_semantic() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckSample.java")) | ||
| .withCheck(new IdentityHashMapBoxedKeyCheck()) | ||
| .withoutSemantic() | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void test_guava() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckGuavaSample.java")) | ||
| .withCheck(new IdentityHashMapBoxedKeyCheck()) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void test_guava_without_semantic() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckGuavaSample.java")) | ||
| .withCheck(new IdentityHashMapBoxedKeyCheck()) | ||
| .withoutSemantic() | ||
| .verifyNoIssues(); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9401.html
This file contains hidden or 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,34 @@ | ||
| <p>This rule raises an issue when an <code>IdentityHashMap</code> is created with a boxed primitive type as its key type.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p><code>IdentityHashMap</code> compares keys by reference instead of calling <code>equals()</code>. Boxed primitive types represent values as | ||
| objects, but boxing the same primitive value more than once does not always return the same object. For example, some <code>Integer</code> values are | ||
| cached while others may be represented by distinct instances.</p> | ||
| <p>Consequently, an <code>IdentityHashMap</code> with boxed primitive keys can appear to work for some values and fail for others. A lookup can return | ||
| <code>null</code> even when the map contains a key with the same primitive value.</p> | ||
| <h2>How to fix it</h2> | ||
| <p>Use a map implementation that compares keys by value when the key represents a primitive value. If reference equality is required, use key objects | ||
| whose identity is deliberate and stable.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| Map<Integer, UserSession> sessions = new IdentityHashMap<>(); // Noncompliant | ||
|
|
||
| sessions.put(500, session); | ||
| UserSession retrieved = sessions.get(500); // May return null | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| Map<Integer, UserSession> sessions = new HashMap<>(); | ||
|
|
||
| sessions.put(500, session); | ||
| UserSession retrieved = sessions.get(500); | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li>Java Documentation - <a | ||
| href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/IdentityHashMap.html"><code>IdentityHashMap</code> class</a></li> | ||
| <li>Java Documentation - <a | ||
| href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#valueOf(int)"><code>Integer.valueOf(int)</code> | ||
| method</a></li> | ||
| </ul> | ||
23 changes: 23 additions & 0 deletions
23
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9401.json
This file contains hidden or 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,23 @@ | ||
| { | ||
| "title": "IdentityHashMap keys should not be boxed primitive types", | ||
| "type": "BUG", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "5min" | ||
| }, | ||
| "tags": [ | ||
| "suspicious" | ||
| ], | ||
| "defaultSeverity": "Major", | ||
| "ruleSpecification": "RSPEC-9401", | ||
| "sqKey": "S9401", | ||
| "scope": "All", | ||
| "quickfix": "infeasible", | ||
| "code": { | ||
| "impacts": { | ||
| "RELIABILITY": "MEDIUM" | ||
| }, | ||
| "attribute": "LOGICAL" | ||
| } | ||
| } |
Empty file.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.