Showing posts with label Code analysis. Show all posts
Showing posts with label Code analysis. Show all posts

Wednesday 17 June 2020

Multiple enum values set to same value codefix for VS

I created a new extension in Visual Studio today! The UniqueEnumValueFixer vs extension is now available here! https://marketplace.visualstudio.com/items?itemName=ToreAurstadIT.EXT001 The extension is actually a Code Fix for Visual Studio. It flags a warning to the developer if an enum contains multiple members mapped to the same value. Having a collision with values for enum causes ambiguity and confusion for the developer. An enum value has not got a single mapping from enum member to integer value. Example like this: Here we see that iceconverted is set to Fudge, which is the last of the colliding valued enum members. This gives code which is not clear and confusing and ambiguous. It is perfectly valid, but programmers will perhaps sigh a bit when they see enums with multiple members mapped to same value. The following sample code shows a violation of the rule:

    enum IceCream
    {
        Vanilla = 0, 
        Chocolate = 2,
        Strawberry = Vanilla,
        Peach = 2
    }

Here, multiple members are mapped to the same value in the enum. Strawberry and Vanilla points to the same value through assignment. And Peach is set to same value as Chocolate. The code fix will show enums containing the violation after compiling the solution in the Errors and Warnings pane of Visual Studio.

   public override void Initialize(AnalysisContext context)
        {
            // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols
            // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/Analyzer%20Actions%20Semantics.md for more information
            context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);

        }

        private static void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            try
            {
                var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
                if (namedTypeSymbol.EnumUnderlyingType != null)
                {
                    var valueListForEnum = new List<Tuple<string, int>>();
                    //Debugger.Launch();
                    //Debugger.Break();
                    var typeResolved = context.Compilation.GetTypeByMetadataName(namedTypeSymbol.MetadataName) ?? context.Compilation.GetTypeByMetadataName(namedTypeSymbol.ToString());
                    if (typeResolved != null)
                    {
                        foreach (var member in typeResolved.GetMembers())
                        {
                            var c = member.GetType().GetRuntimeProperty("ConstantValue");
                            if (c == null)
                            {
                                c = member.GetType().GetRuntimeProperties().FirstOrDefault(prop =>
                                    prop != null && prop.Name != null &&
                                    prop.Name.Contains("IFieldSymbol.ConstantValue"));
                                if (c == null)
                                {
                                    continue;
                                }
                            }

                            var v = c.GetValue(member) as int?;
                            if (v.HasValue)
                            {
                                valueListForEnum.Add(new Tuple<string, int>(member.Name, v.Value));
                            }
                        }
                        if (valueListForEnum.GroupBy(v => v.Item2).Any(g => g.Count() > 1))
                        {
                            var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0],
                                namedTypeSymbol.Name);
                            context.ReportDiagnostic(diagnostic);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }

        }

The source code is available on Github here: https://github.com/toreaurstadboss/UniqueEnumValuesAnalyzer

Monday 15 July 2019

Using Ndepend to investigate method cycles

Ndepend is a very powerful Code analysis platform for DotNet and I have created a method cycle detection rule. The method cycle detection also supports property setters and getters. A cycle in a property or method will often cause problems, such as stack overflow exceptions due to too many recursive calls. Spotting such cycles can often be hard in real-world scenarios. A classic error is to actually do a cycle through a property getter, by just calling the getter once more or a property setter for that instance. The following C# attribute invokes a Rules extracted from Source code from Ndepend.

using System;
using NDepend.Attributes;

namespace Hemit.OpPlan.Client.Infrastructure.Aspects
{
    /// Ndepend attribute to enable cyclic loops in methods in the source code 
    [CodeRule(@"// <Name>Avoid methods of a type to be in cycles. Detect also recursive property setter calls</Name>
warnif count > 0

from t in Application.Types
                 .Where(t => t.ContainsMethodDependencyCycle != null && 
                             t.ContainsMethodDependencyCycle.Value)

// Optimization: restreint methods set
// A method involved in a cycle necessarily have a null Level.
let methodsSuspect = t.Methods.Where(m => m.Level == null)

// hashset is used to avoid iterating again on methods already caught in a cycle.
let hashset = new HashSet<IMethod>()


from suspect in methodsSuspect
   // By commenting this line, the query matches all methods involved in a cycle.
   where !hashset.Contains(suspect)

   // Define 2 code metrics
   // - Methods depth of is using indirectly the suspect method.
   // - Methods depth of is used by the suspect method indirectly.
   // Note: for direct usage the depth is equal to 1.
   let methodsUserDepth = methodsSuspect.DepthOfIsUsing(suspect)
   let methodsUsedDepth = methodsSuspect.DepthOfIsUsedBy(suspect)

   // Select methods that are both using and used by methodSuspect
   let usersAndUsed = from n in methodsSuspect where 
                         methodsUserDepth[n] > 0 && 
                         methodsUsedDepth[n] > 0 
                      select n

   where usersAndUsed.Count() > 0

   // Here we've found method(s) both using and used by the suspect method.
   // A cycle involving the suspect method is found!
   let cycle = System.Linq.Enumerable.Append(usersAndUsed,suspect)


   // Fill hashset with methods in the cycle.
   // .ToArray() is needed to force the iterating process.
   let unused1 = (from n in cycle let unused2 = hashset.Add(n) select n).ToArray()

let cycleContainsSetter = (from n1 in cycle where n1.IsPropertySetter select n1).Count()

  
select new { suspect, cycle, cycleContainsSetter }",
        Active = true,
        DisplayStatInReport = true,
        DisplayListInReport = true,
        DisplaySelectionViewInReport = true,
        IsCriticalRule = false)]
    public class MethodCycleDetectionAttribute : Attribute
    {
    }
}


Note that this Ndepend Code rule uses the CQLinq syntax placed into a C# attribute class that inherits from Attribute and itself is attributed with a Ndepend.Attributes.CodeRuleAttribute. I had to adjust the attribute a little bit using the ExtensionMethodsEnumerable fix for .Net 4.6.2 mentioned on Ndepend blog post here: https://blog.ndepend.com/problem-extension-methods/ The following screen shot shows Visual Studio 2019 with Ndepend version 2019.2.5 installed. It shows the method cycle detection code rule I created showing up as a code rule through source code. Selecting that code rule in the menu Ndepend => Rules Explorer that selects Queries and Rules Explorer allows to not only view the code rule but quickly see the code analysis results.
One method cycle I have is shown in the following image, the method ProcessPasRequest of my system. This case shows how advanced Ndepend really is in code analysis. It can detect transitive cycles with multiple function calls. The following two screen shots shows the cycle in question. In this case, it was not a bug, since the cycle will only happend a finite amount of times for a given set of patients, but it still can go into an infinite loop if the external system is not working correct. However in this case, if that external system is not working, the system I have been working with also faults as it relies on that external system. With Ndepend I could spot method cycles with transitive cycles with a breeze! I can also spot property getter and setter cycles, as property getters and setters in C# are methods anyways (compiler generated). I managed to get Ndepend back to the main menu in Visual Studio 2019 using this extension.
https://marketplace.visualstudio.com/items?itemName=Evgeny.RestoreExtensions