Fix MA0037 code fix crash on embedded empty statements

Merged
ME
2mo ago
+181-19

What

The MA0037 code fix only replaced the empty statement with an empty block when it was the body of a while, for or foreach statement. For the other statements that embed a statement, it tried to remove the node, which throws ArgumentNullException (Parameter 'statement'), as the parent requires a statement:

if (b) ;
if (b) { } else ;
lock (o) ;
using (d) ;
foreach (var (x, y) in items) ; // ForEachVariableStatement
do ; while (b);
fixed (int* p = array) ;

Expected: the empty statement is replaced with { }. Actual: the code fix crashes.

Fix

The empty statement is removed only when it is in a list of statements (a block, a switch section, or a top-level statement). In all other cases it is an embedded statement, so it is replaced with an empty block.

Tests

  • Added EmbeddedStatement (theory: if, else, while, lock, using, foreach with deconstruction), EmbeddedStatement_SameLine, DoStatement, FixedStatement, EmptyStatementInSwitchSection and EmptyStatementInTopLevelStatements.
  • The embedded statement tests (except while) failed before the fix. RemoveEmptyStatementAnalyzerTests passes on roslyn5.9 and roslyn4.8 (17 tests each).