Skip to content

Commit

Permalink
Handle NotPattern (RR0133)
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt committed Nov 12, 2021
1 parent 9e6851b commit a7eb09a
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ private static (bool success, ExpressionSyntax switchExpression) Analyze(

PatternSyntax pattern = isPatternExpression.Pattern;

SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern), pattern);
SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern), pattern);

if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern))
if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern))
return default;

ExpressionSyntax expression = isPatternExpression.Expression.WalkDownParentheses();
Expand Down Expand Up @@ -270,6 +270,12 @@ private static SyntaxList<SwitchLabelSyntax> CreateSwitchLabels(IfStatementSynta
{
return SingletonList<SwitchLabelSyntax>(CasePatternSwitchLabel(pattern, Token(SyntaxKind.ColonToken)));
}
else if (pattern.IsKind(SyntaxKind.NotPattern))
{
var notPattern = (UnaryPatternSyntax)pattern;

return SingletonList<SwitchLabelSyntax>(CasePatternSwitchLabel(notPattern, Token(SyntaxKind.ColonToken)));
}
else
{
throw new InvalidOperationException();
Expand Down
47 changes: 47 additions & 0 deletions src/Tests/Refactorings.Tests/RR0133ConvertIfToSwitchTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,53 @@ int M()
", equivalenceKey: RefactoringId);
}

[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.ConvertIfToSwitch)]
public async Task Test_NotPattern()
{
await VerifyRefactoringAsync(@"
class C
{
int M()
{
object x = null;
[||]if (x is string s)
{
return 1;
}
else if (x is not null)
{
}
return 0;
}
}
", @"
class C
{
int M()
{
object x = null;
switch (x)
{
case string s:
{
return 1;
}
case not null:
{
break;
}
}
return 0;
}
}
", equivalenceKey: RefactoringId);
}

[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.ConvertIfToSwitch)]
public async Task Test_ConstantAndPattern()
{
Expand Down

0 comments on commit a7eb09a

Please sign in to comment.