Skip to content

Commit

Permalink
Merge pull request #3633 from bjornhellander/feature/sa1515-file-header
Browse files Browse the repository at this point in the history
Correct SA1515 to not fire on the second line of a file header
  • Loading branch information
sharwell authored Apr 12, 2023
2 parents e1fa460 + e32f78a commit ccaac20
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace StyleCop.Analyzers.Test.LayoutRules
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
Expand Down Expand Up @@ -269,5 +270,36 @@ public Class1()

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

/// <summary>
/// Verifies that the analyzer does not fire in file headers (i.e. one line comments at the start of the file).
/// </summary>
/// <param name="startWithPragma"><see langword="true"/> if the source code should start with a pragma; otherwise, <see langword="false"/>.</param>
/// <param name="numberOfHeaderLines">The number of lines in the header.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[CombinatorialData]
[WorkItem(3630, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3630")]
public async Task TestFileHeaderAsync(
bool startWithPragma,
[CombinatorialValues(1, 2, 3)] int numberOfHeaderLines)
{
var testCode = @"
class TestClass
{
}";

for (var i = 0; i < numberOfHeaderLines; i++)
{
testCode = "// A comment line." + Environment.NewLine + testCode;
}

if (startWithPragma)
{
testCode = "#pragma warning disable CS1591" + Environment.NewLine + testCode;
}

await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,19 @@ private static void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
private static bool IsOnOwnLine<T>(T triviaList, int triviaIndex)
where T : IReadOnlyList<SyntaxTrivia>
{
if (triviaList[triviaIndex].Span.Start == 0)
{
return true;
}

while (triviaIndex >= 0)
{
if (triviaList[triviaIndex].IsDirective)
{
// directive trivia are special, as they have a 'built-in' end-of-line.
return true;
}

if (triviaList[triviaIndex].IsKind(SyntaxKind.EndOfLineTrivia))
{
return true;
Expand Down Expand Up @@ -275,6 +286,7 @@ private static bool IsPrecededByDirectiveTrivia<T>(T triviaList, int triviaIndex
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.PragmaWarningDirectiveTrivia:
return true;

default:
Expand Down

0 comments on commit ccaac20

Please sign in to comment.