Home / Market / roslyn analyzers

roslyn analyzers

Build, review, debug, package, and test Roslyn diagnostic analyzers, code fix providers, and incremental source generators. Use for DiagnosticAnalyzer, CodeFixProvider, IIncrementalGenerator, IOperation analysis, Microsoft.CodeAnalysis dependency pinning, Roslyn test harnesses, C#/VB tests, and analyzer NuGet packaging.

skill★ 417980 dlgithubMITInstall in CosmosUpstream Source

Documentation & Preview

--- name: roslyn-analyzers description: 'Build, review, debug, package, and test Roslyn diagnostic analyzers, code fix providers, and incremental source generators. Use for DiagnosticAnalyzer, CodeFixProvider, IIncrementalGenerator, IOperation analysis, Microsoft.CodeAnalysis dependency pinning, Roslyn test harnesses, C#/VB tests, and analyzer NuGet packaging.'

---

Roslyn Analyzers and Source Generators

Use this workflow when adding or changing a Roslyn analyzer, code fix, source generator, tests, dependencies, or package layout. First inspect the repository's target frameworks, central package management, test framework, analyzer and generator conventions, diagnostic ID allocation, localization, and packaging. Preserve established conventions unless they conflict with the compatibility rules below.

Non-negotiable design rules

Implementation workflow

  1. Write down examples that must report and near-misses that must not report. Decide the exact diagnostic span and message arguments before implementation.
  2. Determine whether the rule is semantic. Prefer, in order, operation actions, operation-block actions, symbol actions, compilation-start actions that register one of those actions, and finally syntax actions.
  3. Resolve well-known named types once in a compilation-start action with Compilation.GetTypeByMetadataName when needed. Resolve expected members from the resulting containing type by name and full signature; GetTypeByMetadataName does not resolve methods, properties, fields, or events. If a required type or member is absent, register no inner action. Capture the resolved ISymbol in the registered callback and compare encountered symbols with SymbolEqualityComparer.Default.Equals. When generic substitutions are irrelevant, normalize both expected and encountered named types, properties, fields, and events with OriginalDefinition before comparing them; this includes comparing AttributeData.AttributeClass with a resolved generic attribute definition. For methods, normalize each IMethodSymbol with (method.ReducedFrom ?? method).OriginalDefinition so constructed generic and reduced extension methods match their declaration. Inspect type arguments separately when they matter. Never use ToDisplayString() plus a string literal as a substitute for symbol identity. Check metadata names, arity, containing type, and signature as appropriate when selecting members; do not identify APIs by simple method name alone.
  4. Define a stable diagnostic ID and descriptor. Follow repository practices for category, severity, localization, help links, telemetry tags, and release tracking.
  5. Add or update the diagnostic's documentation page and wire the descriptor's HelpLinkUri to its published URL.
  6. Report the smallest useful source location. Avoid diagnostics on generated code unless that is intentional.
  7. Add or update the code fix in the separate code-fix assembly. Preserve trivia, use syntax generators or typed syntax APIs, annotate simplifiable/formattable nodes where appropriate, provide stable equivalence keys for distinct actions, and offer FixAllProvider only when batch application is correct.
  8. Add positive, negative, edge, and code-fix tests in one test class for the rule.
  9. Verify that every analyzer project has per-commit assembly versioning and that its project-local version configuration is actually honored.
  10. Run the narrow test class or method first, then the test project, then the repository's normal build or analyzer validation. Honor the repository's test-runner syntax; do not assume VSTest --filter is supported.

For a source generator, replace steps 1-8 with: define generated API examples and invalid-input diagnostics; model each independent input; build an incremental provider graph; render with SourceWriter; and test output, diagnostics, determinism, and incremental caching before continuing with versioning, packaging, and repository validation.

Analyzer pattern

This is the preferred shape for a semantic rule. Adapt descriptor construction and generated-code policy to local conventions.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class AvoidBlockingAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "LIB0001";

    private static readonly DiagnosticDescriptor Rule = new(
        DiagnosticId,
        "Avoid blocking calls",
        "Do not call '{0}'",
        "Usage",
        DiagnosticSeverity.Warning,
        isEnabledByDefault: true);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule];

    public override void Initialize(AnalysisContext context)
    {
        context.EnableConcurrentExecution();
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.RegisterCompilationStartAction(static context =>
        {
            INamedTypeSymbol? taskType = context.Compilation.GetTypeByMetadataName(KnownApis.Task.FullName);
            if (taskType is null)
            {
                return;
            }

            context.RegisterOperationAction(
                operationContext => AnalyzeInvocation(operationContext, taskType),
                OperationKind.Invocation);
        });
    }

    private static void AnalyzeInvocation(OperationAnalysisContext context, INamedTypeSymbol taskType)
    {
        var invocation = (IInvocationOperation)context.Operation;
        IMethodSymbol method = invocation.TargetMethod;
        if (method.Name == KnownApis.Task.Wait &&
            SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType))
        {
            context.ReportDiagnostic(Diagnostic.Create(
                Rule,
                invocation.Syntax.GetLocation(),
                method.Name));
        }
    }
}

public static class KnownApis
{
    public static class Task
    {
        public const string FullName = "System.Threading.Tasks.Task";
        public const string Wait = "Wait";
    }
}

When supporting both languages, use [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] only if all analysis and diagnostic locations are actually language-neutral or both languages are separately handled and tested.

Syntax-analysis exception

Use syntax callbacks only when syntax itself controls the rule. Use the callback's existing semantic model if semantic information is unavoidable:

private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
    var invocation = (InvocationExpressionSyntax)context.Node;
    ISymbol? symbol = context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol;
    // Do not call context.Compilation.GetSemanticModel(invocation.SyntaxTree).
}

Before choosing this pattern, check whether IInvocationOperation.TargetMethod, IArgumentOperation.Parameter, IConversionOperation, or another operation supplies the same information.

Incremental source generators

Always implement IIncrementalGenerator. Do not wrap an ISourceGenerator with AsSourceGenerator; that preserves the old execution model rather than designing for incrementality.

Build a pipeline with these properties: