[java] ArrayIsStoredDirectly - fix field access with this

Fixes #1185
This commit is contained in:
Andreas Dangel
2022-04-21 14:48:23 +02:00
parent 5566290821
commit 0d8373d290
3 changed files with 27 additions and 2 deletions

View File

@ -22,6 +22,7 @@ This is a {{ site.pmd.release_type }} release.
* doc
* [#2505](https://github.com/pmd/pmd/issues/2505): \[doc] Improve side bar to show release date
* java
* [#1185](https://github.com/pmd/pmd/issues/1185): \[java] ArrayIsStoredDirectly false positive with field access
* [#1474](https://github.com/pmd/pmd/issues/1474): \[java] ArrayIsStoredDirectly false positive with method call
* [#3879](https://github.com/pmd/pmd/issues/3879) \[java] ArrayIsStoredDirectly reports duplicated violation
* [#3889](https://github.com/pmd/pmd/pull/3889): \[java] Catch LinkageError in UselessOverridingMethodRule

View File

@ -84,10 +84,15 @@ public class ArrayIsStoredDirectlyRule extends AbstractSunSecureRule {
return null;
}
if (assignedVar == null) {
ASTPrimarySuffix suffix = e.getFirstDescendantOfType(ASTPrimarySuffix.class);
ASTPrimaryPrefix prefix = null;
ASTPrimarySuffix suffix = null;
if (e.getNumChildren() > 0 && e.getChild(0) instanceof ASTPrimaryExpression) {
ASTPrimaryExpression primaryExpression = (ASTPrimaryExpression) e.getChild(0);
prefix = (ASTPrimaryPrefix) primaryExpression.getChild(0);
suffix = primaryExpression.getFirstChildOfType(ASTPrimarySuffix.class);
}
if (suffix != null) {
assignedVar = suffix.getImage();
ASTPrimaryPrefix prefix = e.getFirstDescendantOfType(ASTPrimaryPrefix.class);
if (prefix != null) {
if (prefix.usesThisModifier()) {
assignedVar = "this." + assignedVar;

View File

@ -303,6 +303,25 @@ public class TestArrayIsStoredDirectly {
energy[0] = energy(1);
}
}
]]></code>
</test-code>
<test-code>
<description>[java] ArrayIsStoredDirectly false positive with field access #1185</description>
<rule-property name="allowPrivate">false</rule-property>
<expected-problems>0</expected-problems>
<code><![CDATA[
class TestArrayIsStoredDirectly {
private final boolean[] a;
private final foo b;
private TestArrayIsStoredDirectly(boolean[] a) {
this.a = null;
this.a = a.clone(); // no violation, it doesn't matter what the state of this.a is
this.b = new TestArrayIsStoredDirectly(a); // no violation
this.b = new TestArrayIsStoredDirectly(this.a); // false positive violation here
}
}
]]></code>
</test-code>