From afd1e50d2c4db2136b8b168335e65e270922bbd4 Mon Sep 17 00:00:00 2001 From: Chelaris182 Date: Mon, 9 Oct 2017 22:33:34 +0200 Subject: [PATCH] Rule S4070: Use xor operator to verify flags --- .../Rules/DoNotMarkEnumsWithFlags.cs | 18 ++++++++--------- .../TestCases/DoNotMarkEnumsWithFlags.cs | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/DoNotMarkEnumsWithFlags.cs b/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/DoNotMarkEnumsWithFlags.cs index c5fee781332..0320b6ce2d7 100644 --- a/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/DoNotMarkEnumsWithFlags.cs +++ b/sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/DoNotMarkEnumsWithFlags.cs @@ -39,6 +39,7 @@ public sealed class DoNotMarkEnumsWithFlags : SonarDiagnosticAnalyzer private static readonly DiagnosticDescriptor rule = DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager); + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(rule); protected override void Initialize(SonarAnalysisContext context) @@ -114,20 +115,19 @@ private static bool IsCombinationOfOtherValues(ulong value, List otherVal } var newValue = value; - foreach (var otherValue in otherValues) + foreach (var otherValue in otherValues.SkipWhile(v => value <= v)) { - if (newValue <= 0) - { - return true; - } - - if (otherValue < value) + if (otherValue <= newValue) { - newValue -= otherValue; + newValue ^= otherValue; + if (newValue == 0) + { + return true; + } } } return newValue == 0; } } -} +} \ No newline at end of file diff --git a/sonaranalyzer-dotnet/src/Tests/SonarAnalyzer.UnitTest/TestCases/DoNotMarkEnumsWithFlags.cs b/sonaranalyzer-dotnet/src/Tests/SonarAnalyzer.UnitTest/TestCases/DoNotMarkEnumsWithFlags.cs index 9761bf56956..ef6e5555cfd 100644 --- a/sonaranalyzer-dotnet/src/Tests/SonarAnalyzer.UnitTest/TestCases/DoNotMarkEnumsWithFlags.cs +++ b/sonaranalyzer-dotnet/src/Tests/SonarAnalyzer.UnitTest/TestCases/DoNotMarkEnumsWithFlags.cs @@ -88,4 +88,24 @@ public enum InvalidStringEnum : string // Noncompliant { MyValue = "toto" // Secondary } + + [Flags] + enum EnumFoo3 + { + N1 = 1, + N2 = 2, + N3 = N1 | N2, + N4 = 4, + N5 = N4 | N1, + N6 = N4 | N2 + } + + [Flags] + enum EnumFoo4 // Noncompliant + { + N1 = 1, + N2 = 2, + N3 = N1 | N2, + N5 = 5 // Secondary + } }