Repository navigation
Add a skill for authoring .NET analyzers #55510
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
tannergooding
merged 14 commits into
dotnet:main
from
tannergooding:tannergooding-add-net-analyzer-skill
Jul 30, 2026
Merged
Changes from 1 commit
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
14d219a
Add a skill for authoring .NET analyzers
tannergooding 8033773
Fix the xlf regeneration command in the analyzer skill
tannergooding 4c9f032
Document the SeparatedSyntaxList multi-node removal trap
tannergooding 9d11aef
Stop claiming RulesMissingDocumentation.md guards the help link
tannergooding 413035b
Require a no-fix test for each context the rewrite is invalid in
tannergooding 2f47808
Describe how the batch fix-all provider actually merges edits
tannergooding e46b981
Stop presenting the fix-all conflict list as a substitute for testing
tannergooding 11eb216
Point the analyzer skill at the in-repo helpers before the general sk…
tannergooding 9e0b518
Defer the xUnit to MSTest mapping to the migration skill
tannergooding a7fd1af
Leave opening the docs PR to the user
tannergooding 168ddd6
Correct the analyzer, severity, and fixer guidance in the reference doc
tannergooding aa1d90d
Stop the skill index restating the reference doc
tannergooding 76e25c0
Fix release tracking documentation links pointing at the wrong rule
tannergooding d209403
Address review feedback on authoring-patterns.md
tannergooding File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| --- | ||
| name: add-net-analyzer | ||
| description: > | ||
| Add, port, or change a .NET code analysis rule (CA####) under | ||
| src/Microsoft.CodeAnalysis.NetAnalyzers. USE FOR: implementing a new CA analyzer and | ||
| its code fixer, porting a rule or PR from the retired dotnet/roslyn-analyzers repo, | ||
| allocating a diagnostic ID from DiagnosticCategoryAndIdRanges.txt, choosing | ||
| RuleLevel/severity/category, wiring resx + xlf strings, recording the rule in | ||
| AnalyzerReleases.Unshipped.md, regenerating the analyzer documentation/sarif files, and | ||
| writing MSTest analyzer/code-fix tests with the VerifyCS/VerifyVB harness. DO NOT USE | ||
| FOR: NETSDK#### MSBuild diagnostics (src/Tasks), CS####/BC#### compiler diagnostics or | ||
| IDE#### analyzers (dotnet/roslyn), or CONTAINER#### diagnostics (src/Containers). | ||
| license: MIT | ||
| --- | ||
|
|
||
| # Add or port a .NET code analysis (CA) rule | ||
|
|
||
| [`AGENTS.md`](../../../src/Microsoft.CodeAnalysis.NetAnalyzers/AGENTS.md) maps the tree and | ||
| carries the build/test commands and environment gotchas. Paths below are relative to `$NA` | ||
| = `src/Microsoft.CodeAnalysis.NetAnalyzers`. | ||
|
|
||
| | File | Load when | | ||
| |---|---| | ||
| | [`references/authoring-patterns.md`](references/authoring-patterns.md) | Writing the analyzer, the fixer, or the tests. | | ||
| | [`references/porting-from-roslyn-analyzers.md`](references/porting-from-roslyn-analyzers.md) | Porting a rule or PR from the archived `dotnet/roslyn-analyzers`. | | ||
|
|
||
| ## 1. Confirm the rule is wanted | ||
|
|
||
| New CA rules are proposed and triaged before implementation — .NET API-related ones in | ||
| `dotnet/runtime` under the `code-analyzer` label. If an API review already decided the | ||
| category, severity, and whether a fixer is wanted, **follow that decision** and cite it in | ||
| the PR rather than re-deriving one. Ask before diverging from it. | ||
|
|
||
| ## 2. Allocate the diagnostic ID | ||
|
|
||
| `DiagnosticCategoryAndIdRanges.txt` records only *merged* work, so the "next" ID is | ||
| routinely already claimed by an open PR or a concurrent branch. Run: | ||
|
|
||
| ```powershell | ||
| ./.dotnet/dotnet .github/skills/add-net-analyzer/scripts/NextDiagnosticId.cs Performance | ||
| ``` | ||
|
|
||
| It scans forward from the end of the category's range until it finds an ID unclaimed in the | ||
| working tree, on any local branch, and in any open `dotnet/sdk` PR, prints the exact range | ||
| edit to apply, and reports anything it skipped. Exit `0` means every check ran, `1` means | ||
| the ID is proposed but open PRs went unchecked, and `2` is a hard failure — including "every | ||
| candidate in the scan window is already taken". The PR check matches titles and bodies | ||
| rather than diffs, so treat it as a strong heuristic, not proof. | ||
|
|
||
| ## 3. Implement the analyzer and fixer | ||
|
|
||
| Read [`references/authoring-patterns.md`](references/authoring-patterns.md) first. | ||
|
|
||
| The language-agnostic analyzer goes in | ||
| `$NA/src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.<Group>.Analyzers/<Category>/<Name>.cs`, | ||
| the fixer in `<Name>.Fixer.cs` beside it. Derive C#/VB types only where you genuinely need | ||
| syntax; those go at the same relative path inside | ||
| `$NA/src/Microsoft.CodeAnalysis.CSharp.NetAnalyzers/` or `…VisualBasic.NetAnalyzers/`. The | ||
| folder is the *rule group's* category — the `category:` you report can differ, and comes | ||
| from the `DiagnosticCategory` constants, never a raw string. The decisions that are yours | ||
| rather than pattern-matching an existing rule: | ||
|
|
||
| - **`RuleLevel`** — `IdeSuggestion` unless you have a reason. Everything at `IdeSuggestion` | ||
| or stronger is required to have **no false positives**; `IdeHidden_BulkConfigurable` is | ||
| the first level that tolerates any, and `BuildWarning` additionally breaks builds under | ||
| `TreatWarningsAsErrors`. | ||
| - **Whether to ship a fixer at all** — if applying it could change semantics, report the | ||
| diagnostic without one. | ||
|
|
||
| The two things reviewers reject on: | ||
|
|
||
| - **The analyzer owns the eligibility decision.** Binding a symbol does not guarantee the | ||
| syntax has the shape you expect, and a fixer that declines because the code was never | ||
| eligible leaves the user with a lightbulb that does nothing. (Its own defensive checks | ||
| against a stale span stay.) | ||
| - **Fix-all.** `WellKnownFixAllProviders.BatchFixer` produces a wrong tree when diagnostics | ||
| overlap or nest. If yours can, derive from `OrderedCodeFixProvider`. | ||
|
333fred marked this conversation as resolved.
Resolved
|
||
|
|
||
| ## 4. Add the strings | ||
|
|
||
| Append to the resx for the rule group — e.g. | ||
| `$NA/src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.NetCore.Analyzers/MicrosoftNetCoreAnalyzersResources.resx` | ||
| — one entry each for | ||
| `<Name>Title`, `<Name>Message`, `<Name>Description`, plus `<Name>CodeFixTitle` if there is | ||
| a fixer. Reference them via `CreateLocalizableResourceString(nameof(<Name>Title))` with | ||
| `using static <Resources>;` at the top of the namespace. | ||
|
|
||
| `<Name>CodeFixTitle` names the *action* the fix performs ("Extract to static readonly | ||
| field"), not the problem the analyzer reports. Terms that must not be translated get | ||
| `<comment>{Locked="static readonly"}</comment>`; multiple terms are adjacent braces with no | ||
| separator. | ||
|
|
||
| Then regenerate the 13 `.xlf` files in the `xlf/` subfolder beside it: | ||
|
|
||
| ```powershell | ||
| ./build.cmd -projects src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.slnx -c Debug /t:UpdateXlf | ||
| ``` | ||
|
|
||
| ## 5. Record the rule in release tracking | ||
|
|
||
| Each of the three analyzer projects has its own `AnalyzerReleases.Unshipped.md` at its | ||
| root; the row goes in the project that *declares the descriptor*, which for a | ||
| language-agnostic rule is `Microsoft.CodeAnalysis.NetAnalyzers`. The `RS2000`/`RS2001` | ||
| meta-analyzers fail the build if you skip this, and they ship a code fix that writes the | ||
| row for you. | ||
|
|
||
| ``` | ||
| Rule ID | Category | Severity | Notes | ||
| --------|----------|----------|------- | ||
| CA#### | Performance | Info | <Name>Analyzer, [Documentation](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca####) | ||
| ``` | ||
|
|
||
| `Severity` is the release-tracking severity for your `RuleLevel`, which is **not** always | ||
| the descriptor's `DiagnosticSeverity` — a disabled rule carries `Warning` on the descriptor | ||
| but tracks as `Disabled`: | ||
|
|
||
| | `RuleLevel` | `Severity` column | | ||
| |---|---| | ||
| | `BuildError` | `Error` | | ||
| | `BuildWarning` | `Warning` | | ||
| | `IdeSuggestion`, `BuildWarningCandidate` | `Info` | | ||
| | `IdeHidden_BulkConfigurable` | `Hidden` | | ||
| | `Disabled`, `CandidateForRemoval` | `Disabled` | | ||
|
|
||
| The `Documentation` link is the **lowercased** ID and must match the rule ID in the same | ||
| row. Nothing validates it, so a row copy-pasted from the one above — carrying that rule's ID | ||
| or a stray capital — silently ships a link to the wrong page. Check it by eye; wrong links | ||
| are already in these files. | ||
|
|
||
| Rows move to `AnalyzerReleases.Shipped.md` at release time — don't move them yourself. | ||
|
|
||
| ## 6. Write the tests | ||
|
|
||
| Tests go in | ||
| `$NA/tests/Microsoft.CodeAnalysis.NetAnalyzers.UnitTests/Microsoft.<Group>.Analyzers/<Category>/<Name>Tests.cs`, | ||
| mirroring the analyzer's folder. Full conventions are in | ||
| [`references/authoring-patterns.md`](references/authoring-patterns.md); the coverage bar: | ||
|
|
||
| - C# fully; VB at least mainline positive and negative, fully if any VB-specific code | ||
| exists. Group by behavior and cover both languages in one test method. | ||
| - When a fixer exists, write *every* test as a code-fix test, and include a trivia case. | ||
| If the diagnostic can nest, add a nested case — that is what catches a broken fix-all. | ||
| - The negative cases you reasoned about while designing. Reviewers will ask for them. | ||
|
|
||
| ## 7. Build and test | ||
|
|
||
| ```powershell | ||
| # ~10s incremental once .dotnet is provisioned; the first run provisions it. | ||
| ./build.cmd -projects src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.slnx -c Debug | ||
|
|
||
| ./.dotnet/dotnet test src/Microsoft.CodeAnalysis.NetAnalyzers/tests/Microsoft.CodeAnalysis.NetAnalyzers.UnitTests/Microsoft.CodeAnalysis.NetAnalyzers.UnitTests.csproj --filter "FullyQualifiedName~<Name>Tests" | ||
| ``` | ||
|
|
||
| Then `git status` and commit the regenerated files along with your change. `./build.sh` on | ||
| Linux/macOS; never pass `-restore`/`-build` alongside `-projects`. | ||
|
|
||
| ## 8. Validate the rule against real code | ||
|
|
||
| Unit tests prove the rule fires; they don't tell you the false-positive rate, and that is | ||
| what decides the `RuleLevel`. Every level from `IdeSuggestion` up requires **no false | ||
| positives**, so before proposing one, run the built analyzer over a large real codebase | ||
| (`dotnet/runtime`, `dotnet/roslyn`) and triage every hit. Report the result in the PR. | ||
| [`docs/netcore-getting-started.md`](../../../src/Microsoft.CodeAnalysis.NetAnalyzers/docs/netcore-getting-started.md) | ||
| has the mechanics and the full definition of done. | ||
|
|
||
| ## 9. Documentation | ||
|
|
||
| Each `CA####` is auto-assigned the help link | ||
| `https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca####`, | ||
| backed by `ca####.md` in | ||
| [`dotnet/docs`](https://github.com/dotnet/docs/tree/main/docs/fundamentals/code-analysis/quality-rules). | ||
| A docs PR is required **within one week** of the rule merging, or the implementation may be | ||
| reverted. Say so in the PR description, then open the docs PR. | ||
|
tannergooding marked this conversation as resolved.
Resolved
|
||
|
|
||
| ## Checklist | ||
|
|
||
| - [ ] Rule proposal reviewed and accepted, and the decision cited in the PR. | ||
| - [ ] ID unclaimed by any local branch or open PR, and the category's range extended to | ||
| cover it. | ||
| - [ ] `AnalyzerReleases.Unshipped.md` row added, its `Documentation` link matching the row's | ||
| own ID in lowercase. | ||
| - [ ] `.resx` edited and `.xlf` regenerated via `/t:UpdateXlf` — neither hand-edited. | ||
| - [ ] Regenerated `.md` / `.sarif.template` / `RulesMissingDocumentation.md` committed. | ||
| - [ ] Targeted test run passes, covering VB and the negative cases. | ||
| - [ ] Fix-all handles nesting (`OrderedCodeFixProvider`, not the batch fixer), if the | ||
| diagnostic can overlap or nest. | ||
| - [ ] Rule run against a real codebase and hits triaged, at `IdeSuggestion` or stronger. | ||
| - [ ] `dotnet/docs` PR opened, or explicitly committed to in the PR description. | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.