csharpsquid:S2583 does not recognize `Queue.Dequeue()`

  • What language is this for?
    C#
  • Which rule?
    csharpsquid:S2583
  • Are you using
    SonarQube Version 10.2 (build 77647)

The rule does not seem to recognize Dequeue as a method which can change the Count of a Queue.

This code:

var preambleParts = new Queue<IList<OpenXmlLeafElement>> { };
// some code which might enqueue items
var preamble = new Run();
if (preambleParts.Count > 0)
{
    preamble.Append(preambleParts.Dequeue()); // <- the queue is shrunk here
    while (preambleParts.Count > 0) // <- here
    {
        preamble.AppendChild(new Break());
        preamble.Append(preambleParts.Dequeue()); // <- the queue is shrunk here
    }
}

produces tnhis report:

Change this condition so that it does not always evaluate to ‘True’.

Hello @m-gallesio and thanks for your report.

The re-implementation of S2583 that was included in SonaQube 10.2 does take into account the Dequeue method.

Unfortunately, I could not reproduce this issue with the given code snippet. In fact, for me, the rule is raising the first time that preambleParts.Count > 0 is checked, as expected, since the collection is initialized empty and the count will never be over 0.

But even when I initialize the collection to not be empty I still don’t get any issue in the first or second time that the collection is checked for emptiness.

Could you please tell me with which msbuild version or dotnet version you are analyzing your project? It might be possible that the old rule implementation is triggered.

Or maybe this is just a reproducer and there’s more to the actual code where the issue is raised?

Thanks!

The issue is also raised locally with SonarLint 7.3.0.77872 (not connected) on Visual Studio 17.7.4.

The same code with some dummy initialization to actually trigger the rule:

var preambleParts = new Queue<IList<OpenXmlLeafElement>> { };

if (Random.Shared.Next(10) > 5) { 
    preambleParts.Enqueue(Array.Empty<OpenXmlLeafElement>());
    preambleParts.Enqueue(Array.Empty<OpenXmlLeafElement>());
}

var preamble = new Run();
if (preambleParts.Count > 0)
{
    preamble.Append(preambleParts.Dequeue());
    while (preambleParts.Count > 0) // <- here
    {
        preamble.AppendChild(new Break());
        preamble.Append(preambleParts.Dequeue());
    }
}

Hello @m-gallesio ,

Thanks a lot - this was very helpful.

This FP has been fixed since sonar-dotnet 9.9, but SonarQube Version 10.2 comes with version 9.8.
Apologies, I did not see properly the versions.

Best Regards
Mary

1 Like