ArchiMetrics
ArchiMetrics copied to clipboard
Depth of Inheritance doesn't work
Depth of Inheritance doesn't work,
Neither does this kind of bug report.
Analyzer Code:
var codeMetricResult = new CodeMetricsCalculator().Calculate(new[] { context.Tree }).Result;
//For each namespace
foreach (var nsResult in codeMetricResult)
{
foreach (var typeResult in nsResult.TypeMetrics)
{
var diagnostic = Diagnostic.Create(DemoDiagnostic, Location.None, "=> Type Name: " + typeResult.Name + ", Depth Of Inheritance : " + typeResult.DepthOfInheritance);
context.ReportDiagnostic(diagnostic);
}
}
Code to analyze:
namespace SampleApp
{
class A
{
}
class B : A
{
}
class C : B
{
}
class D : C
{
}
class MainClass:D
{
public static void Main()
{
Console.WriteLine("Hello world");
}
}
}
Outputs: Depth of inheritance 1 for each class, even for MainClass
In DepthOfInheritanceAnalyzer.cs , I debugged and found when type is D, (in fact for all type which has base), symbolInfo.Symbol is null inside
foreach (var symbolInfo in type.BaseList.Types.Select(syntax => ModelExtensions.GetSymbolInfo(_semanticModel, syntax)))
For that reason variable num inside the loop doesn't increase.
This is what I have anlysed, hope this helps.
public int Calculate(TypeDeclarationSyntax type)
{
var num = type.IsKind(SyntaxKind.ClassDeclaration) || type.IsKind(SyntaxKind.StructDeclaration) ? 1 : 0;
if (type.BaseList != null)
{
// For any type which has base it gets symbolinfo.Symbol as null, so the variable num doesn't increase
foreach (var symbolInfo in type.BaseList.Types.Select(syntax => ModelExtensions.GetSymbolInfo(_semanticModel, syntax)))
{
for (var symbol = symbolInfo.Symbol as INamedTypeSymbol; symbol != null; symbol = symbol.BaseType)
{
if (_inheritableTypes.Any(x => x == symbol.TypeKind))
{
num++;
}
}
}
}
return num == 0 && (type.IsKind(SyntaxKind.ClassDeclaration) || type.IsKind(SyntaxKind.StructDeclaration))
? 1
: num;
}
@jjrdk : Could you please check this ?
Thanks Enamul
If we change below line
foreach (var symbolInfo in type.BaseList.Types.Select(syntax => ModelExtensions.GetSymbolInfo(_semanticModel, syntax)))
as
foreach (var symbolInfo in type.BaseList.Types.Select(syntax => ModelExtensions.GetSymbolInfo(_semanticModel, syntax.Type)))
then the issue gets fixed
Thanks for finding the fix. Can I ask you to submit a pull request?