1
---
2
name: roslyn-analyzers
3
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.'
4
---
5
6
# Roslyn Analyzers and Source Generators
7
8
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.
9
10
## Non-negotiable design rules
11
12
- Prefer `IOperation`-based analysis wherever possible. Register the narrowest applicable `OperationKind` and inspect typed operations such as `IInvocationOperation`, `IAwaitOperation`, or `IObjectCreationOperation`. This usually supports C# and VB with one analyzer and gives direct access to symbols and conversions.
13
- Use syntax analysis only for inherently syntactic rules or syntax not represented adequately by `IOperation`. A syntax-node callback already has a `SemanticModel`; do not call `Compilation.GetSemanticModel` or fetch another semantic model from it. Repeated semantic-model creation is expensive and often indicates that an operation or symbol action is the better abstraction.
14
- Every analyzer must support C#. VB.NET support is optional until requested or established repository precedent requires it. A language-neutral operation analyzer may declare both languages. If VB support is promised, include equivalent C# and VB snippets in tests; do not infer VB correctness from shared implementation alone.
15
- Keep analyzer and code-fix providers in distinct assemblies. The analyzer project must never reference Roslyn Workspaces packages. Workspaces dependencies belong only in the code-fix and test projects.
16
- Analyzer callbacks must be stateless or concurrency-safe. Call `EnableConcurrentExecution()`. Make an explicit generated-code choice with `ConfigureGeneratedCodeAnalysis(...)`; follow repository policy rather than silently accepting the default.
17
- Respect cancellation where APIs expose a token. Do not retain compilations, operations, syntax trees, symbols, or semantic models in static state.
18
- Avoid `InternalsVisibleTo`. Test analyzers through their public `DiagnosticAnalyzer` and `CodeFixProvider` APIs and the Roslyn test harness. A small analyzer helper may be public when direct testing is genuinely useful, but most behavior should be tested end to end.
19
- Centralize metadata names and member names instead of propagating magic strings. Use one shared static catalog for fully qualified type names, namespaces, and API member names.
20
- Never identify a symbol, including an attribute class, by calling `ToDisplayString()` and comparing the result with a string literal. Resolve an expected named type from the `Compilation` once by metadata name. To resolve a method, property, field, or event, first resolve its containing type, then select the expected member by name and signature. Compare encountered symbols with `SymbolEqualityComparer.Default.Equals(actual, expected)`. When generic substitutions are irrelevant, compare named types, properties, fields, and events by `OriginalDefinition`; compare methods after replacing a reduced extension method with `ReducedFrom ?? method` and then taking `OriginalDefinition`. Normalize both expected and encountered symbols, and inspect type arguments separately when they are part of the match. Display strings are for presentation, not identity, and can vary with formatting, aliases, qualification, nullability, and other context.
21
- Document every diagnostic ID. When the repository uses Docfx, put analyzer documentation under its Docfx tree, typically `docfx/analyzers`, and include each page in the relevant table of contents.
22
- Set every analyzer assembly's version precisely enough that each commit produces a unique assembly version. When using Nerdbank.GitVersioning, give each analyzer project its own `version.json` with `assemblyVersion.precision` set to `revision` and ensure that repository-wide MSBuild properties do not prevent that file from being discovered.
23
- Source generators must implement `IIncrementalGenerator`, not `ISourceGenerator`. Design the provider graph so unchanged inputs remain cached and do not regenerate output.
24
- Source generators must use a small `SourceWriter` abstraction for deterministic newlines, indentation, encoding, and balanced output. Start from [SourceWriter.cs](./references/SourceWriter.cs) and tailor its namespace and target-framework details to the receiving repository.
25
26
## Implementation workflow
27
28
1. Write down examples that must report and near-misses that must not report. Decide the exact diagnostic span and message arguments before implementation.
29
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.
30
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.
31
4. Define a stable diagnostic ID and descriptor. Follow repository practices for category, severity, localization, help links, telemetry tags, and release tracking.
32
5. Add or update the diagnostic's documentation page and wire the descriptor's `HelpLinkUri` to its published URL.
33
6. Report the smallest useful source location. Avoid diagnostics on generated code unless that is intentional.
34
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.
35
8. Add positive, negative, edge, and code-fix tests in one test class for the rule.
36
9. Verify that every analyzer project has per-commit assembly versioning and that its project-local version configuration is actually honored.
37
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.
38
39
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.
40
41
## Analyzer pattern
42
43
This is the preferred shape for a semantic rule. Adapt descriptor construction and generated-code policy to local conventions.
44
45
```csharp
46
using System.Collections.Immutable;
47
using Microsoft.CodeAnalysis;
48
using Microsoft.CodeAnalysis.Diagnostics;
49
using Microsoft.CodeAnalysis.Operations;
50
51
[DiagnosticAnalyzer(LanguageNames.CSharp)]
52
public sealed class AvoidBlockingAnalyzer : DiagnosticAnalyzer
53
{
54
public const string DiagnosticId = "LIB0001";
55
56
private static readonly DiagnosticDescriptor Rule = new(
57
DiagnosticId,
58
"Avoid blocking calls",
59
"Do not call '{0}'",
60
"Usage",
61
DiagnosticSeverity.Warning,
62
isEnabledByDefault: true);
63
64
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule];
65
66
public override void Initialize(AnalysisContext context)
67
{
68
context.EnableConcurrentExecution();
69
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
70
context.RegisterCompilationStartAction(static context =>
71
{
72
INamedTypeSymbol? taskType = context.Compilation.GetTypeByMetadataName(KnownApis.Task.FullName);
73
if (taskType is null)
74
{
75
return;
76
}
77
78
context.RegisterOperationAction(
79
operationContext => AnalyzeInvocation(operationContext, taskType),
80
OperationKind.Invocation);
81
});
82
}
83
84
private static void AnalyzeInvocation(OperationAnalysisContext context, INamedTypeSymbol taskType)
85
{
86
var invocation = (IInvocationOperation)context.Operation;
87
IMethodSymbol method = invocation.TargetMethod;
88
if (method.Name == KnownApis.Task.Wait &&
89
SymbolEqualityComparer.Default.Equals(method.ContainingType, taskType))
90
{
91
context.ReportDiagnostic(Diagnostic.Create(
92
Rule,
93
invocation.Syntax.GetLocation(),
94
method.Name));
95
}
96
}
97
}
98
99
public static class KnownApis
100
{
101
public static class Task
102
{
103
public const string FullName = "System.Threading.Tasks.Task";
104
public const string Wait = "Wait";
105
}
106
}
107
```
108
109
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.
110
111
## Syntax-analysis exception
112
113
Use syntax callbacks only when syntax itself controls the rule. Use the callback's existing semantic model if semantic information is unavoidable:
114
115
```csharp
116
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
117
{
118
var invocation = (InvocationExpressionSyntax)context.Node;
119
ISymbol? symbol = context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol;
120
// Do not call context.Compilation.GetSemanticModel(invocation.SyntaxTree).
121
}
122
```
123
124
Before choosing this pattern, check whether `IInvocationOperation.TargetMethod`, `IArgumentOperation.Parameter`, `IConversionOperation`, or another operation supplies the same information.
125
126
## Incremental source generators
127
128
Always implement `IIncrementalGenerator`. Do not wrap an `ISourceGenerator` with `AsSourceGenerator`; that preserves the old execution model rather than designing for incrementality.
129
130
Build a pipeline with these properties:
131
132
- Use `SyntaxProvider.ForAttributeWithMetadataName` for attribute-driven discovery. Otherwise, use `CreateSyntaxProvider` with a very cheap syntactic predicate and perform semantic work only in its transform.
133
- Transform syntax and symbols immediately into small immutable, value-equatable models containing only information needed for generation. Do not carry `SyntaxNode`, `ISymbol`, `SemanticModel`, or `Compilation` into later stages because their identity changes defeat caching.
134
- Keep independent inputs in independent providers. Combine providers as late as possible. Avoid combining every item with `CompilationProvider` merely for convenience.
135
- Avoid `Collect()` unless one output truly depends on the complete set. Prefer one output per model so editing one declaration invalidates only that output.
136
- Use stable equality. Records and immutable value types are good models; add `WithComparer` when normal equality does not represent semantic equivalence.
137
- Keep transforms and output callbacks static, pure, deterministic, and cancellation-aware. Do not read ambient files, clocks, environment state, or mutable static state. Model configuration, additional files, analyzer config options, and parse options as explicit providers.
138
- Give providers `WithTrackingName` labels while developing or testing incremental behavior.
139
- Generate stable, collision-resistant hint names. Sort any aggregated inputs explicitly before emitting output.
140
- Report invalid user input with generator diagnostics instead of throwing. Generator exceptions surface as compiler failures.
141
- Use `SourceText` with an explicit encoding when calling `AddSource`.
142
143
A compact pipeline should look like this:
144
145
```csharp
146
[Generator(LanguageNames.CSharp)]
147
public sealed class FactoryGenerator : IIncrementalGenerator
148
{
149
public void Initialize(IncrementalGeneratorInitializationContext context)
150
{
151
IncrementalValuesProvider<TypeModel> models = context.SyntaxProvider
152
.ForAttributeWithMetadataName(
153
"Product.GenerateFactoryAttribute",
154
static (node, _) => node is TypeDeclarationSyntax,
155
static (attributeContext, cancellationToken) =>
156
TypeModel.Create(attributeContext, cancellationToken))
157
.WithTrackingName("FactoryModels");
158
159
context.RegisterSourceOutput(models, static (productionContext, model) =>
160
{
161
var writer = new SourceWriter();
162
writer.WriteLine("// <auto-generated/>");
163
writer.WriteLine($"namespace {model.Namespace};");
164
writer.WriteLine();
165
writer.WriteLine($"partial class {model.TypeName}");
166
writer.WriteLine('{');
167
writer.Indentation++;
168
writer.WriteLine($"public static {model.TypeName} Create() => new();");
169
writer.Indentation--;
170
writer.WriteLine('}');
171
productionContext.AddSource(model.HintName, writer.ToSourceText());
172
});
173
}
174
}
175
```
176
177
The model creation step must normalize symbol data into strings, booleans, enums, and other immutable values, validate unsupported declarations, escape identifiers, and derive a stable hint name. The output callback should only render the model. Use the complete [SourceWriter.cs](./references/SourceWriter.cs) example rather than ad hoc `StringBuilder` concatenation, then adapt indentation style and framework compatibility to the repository.
178
179
### Generator tests
180
181
Test source generators with `GeneratorDriver` or the repository's generator test harness. Cover:
182
183
- exact generated hint names and source text;
184
- multiple and nested declarations, namespaces, generics, escaped identifiers, and partial types;
185
- malformed or unsupported inputs and their diagnostic locations;
186
- additional files, analyzer config options, and parse options when consumed;
187
- deterministic output independent of input enumeration and operating-system newlines;
188
- a second driver run with identical inputs that caches all expected tracked steps;
189
- a narrowly changed input that reruns only the affected pipeline and output;
190
- compilation of generated output without unexpected diagnostics.
191
192
Enable incremental step tracking in tests and assert run reasons such as cached, unchanged, modified, or newly produced according to the Roslyn version in use. Do not settle for snapshot-only tests: identical generated text can hide a pipeline that recomputes everything.
193
194
## Diagnostic documentation and help links
195
196
Create one discoverable documentation page for every diagnostic code. A useful page includes:
197
198
- the diagnostic ID, title, category, and default severity;
199
- the exact condition that triggers the diagnostic;
200
- why the reported pattern is problematic;
201
- bad and corrected C# examples;
202
- VB examples when VB support is promised;
203
- exceptions, configuration, suppression guidance, and code-fix behavior when relevant.
204
205
If the repository has a Docfx site, place these pages under its existing analyzer documentation area, typically:
206
207
```text
208
docfx/
209
analyzers/
210
LIB0001.md
211
toc.yml
212
```
213
214
Follow the site's existing URL and navigation conventions. Add each page to the applicable `toc.yml` so it is rendered and discoverable. The descriptor's help link must be the public GitHub Pages URL that Docfx will produce, not a source-tree path. Centralize construction when all diagnostics share a route:
215
216
```csharp
217
private static string GetHelpLink(string diagnosticId)
218
=> $"https://example.github.io/product/analyzers/{diagnosticId}.html";
219
220
private static readonly DiagnosticDescriptor Rule = new(
221
id: DiagnosticId,
222
title: "Avoid blocking calls",
223
messageFormat: "Do not call '{0}'",
224
category: "Usage",
225
defaultSeverity: DiagnosticSeverity.Warning,
226
isEnabledByDefault: true,
227
helpLinkUri: GetHelpLink(DiagnosticId));
228
```
229
230
Derive the exact hostname, base path, output extension, casing, and route from the repository's Docfx configuration and deployment setup. Confirm that the generated site's route matches `HelpLinkUri`; do not merely assume that a Markdown path maps to the expected URL. When no Docfx folder exists, follow the repository's established documentation system or create an equivalent durable page and public help URL.
231
232
## Project and dependency boundaries
233
234
A typical solution has three projects:
235
236
```text
237
Product.Analyzers -> Microsoft.CodeAnalysis.Common/CSharp only
238
Product.CodeFixes -> Product.Analyzers + Roslyn Workspaces/Features APIs
239
Product.Analyzers.Tests -> analyzer + code-fix projects + current testing packages
240
```
241
242
Target analyzer assemblies conservatively, commonly `netstandard2.0`, unless host requirements dictate otherwise. Treat the analyzer's Roslyn version as a host-compatibility floor, not a routine dependency to float.
243
244
Choose exactly one Roslyn reference-assembly version for shipping analyzer projects. Pin it independently from the latest Roslyn version used by code-fix tests or the rest of the repository. Pin the analyzer dependency's entire transitive closure to mutually compatible versions, including packages such as `System.Collections.Immutable`, `System.Memory`, `System.Reflection.Metadata`, `System.Runtime.CompilerServices.Unsafe`, and `System.Threading.Tasks.Extensions` when they appear in restore. Directly pinning only `Microsoft.CodeAnalysis.*` is insufficient: a newer centrally managed transitive dependency can make the analyzer fail in an older compiler host.
245
246
With central package management, create a dedicated `Directory.Packages.Analyzers.props` at the repository root and import it only for shipping analyzer, source-generator, and code-fix projects. Do not fold these overrides into the general `Directory.Packages.props`: the separate file makes the compatibility boundary visible and lets dependency automation treat it specially.
247
248
Use this three-part pattern.
249
250
First, have every shipping analyzer, source-generator, and code-fix project import one shared props file such as `src/AnalyzerCompatibility.props`. That file should identify the project:
251
252
```xml
253
<Project>
254
<PropertyGroup>
255
<!-- This is set so that Directory.Packages.Analyzers.props can apply version overrides specific to analyzer projects. -->
256
<IsAnalyzerCompatibilityProject>true</IsAnalyzerCompatibilityProject>
257
</PropertyGroup>
258
</Project>
259
```
260
261
Second, conditionally import the dedicated package file from a repository-wide props or targets file after central package versions are available:
262
263
```xml
264
<Import Project="$(MSBuildThisFileDirectory)Directory.Packages.Analyzers.props"
265
Condition="'$(IsAnalyzerCompatibilityProject)' == 'true'" />
266
```
267
268
Third, copy this `Directory.Packages.Analyzers.props` structure and tailor the baseline comment, Roslyn version, and transitive versions to the oldest supported compiler or SDK host. Use `Update` only for a package already declared by the repository's central package file; use `Include` to add a pin for a package that is otherwise transitive-only. The example assumes the Roslyn packages are already declared and the listed runtime dependencies are new pins:
269
270
```xml
271
<Project>
272
<!-- These versions are chosen to support the oldest compiler/SDK host named here. -->
273
<PropertyGroup>
274
<CodeAnalysisVersionForAnalyzers>4.11.0</CodeAnalysisVersionForAnalyzers>
275
<!-- Apply analyzer compatibility pins to packages referenced only transitively. -->
276
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
277
</PropertyGroup>
278
<ItemGroup>
279
<PackageVersion Update="Microsoft.CodeAnalysis" Version="$(CodeAnalysisVersionForAnalyzers)" />
280
<PackageVersion Update="Microsoft.CodeAnalysis.Common" Version="$(CodeAnalysisVersionForAnalyzers)" />
281
<PackageVersion Update="Microsoft.CodeAnalysis.CSharp" Version="$(CodeAnalysisVersionForAnalyzers)" />
282
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="$(CodeAnalysisVersionForAnalyzers)" />
283
<PackageVersion Update="Microsoft.CodeAnalysis.VisualBasic" Version="$(CodeAnalysisVersionForAnalyzers)" />
284
<PackageVersion Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="$(CodeAnalysisVersionForAnalyzers)" />
285
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="8.0.0" />
286
<PackageVersion Include="System.Collections.Immutable" Version="8.0.0" />
287
<PackageVersion Include="System.Memory" Version="4.5.5" />
288
<PackageVersion Include="System.Reflection.Metadata" Version="8.0.0" />
289
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
290
<PackageVersion Include="System.Text.Json" Version="8.0.0" />
291
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
292
</ItemGroup>
293
</Project>
294
```
295
296
The XML comments in these samples are required, not decorative. Keep equivalent comments in the receiving repository explaining why `IsAnalyzerCompatibilityProject` exists, why the conditional import exists when its purpose is not obvious, which oldest host the pinned versions support, and why these versions intentionally differ from the repository defaults. Include the Roslyn version-support documentation URL in or next to the baseline comment when it helps maintainers choose the correct compiler baseline. Future dependency updates must preserve or update these comments so users do not mistake deliberate compatibility pins for stale packages.
297
298
The versions above are a structural example, not universal recommendations. Recalculate the complete package set for the selected oldest host by inspecting the resolved dependency graph. Retain each package that Roslyn or the generator loads in the compiler process, even when the repository does not reference it directly. `Workspaces` entries centrally pin versions for code-fix projects but must not be referenced by analyzer or source-generator projects. The test project should remain outside `IsAnalyzerCompatibilityProject` and use the latest repository-approved Roslyn and analyzer-testing packages so tests also catch compatibility with current APIs and compilers.
299
300
Always prefer the latest available version of `Microsoft.CodeAnalysis.Analyzers`. It is a development-time analyzer package, not a compiler-host runtime dependency, so it does not need to match `Microsoft.CodeAnalysis`, `Microsoft.CodeAnalysis.Common`, C#/VB, or Workspaces package versions and must not be held back to the analyzer compatibility baseline. Keep it on the repository's normal latest-version update path and reference it without flowing it to consumers:
301
302
```xml
303
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
304
```
305
306
Do not set its central version to `$(CodeAnalysisVersionForAnalyzers)` and do not include it among packages excluded from minor or major dependency updates. This exception applies specifically to `Microsoft.CodeAnalysis.Analyzers`; packages loaded with the shipping analyzer or generator still belong to the carefully pinned compatibility closure.
307
308
Configure dependency automation so the analyzer baseline is not upgraded across Roslyn versions. For Renovate, isolate the analyzer version file or package group and disallow updates:
309
310
```json
311
{
312
"packageRules": [
313
{
314
"matchFileNames": ["Directory.Packages.Analyzers.props"],
315
"enabled": false
316
}
317
]
318
}
319
```
320
321
For Dependabot, use an `ignore` entry for each analyzer-baseline package with `update-types` containing `version-update:semver-major`, `version-update:semver-minor`, and `version-update:semver-patch`. Include the pinned transitive packages, not only `Microsoft.CodeAnalysis.*`. If the tool cannot distinguish analyzer-only central versions from repository-wide versions, place the analyzer pins in a dedicated file/directory or make those upgrades manual.
322
323
Verify dependency isolation with a restore graph or assets file and, when practical, load the built analyzer in the oldest supported compiler/IDE host. A successful build on the newest SDK does not prove host compatibility.
324
325
## Code-fix boundaries
326
327
The code-fix project may reference packages such as `Microsoft.CodeAnalysis.CSharp.Workspaces` or `Microsoft.CodeAnalysis.VisualBasic.Workspaces`; the analyzer project may not. Keep the code fix optional from the analyzer's perspective. A fix should:
328
329
- register only when the diagnostic can be fixed safely;
330
- find the target node from the diagnostic span defensively;
331
- preserve leading/trailing trivia and imports;
332
- use `Simplifier.Annotation` and `Formatter.Annotation` where appropriate;
333
- return a new document or solution without mutating shared state;
334
- support cancellation and avoid blocking async Roslyn APIs;
335
- use a meaningful, stable equivalence key, especially when multiple fixes share a title;
336
- return the batch fixer only when fixes do not conflict or depend on application order.
337
338
## Unique assembly versions
339
340
Analyzer hosts cache and identify assemblies by assembly identity. Every commit that can change an analyzer should therefore produce a unique, precise assembly version; relying only on package version or file version is insufficient.
341
342
With Nerdbank.GitVersioning, put a `version.json` directly in every analyzer project directory, including each language-specific analyzer assembly when those are separate:
343
344
```json
345
{
346
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json",
347
"inherit": true,
348
"assemblyVersion": {
349
"precision": "revision"
350
}
351
}
352
```
353
354
Then inspect all imported `Directory.Build.props`, `Directory.Build.targets`, and project SDK props for `GitVersionBaseDirectory`. A repository may set that property to a shared root so version calculation happens once; that can cause a project-local `version.json` to be ignored. In each analyzer project file, reset it to the analyzer project's own directory:
355
356
```xml
357
<PropertyGroup>
358
<!-- Honor this analyzer project's version.json and produce a unique assembly identity per commit. -->
359
<GitVersionBaseDirectory>$(MSBuildProjectDirectory)</GitVersionBaseDirectory>
360
</PropertyGroup>
361
```
362
363
Apply this override after any shared property import that sets the value, or otherwise ensure normal MSBuild precedence leaves the project-local value effective. Do not add the override blindly: first locate the controlling assignment and confirm which `version.json` the evaluated analyzer project uses.
364
365
Validate the built assembly rather than only inspecting MSBuild source. Build the same analyzer from two distinct commits when practical and confirm that `AssemblyName.Version` differs. At minimum, inspect the evaluated `GitVersionBaseDirectory`, the selected version file, and the resulting assembly version. Repeat this for every analyzer assembly, not merely the packaging or code-fix project.
366
367
## Test structure
368
369
Use `Microsoft.CodeAnalysis.Testing` or the repository's established equivalent. Keep one test class per diagnostic rule for analyzer and code-fix behavior together. Do not create a separate code-fix test class. Even when a diagnostic intentionally has no fix, instantiate the same analyzer-plus-code-fix harness with `EmptyCodeFixProvider`; this keeps all cases and configuration for the rule together.
370
371
Annotate every verifier/helper parameter that accepts C# source with `[StringSyntax("c#-test")]` from `System.Diagnostics.CodeAnalysis`. This enables syntax highlighting and language services at test call sites. Start from [CSharpCodeFixVerifier.cs](./references/CSharpCodeFixVerifier.cs) for a complete example and apply the attribute to analyzer-only and generator test helpers as well. If the target framework does not define `StringSyntaxAttribute`, use the repository's compatibility/polyfill pattern.
372
373
When C# source is assigned to a local variable instead of passed directly to an annotated parameter, add a language comment before the literal:
374
375
```csharp
376
const string source = /* lang=c#-test */ """
377
// C# code here
378
""";
379
```
380
381
Prefer inline markup to hard-coded line/column spans:
382
383
```csharp
384
using Verify = CSharpCodeFixVerifier<AvoidBlockingAnalyzer, AvoidBlockingCodeFix>;
385
386
public class AvoidBlockingTests
387
{
388
[Fact]
389
public async Task ReportsBlockingCallAndFixesIt()
390
{
391
const string source = /* lang=c#-test */ """
392
using System.Threading.Tasks;
393
class C
394
{
395
void M(Task task) => [|task.Wait()|];
396
}
397
""";
398
const string fixedSource = /* lang=c#-test */ """
399
using System.Threading.Tasks;
400
class C
401
{
402
async Task M(Task task) => await task;
403
}
404
""";
405
406
await Verify.VerifyCodeFixAsync(source, fixedSource);
407
}
408
409
[Fact]
410
public async Task DoesNotReportAwaitedTask()
411
{
412
const string source = /* lang=c#-test */ """
413
using System.Threading.Tasks;
414
class C
415
{
416
async Task M(Task task) => await task;
417
}
418
""";
419
420
await Verify.VerifyAnalyzerAsync(source);
421
}
422
}
423
```
424
425
Never describe an expected diagnostic with hard-coded line/column numbers (`WithSpan(...)`, `WithLocation(line, column)`, `new DiagnosticResult(...).WithSpan(...)`). Mark the span in the source with one of these `Microsoft.CodeAnalysis.Testing` markup forms instead, choosing the simplest that fits. Pick the first form that expresses what the test needs:
426
427
- `[|code|]`: the analyzer reports a single diagnostic ID and nothing beyond the span needs asserting. No `DiagnosticResult` is needed; the verifier infers the diagnostic from the analyzer's only supported descriptor.
428
- `{|DiagnosticId:code|}` (for example `{|CA2000:new Foo()|}`): the analyzer can report multiple IDs, or compiler diagnostics (such as `CS0103`) are expected, and only the ID and span matter. The ID in the markup is the assertion; no `DiagnosticResult` is needed.
429
- `{|#0:code|}`: the diagnostic needs more than an ID and span (message arguments, severity, a specific descriptor, or additional locations). The marker only labels the location; pass a hand-authored `DiagnosticResult` with `.WithLocation(0)` (the integer key from `#0`) to `VerifyAnalyzerAsync`/`VerifyCodeFixAsync` or add it to `test.ExpectedDiagnostics`.
430
431
```csharp
432
await Verify.VerifyAnalyzerAsync(
433
/* lang=c#-test */ """
434
class C { void M() => {|#0:Old()|}; void Old() { } }
435
""",
436
Verify.Diagnostic(AvoidOldAnalyzer.Rule).WithLocation(0).WithArguments("Old"));
437
```
438
439
Relevant `DiagnosticResult` members:
440
441
- `WithLocation(int markupKey)`: binds to the `{|#n:...|}` span. Calling it again on the same result adds additional locations (for example related symbols), in order.
442
- An indexed marker only labels a location and does not create an expected diagnostic; pair each marker intended for validation with a `DiagnosticResult` using `WithLocation(n)`, or the span is never checked. When a code fix test's `fixedSource` still contains the diagnostic, add the same result to `FixedState.ExpectedDiagnostics`.
443
- Markup keys are resolved across every file in the test state, so `WithLocation(int markupKey)` also works for `{|#n:...|}` markers placed in additional `TestState.Sources` or `AdditionalFiles`; use a distinct key per marker.
444
- `WithArguments(params object[])`, `WithMessage(string)`, `WithMessageFormat(LocalizableString)`, `WithSeverity(DiagnosticSeverity)`, `WithIsSuppressed(bool)`, `WithOptions(...)`: assert the remaining diagnostic details.
445
- `DiagnosticResult.CompilerError(string id)` and `DiagnosticResult.CompilerWarning(string id)`: expected compiler diagnostics, combined with `{|#n:...|}`.
446
- Markup forms can be mixed in one test: `[|...|]` for the analyzer's own diagnostic and `{|CS0168:...|}` for an expected compiler diagnostic, for instance.
447
448
If there is no code fix:
449
450
```csharp
451
using Verify = CSharpCodeFixVerifier<AvoidBlockingAnalyzer, EmptyCodeFixProvider>;
452
```
453
454
When VB support is required, use the corresponding Visual Basic verifier and include VB source, fixed source, and negative snippets. Keep shared behavioral cases aligned across languages while retaining language-specific parser/reference configuration.
455
456
Test at least:
457
458
- a straightforward positive case with the exact diagnostic span;
459
- a straightforward negative case;
460
- qualified, aliased, generic, inherited, overloaded, and extension-method forms relevant to symbol matching;
461
- nullability, implicit conversions, conditional access, lambdas/local functions, and malformed code when relevant;
462
- absence of an optional referenced type or assembly;
463
- generated code according to declared policy;
464
- every offered code action and equivalence key;
465
- fix-all behavior when advertised;
466
- preservation of trivia, imports, and formatting;
467
- both C# and VB for every promised cross-language behavior.
468
469
Prefer reference-assembly definitions supplied by the test framework over references copied from the executing runtime. Add only the metadata references and additional files needed by the scenario. Keep test parse options explicit when testing language-version-sensitive syntax.
470
471
## Packaging
472
473
Prefer bundling analyzer assemblies in the same NuGet package as the library they serve so consumers receive diagnostics automatically. Put analyzer DLLs under language-appropriate analyzer paths such as `analyzers/dotnet/cs` and `analyzers/dotnet/vb`; do not place them under `lib`. Include code-fix assemblies and their required dependencies according to the target host/package convention.
474
475
Package source generators as analyzer assets as well, commonly under `analyzers/dotnet/cs`. Keep generator runtime dependencies self-contained and minimal because compiler hosts do not resolve dependencies like ordinary application projects. Validate generator loading and generated output from a packed consumer project.
476
477
A separate `Product.Analyzers` package is also valid. In that model, the main library package should depend on it with appropriate asset metadata so analyzers flow to consumers without becoming runtime dependencies. Validate the packed `.nupkg`, not merely the build output: inspect paths, dependencies, satellite resources, build/buildTransitive assets, and verify the analyzer loads from a sample consumer project.
478
479
## Review checklist
480
481
- The implementation uses the narrowest suitable `IOperation` or symbol action.
482
- Every source generator implements `IIncrementalGenerator`, uses immutable equatable pipeline models, and has tests proving cached and selective recomputation.
483
- Generated code uses the shared `SourceWriter` for deterministic formatting and encoding.
484
- No syntax callback fetches another semantic model.
485
- C# behavior is implemented and tested; promised VB behavior has equivalent VB tests.
486
- Analyzer and code-fix assemblies are separate, and the analyzer has no Workspaces dependency.
487
- Shipping Roslyn references and their transitive dependency closure are coherently pinned to one compatibility baseline.
488
- `Microsoft.CodeAnalysis.Analyzers` uses the latest available version as a private development dependency and is not tied to the shipping Roslyn baseline.
489
- Shipping analyzer, source-generator, and code-fix projects set `IsAnalyzerCompatibilityProject`, conditionally import a dedicated `Directory.Packages.Analyzers.props`, and retain XML comments explaining the compatibility baseline and override mechanism.
490
- Renovate or Dependabot cannot automatically advance that baseline at any SemVer level: patch, minor, or major.
491
- API/type/member names come from a shared catalog rather than scattered literals.
492
- Symbol and attribute matching resolves expected named types from the compilation and expected members from their containing types by name and signature. When generic substitutions are irrelevant, it normalizes both expected and encountered named types, properties, fields, and events with `OriginalDefinition`, and methods with `(method.ReducedFrom ?? method).OriginalDefinition`, then uses `SymbolEqualityComparer.Default`; it inspects relevant type arguments separately and never compares `ToDisplayString()` output with a literal.
493
- Every diagnostic ID has a documentation page, is present in site navigation, and has a `HelpLinkUri` matching the published URL.
494
- Every analyzer project produces a unique assembly version per commit; with Nerdbank.GitVersioning, its local `version.json` uses revision precision and any shared `GitVersionBaseDirectory` is overridden correctly.
495
- Tests use inline markup where possible and cover positive and negative behavior.
496
- C# verifier parameters use `[StringSyntax("c#-test")]`, and local C# source literals use `/* lang=c#-test */` where useful.
497
- One rule-focused test class contains analyzer and code-fix cases, using `EmptyCodeFixProvider` when needed.
498
- Tests exercise public APIs without `InternalsVisibleTo`.
499
- The packed package places analyzer assets correctly and has been tested from a consumer project.
500
- Focused tests, the full test project, and the repository build pass without new analyzer warnings.
501