Do not offer the MA0202 code fix to merge non-adjacent branches
What
The MA0202 code fix merges an #elif branch with the first earlier branch that has the same code, even when the two branches aren't next to each other. When a branch in between can also be active, the merge changes which code is compiled:
#if A
_ = 0;
#elif B
_ = 1;
#elif C // MA0202
_ = 0;
#else
_ = 2;
#endif
The fix produced #if (A) || (C) / _ = 0; / #elif B / _ = 1;. With B and C defined, the original code compiles _ = 1; and the fixed code compiles _ = 0;.
Fix
The code fix now merges a branch only with the branch right before it, when that branch has the same code. In the example above, no code fix is offered. For #if A / #elif B / #elif C where B and C have the same code, the fix gives #elif (B) || (C). Before, a third identical branch was merged into the first one. It is now merged into the adjacent one, which gives the same result.
The remove fix (#if / #else with 2 identical branches) only applies to adjacent branches, so it doesn't change. BranchGroup.FindPreviousDuplicateBranchIndex was only used by the fixer, so it is removed.
The analyzer still reports non-adjacent duplicates. The docs say that a branch with the same code as any previous branch is reported, and the existing NonAdjacentDuplicateBranch test covers this. The duplicated code can still be simplified by hand. The MA0202 docs now have a "Code fix" section that explains when the fix is offered.
I checked for other MA0202 work first: #1511 (nested conditionals) is merged and no MA0202 PR is open.
Tests
- Added
Fix_ElifElif_SameCode_MergesConditionsandFix_NonAdjacentElif_SameCode_NoCodeFix. The second one failed before the fix. - Ran
ConditionalCompilationBranchesAreIdenticalAnalyzerTestson roslyn5.9 and roslyn4.8: 19/19 passed on each.