Browse Source

Fix crash in ConvertIfToSwitchAction when there are nested if statements.

pull/45/merge
Daniel Grunwald 12 years ago
parent
commit
e22be6ea28
  1. 24
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs
  2. 37
      ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs

24
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs

@ -174,22 +174,16 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
static void CollectSwitchSectionStatements (AstNodeCollection<Statement> result, RefactoringContext context, static void CollectSwitchSectionStatements (AstNodeCollection<Statement> result, RefactoringContext context,
Statement statement) Statement statement)
{ {
BlockStatement blockStatement; BlockStatement blockStatement = statement as BlockStatement;
if (statement is BlockStatement) if (blockStatement != null)
blockStatement = (BlockStatement)statement.Clone (); result.AddRange(blockStatement.Statements.Select(s => s.Clone()));
else else
blockStatement = new BlockStatement { statement.Clone () }; result.Add(statement.Clone());
var breackStatement = new BreakStatement (); // add 'break;' at end if necessary
blockStatement.Add (breackStatement); var reachabilityAnalysis = context.CreateReachabilityAnalysis (statement);
// check if break is needed if (reachabilityAnalysis.IsEndpointReachable(statement))
var reachabilityAnalysis = context.CreateReachabilityAnalysis (blockStatement); result.Add(new BreakStatement());
if (!reachabilityAnalysis.IsReachable (breackStatement))
blockStatement.Statements.Remove (breackStatement);
var statements = blockStatement.Statements.ToArray ();
blockStatement.Statements.Clear ();
result.AddRange (statements);
} }
} }
} }

37
ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs

@ -30,7 +30,7 @@ using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.CodeActions namespace ICSharpCode.NRefactory.CSharp.CodeActions
{ {
[TestFixture] [TestFixture]
public class ConvertIfToSwtichTests : ContextActionTestBase public class ConvertIfToSwitchTests : ContextActionTestBase
{ {
[Test] [Test]
@ -467,5 +467,40 @@ class TestClass
}"); }");
} }
[Test]
public void TestNestedIf ()
{
Test<ConvertIfToSwitchAction> (@"
class TestClass
{
void TestMethod (int a)
{
int b;
$if (a == 0) {
if (b == 0)
return;
} else if (a == 2 || a == 3) {
b = 2;
}
}
}", @"
class TestClass
{
void TestMethod (int a)
{
int b;
switch (a) {
case 0:
if (b == 0)
return;
break;
case 2:
case 3:
b = 2;
break;
}
}
}");
}
} }
} }

Loading…
Cancel
Save