Report MA0179 when the constant is on the left of the length comparison

Merged
ME
2mo ago
+83-10

What

UseAttributeIsDefinedAnalyzer (MA0179) only detected GetCustomAttributes().Length / .Count() existence checks when the length was the left operand. The reversed form was silently missed:

member.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0  // MA0179 reported
0 < member.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length  // no diagnostic

Why

IsValidLengthComparisonPattern takes a lengthIsOnLeft flag and carefully implements both orientations. But both call sites hard-coded lengthIsOnLeft: true and only ever passed (operation.LeftOperand, operation.RightOperand) in that order, so the entire else block was unreachable dead code.

IsGetCustomAttributeComparison (the == null variant) already handles both orientations, which makes the asymmetry an oversight rather than a deliberate scope decision — so this fixes it rather than deleting the branch.

Changes

  • AnalyzeBinary now tries both operand orders for the Length and Count() comparisons, passing the orientation through to IsValidLengthComparisonPattern instead of hard-coding true.
  • Renamed the left/right parameters of the two helpers to lengthOperand/countOperand and otherOperand, since they no longer correspond to syntactic sides.
  • Documented the reversed form in docs/Rules/MA0179.md.

Note for reviewers

The code fixer needed no change. ShouldNegateLengthComparison already implemented both orientations and already searched both operands — it was dead in exactly the same way as the analyzer's else block, and simply becomes live now. That is why the diff touches only the analyzer.

Tests

15 new cases in UseAttributeIsDefinedAnalyzerTests, each asserting the diagnostic and the fixed code, so the negation direction is verified rather than just detection:

  • 6 reversed Length forms added to the existing theory: 0 == len → !IsDefined, 0 != len → IsDefined, 0 < len → IsDefined, 1 <= len → IsDefined, 1 > len → !IsDefined, 0 >= len → !IsDefined
  • 6 equivalent reversed Count() forms
  • 3 negative cases confirming ambiguous reversed comparisons stay unreported (0 > len, 1 == len, 2 <= len)

Verification

  • dotnet test --max-parallel-test-modules 2 across all five Roslyn versions: 22751 passed, 0 failed.
  • Confirmed the new tests actually ran by checking the test names in the .trx output rather than relying on the pass count.
  • dotnet run --project src/DocumentationGenerator exits 0 with no further markdown changes.