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
18 changes: 18 additions & 0 deletions documentation/SA1003.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ if (!value)
}
```

Starting with C# 8.0, a null-forgiving operator (`!`) may appear at the end of a line after any expression. Postfix
increment and decrement operators (`++` and `--`) may also appear at the end of a line when the next token begins on a
new line. A null-forgiving operator is also written without a space before element access. For example:

```csharp
Print(
value: nullableValue! // trailing comment
);

var result = nullableValue!
.ToString();

var item = nullableArray![0];

var incrementedValue = GetCounter().Value++
+ 2;
```

The C# 8 *index-from-end* operator (`^`) follows the same unary spacing requirements. It is written adjacent to its
operand without a trailing space, and no additional space is inserted after `[` or `(` when it appears immediately after
one of those tokens. Examples:
Expand Down
19 changes: 19 additions & 0 deletions documentation/ru-ru/SA1003.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ if (!value)
}
```

Начиная с C# 8.0, оператор подавления предупреждений о значении null (`!`) может находиться в конце строки после любого
выражения. Постфиксные операторы инкремента и декремента (`++` и `--`) также могут находиться в конце строки, если
следующий токен начинается с новой строки. Перед выражением доступа к элементу оператор подавления записывается без
пробела. Например:

```csharp
Print(
value: nullableValue! // trailing comment
);

var result = nullableValue!
.ToString();

var item = nullableArray![0];

var incrementedValue = GetCounter().Value++
+ 2;
```

Оператор *индекса от конца* (`^`), введённый в C# 8, подчиняется тем же правилам для унарных операторов.
Он записывается вплотную к операнду, без пробела после оператора. Если он следует непосредственно за `[` или `(`,
между ним и скобкой также не добавляется пробел. Примеры:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ private static void HandlePostfixUnaryExpression(SyntaxNodeAnalysisContext conte
{
var unaryExpression = (PostfixUnaryExpressionSyntax)context.Node;
var followingToken = unaryExpression.OperatorToken.GetNextToken();
var isNullForgivingExpression = unaryExpression.IsKind(SyntaxKindEx.SuppressNullableWarningExpression);

bool mustHaveTrailingWhitespace;
switch (followingToken.Kind())
Expand All @@ -377,6 +378,10 @@ private static void HandlePostfixUnaryExpression(SyntaxNodeAnalysisContext conte
mustHaveTrailingWhitespace = false;
break;

case SyntaxKind.OpenBracketToken:
mustHaveTrailingWhitespace = !isNullForgivingExpression;
break;

case SyntaxKind.QuestionToken:
mustHaveTrailingWhitespace = !(followingToken.Parent is ConditionalAccessExpressionSyntax);
break;
Expand All @@ -396,7 +401,17 @@ private static void HandlePostfixUnaryExpression(SyntaxNodeAnalysisContext conte

// Determine if the operator is allowed at the end of a line
bool allowEndOfLine;
if (followingToken.IsKind(SyntaxKind.CloseBraceToken))
if (isNullForgivingExpression)
{
allowEndOfLine = true;
}
else if ((unaryExpression.IsKind(SyntaxKind.PostIncrementExpression) || unaryExpression.IsKind(SyntaxKind.PostDecrementExpression))
&& followingToken.IsFirstInLine())
Comment on lines +408 to +409

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i know it's already merged, but i think this is worth a look. followingToken is default(SyntaxToken) when the operator is the last non-zero-width token in the file, like i++ without a ; while you're typing. IsFirstInLine touches token.SyntaxTree before its null check, so it blows up and shows up as AD0001. before this change it only got reached after a kind check on followingToken, which default never matches

Suggested change
else if ((unaryExpression.IsKind(SyntaxKind.PostIncrementExpression) || unaryExpression.IsKind(SyntaxKind.PostDecrementExpression))
&& followingToken.IsFirstInLine())
else if ((unaryExpression.IsKind(SyntaxKind.PostIncrementExpression) || unaryExpression.IsKind(SyntaxKind.PostDecrementExpression))
&& !followingToken.IsKind(SyntaxKind.None)
&& followingToken.IsFirstInLine())

{
// Allow postfix increment and decrement operators to end a line when the next token begins a new line.
allowEndOfLine = true;
}
else if (followingToken.IsKind(SyntaxKind.CloseBraceToken))
{
// If the next token is a close brace token we are in an anonymous object creation or an initialization.
// Then we allow a new line
Expand Down Expand Up @@ -424,7 +439,7 @@ followingToken.Parent is ConditionalExpressionSyntax &&
allowEndOfLine = false;
}

CheckToken(context, unaryExpression.OperatorToken, false, allowEndOfLine, mustHaveTrailingWhitespace);
CheckToken(context, unaryExpression.OperatorToken, false, allowEndOfLine, mustHaveTrailingWhitespace, allowTrailingComment: isNullForgivingExpression);
}

private static void HandleAssignmentExpression(SyntaxNodeAnalysisContext context)
Expand Down Expand Up @@ -477,12 +492,12 @@ private static void HandleSwitchExpressionArm(SyntaxNodeAnalysisContext context)
CheckToken(context, switchExpressionArm.EqualsGreaterThanToken, true, true, true);
}

private static void CheckToken(SyntaxNodeAnalysisContext context, SyntaxToken token, bool withLeadingWhitespace, bool allowAtEndOfLine, bool withTrailingWhitespace, string tokenText = null)
private static void CheckToken(SyntaxNodeAnalysisContext context, SyntaxToken token, bool withLeadingWhitespace, bool allowAtEndOfLine, bool withTrailingWhitespace, string tokenText = null, bool allowTrailingComment = false)
{
tokenText = tokenText ?? token.Text;

CheckTokenLeadingWhitespace(context, token, withLeadingWhitespace, tokenText);
CheckTokenTrailingWhitespace(context, token, allowAtEndOfLine, withTrailingWhitespace, tokenText);
CheckTokenTrailingWhitespace(context, token, allowAtEndOfLine, withTrailingWhitespace, tokenText, allowTrailingComment);
}

private static void CheckTokenLeadingWhitespace(SyntaxNodeAnalysisContext context, SyntaxToken token, bool withLeadingWhitespace, string tokenText = null)
Expand Down Expand Up @@ -516,7 +531,7 @@ private static void CheckTokenLeadingWhitespace(SyntaxNodeAnalysisContext contex
}
}

private static void CheckTokenTrailingWhitespace(SyntaxNodeAnalysisContext context, SyntaxToken token, bool allowAtEndOfLine, bool withTrailingWhitespace, string tokenText = null)
private static void CheckTokenTrailingWhitespace(SyntaxNodeAnalysisContext context, SyntaxToken token, bool allowAtEndOfLine, bool withTrailingWhitespace, string tokenText = null, bool allowTrailingComment = false)
{
tokenText = tokenText ?? token.Text;

Expand All @@ -537,6 +552,13 @@ private static void CheckTokenTrailingWhitespace(SyntaxNodeAnalysisContext conte
return;
}

if (allowTrailingComment
&& !withTrailingWhitespace
&& followingTriviaList.Any(SyntaxKind.SingleLineCommentTrivia))
{
return;
}

if (withTrailingWhitespace)
{
if ((followingTriviaList.Count == 0) || !(followingTriviaList.First().IsKind(SyntaxKind.WhitespaceTrivia) || followingTriviaList.First().IsKind(SyntaxKind.EndOfLineTrivia)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,80 @@ public void TestMethod()
}
}
}
";

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

[Fact]
[WorkItem(4264, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4264")]
public async Task TestNullForgivingOperatorAtEndOfMultilineArgumentListAsync()
{
var testCode = @"
namespace TestNamespace
{
public class TestClass
{
public void TestMethod()
{
Print(
para1: null!,
para2: null!,
para3: null! // trailing comment
);

Print(
para1: null!,
para2: null!,
para3: null!
);

var stillValid = GetValue()!
+ ""suffix"";

var missingWhitespace = GetValue(){|#1:!|}/*block comment*/ // trailing comment
+ ""suffix"";
}

private void Print(string para1, string para2, string para3)
{
}

private string? GetValue() => null;
}
}
";

await VerifyCSharpDiagnosticAsync(
testCode,
Diagnostic(DescriptorFollowedByWhitespace).WithLocation(1).WithArguments("!"),
CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that null-forgiving operators are adjacent to element access expressions.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4266, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4266")]
public async Task TestNullForgivingOperatorBeforeElementAccessAsync()
{
var testCode = @"
namespace TestNamespace
{
public class TestClass
{
private string[]? _list;
private string[]? _array;

public string TestMethod()
{
var listItem = _list![0];
var arrayItem = _array![0];
return listItem + arrayItem;
}
}
}
";

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
Expand Down
37 changes: 37 additions & 0 deletions test/StyleCop.Analyzers.Test/SpacingRules/SA1001UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,43 @@ public async Task TestFirstCommaInLineAsync()
await this.TestCommaInStatementOrDeclAsync(testStatement, expected, fixedStatement).ConfigureAwait(false);
}

[Fact]
public async Task TestCommaAfterPostfixIncrementAtEndOfLineAsync()
{
var testCode = @"
public class TestClass
{
public void TestMethod()
{
var value = 0;
var values = new[]
{
value++
{|#0:,|} value
};
}
}
";

var fixedCode = @"
public class TestClass
{
public void TestMethod()
{
var value = 0;
var values = new[]
{
value++,
value
};
}
}
";

DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(0);
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}

[Fact]
public async Task TestCommentBeforeFirstCommaInLineAsync()
{
Expand Down
53 changes: 41 additions & 12 deletions test/StyleCop.Analyzers.Test/SpacingRules/SA1003UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,43 @@ public void Bar()
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies that postfix increment and decrement operators may end a line before the next token.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestPostfixIncrementAndDecrementAtEndOfLineAsync()
{
var testCode = @"
public class TestClass
{
public void TestMethod()
{
var incrementedValue = GetCounter().Value++
+ 2;
var decrementedValue = GetCounter().Value--
+ 2;
var postfixValues = new[]
{
GetCounter().Value++
,
GetCounter().Value--
,
};
}

private Counter GetCounter() => new Counter();

private class Counter
{
public int Value;
}
}
";

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

/// <summary>
/// Verifies that Invalid unary expressions produce the correct diagnostics and code fixes.
/// </summary>
Expand Down Expand Up @@ -106,25 +143,21 @@ public void Bar()

var v9_1 = new
{
Property = v1++
,
Property = v1++,
};
var v9_2 = new
{
Property = v1--
,
Property = v1--,
};
var v9_3 = new int[]
{
v1++,
v1++
,
v1++,
};
var v9_4 = new int[]
{
v1--,
v1--
,
v1--,
};
}
}
Expand Down Expand Up @@ -183,10 +216,6 @@ public void Bar()
Diagnostic(DescriptorNotFollowedByComment).WithLocation(15, 18).WithArguments("~"),
Diagnostic(DescriptorNotPrecededByWhitespace).WithLocation(17, 20).WithArguments("(byte)"),
Diagnostic(DescriptorNotPrecededByWhitespace).WithLocation(18, 22).WithArguments("~"),
Diagnostic(DescriptorNotAtEndOfLine).WithLocation(22, 26).WithArguments("++"),
Diagnostic(DescriptorNotAtEndOfLine).WithLocation(27, 26).WithArguments("--"),
Diagnostic(DescriptorNotAtEndOfLine).WithLocation(33, 15).WithArguments("++"),
Diagnostic(DescriptorNotAtEndOfLine).WithLocation(39, 15).WithArguments("--"),
},
RemainingDiagnostics =
{
Expand Down
Loading