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
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