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
1 change: 1 addition & 0 deletions documentation/SA1118.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ cases:
* Invocation expressions may span multiple lines
* Object and array creation expressions may span multiple lines
* Tuple expressions may span multiple lines
* String literals and interpolated strings (including verbatim, raw, and UTF-8 strings) may span multiple lines
* `with` expressions (C# 9) may span multiple lines

These exceptions apply to attribute arguments as well as method and indexer arguments.
Expand Down
1 change: 1 addition & 0 deletions documentation/cs-cz/SA1118.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ následujících případů:
* Výrazy volání mohou zasahovat do více řádků.
* Výrazy vytvářející objekty a pole mohou zasahovat do více řádků.
* Výrazy s n-ticemi mohou zasahovat do více řádků.
* Řetězcové literály a interpolované řetězce (včetně doslovných, nezpracovaných a UTF-8 řetězců) mohou zasahovat do více řádků.
* Výrazy `with` (C# 9) mohou zasahovat do více řádků.

Tyto výjimky se vztahují na argumenty atributů i na argumenty metod a indexerů.
Expand Down
1 change: 1 addition & 0 deletions documentation/ru-ru/SA1118.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* Выражения вызова могут занимать несколько строк
* Выражения создания объектов и массивов могут занимать несколько строк
* Выражения кортежей могут занимать несколько строк
* Строковые литералы и интерполированные строки (включая дословные, необработанные строки и строки UTF-8) могут занимать несколько строк
* Выражения `with` (C# 9) могут занимать несколько строк.

Эти исключения относятся как к аргументам атрибутов, так и к аргументам методов и индексаторов.
Expand Down
1 change: 1 addition & 0 deletions documentation/zh-cn/SA1118.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ C# 方法或索引器中除第一个参数以外的某个参数跨越多行。
* 匿名方法(包括 lambda 表达式)可以跨越多行。
* 调用表达式可以跨越多行。
* 对象和数组创建表达式可以跨越多行。
* 字符串字面量和内插字符串(包括逐字字符串、原始字符串和 UTF-8 字符串)可以跨越多行。
* `with` 表达式(C# 9)可以跨越多行。

这些例外既适用于特性实参,也适用于方法和索引器实参。
Expand Down
1 change: 1 addition & 0 deletions src/StyleCop.Analyzers/Lightup/SyntaxKindEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ internal static class SyntaxKindEx
public const SyntaxKind UnsignedRightShiftAssignmentExpression = (SyntaxKind)8726;
public const SyntaxKind IndexExpression = (SyntaxKind)8741;
public const SyntaxKind DefaultLiteralExpression = (SyntaxKind)8755;
public const SyntaxKind Utf8StringLiteralExpression = (SyntaxKind)8756;
public const SyntaxKind LocalFunctionStatement = (SyntaxKind)8830;
public const SyntaxKind FileScopedNamespaceDeclaration = (SyntaxKind)8845;
public const SyntaxKind TupleType = (SyntaxKind)8924;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ namespace StyleCop.Analyzers.ReadabilityRules
/// <remarks>
/// <para>To prevent method calls from becoming excessively complicated and unreadable, only the first parameter to
/// a method or indexer call is allowed to span across multiple lines. Certain expression forms, including
/// anonymous methods and tuple expressions, are also allowed to span multiple lines. A violation of this rule
/// anonymous methods, tuple expressions, and strings, are also allowed to span multiple lines. A violation of this rule
/// occurs whenever a parameter other than the first parameter spans across multiple lines, and its expression is
/// not one of the forms allowed to span multiple lines.</para>
///
Expand Down Expand Up @@ -87,6 +87,9 @@ internal class SA1118ParameterMustNotSpanMultipleLines : DiagnosticAnalyzer
SyntaxKindEx.ImplicitObjectCreationExpression,
SyntaxKindEx.CollectionExpression,
SyntaxKindEx.TupleExpression,
SyntaxKind.StringLiteralExpression,
SyntaxKind.InterpolatedStringExpression,
SyntaxKindEx.Utf8StringLiteralExpression,
};

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// 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.CSharp11.ReadabilityRules;

using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp10.ReadabilityRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopDiagnosticVerifier<StyleCop.Analyzers.ReadabilityRules.SA1118ParameterMustNotSpanMultipleLines>;

public partial class SA1118CSharp11UnitTests : SA1118CSharp10UnitTests
{
/// <summary>
/// Verifies the reported migration constraint arguments using raw and verbatim strings.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineStringCheckConstraintAsync()
{
var testCode = """"
class MigrationBuilder
{
void AddCheckConstraint(string name, string table, string sql) { }
void Test(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddCheckConstraint(
"CK_TableName_ColumnName",
"TableName",
"""
(
[Value1] IS NULL
AND [Value2] IS NOT NULL
)
""");

migrationBuilder.AddCheckConstraint(
"CK_TableName_ColumnName",
"TableName",
@"
(
[Value1] IS NULL
AND [Value2] IS NOT NULL
)
");
}
}
"""";

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

/// <summary>
/// Verifies that raw strings and interpolation expressions can span multiple lines.
/// </summary>
/// <param name="expression">The string expression to pass as an argument.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("\"\"\"\nfirst\nsecond\n\"\"\"")]
[InlineData("$\"\"\"\nfirst {1}\nsecond\n\"\"\"")]
[InlineData("$$\"\"\"\n{ \"value\": {{1}} }\n\"\"\"")]
[InlineData("$$$\"\"\"\"\n{{ \"value\": {{{1}}} }}\n\"\"\"\"")]
[InlineData("$\"first {1 +\n2} second\"")]
[InlineData("$\"\"\"first {1 +\n2} second\"\"\"")]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineRawOrInterpolatedStringArgumentAsync(string expression)
{
await VerifyMultilineStringArgumentAsync(expression).ConfigureAwait(false);
}

/// <summary>
/// Verifies that multiline UTF-8 string literals receive the same exemption.
/// </summary>
/// <param name="expression">The UTF-8 string expression to pass as an argument.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("@\"first\nsecond\"u8")]
[InlineData("\"\"\"\nfirst\nsecond\n\"\"\"u8")]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineUtf8StringArgumentAsync(string expression)
{
var testCode = $$"""
using System;
class C
{
C(int value, ReadOnlySpan<byte> text) { }
ReadOnlySpan<byte> this[int value, ReadOnlySpan<byte> text] { get { return text; } }
void M(int value, ReadOnlySpan<byte> text) { }
void Test()
{
M(0, {{expression}});
M(0, text: {{expression}});
var instance = new C(0, {{expression}});
var result = this[0, {{expression}}];
}
}
""";

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

/// <summary>
/// Verifies the raw string exemption in positional and named attribute arguments.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineRawStringAttributeArgumentAsync()
{
var testCode = """"
[Example(0, """
first
second
""", Text = $"""
third
fourth
""")]
class ExampleAttribute : System.Attribute
{
public ExampleAttribute(int value, string text) { }
public string Text { get; set; }
}
"""";

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

/// <summary>
/// Verifies that concatenating raw strings still reports a multiline argument.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineRawStringConcatenationArgumentAsync()
{
var testCode = """"
class C
{
void M(int value, string text) { }
void Test()
{
M(0, {|#0:"""
first
second
""" +
"third"|});
}
}
"""";

await VerifyCSharpDiagnosticAsync(testCode, Diagnostic().WithLocation(0), CancellationToken.None).ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// 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.ReadabilityRules;

using System.Threading.Tasks;
using StyleCop.Analyzers.Test.CSharp7.ReadabilityRules;
using Xunit;

public partial class SA1118CSharp8UnitTests : SA1118CSharp7UnitTests
{
/// <summary>
/// Verifies that interpolated verbatim strings also support the reversed prefix order.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineVerbatimStringWithReversedPrefixArgumentAsync()
{
await VerifyMultilineStringArgumentAsync("@$\"first {1}\nsecond\"").ConfigureAwait(false);
}
}
89 changes: 89 additions & 0 deletions test/StyleCop.Analyzers.Test/ReadabilityRules/SA1118UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,70 @@ public class SA1118UnitTests
},
};

/// <summary>
/// Verifies that verbatim strings, including interpolated strings, can span multiple lines.
/// </summary>
/// <param name="expression">The string expression to pass as an argument.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("@\"first\nsecond\"")]
[InlineData("$@\"first {1}\nsecond\"")]
[InlineData("$@\"{1 +\n2}\"")]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineVerbatimStringArgumentAsync(string expression)
{
await VerifyMultilineStringArgumentAsync(expression).ConfigureAwait(false);
}

/// <summary>
/// Verifies that verbatim strings in attribute arguments can span multiple lines.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineVerbatimStringAttributeArgumentAsync()
{
var testCode = """
[Example(0, @"first
second", Text = @"third
fourth")]
class ExampleAttribute : System.Attribute
{
public ExampleAttribute(int value, string text) { }
public string Text { get; set; }
}
""";

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

/// <summary>
/// Verifies that the string exemption does not extend to concatenation expressions.
/// </summary>
/// <param name="prefix">The prefix of the string literal.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("@")]
[InlineData("$@")]
[WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")]
public async Task TestMultilineStringConcatenationArgumentAsync(string prefix)
{
var testCode = $$"""
class C
{
void M(int value, string text) { }
void Test()
{
M(0, {|#0:{{prefix}}"first
second" +
"third"|});
}
}
""";

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

[Fact]
public async Task TestMethodCallWithTwoParametersSecondSpansMoreThanOneLineAsync()
{
Expand Down Expand Up @@ -453,5 +517,30 @@ public void Bar()

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

protected static async Task VerifyMultilineStringArgumentAsync(string expression)
{
var testCode = $$"""
class C
{
C(int value, string text) { }
string this[int value, string text] { get { return text; } }
void M(int value, string text) { }
void Test()
{
M(0, {{expression}});
M(0, text: {{expression}});
var instance = new C(0, {{expression}});
var result = this[0, {{expression}}];
}
}
""";

await new CSharpTest
{
TestCode = testCode,
TestState = { MarkupHandling = MarkupMode.None },
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}
Loading