Migrating to Microsoft StyleCop SDK: From Legacy StyleCop to Modern Tooling

Extending Code Analysis: Advanced Techniques with Microsoft StyleCop SDK

Overview

This guide covers advanced techniques for extending StyleCop-style analysis using the Microsoft/StyleCop analyzers ecosystem and the Roslyn analyzer SDK: writing robust custom rules, creating code fixes, configuring analyzers, and integrating into CI.

Key components

  • Roslyn Analyzer — implements diagnostics by inspecting syntax/semantic models.
  • Code Fix Provider — offers automated fixes shown in IDE lightbulb.
  • Diagnostic Descriptor — ID, title, message, category, severity.
  • Additional files / Analyzer config — use .editorconfig or additional files for rule options.
  • Unit tests — use Microsoft.CodeAnalysis.Testing (xUnit/NUnit) to validate diagnostics and fixes.

Advanced techniques

  1. Target the right analysis model
    • Prefer semantic model analysis when rules need symbol info; use syntax walkers for lightweight, high-performance checks.
  2. Design stable diagnostic IDs & messages
    • Follow CA/SA-style ID patterns, make messages actionable and locale-friendly.
  3. Provide precise locations
    • Report diagnostics on the smallest appropriate syntax node or token to make fixes intuitive.
  4. Support configurability
    • Read options from .editorconfig (dotnetdiagnostic..severity) and from additional files for custom data (e.g., naming maps).
  5. Implement safe, idempotent code fixes
    • Ensure fixes preserve semantics, handle edge cases, and are reversible if possible.
  6. Use CodeFix equivalence keys
    • Provide equivalence keys to group related fixes and enable batch fixing.
  7. Offer refactorings when appropriate
    • Use RefactoringProviders for transformations not tied to diagnostics.
  8. Optimize performance
    • Avoid expensive operations in analysis entry points; cache results; use Immutable collections and cancellation tokens.
  9. Comprehensive testing
    • Unit test analyzer diagnostics, code fixes, and edge cases; include multi-file tests and generated-code exclusions.
  10. Packaging & distribution
    • Package as a NuGet analyzer with integrated build targets; include docs, sample .editorconfig, and changelog.
  11. CI integration
    • Fail builds on configured severities, run analyzers during PR checks, and surface diagnostics in GitHub Actions/Azure Pipelines.
  12. Migration & compatibility
    • Provide clear migration notes from legacy StyleCop; support both SDK-style projects and older project formats via installation guidance.

Example snippet (analyzer registration)

csharp

[DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class MyAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = “SA9001”; private static readonly DiagnosticDescriptor Rule = new( DiagnosticId, “Title”, “Message format”, “Style”, DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { /* … */ } }

References & resources

  • Roslyn Analyzer SDK: writing analyzers & code fixes
  • Microsoft docs: Configure code analysis / EditorConfig options
  • StyleCopAnalyzers GitHub: rule implementations and configuration examples
  • Microsoft.CodeAnalysis.Testing libraries for unit testing analyzers

If you want, I can: provide a starter analyzer + code-fix project, an .editorconfig template for configurable options, or a sample CI workflow to run analyzers—tell me which.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *