S2437 (VB.Net) "Remove this silly bit operation" false positive

Flagged up on the third line of “DoThing” function below - doesn’t seem that the operation is silly to me. :slight_smile:

Imports System.Collections.Generic
Imports System.Collections.Specialized

Public Class DayOfWeekTester

Public ReadOnly Property DaysOfWeek() As IList(Of DayOfWeek)

Sub New()
Me.DaysOfWeek = New List(Of DayOfWeek)({…some days here…})
End Sub

Public Sub DoThing()
Dim daysOfWeekBitField As Integer = 0
For Each dow As DayOfWeek In Me.DaysOfWeek
daysOfWeekBitField = daysOfWeekBitField Or (1 << CInt(dow))


End Sub

End Class

1 Like

I take it you mean the new vbnet:S2437 rule on SonarCloud…

Looking at sonar-dotnet/SillyBitwiseOperationBase.cs at master · SonarSource/sonar-dotnet (github.com) it probably should look for the absence of a bit shift in the expression as well (instead of just looking for an integer constant)

Another example that feels like a false positive:

Dim fail As Boolean = False
For Each con As Container In cons
    For Each rt As RateType In rts
        For Each rm As RunMode In rms
            fail = fail Or Not CheckRate(con, rt, rm) ' This line gets flagged, with vbnet:S2437 

So you can see that this is effectively looping over a cross product, and seeing if any return true. Changing to use OrElse would change the behaviour, and may not work as intended.

Specifically quoting the rule description:

Specifically, using AnyValue And -1 will always result in the original value, as will AnyValue Xor 0 and AnyValue Or 0

This doesn’t seem to account for being within a loop, which also appears to be @Hippunky 's case too

Any news on this one?

Hi @Hippunky and @RowlandShaw ,

Thank you for reporting these cases. I can confirm them as False Positives. I’ve created this issue to track them: Fix S2437 FP: Silly bit operation with iterative aggregation · Issue #4399 · SonarSource/sonar-dotnet · GitHub

@Hippunky : You can work around this issue with this, if there’s no additional logic inside the loop.

Dim daysOfWeekBitField As Integer = Me.DaysOfWeek.Select(Function(X) 1 << X).Sum    

@Hippunky and @RowlandShaw : You can workaround this issue by removing the default initialization value from your aggregation variable. CLR will do that for you anyway.

Dim daysOfWeekBitField As Integer 'Remove initialization
Dim fail As Boolean 'Remove initialization
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.