SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
794 stars 228 forks source link

SE: Improve arithmetic handling in loops #8695

Open Tim-Pohlmann opened 9 months ago

Tim-Pohlmann commented 9 months ago

Follow-up to #8474 Specification

Currently, the SE engine is not conducting any calculations for arithmetic operations in loops. The following assumptions are approximations for calculations in a loop and can be added one by one:

pavel-mikula-sonarsource commented 9 months ago

Addition: What about positive+negative? Is that intended to implicitly fall back to "we don't know" scenario?

pavel-mikula-sonarsource commented 9 months ago

We should be able to do multiplication for negative*negative too?

pavel-mikula-sonarsource commented 9 months ago

Why do the multiplication and division needs to work with constants only, and not positive/negative?

Tim-Pohlmann commented 9 months ago

@pavel-mikula-sonarsource Generally speaking, my idea is, "Let's assume that the result is assigned to one of the operands and thus reused in this calculation in later iterations."

What about positive+negative? Is that intended to implicitly fall back to "we don't know" scenario? Yes. We should be able to do multiplication for negative*negative too? This would always be positive. But if it is assigned to one of the two operands, its signage would flip, and future iterations would give different results. Why do the multiplication and division needs to work with constants only, and not positive/negative? I want to avoid cases where the signage would flip. If the second operand is a constant, the result can only be assigned to the left operand, which would not result in a flipped signage.

pavel-mikula-sonarsource commented 9 months ago

I want to avoid cases where the signage would flip. If the second operand is a constant, the result can only be assigned to the left operand, which would not result in a flipped signage.

That's the gap I'm asking about. If we do it with number (not constants) and we know if they are positive/negative, we never flip the signage.

Tim-Pohlmann commented 9 months ago

We don't, because we don't know what the result will be assigned to:

var negative = -1;
var positive = 5;
while (condition)
{
    positive = positive * negative;    
}