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
5 changes: 5 additions & 0 deletions documentation/SA1017.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ A violation of this rule occurs when the spacing around a closing attribute brac

A closing attribute bracket should never be preceded by whitespace, unless the bracket is the first character on the line.

The last attribute bracket on a parameter or type parameter should be followed by a space before the parameter type, modifier, or name, unless the declaration continues on the next line. Adjacent attribute lists do not require a space between them.

For example, use `[NotNullWhen(true)] out string? foo` instead of `[NotNullWhen(true)]out string? foo`. Multiple spaces are reported separately by [SA1025](SA1025.md).

## How to fix violations

To fix a violation of this rule, ensure that there is no whitespace before the closing attribute bracket.
For parameter and type parameter attributes, also ensure that a space follows the last closing attribute bracket on the same line.

## How to suppress violations

Expand Down
5 changes: 5 additions & 0 deletions documentation/cs-cz/SA1017.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ K porušení tohoto pravidla dojde, pokud nejsou mezery kolem uzavírací hranat

Uzavírací hranaté závorce atributu nikdy nemá předcházet bílý znak, s výjimkou případu, kdy je tato závorka prvním znakem na řádku.

Za poslední hranatou závorkou atributu parametru nebo parametru typu má následovat mezera před typem, modifikátorem nebo názvem parametru, pokud deklarace nepokračuje na dalším řádku. Mezi sousedními seznamy atributů není mezera vyžadována.

Například použijte `[NotNullWhen(true)] out string? foo` místo `[NotNullWhen(true)]out string? foo`. Více mezer hlásí samostatně pravidlo [SA1025](SA1025.md).

## Jak opravit porušení

Chcete-li porušení tohoto pravidla opravit, zajistěte, aby před uzavírací hranatou závorkou atributu nebyl žádný bílý znak.
U atributů parametrů a parametrů typu také zajistěte, aby za poslední uzavírací hranatou závorkou atributu na stejném řádku následovala mezera.

## Jak potlačit porušení

Expand Down
5 changes: 5 additions & 0 deletions documentation/ru-ru/SA1017.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@

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

После последней скобки атрибута параметра или параметра типа должен следовать пробел перед типом, модификатором или именем параметра, если объявление не продолжается на следующей строке. Между соседними списками атрибутов пробел не требуется.

Например, используйте `[NotNullWhen(true)] out string? foo` вместо `[NotNullWhen(true)]out string? foo`. Несколько пробелов отдельно обнаруживаются правилом [SA1025](SA1025.md).

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

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

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

Expand Down
5 changes: 5 additions & 0 deletions documentation/zh-cn/SA1017.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ C# 元素中特性右方括号周围的空格不正确。

特性右方括号前不得有空白字符,除非它是一行中的第一个字符。

参数或类型参数的最后一个特性右方括号与其后的参数类型、修饰符或名称之间应有一个空格,除非声明在下一行继续。相邻特性列表之间不要求空格。

例如,应使用 `[NotNullWhen(true)] out string? foo`,而不是 `[NotNullWhen(true)]out string? foo`。多个连续空格由 [SA1025](SA1025.md) 单独报告。

## 如何修复违规

确保特性右方括号前没有任何空白字符即可修复违规。
对于参数和类型参数的特性,还应确保最后一个特性右方括号后在同一行上有一个空格。

## 如何抑制违规

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ namespace StyleCop.Analyzers.SpacingRules
///
/// <para>A closing attribute bracket should never be preceded by whitespace, unless the bracket is the first
/// character on the line.</para>
///
/// <para>The last attribute bracket on a parameter or type parameter should be followed by whitespace,
/// unless the parameter declaration continues on the next line.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class SA1017ClosingAttributeBracketsMustBeSpacedCorrectly : DiagnosticAnalyzer
Expand All @@ -30,11 +33,15 @@ internal class SA1017ClosingAttributeBracketsMustBeSpacedCorrectly : DiagnosticA
private static readonly string HelpLink = HelpLinkHelper.GetHelpLink(DiagnosticId);
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(SpacingResources.SA1017Title), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(SpacingResources.SA1017MessageFormat), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly LocalizableString MessageFollowed = new LocalizableResourceString(nameof(SpacingResources.SA1017MessageFollowed), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(SpacingResources.SA1017Description), SpacingResources.ResourceManager, typeof(SpacingResources));

private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.SpacingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);

private static readonly DiagnosticDescriptor DescriptorFollowed =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFollowed, AnalyzerCategory.SpacingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);

private static readonly Action<SyntaxTreeAnalysisContext, SyntaxTreeTokens> SyntaxTreeAction = HandleSyntaxTree;

/// <inheritdoc/>
Expand Down Expand Up @@ -78,6 +85,18 @@ private static void HandleCloseBracketToken(SyntaxTreeAnalysisContext context, S
return;
}

if ((token.Parent.Parent.IsKind(SyntaxKind.Parameter) || token.Parent.Parent.IsKind(SyntaxKind.TypeParameter))
&& !token.GetNextToken().IsKind(SyntaxKind.OpenBracketToken)
&& !token.IsLastInLine()
&& !token.IsFollowedByWhitespace())
{
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable RS1005 // ReportDiagnostic invoked with an unsupported DiagnosticDescriptor (https://github.com/dotnet/roslyn-analyzers/issues/4103)
context.ReportDiagnostic(Diagnostic.Create(DescriptorFollowed, token.GetLocation(), TokenSpacingProperties.InsertFollowing));
#pragma warning restore RS1005 // ReportDiagnostic invoked with an unsupported DiagnosticDescriptor
#pragma warning restore IDE0079 // Remove unnecessary suppression
}

if (token.IsFirstInLine())
{
return;
Expand Down
3 changes: 3 additions & 0 deletions src/StyleCop.Analyzers/SpacingRules/SpacingResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,9 @@
<data name="SA1017MessageFormat" xml:space="preserve">
<value>Closing attribute brackets should not be preceded by a space</value>
</data>
<data name="SA1017MessageFollowed" xml:space="preserve">
<value>Closing attribute brackets should be followed by a space</value>
</data>
<data name="SA1017Title" xml:space="preserve">
<value>Closing attribute brackets should be spaced correctly</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,9 @@
<data name="SA1017MessageFormat" xml:space="preserve">
<value>Закрывающие скобки атрибута не должны предваряться пробелом</value>
</data>
<data name="SA1017MessageFollowed" xml:space="preserve">
<value>После закрывающей скобки атрибута должен стоять пробел</value>
</data>
<data name="SA1017Title" xml:space="preserve">
<value>Пробелы вокруг закрывающих скобок атрибутов должны быть расставлены правильно</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,9 @@
<data name="SA1017MessageFormat" xml:space="preserve">
<value>特性右方括号前不应有空格</value>
</data>
<data name="SA1017MessageFollowed" xml:space="preserve">
<value>特性右方括号后应有空格</value>
</data>
<data name="SA1017Title" xml:space="preserve">
<value>特性右方括号周围的空格应正确</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Test.CSharp8.SpacingRules;

using System.Threading;
using System.Threading.Tasks;
using StyleCop.Analyzers.Test.CSharp7.SpacingRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1017ClosingAttributeBracketsMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;

public partial class SA1017CSharp8UnitTests : SA1017CSharp7UnitTests
{
/// <summary>
/// Verifies spacing after a nullable flow-analysis attribute on an out parameter.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(3118, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3118")]
public async Task TestMissingSpaceAfterNotNullWhenAttributeAsync()
{
var testCode = """
#nullable enable
using System.Diagnostics.CodeAnalysis;

class TestClass
{
bool Method([NotNullWhen(true){|#0:]|}out string? foo)
{
foo = "";
return true;
}
}

""";
var fixedCode = """
#nullable enable
using System.Diagnostics.CodeAnalysis;

class TestClass
{
bool Method([NotNullWhen(true)] out string? foo)
{
foo = "";
return true;
}
}

""";

await VerifyCSharpFixAsync(testCode, Diagnostic().WithLocation(0).WithMessage("Closing attribute brackets should be followed by a space"), fixedCode, CancellationToken.None).ConfigureAwait(false);
}
}
153 changes: 150 additions & 3 deletions test/StyleCop.Analyzers.Test/SpacingRules/SA1017UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ class ClassNam3

DiagnosticResult[] expected =
{
Diagnostic().WithLocation(0),
Diagnostic().WithLocation(1),
Diagnostic().WithLocation(2),
Diagnostic().WithLocation(0).WithMessage("Closing attribute brackets should not be preceded by a space"),
Diagnostic().WithLocation(1).WithMessage("Closing attribute brackets should not be preceded by a space"),
Diagnostic().WithLocation(2).WithMessage("Closing attribute brackets should not be preceded by a space"),
};

await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
Expand Down Expand Up @@ -141,5 +141,152 @@ void MethodName()

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

/// <summary>
/// Verifies spacing between parameter attributes and parameter types or modifiers.
/// </summary>
/// <param name="parameter">The parameter declaration following the attribute.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("int value")]
[InlineData("ref int value")]
[InlineData("out int value")]
[InlineData("params int[] values")]
[InlineData("this string value")]
[WorkItem(3118, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3118")]
public async Task TestMissingSpaceAfterParameterAttributeAsync(string parameter)
{
var testCode = $$"""
static class TestClass
{
static void Method([My{|#0:]|}{{parameter}})
{
throw new System.NotImplementedException();
}
}

class MyAttribute : System.Attribute { }

""";
var fixedCode = $$"""
static class TestClass
{
static void Method([My] {{parameter}})
{
throw new System.NotImplementedException();
}
}

class MyAttribute : System.Attribute { }

""";

await VerifyCSharpFixAsync(testCode, Diagnostic().WithLocation(0).WithMessage("Closing attribute brackets should be followed by a space"), fixedCode, CancellationToken.None).ConfigureAwait(false);
}

/// <summary>
/// Verifies spacing after attributes in different parameter declarations.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(3118, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3118")]
public async Task TestMissingSpaceAfterAttributesInParameterDeclarationsAsync()
{
var testCode = """
delegate void Callback([My{|#0:]|}int value);

class TestClass<[My{|#1:]|}T>
{
TestClass([My{|#2:]|}int value) { }

int this[[My{|#3:]|}int index] => 0;

void Method<[My{|#4:]|}U>([My][My{|#5:]|}int value) { }

void MultilineAttribute([My
{|#6:]|}int value) { }

void Comment([My{|#7:]|}/* keep */int value) { }

void BothSides([My {|#8:]|}int value) { }
}

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
class MyAttribute : System.Attribute { }

""";
var fixedCode = """
delegate void Callback([My] int value);

class TestClass<[My] T>
{
TestClass([My] int value) { }

int this[[My] int index] => 0;

void Method<[My] U>([My][My] int value) { }

void MultilineAttribute([My
] int value) { }

void Comment([My] /* keep */int value) { }

void BothSides([My] int value) { }
}

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
class MyAttribute : System.Attribute { }

""";

DiagnosticResult[] expected =
{
Diagnostic().WithLocation(0).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(1).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(2).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(3).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(4).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(5).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(6).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(7).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(8).WithMessage("Closing attribute brackets should be followed by a space"),
Diagnostic().WithLocation(8).WithMessage("Closing attribute brackets should not be preceded by a space"),
};

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

/// <summary>
/// Verifies that attribute spacing preserves line breaks and adjacent attribute lists.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(3118, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3118")]
public async Task TestValidSpacingAfterParameterAttributesAsync()
{
var testCode = """
[My]class TestClass<[My] T>
{
void Method([My] int value) { }

void Multiple([My][My] int value) { }

void Multiline(
[My]
int value) { }

void Comment([My] /* keep */int value) { }

void MultilineComment([My]/* keep
*/int value) { }
}

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
class MyAttribute : System.Attribute { }

""";

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