Skip to content
Merged
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
3 changes: 3 additions & 0 deletions documentation/SA1114.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public string JoinName(

## How to fix violations

Comment lines between the opening bracket and the first parameter or argument are allowed.
Blank lines before or after these comments still violate this rule.

To fix a violation of this rule, ensure that the parameter list begins on the same line as the opening bracket, or on the next line.

## How to suppress violations
Expand Down
3 changes: 3 additions & 0 deletions documentation/cs-cz/SA1114.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public string JoinName(

## Jak opravit porušení

Řádky s komentáři mezi otevírací závorkou a prvním parametrem nebo argumentem jsou povoleny.
Prázdné řádky před těmito komentáři nebo za nimi nadále porušují toto pravidlo.

Chcete-li opravit porušení tohoto pravidla, ensure that the parameter list begins on the same line as the opening bracket, or on the next line.

## Jak potlačit porušení
Expand Down
3 changes: 3 additions & 0 deletions documentation/ru-ru/SA1114.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public string JoinName(

## Как исправить нарушения

Строки комментариев между открывающей скобкой и первым параметром или аргументом допускаются.
Пустые строки до или после этих комментариев по-прежнему нарушают это правило.

Чтобы исправить нарушение этого правила, убедитесь, что список параметров начинается в той же строке, что и открывающая скобка, или в следующей строке.

## Как подавить нарушения
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,8 @@ private static void AnalyzeRankSpecifiers(SyntaxNodeAnalysisContext context, Arr
}

if (openBracketLineSpan.EndLinePosition.Line != firstSizeLineSpan.StartLinePosition.Line &&
openBracketLineSpan.EndLinePosition.Line != (firstSizeLineSpan.StartLinePosition.Line - 1))
openBracketLineSpan.EndLinePosition.Line != (firstSizeLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(openBracketToken, firstSize))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstSize.GetLocation()));
}
Expand Down Expand Up @@ -264,7 +265,8 @@ private static void AnalyzeAttributeList(SyntaxNodeAnalysisContext context, Attr
}

if (openBracketLineSpan.EndLinePosition.Line != firstAttributeLineSpan.StartLinePosition.Line &&
openBracketLineSpan.EndLinePosition.Line != (firstAttributeLineSpan.StartLinePosition.Line - 1))
openBracketLineSpan.EndLinePosition.Line != (firstAttributeLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(openBracketToken, firstAttribute))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstAttribute.GetLocation()));
}
Expand Down Expand Up @@ -299,7 +301,8 @@ private static void AnalyzeArgumentList(SyntaxNodeAnalysisContext context, Brack
}

if (openBracketLineSpan.EndLinePosition.Line != firstArgumentLineSpan.StartLinePosition.Line &&
openBracketLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1))
openBracketLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(openBracketToken, firstArgument))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
}
Expand Down Expand Up @@ -334,7 +337,8 @@ private static void AnalyzeArgumentList(SyntaxNodeAnalysisContext context, Attri
}

if (openParenLineSpan.EndLinePosition.Line != firstArgumentLineSpan.StartLinePosition.Line &&
openParenLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1))
openParenLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(argumentListSyntax.OpenParenToken, firstArgument))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
}
Expand Down Expand Up @@ -369,7 +373,8 @@ private static void AnalyzeArgumentList(SyntaxNodeAnalysisContext context, Argum
}

if (openParenLineSpan.EndLinePosition.Line != firstArgumentLineSpan.StartLinePosition.Line &&
openParenLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1))
openParenLineSpan.EndLinePosition.Line != (firstArgumentLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(openParenToken, firstArgument))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
}
Expand Down Expand Up @@ -400,7 +405,8 @@ private static void AnalyzeBracketParametersList(SyntaxNodeAnalysisContext conte
}

if (openBracketLineSpan.EndLinePosition.Line != firstParameterLineSpan.StartLinePosition.Line &&
openBracketLineSpan.EndLinePosition.Line != (firstParameterLineSpan.StartLinePosition.Line - 1))
openBracketLineSpan.EndLinePosition.Line != (firstParameterLineSpan.StartLinePosition.Line - 1) &&
!HasOnlyCommentLinesBetween(openBracketToken, firstParameter))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstParameter.GetLocation()));
}
Expand Down Expand Up @@ -430,12 +436,51 @@ private static void AnalyzeParametersList(SyntaxNodeAnalysisContext context, Par

var parenLine = parameterListSyntax.OpenParenToken.GetLineSpan().EndLinePosition.Line;

if ((firstParameterLine - parenLine) > 1)
if ((firstParameterLine - parenLine) > 1 &&
!HasOnlyCommentLinesBetween(parameterListSyntax.OpenParenToken, firstParameter))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstParameter.GetLocation()));
}
}

private static bool HasOnlyCommentLinesBetween(SyntaxToken openingToken, SyntaxNode firstItem)
{
var onBlankLine = false;
return HasOnlyCommentLines(openingToken.TrailingTrivia, ref onBlankLine)
&& HasOnlyCommentLines(firstItem.GetLeadingTrivia(), ref onBlankLine);
}

private static bool HasOnlyCommentLines(SyntaxTriviaList triviaList, ref bool onBlankLine)
{
for (var i = 0; i < triviaList.Count; i++)
{
switch (triviaList[i].Kind())
{
case SyntaxKind.WhitespaceTrivia:
break;

case SyntaxKind.EndOfLineTrivia:
if (onBlankLine)
{
return false;
}

onBlankLine = true;
break;

case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
onBlankLine = false;
break;

default:
return false;
}
}

return true;
}

private static bool IsValidTrivia(SyntaxTrivia trivia)
{
switch (trivia.Kind())
Expand Down
127 changes: 127 additions & 0 deletions test/StyleCop.Analyzers.Test/ReadabilityRules/SA1114UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,133 @@ public void Bar()
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that comments grouping arguments do not count as blank lines.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(2917, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2917")]
public async Task TestMethodCallWithGroupedArgumentsAsync()
{
var testCode = @"
class Foo
{
void Func(string a, string b, string c, int d, int e, int f) { }
void M()
{
Func(
// Chars
""A"", ""B"", ""C"",
// Numbers
1, 2, 3);
}
}";

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

/// <summary>
/// Verifies that blank lines before or after an argument comment still result in diagnostics.
/// </summary>
/// <param name="beforeComment">The whitespace before the comment.</param>
/// <param name="afterComment">The whitespace after the comment.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("\r\n\r\n", "\r\n")]
[InlineData("\r\n", "\r\n\r\n")]
[WorkItem(2917, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2917")]
public async Task TestMethodCallWithCommentAndBlankLineAsync(string beforeComment, string afterComment)
{
var testCode = @"
class Foo
{
void Func(string a) { }
void M()
{
Func(" + beforeComment + "// Chars" + afterComment + @"{|#0:""A""|});
}
}";

await VerifyCSharpDiagnosticAsync(testCode, Diagnostic().WithLocation(0), CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that comments are allowed in each kind of list, but surrounding blank lines are not.
/// </summary>
/// <param name="code">The code containing a list.</param>
/// <param name="comment">The comment before the first item.</param>
/// <param name="beforeComment">The whitespace before the comment.</param>
/// <param name="blankLinePosition">The position of an optional blank line.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[CombinatorialData]
[WorkItem(2917, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2917")]
public async Task TestListsWithCommentsAsync(
[CombinatorialValues(
"class Foo { void M($$int a) { } }",
"class Foo { public int this[$$int a] { get { return a; } } }",
"class Foo { void M() { M($$); } void M(int a) { } }",
"class Foo { void M(int[] a) { var b = a[$$]; } }",
"[System.Obsolete($$)] class Foo { }",
"[$$] class Foo { }",
"class Foo { void M() { var a = new int[$$]; } }")] string code,
[CombinatorialValues("// Comment", "// First\r\n// Second", "/* Comment */", "/* First\r\nSecond */", "/* First\r\n\r\nSecond */")] string comment,
[CombinatorialValues("\r\n", " ")] string beforeComment,
[CombinatorialValues(0, 1, 2)] int blankLinePosition)
{
string item;
if (code.Contains("$$int a"))
{
item = "int a";
code = code.Replace("$$int a", "$$");
}
else if (code.StartsWith("[System.Obsolete"))
{
item = "\"message\"";
}
else if (code.StartsWith("[$$"))
{
item = "System.Obsolete";
}
else
{
item = "1";
}

var trivia = (blankLinePosition == 1 ? "\r\n\r\n" : beforeComment)
+ comment
+ (blankLinePosition == 2 ? "\r\n\r\n" : "\r\n")
+ " ";
var testCode = code.Replace("$$", trivia + (blankLinePosition == 0 ? item : "{|#0:" + item + "|}"));
var expected = blankLinePosition == 0 ? DiagnosticResult.EmptyDiagnosticResults : new[] { Diagnostic().WithLocation(0) };

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

/// <summary>
/// Verifies that the comment exemption does not change the handling of conditional directives in arguments.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestMethodCallWithConditionalDirectiveAsync()
{
var testCode = @"
class Foo
{
void M(int a) { }
void M()
{
M(
#if true
{|#0:1|}
#endif
);
}
}";

await VerifyCSharpDiagnosticAsync(testCode, Diagnostic().WithLocation(0), CancellationToken.None).ConfigureAwait(false);
}

[Fact]
public async Task TestMethodCallNoParametersAsync()
{
Expand Down
Loading