Code block analyzers register code block actions to analyze executable code blocks in the compilation. You can register either a stateless CodeBlockAction or a stateful CodeBlockStartAction with nested actions to analyze syntax nodes within a code block. Our analyzer registers a CodeBlockStartAction to perform stateful analysis.
context.RegisterCodeBlockStartAction<SyntaxKind>(startCodeBlockContext =>
{
...
}
Analysis begins with a couple of early bail out checks: we are only interested in analyzing executable code within a method body and methods that have at least one parameter.
// We only care about method bodies.
if (startCodeBlockContext.OwningSymbol.Kind != SymbolKind.Method)
{
return;
}
// We only care about methods with parameters.
var method = (IMethodSymbol)startCodeBlockContext.OwningSymbol;
if (method.Parameters.IsEmpty)
{
return;
}
We allocate a new UnusedParametersAnalyzer instance for every method to be analyzed. A constructor of this type initializes the mutable state tracked for analysis (explained later):
// Initialize local mutable state in the start action.
var analyzer = new UnusedParametersAnalyzer(method);
We then register a nested syntax node action, UnusedParametersAnalyzer.AnalyzeSyntaxNode, on the given code block context for the given method. We register interest in analyzing IdentifierName syntax nodes within the code block:
// Register an intermediate non-end action that accesses and modifies the state. startCodeBlockContext.RegisterSyntaxNodeAction(analyzer.AnalyzeSyntaxNode, SyntaxKind.IdentifierName);
Finally, we register a nested CodeBlockEndAction to be executed on the instance of UnusedParametersAnalyzer at the end of the code block analysis.
// Register an end action to report diagnostics based on the final state. startCodeBlockContext.RegisterCodeBlockEndAction(analyzer.CodeBlockEndAction);
Nested end actions are always guaranteed to be executed after all the nested non-end actions registered on the same analysis context have finished executing.
Let's now understand the working of the core UnusedParametersAnalyzer type to analyze a specific code block. This analyzer defines mutable state fields to track parameters (and their names) that are considered to be unused:
#region Per-CodeBlock mutable state
private readonly HashSet<IParameterSymbol> _unusedParameters;
private readonly HashSet<string> _unusedParameterNames;
#endregion
We initialize this mutable state in the constructor of the analyzer. At the start of the analysis, we filter out implicitly declared parameters and parameters with no source locations - these are never considered to be redundant. We mark the remaining parameters as unused.
#region State intialization
public UnusedParametersAnalyzer(IMethodSymbol method)
{
// Initialization: Assume all parameters are unused, except for:
// 1. Implicitly declared parameters
// 2. Parameters with no locations (example auto-generated parameters for accessors)
var parameters = method.Parameters.Where(p => !p.IsImplicitlyDeclared && p.Locations.Length > 0);
_unusedParameters = new HashSet<IParameterSymbol>(parameters);
_unusedParameterNames = new HashSet<string>(parameters.Select(p => p.Name));
}
#endregion
AnalyzeSyntaxNode has been registered as a nested syntax node action to analyze all IdentifierName nodes within the code block. We perform a couple of quick checks at the start of the method and bail out of analysis if (a) We have no unused parameters in our current analysis state, or (b) The identifier name doesn't match any of the unused parameter names. The latter check is done to avoid the performance hit of attempting to compute symbol info for the identifier.
#region Intermediate actions
public void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context)
{
// Check if we have any pending unreferenced parameters.
if (_unusedParameters.Count == 0)
{
return;
}
// Syntactic check to avoid invoking GetSymbolInfo for every identifier.
var identifier = (IdentifierNameSyntax)context.Node;
if (!_unusedParameterNames.Contains(identifier.Identifier.ValueText))
{
return;
}
Then, we use the semantic model APIs to get semantic symbol info for the identifier name and check if it binds to one of the parameters that is currently considered unused. If so, we remove this parameter (and it's name) from the unused set.
// Mark parameter as used.
var parmeter = context.SemanticModel.GetSymbolInfo(identifier, context.CancellationToken).Symbol as IParameterSymbol;
if (parmeter != null && _unusedParameters.Contains(parmeter))
{
_unusedParameters.Remove(parmeter);
_unusedParameterNames.Remove(parmeter.Name);
}
}
#endregion
Finally, the registered code block end action walks through all the remaining parameters in the unused set and flags them as unused parameters.
#region End action
public void CodeBlockEndAction(CodeBlockAnalysisContext context)
{
// Report diagnostics for unused parameters.
foreach (var parameter in _unusedParameters)
{
var diagnostic = Diagnostic.Create(Rule, parameter.Locations[0], parameter.Name, parameter.ContainingSymbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
#endregion