Fix MA0011 inserting the IFormatProvider in an invalid argument position

Merged
ME
2mo ago
+126-29

The MA0011 code fix interpreted the ordinal of the IFormatProvider parameter in the target overload as a position in the written argument list, and inserted an unnamed argument there. Named arguments can be written in another order, so the inserted positional argument could follow an out-of-order named argument, which does not compile, or could be bound to another parameter.

Repro

_ = decimal.Parse(style: System.Globalization.NumberStyles.Number, s: "1");

MA0011 reports the call, and the "Use CultureInfo.InvariantCulture" fix produced:

_ = decimal.Parse(style: System.Globalization.NumberStyles.Number, s: "1", System.Globalization.CultureInfo.InvariantCulture);

which fails to compile with CS1739: The best overload for 'Parse' does not have a parameter named 'style' (confirmed with a standalone compilation of the emitted source).

Changes

Same approach as #1490 for MA0166:

  • The positional insertion is only used when all the arguments written before the insertion index are positional, which is the only case where the index of the parameter is also the index in the argument list.
  • Otherwise, the provider is added as a named argument at the end of the list, which is valid whatever the order of the existing arguments and keeps their evaluation order. The repro is now fixed to decimal.Parse(style: ..., s: "1", provider: System.Globalization.CultureInfo.InvariantCulture).
  • Both candidates are bound with GetSpeculativeSymbolInfo before RegisterCodeFix, so the fix is only offered when the new invocation compiles and the new argument is bound to an IFormatProvider parameter.
  • The ToString(null, provider) fix is built the same way. This also removes its two paths that returned the document unchanged after the fix had already been offered, per the code fixer guidance in AGENTS.md.

Tests

Three tests added to UseIFormatProviderAnalyzerTests:

  • Parse_OutOfOrderNamedArguments_CodeFix: the repro above (fails on the previous fixer with exactly the invalid output).
  • Parse_InOrderNamedArguments_CodeFix: named arguments written in order.
  • Parse_NamedArgumentAfterInsertionIndex_CodeFix: a named argument written after the insertion index, which checks the positional insertion is still used where it is valid.

MA0011 tests pass on Roslyn 4.8, 4.14, 5.0, 5.6 and 5.9 (101 tests each). The full Roslyn 5.9 suite passes (4578 tests). dotnet run --project src/DocumentationGenerator exits 0 with no markdown change.