Skip to content

Add analyzer for identical conditional compilation branches#1169

Merged
meziantou merged 3 commits into
mainfrom
meziantou/duplicate-preprocessor-branches
May 23, 2026
Merged

Add analyzer for identical conditional compilation branches#1169
meziantou merged 3 commits into
mainfrom
meziantou/duplicate-preprocessor-branches

Conversation

@meziantou
Copy link
Copy Markdown
Owner

Why

Conditional compilation blocks can easily accumulate duplicated branches (for example #if and #elif with the same body), which adds noise and can hide unnecessary conditions. This change adds an explicit analyzer rule to surface those duplicates.

What changed

  • Added new rule identifier MA0202 and a new analyzer: ConditionalCompilationBranchesAreIdenticalAnalyzer.
  • The analyzer walks #if ... #endif directive groups and compares branch bodies (#if, #elif, #else) using token-based signatures so trivia differences (whitespace/comments) do not prevent detection.
  • A diagnostic is reported on the duplicated branch directive when it matches any earlier branch in the same group.
  • Added focused tests for:
    • #if vs #elif duplicates
    • #if vs #else duplicates
    • non-adjacent duplicates
    • duplicates with comment differences
    • non-duplicate branches
  • Added rule documentation (docs/Rules/MA0202.md) and regenerated rule listings/editorconfig outputs.

Validation

  • dotnet build
  • dotnet test --filter "FullyQualifiedName~ConditionalCompilationBranchesAreIdenticalAnalyzerTests"
  • dotnet test /p:RoslynVersion=roslyn4.2 --filter "FullyQualifiedName~ConditionalCompilationBranchesAreIdenticalAnalyzerTests"
  • dotnet test /p:RoslynVersion=roslyn4.14 --filter "FullyQualifiedName~ConditionalCompilationBranchesAreIdenticalAnalyzerTests"

meziantou and others added 3 commits May 22, 2026 15:16
Add MA0202 to detect identical code across #if/#elif/#else branches in the same conditional compilation block, with tests and generated documentation/configuration updates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@meziantou meziantou merged commit 231ff74 into main May 23, 2026
13 checks passed
@meziantou meziantou deleted the meziantou/duplicate-preprocessor-branches branch May 23, 2026 00:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant