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