'How to identify if a loop contains a logging statement in a Roslyn Analyser
I'm trying to teach myself to write Roslyn Analyzers (using VS 2022).
I have a piece od sample code I'm playing with;
Dictionary<string, string> GetVessels(Dictionary<string, string> dicta, Dictionary<string, string> dictb)
{
Dictionary<string, string> dictc = new Dictionary<string, string>();
foreach(KeyValuePair<string, string> kvp in dicta)
{
Log.Verbose(kvp.Key, kvp.Value);
if(!dictc.ContainsKey(kvp.Key))
dictc.Add(kvp.Key, kvp.Value);
}
foreach(KeyValuePair<string, string> kvp in dictb)
{
if(!dictc.ContainsKey(kvp.Key))
dictc.Add(kvp.Key, kvp.Value);
}
return dictc;
}
This is really just pseudo code but the idea is that I want the Analyzer to identify foreach loops that don't have a logging statement.
In the analyzer itself I'm reasonably certain that I ought to be looking for ForEachStatements so I have the following in the Initialize method;
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ForEachStatement);
Now what I'd really like to know is whether my approach to identify the presence of a logging statement in the AnalyzeNode method is correct?
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var foreachDeclaration = (ForEachStatementSyntax)context.Node;
var invocationExpression = (InvocationExpressionSyntax)context.Node;
if(foreachDeclaration.Contains(invocationExpression))
if (invocationExpression.Expression.ToString() == "Log.Verbose")
{
return;
} else
{
var diagnostic = Diagnostic.Create(Rule, foreachDeclaration.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
I realise I have still to I have still to identify the semantic model of the node so the avove code clearly has flaws but first and foremost is this the correct approach to determine whether a foreach loop contains a particular statement?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
