From 3e3de67baec027ae3cebe4e5e2f86e565eb9bda6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Hellander?= Date: Sat, 8 Apr 2023 08:16:41 +0200 Subject: [PATCH] Correct SA1515 to not fire on the second line of a file header #3630 --- .../LayoutRules/SA1515UnitTests.cs | 26 +++++++++++++++++++ ...gleLineCommentMustBePrecededByBlankLine.cs | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1515UnitTests.cs b/StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1515UnitTests.cs index 778af1e74..96c55e982 100644 --- a/StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1515UnitTests.cs +++ b/StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1515UnitTests.cs @@ -5,6 +5,7 @@ namespace StyleCop.Analyzers.Test.LayoutRules { + using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; @@ -269,5 +270,30 @@ public Class1() await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } + + /// + /// Verifies that the analyzer does not fire in file headers (i.e. one line comments at the start of the file). + /// + /// The number of lines in the header. + /// A representing the asynchronous unit test. + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [WorkItem(3630, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3630")] + public async Task TestFileHeaderAsync(int numberOfHeaderLines) + { + var testCode = @" +class TestClass +{ +}"; + + for (var i = 0; i < numberOfHeaderLines; i++) + { + testCode = "// A comment line." + Environment.NewLine + testCode; + } + + await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); + } } } diff --git a/StyleCop.Analyzers/StyleCop.Analyzers/LayoutRules/SA1515SingleLineCommentMustBePrecededByBlankLine.cs b/StyleCop.Analyzers/StyleCop.Analyzers/LayoutRules/SA1515SingleLineCommentMustBePrecededByBlankLine.cs index 6e9faf64c..e19dfb582 100644 --- a/StyleCop.Analyzers/StyleCop.Analyzers/LayoutRules/SA1515SingleLineCommentMustBePrecededByBlankLine.cs +++ b/StyleCop.Analyzers/StyleCop.Analyzers/LayoutRules/SA1515SingleLineCommentMustBePrecededByBlankLine.cs @@ -198,7 +198,7 @@ private static bool IsPrecededBySingleLineCommentOnOwnLineOrDocumentation(T t break; case SyntaxKind.SingleLineCommentTrivia: - return IsOnOwnLine(triviaList, triviaIndex); + return IsOnOwnLine(triviaList, triviaIndex) || currentTrivia.Span.Start == 0; case SyntaxKind.SingleLineDocumentationCommentTrivia: return true;