Skip to content

Commit

Permalink
Fix SA1516 reporting location for top-level programs
Browse files Browse the repository at this point in the history
  • Loading branch information
sharwell committed Dec 5, 2020
1 parent 363a36c commit 61a7218
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,60 @@

namespace StyleCop.Analyzers.Test.CSharp9.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp8.LayoutRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.LayoutRules.SA1516ElementsMustBeSeparatedByBlankLine,
StyleCop.Analyzers.LayoutRules.SA1516CodeFixProvider>;

public class SA1516CSharp9UnitTests : SA1516CSharp8UnitTests
{
/// <summary>
/// Verifies that SA1516 is reported at the correct location in top-level programs.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(3242, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3242")]
public async Task TestStatementSpacingInTopLevelProgramAsync()
{
var testCode = @"using System;
using System.Threading;
{|#0:return|} 0;
";
var fixedCode = @"using System;
using System.Threading;
return 0;
";

await new CSharpTest(LanguageVersion.CSharp9)
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = testCode,
ExpectedDiagnostics =
{
// /0/Test0.cs(3,1): warning SA1516: Elements should be separated by blank line
Diagnostic().WithLocation(0),

// /0/Test0.cs(3,1): warning SA1516: Elements should be separated by blank line
Diagnostic().WithLocation(0),
},
FixedCode = fixedCode,
SolutionTransforms =
{
(solution, projectId) =>
{
var project = solution.GetProject(projectId);
var options = project.CompilationOptions;
return solution.WithProjectCompilationOptions(projectId, options.WithOutputKind(OutputKind.ConsoleApplication));
},
},
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -366,10 +366,16 @@ private static Location GetDiagnosticLocation(SyntaxNode node)
return node.GetLeadingTrivia()[0].GetLocation();
}

// Prefer the first token which is a direct child, but fall back to the first descendant token
var firstToken = node.ChildTokens().FirstOrDefault();
if (firstToken.IsKind(SyntaxKind.None))
{
firstToken = node.GetFirstToken();
}

if (firstToken != default)
{
return node.ChildTokens().First().GetLocation();
return firstToken.GetLocation();
}

return Location.None;
Expand Down

0 comments on commit 61a7218

Please sign in to comment.