diff --git a/documentation/SA1118.md b/documentation/SA1118.md index 762f5f7ce..d45d4fcb5 100644 --- a/documentation/SA1118.md +++ b/documentation/SA1118.md @@ -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. diff --git a/documentation/cs-cz/SA1118.md b/documentation/cs-cz/SA1118.md index 39bf9eee4..639704c52 100644 --- a/documentation/cs-cz/SA1118.md +++ b/documentation/cs-cz/SA1118.md @@ -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ů. diff --git a/documentation/ru-ru/SA1118.md b/documentation/ru-ru/SA1118.md index d9282864f..08e1de5e7 100644 --- a/documentation/ru-ru/SA1118.md +++ b/documentation/ru-ru/SA1118.md @@ -14,6 +14,7 @@ * Выражения вызова могут занимать несколько строк * Выражения создания объектов и массивов могут занимать несколько строк * Выражения кортежей могут занимать несколько строк +* Строковые литералы и интерполированные строки (включая дословные, необработанные строки и строки UTF-8) могут занимать несколько строк * Выражения `with` (C# 9) могут занимать несколько строк. Эти исключения относятся как к аргументам атрибутов, так и к аргументам методов и индексаторов. diff --git a/documentation/zh-cn/SA1118.md b/documentation/zh-cn/SA1118.md index 9534c788b..cd2dca79b 100644 --- a/documentation/zh-cn/SA1118.md +++ b/documentation/zh-cn/SA1118.md @@ -15,6 +15,7 @@ C# 方法或索引器中除第一个参数以外的某个参数跨越多行。 * 匿名方法(包括 lambda 表达式)可以跨越多行。 * 调用表达式可以跨越多行。 * 对象和数组创建表达式可以跨越多行。 +* 字符串字面量和内插字符串(包括逐字字符串、原始字符串和 UTF-8 字符串)可以跨越多行。 * `with` 表达式(C# 9)可以跨越多行。 这些例外既适用于特性实参,也适用于方法和索引器实参。 diff --git a/src/StyleCop.Analyzers/Lightup/SyntaxKindEx.cs b/src/StyleCop.Analyzers/Lightup/SyntaxKindEx.cs index 4c2d8f9ec..b3f5a010d 100644 --- a/src/StyleCop.Analyzers/Lightup/SyntaxKindEx.cs +++ b/src/StyleCop.Analyzers/Lightup/SyntaxKindEx.cs @@ -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; diff --git a/src/StyleCop.Analyzers/ReadabilityRules/SA1118ParameterMustNotSpanMultipleLines.cs b/src/StyleCop.Analyzers/ReadabilityRules/SA1118ParameterMustNotSpanMultipleLines.cs index 63652f4f7..e44828f17 100644 --- a/src/StyleCop.Analyzers/ReadabilityRules/SA1118ParameterMustNotSpanMultipleLines.cs +++ b/src/StyleCop.Analyzers/ReadabilityRules/SA1118ParameterMustNotSpanMultipleLines.cs @@ -19,7 +19,7 @@ namespace StyleCop.Analyzers.ReadabilityRules /// /// 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. /// @@ -87,6 +87,9 @@ internal class SA1118ParameterMustNotSpanMultipleLines : DiagnosticAnalyzer SyntaxKindEx.ImplicitObjectCreationExpression, SyntaxKindEx.CollectionExpression, SyntaxKindEx.TupleExpression, + SyntaxKind.StringLiteralExpression, + SyntaxKind.InterpolatedStringExpression, + SyntaxKindEx.Utf8StringLiteralExpression, }; /// diff --git a/test/StyleCop.Analyzers.Test.CSharp11/ReadabilityRules/SA1118CSharp11UnitTests.cs b/test/StyleCop.Analyzers.Test.CSharp11/ReadabilityRules/SA1118CSharp11UnitTests.cs new file mode 100644 index 000000000..c839cac1b --- /dev/null +++ b/test/StyleCop.Analyzers.Test.CSharp11/ReadabilityRules/SA1118CSharp11UnitTests.cs @@ -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; + +public partial class SA1118CSharp11UnitTests : SA1118CSharp10UnitTests +{ + /// + /// Verifies the reported migration constraint arguments using raw and verbatim strings. + /// + /// A representing the asynchronous unit test. + [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); + } + + /// + /// Verifies that raw strings and interpolation expressions can span multiple lines. + /// + /// The string expression to pass as an argument. + /// A representing the asynchronous unit test. + [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); + } + + /// + /// Verifies that multiline UTF-8 string literals receive the same exemption. + /// + /// The UTF-8 string expression to pass as an argument. + /// A representing the asynchronous unit test. + [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 text) { } + ReadOnlySpan this[int value, ReadOnlySpan text] { get { return text; } } + void M(int value, ReadOnlySpan 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); + } + + /// + /// Verifies the raw string exemption in positional and named attribute arguments. + /// + /// A representing the asynchronous unit test. + [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); + } + + /// + /// Verifies that concatenating raw strings still reports a multiline argument. + /// + /// A representing the asynchronous unit test. + [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); + } +} diff --git a/test/StyleCop.Analyzers.Test.CSharp8/ReadabilityRules/SA1118CSharp8UnitTests.cs b/test/StyleCop.Analyzers.Test.CSharp8/ReadabilityRules/SA1118CSharp8UnitTests.cs new file mode 100644 index 000000000..16b51eec2 --- /dev/null +++ b/test/StyleCop.Analyzers.Test.CSharp8/ReadabilityRules/SA1118CSharp8UnitTests.cs @@ -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 +{ + /// + /// Verifies that interpolated verbatim strings also support the reversed prefix order. + /// + /// A representing the asynchronous unit test. + [Fact] + [WorkItem(4330, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/4330")] + public async Task TestMultilineVerbatimStringWithReversedPrefixArgumentAsync() + { + await VerifyMultilineStringArgumentAsync("@$\"first {1}\nsecond\"").ConfigureAwait(false); + } +} diff --git a/test/StyleCop.Analyzers.Test/ReadabilityRules/SA1118UnitTests.cs b/test/StyleCop.Analyzers.Test/ReadabilityRules/SA1118UnitTests.cs index 25050e8e1..61c685710 100644 --- a/test/StyleCop.Analyzers.Test/ReadabilityRules/SA1118UnitTests.cs +++ b/test/StyleCop.Analyzers.Test/ReadabilityRules/SA1118UnitTests.cs @@ -32,6 +32,70 @@ public class SA1118UnitTests }, }; + /// + /// Verifies that verbatim strings, including interpolated strings, can span multiple lines. + /// + /// The string expression to pass as an argument. + /// A representing the asynchronous unit test. + [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); + } + + /// + /// Verifies that verbatim strings in attribute arguments can span multiple lines. + /// + /// A representing the asynchronous unit test. + [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); + } + + /// + /// Verifies that the string exemption does not extend to concatenation expressions. + /// + /// The prefix of the string literal. + /// A representing the asynchronous unit test. + [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() { @@ -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); + } } }