SKILL.md · 24000
out flowing it to consumers:
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
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.
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:
{
"packageRules": [
{
"matchFileNames": ["Directory.Packages.Analyzers.props"],
"enabled": false
}
]
}
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.
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.
Code-fix boundaries
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:
- register only when the diagnostic can be fixed safely;
- find the target node from the diagnostic span defensively;
- preserve leading/trailing trivia and imports;
- use
Simplifier.AnnotationandFormatter.Annotationwhere appropriate; - return a new document or solution without mutating shared state;
- support cancellation and avoid blocking async Roslyn APIs;
- use a meaningful, stable equivalence key, especially when multiple fixes share a title;
- return the batch fixer only when fixes do not conflict or depend on application order.
Unique assembly versions
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.
With Nerdbank.GitVersioning, put a version.json directly in every analyzer project directory, including each language-specific analyzer assembly when those are separate:
{
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json",
"inherit": true,
"assemblyVersion": {
"precision": "revision"
}
}
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:
<PropertyGroup>
<!-- Honor this analyzer project's version.json and produce a unique assembly identity per commit. -->
<GitVersionBaseDirectory>$(MSBuildProjectDirectory)</GitVersionBaseDirectory>
</PropertyGroup>
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.
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.
Test structure
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.
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 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.
When C# source is assigned to a local variable instead of passed directly to an annotated parameter, add a language comment before the literal:
const string source = /* lang=c#-test */ """
// C# code here
""";
Prefer inline markup to hard-coded line/column spans:
using Verify = CSharpCodeFixVerifier<AvoidBlockingAnalyzer, AvoidBlockingCodeFix>;
public class AvoidBlockingTests
{
[Fact]
public async Task ReportsBlockingCallAndFixesIt()
{
const string source = /* lang=c#-test */ """
using System.Threading.Tasks;
class C
{
void M(Task task) => [|task.Wait()|];
}
""";
const string fixedSource = /* lang=c#-test */ """
using System.Threading.Tasks;
class C
{
async Task M(Task task) => await task;
}
""";
await Verify.VerifyCodeFixAsync(source, fixedSource);
}
[Fact]
public async Task DoesNotReportAwaitedTask()
{
const string source = /* lang=c#-test */ """
using System.Threading.Tasks;
class C
{
async Task M(Task task) => await task;
}
""";
await Verify.VerifyAnalyzerAsync(source);
}
}
Use [|bad code|] for one diagnostic and named markup such as {|#0:bad code|} when diagnostics need distinct descriptors, arguments, or locations. Use explicit DiagnosticResult objects for IDs, severities, arguments, and additional locations, but attach them to markup locations where the harness supports it. Hard-coded WithSpan(line, column, ...) is a last resort for locations that markup cannot express.
If there is no code fix:
using Verify = CSharpCodeFixVerifier<AvoidBlockingAnalyzer, EmptyCodeFixProvider>;
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.
Test at least:
- a straightforward positive case with the exact diagnostic span;
- a straightforward negative case;
- qualified, aliased, generic, inherited, overloaded, and extension-method forms relevant to symbol matching;
- nullability, implicit conversions, conditional access, lambdas/local functions, and malformed code when relevant;
- absence of an optional referenced type or assembly;
- generated code according to declared policy;
- every offered code action and equivalence key;
- fix-all behavior when advertised;
- preservation of trivia, imports, and formatting;
- both C# and VB for every promised cross-language behavior.
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.
Packaging
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.
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.
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.
Review checklist
- The implementation uses the narrowest suitable
IOperationor symbol action. - Every source generator implements
IIncrementalGenerator, uses immutable equatable pipeline models, and has tests proving cached and selective recomputation. - Generated code uses the shared
SourceWriterfor deterministic formatting and encoding. - No syntax callback fetches another semantic model.
- C# behavior is implemented and tested; promised VB behavior has equivalent VB tests.
- Analyzer and code-fix assemblies are separate, and the analyzer has no Workspaces dependency.
- Shipping Roslyn references and their transitive dependency closure are coherently pinned to one compatibility baseline.
Microsoft.CodeAnalysis.Analyzersuses the latest available version as a private development dependency and is not tied to the shipping Roslyn baseline.- Shipping analyzer, source-generator, and code-fix projects set
IsAnalyzerCompatibilityProject, conditionally import a dedicatedDirectory.Packages.Analyzers.props, and retain XML comments explaining the compatibility baseline and override mechanism. - Renovate or Dependabot cannot automatically advance that baseline at any SemVer level: patch, minor, or major.
- API/type/member names come from a shared catalog rather than scattered literals.
- 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 usesSymbolEqualityComparer.Default; it inspects relevant type arguments separately and never comparesToDisplayString()output with a literal. - Every diagnostic ID has a documentation page, is present in site navigation, and has a
HelpLinkUrimatching the published URL. - Every analyzer project produces a unique assembly version per commit; with Nerdbank.GitVersioning, its local
version.jsonuses revision precision and any sharedGitVersionBaseDirectoryis overridden correctly. - Tests use inline markup where possible and cover positive and negative behavior.
- C# verifier parameters use
[StringSyntax("c#-test")], and local C# source literals use/* lang=c#-test */where useful. - One rule-focused test class contains analyzer and code-fix cases, using
EmptyCodeFixProviderwhen needed. - Tests exercise public APIs without
InternalsVisibleTo. - The packed package places analyzer assets correctly and has been tested from a consumer project.
- Focused tests, the full test project, and the repository build pass without new analyzer warnings.