Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace StyleCop.Analyzers.MaintainabilityRules
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Lightup;

/// <summary>
/// Implements a code fix for <see cref="SA1407ArithmeticExpressionsMustDeclarePrecedence"/> and <see cref="SA1408ConditionalExpressionsMustDeclarePrecedence"/>.
Expand Down Expand Up @@ -59,6 +60,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
nameof(SA1407SA1408CodeFixProvider)),
diagnostic);
}
else if (BinaryPatternSyntaxWrapper.IsInstance(node))
{
context.RegisterCodeFix(
CodeAction.Create(
MaintainabilityResources.SA1407SA1408CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, root, (BinaryPatternSyntaxWrapper)node),
nameof(SA1407SA1408CodeFixProvider)),
diagnostic);
}
}
}

Expand All @@ -72,5 +82,17 @@ private static Task<Document> GetTransformedDocumentAsync(Document document, Syn

return Task.FromResult(document.WithSyntaxRoot(newSyntaxRoot));
}

private static Task<Document> GetTransformedDocumentAsync(Document document, SyntaxNode root, BinaryPatternSyntaxWrapper syntax)
{
var newNode = (ParenthesizedPatternSyntaxWrapper)SyntaxFactoryEx.ParenthesizedPattern((PatternSyntaxWrapper)syntax.SyntaxNode.WithoutTrivia())
.SyntaxNode
.WithTriviaFrom(syntax)
.WithoutFormatting();

var newSyntaxRoot = root.ReplaceNode(syntax, newNode);

return Task.FromResult(document.WithSyntaxRoot(newSyntaxRoot));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace StyleCop.Analyzers.MaintainabilityRules
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Lightup;

internal sealed class SA1407SA1408FixAllProvider : DocumentBasedFixAllProvider
{
Expand Down Expand Up @@ -44,16 +45,26 @@ protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fi

private static SyntaxNode AddParentheses(SyntaxNode node)
{
if (!(node is BinaryExpressionSyntax syntax))
if (node is BinaryExpressionSyntax syntax)
{
return node;
BinaryExpressionSyntax trimmedSyntax = syntax.WithoutTrivia();

return SyntaxFactory.ParenthesizedExpression(trimmedSyntax)
.WithTriviaFrom(syntax)
.WithoutFormatting();
}

BinaryExpressionSyntax trimmedSyntax = syntax.WithoutTrivia();
if (BinaryPatternSyntaxWrapper.IsInstance(node))
{
BinaryPatternSyntaxWrapper trimmedSyntax = (BinaryPatternSyntaxWrapper)node.WithoutTrivia();

return SyntaxFactoryEx.ParenthesizedPattern(trimmedSyntax)
.SyntaxNode
.WithTriviaFrom(node)
.WithoutFormatting();
}

return SyntaxFactory.ParenthesizedExpression(trimmedSyntax)
.WithTriviaFrom(syntax)
.WithoutFormatting();
return node;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -183,5 +183,68 @@ public object GetValue(bool flag)
FixedCode = fixedCode,
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}

[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestOuterParenthesesAroundParenthesizedPatternAreRemovedAsync()
{
const string testCode = @"
class C
{
void M(int value)
{
if ({|#0:{|#1:(|}(value is (> 0 and < 5)){|#2:)|}|})
{
}
}
}";

const string fixedCode = @"
class C
{
void M(int value)
{
if (value is (> 0 and < 5))
{
}
}
}";

await new CSharpTest()
{
NumberOfIncrementalIterations = 2,
NumberOfFixAllIterations = 2,
TestCode = testCode,
ExpectedDiagnostics =
{
Diagnostic(DiagnosticId).WithLocation(0),
Diagnostic(ParenthesesDiagnosticId).WithLocation(1),
Diagnostic(ParenthesesDiagnosticId).WithLocation(2),
},
FixedCode = fixedCode,
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that parentheses required to clarify precedence within patterns are not removed.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestClarifyingPatternParenthesesAreNotRemovedAsync()
{
const string testCode = @"
class C
{
void M(int value)
{
if (value is (> 0 and < 5) or 10)
{
}
}
}";

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,62 @@

namespace StyleCop.Analyzers.Test.CSharp9.MaintainabilityRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp8.MaintainabilityRules;
using Xunit;

using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.MaintainabilityRules.SA1408ConditionalExpressionsMustDeclarePrecedence,
StyleCop.Analyzers.MaintainabilityRules.SA1407SA1408CodeFixProvider>;

public partial class SA1408CSharp9UnitTests : SA1408CSharp8UnitTests
{
[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestLogicalPatternsDeclarePrecedenceAsync()
{
const string testCode = @"
class C
{
bool M(int value) => value is {|#0:> 0 and < 5|} or 10;
}";
const string fixedCode = @"
class C
{
bool M(int value) => value is (> 0 and < 5) or 10;
}";

DiagnosticResult expected = Diagnostic().WithLocation(0);

await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}

[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestPatternAndWithLogicalOrIsIgnoredAsync()
{
const string testCode = @"
class C
{
bool M(int value, bool flag) => flag || value is > 0 and < 5;
}";

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestPatternOrWithLogicalAndIsIgnoredAsync()
{
const string testCode = @"
class C
{
bool M(int value, bool flag) => flag && value is > 0 or < 5;
}";

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ namespace StyleCop.Analyzers.Test.CSharp9.SpacingRules
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp8.SpacingRules;
using Xunit;

using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1000KeywordsMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;
Expand All @@ -31,47 +30,58 @@ public async Task TestTargetTypedNewInConditionalExpressionAsync()
await this.TestKeywordStatementAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}

[Fact]
[Theory]
[WorkItem(3508, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3508")]
public async Task TestIsBeforeRelationalPatternAsync()
[InlineData("<")]
[InlineData("<=")]
[InlineData(">")]
[InlineData(">=")]
public async Task TestIsBeforeRelationalPatternAsync(string @operator)
{
var statementWithoutSpace = "_ = 1 {|#0:is|}>1;";
var statementWithSpace = "_ = 1 is >1;";
var statementWithoutSpace = $"_ = 1 {{|#0:is|}}{@operator}1;";
var statementWithSpace = $"_ = 1 is {@operator}1;";

var expected = Diagnostic().WithArguments("is", string.Empty, "followed").WithLocation(0);
await this.TestKeywordStatementAsync(statementWithoutSpace, expected, statementWithSpace).ConfigureAwait(false);
}

[Fact]
[Theory]
[WorkItem(3508, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3508")]
public async Task TestNotBeforeRelationalPatternAsync()
[InlineData("<")]
[InlineData("<=")]
[InlineData(">")]
[InlineData(">=")]
public async Task TestNotBeforeRelationalPatternAsync(string relationalOperator)
{
var statementWithoutSpace = "_ = 1 is {|#0:not|}>1;";
var statementWithSpace = "_ = 1 is not >1;";
var statementWithoutSpace = $"_ = 1 is {{|#0:not|}}{relationalOperator}1;";
var statementWithSpace = $"_ = 1 is not {relationalOperator}1;";

var expected = Diagnostic().WithArguments("not", string.Empty, "followed").WithLocation(0);
await this.TestKeywordStatementAsync(statementWithoutSpace, expected, statementWithSpace).ConfigureAwait(false);
}

[Fact]
[Theory]
[WorkItem(3508, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3508")]
public async Task TestAndBeforeRelationalPatternAsync()
[CombinatorialData]
public async Task TestAndBeforeRelationalPatternAsync(
[CombinatorialValues("and", "or")] string logicalOperator,
[CombinatorialValues("<", "<=", ">", ">=")] string relationalOperator)
{
var statementWithoutSpace = "_ = 1 is 1 {|#0:and|}>0;";
var statementWithSpace = "_ = 1 is 1 and >0;";
var statementWithoutSpace = $"_ = (int?)1 is not null {{|#0:{logicalOperator}|}}{relationalOperator}1;";
var statementWithSpace = $"_ = (int?)1 is not null {logicalOperator} {relationalOperator}1;";

var expected = Diagnostic().WithArguments("and", string.Empty, "followed").WithLocation(0);
var expected = Diagnostic().WithArguments(logicalOperator, string.Empty, "followed").WithLocation(0);
await this.TestKeywordStatementAsync(statementWithoutSpace, expected, statementWithSpace).ConfigureAwait(false);
}

[Fact]
[WorkItem(3508, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3508")]
public async Task TestOrBeforeRelationalPatternAsync()
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestNotBeforeConstantPatternMissingSpaceAsync()
{
var statementWithoutSpace = "_ = 1 is 1 {|#0:or|}>1;";
var statementWithSpace = "_ = 1 is 1 or >1;";
var statementWithoutSpace = "_ = new object() is {|#0:not|}(null);";
var statementWithSpace = "_ = new object() is not (null);";

var expected = Diagnostic().WithArguments("or", string.Empty, "followed").WithLocation(0);
var expected = Diagnostic().WithArguments("not", string.Empty, "followed").WithLocation(0);
await this.TestKeywordStatementAsync(statementWithoutSpace, expected, statementWithSpace).ConfigureAwait(false);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,51 @@ void M(bool flag)

await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}

[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestRelationalPatternsAreValidatedAsync()
{
const string testCode = @"
class C
{
void M(int value)
{
_ = value is {|#0:>|}5;
_ = value is{|#1:<|} 5;
_ = value is ( < 5); // Validated by SA1008
_ = value is (< 5);
_ = value is {|#2:<=|}5;
_ = value is {|#3:>=|}5;
_ = value is {|#4:>|}
5;
}
}";

const string fixedCode = @"
class C
{
void M(int value)
{
_ = value is > 5;
_ = value is < 5;
_ = value is ( < 5); // Validated by SA1008
_ = value is (< 5);
_ = value is <= 5;
_ = value is >= 5;
_ = value is > 5;
}
}";

DiagnosticResult[] expected =
{
Diagnostic(DescriptorFollowedByWhitespace).WithLocation(0).WithArguments(">"),
Diagnostic(DescriptorPrecededByWhitespace).WithLocation(1).WithArguments("<"),
Diagnostic(DescriptorFollowedByWhitespace).WithLocation(2).WithArguments("<="),
Diagnostic(DescriptorFollowedByWhitespace).WithLocation(3).WithArguments(">="),
Diagnostic(DescriptorNotAtEndOfLine).WithLocation(4).WithArguments(">"),
};
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,46 @@ public async Task TestDeconstructionInTopLevelProgramAsync(string prefix)
FixedCode = fixedCode,
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}

[Fact]
[WorkItem(3968, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3968")]
public async Task TestLogicalPatternsWithParenthesesAsync()
{
const string testCode = @"
class C
{
void M(int value)
{
_ = value is not{|#0:(|}> 0);
_ = value is > 0 and{|#1:(|}< 5);
_ = value is > 0 and {|#2:(|} < 5);
_ = value is > 10 or{|#3:(|}< 5);
_ = value is > 10 or {|#4:(|} < 5);
}
}";

const string fixedCode = @"
class C
{
void M(int value)
{
_ = value is not (> 0);
_ = value is > 0 and (< 5);
_ = value is > 0 and (< 5);
_ = value is > 10 or (< 5);
_ = value is > 10 or (< 5);
}
}";

DiagnosticResult[] expected =
{
Diagnostic(DescriptorPreceded).WithLocation(0),
Diagnostic(DescriptorPreceded).WithLocation(1),
Diagnostic(DescriptorNotFollowed).WithLocation(2),
Diagnostic(DescriptorPreceded).WithLocation(3),
Diagnostic(DescriptorNotFollowed).WithLocation(4),
};
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
}
}
Loading