False positive for S1854 "Unused assignments should be removed"

  • Operating system: Linux
  • IDE name and flavor/env:
    Using sonarlint as Java library via gradle:
    {module = “org.sonarsource.sonarlint.core:sonarlint-core”, version = “9.8.0.76914” }
    { module = “org.sonarsource.java:sonar-java-plugin”, version = “7.31.0.34839” }

Getting a false positive for the following code:

package com;

public class BCid51 {
  void HJid232(EJid229 YHid199, Yid24.RIid217<MBid37> QJid241) {
    for (XFid148 RJid242 : YHid199.WIid222()) {
      int DHid178;
      if (Fid5.BGid151() == CGid152.DGid153) {
        MBid37 IHid183 = RJid242.OFid139();
        IHid183.AGid150();
      }
    }
  }
}

Message is for line 8:

Remove this useless assignment to local variable IHid183

That’s obviously wrong as the object is used in the next line.

1 Like

Hi David,

My assumption is: We have 2 problems:

  1. The project does not have a valid classpath and some of the types are not resolved properly.
  2. The rule S1854 raises false positives when some types are not resolved. We should remove this noise, I created this ticket SONARJAVA-4960.

Probably, by fixing the classpath used by the analysis, you should be able to remove those false positives.
And if it’s not related to a classpath problem, you should be able to provide a small reproducer using only known types.

Thanks for your feedback,
Alban

Hi Alban,

I have the same false positive issue with rule S1854. I am writing java code on Windows 11 in IntelliJ. I use IntelliJ version 2024.1(.4) with SonarLint plugin version 10.9.0(.79423)

I don’t think there are problems with the classpath (when I ctrl + click on the type of the parameter instance from the reproducible example below, IntelliJ takes me to the correct definition of the class). A smaller reproducible example can be found below:
Random file:

public String doSomething(AClass.BClass<String> instance) {
    String c = "Hi"; // Rule S1854
    return instance.b + c;
}

File AClass.java:

public class AClass {
    public class BClass<T> {
        public T b;
    }
}

Please let me know if you would prefer if I create a new topic for this.

Edit: A couple of days later I reopen the same file and see that the sonarlint warnings have disappeared.

Best regards,
Simon