Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Rule T0016: Separate declarations by an empty line #9147

Merged
merged 4 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ protected override void Initialize(SonarAnalysisContext context)

private void Verify(SonarSyntaxNodeReportingContext context, SyntaxToken arrowToken)
{
if (!arrowToken.IsMissing && Line(arrowToken) > Line(arrowToken.GetPreviousToken()))
if (!arrowToken.IsMissing && arrowToken.Line() > arrowToken.GetPreviousToken().Line())
{
context.ReportIssue(Rule, arrowToken);
}
}

private static int Line(SyntaxToken token) =>
token.GetLocation().GetLineSpan().StartLinePosition.Line;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2024 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

namespace SonarAnalyzer.Rules.CSharp.Styling;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class SeparateDeclarations : StylingAnalyzer
{
public SeparateDeclarations() : base("T0016", "Add an empty line before this declaration.") { }

protected override void Initialize(SonarAnalysisContext context)
{
context.RegisterNodeAction(
ValidateSeparatedMember,
SyntaxKind.ClassDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.ConversionOperatorDeclaration,
SyntaxKind.DestructorDeclaration,
SyntaxKind.EnumDeclaration,
SyntaxKind.MethodDeclaration,
SyntaxKind.NamespaceDeclaration,
SyntaxKind.OperatorDeclaration,
SyntaxKind.RecordDeclaration,
SyntaxKind.RecordStructDeclaration,
SyntaxKind.StructDeclaration);
context.RegisterNodeAction(
ValidatePossibleSingleLineMember,
SyntaxKind.EventDeclaration,
SyntaxKind.EventFieldDeclaration,
SyntaxKind.DelegateDeclaration,
SyntaxKind.FieldDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.PropertyDeclaration);
}

private void ValidatePossibleSingleLineMember(SonarSyntaxNodeReportingContext context)
{
var firstToken = context.Node.GetFirstToken();
if (firstToken.Line() != context.Node.GetLastToken().Line()
|| firstToken.GetPreviousToken().IsKind(SyntaxKind.CloseBraceToken)
|| PreviousDeclarationKind(context.Node) != context.Node.Kind())
{
ValidateSeparatedMember(context);
}

SyntaxKind PreviousDeclarationKind(SyntaxNode node) =>
context.Node.Parent.ChildNodes().TakeWhile(x => x != node).LastOrDefault() is { } preceding
? preceding.Kind()
: SyntaxKind.None;
sebastien-marichal marked this conversation as resolved.
Show resolved Hide resolved
}

private void ValidateSeparatedMember(SonarSyntaxNodeReportingContext context)
{
var firstToken = context.Node.GetFirstToken();
if (!context.Node.GetModifiers().Any(SyntaxKind.AbstractKeyword)
&& !firstToken.GetPreviousToken().IsKind(SyntaxKind.OpenBraceToken)
&& !ContainsEmptyLine(firstToken.LeadingTrivia))
{
var firstComment = firstToken.LeadingTrivia.FirstOrDefault(IsComment);
context.ReportIssue(Rule, firstComment == default ? firstToken.GetLocation() : firstComment.GetLocation());
}
}

private static bool IsComment(SyntaxTrivia trivia) =>
trivia.IsAnyKind(
SyntaxKind.SingleLineCommentTrivia,
SyntaxKind.MultiLineCommentTrivia,
SyntaxKind.SingleLineDocumentationCommentTrivia,
SyntaxKind.MultiLineDocumentationCommentTrivia);

private static bool ContainsEmptyLine(SyntaxTriviaList trivia)
{
var previousLine = -1;
foreach (var trivium in trivia.Where(x => !x.IsKind(SyntaxKind.WhitespaceTrivia)))
{
if (trivium.IsKind(SyntaxKind.EndOfLineTrivia))
{
if (previousLine != trivium.GetLocation().StartLine())
{
return true;
}
}
else
{
previousLine = trivium.GetLocation().EndLine();
}
}
sebastien-marichal marked this conversation as resolved.
Show resolved Hide resolved
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

namespace SonarAnalyzer.Helpers;

internal static class CSharpSyntaxHelper
public static class CSharpSyntaxHelper
{
public static readonly ExpressionSyntax NullLiteralExpression =
SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private static void CheckMultilineComment(SonarSyntaxTreeReportingContext contex
{
if (IsCode(triviaLines[triviaLineNumber]))
{
var triviaStartingLineNumber = trivia.GetLocation().GetLineSpan().StartLinePosition.Line;
var triviaStartingLineNumber = trivia.GetLocation().StartLine();
var lineNumber = triviaStartingLineNumber + triviaLineNumber;
var lineSpan = context.Tree.GetText().Lines[lineNumber].Span;
var commentLineSpan = lineSpan.Intersection(trivia.GetLocation().SourceSpan);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ protected override void Initialize(SonarAnalysisContext context)
private static bool TryGetPreviousTokenInSameLine(SyntaxToken token, out SyntaxToken previousToken)
{
previousToken = token.GetPreviousToken();
return GetFirstLineNumber(previousToken) == GetFirstLineNumber(token);
return previousToken.Line() == token.Line();
}

private static int GetFirstLineNumber(SyntaxToken token)
=> token.GetLocation().GetLineSpan().StartLinePosition.Line;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ private void ReportOnAssignment(AssignmentExpressionSyntax assignment, Expressio

private static Location GetFirstLineLocationFromToken(SyntaxToken issueStartToken, SyntaxNode wholeIssue)
{
var line = wholeIssue.SyntaxTree.GetText().Lines[issueStartToken.GetLocation().GetLineSpan().StartLinePosition.Line];
var line = wholeIssue.SyntaxTree.GetText().Lines[issueStartToken.GetLocation().StartLine()];
var rightSingleLine = line.Span.Intersection(TextSpan.FromBounds(issueStartToken.SpanStart, wholeIssue.Span.End));
return Location.Create(wholeIssue.SyntaxTree, TextSpan.FromBounds(issueStartToken.SpanStart, rightSingleLine.HasValue ? rightSingleLine.Value.End : issueStartToken.Span.End));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protected override void VisitInvocations(SonarSyntaxNodeReportingContext context
var invocationLocation = invocation.GetLocation();
var secondaryLocation = objectCreation.Expression.GetLocation();

var diagnostic = invocationLocation.GetLineSpan().StartLinePosition.Line == secondaryLocation.GetLineSpan().StartLinePosition.Line
var diagnostic = invocationLocation.StartLine() == secondaryLocation.StartLine()
? Diagnostic.Create(Rule, invocationLocation)
: Rule.CreateDiagnostic(context.Compilation, invocationLocation, additionalLocations: new[] {secondaryLocation}, properties: null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ private static void CheckElse(SonarSyntaxNodeReportingContext context)

private static Location GetFirstLineOfNode(SyntaxNode node)
{
var lineNumber = node.GetLocation().GetLineSpan().StartLinePosition.Line;
var lineNumber = node.GetLocation().StartLine();
var wholeLineSpan = node.SyntaxTree.GetText().Lines[lineNumber].Span;
var secondaryLocationSpan = wholeLineSpan.Intersection(node.GetLocation().SourceSpan);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ protected override void Initialize(SonarAnalysisContext context)

private static bool StartsLine(SyntaxToken token)
{
return token.GetPreviousToken().GetLocation().GetLineSpan().EndLinePosition.Line != token.GetLocation().GetLineSpan().StartLinePosition.Line;
return token.GetPreviousToken().GetLocation().EndLine() != token.GetLocation().StartLine();
}

private static bool IsOnSameLineAsOpenBrace(SyntaxToken closeBraceToken)
{
var openBraceToken = closeBraceToken.Parent.ChildTokens().Single(token => token.IsKind(SyntaxKind.OpenBraceToken));
return openBraceToken.GetLocation().GetLineSpan().StartLinePosition.Line == closeBraceToken.GetLocation().GetLineSpan().StartLinePosition.Line;
return openBraceToken.GetLocation().StartLine() == closeBraceToken.GetLocation().StartLine();
}

private static bool IsInitializer(SyntaxNode node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,22 @@ public static class LocationExtensions
GeneratedCodeRecognizer.IsRazorGeneratedFile(location.SourceTree)
? location.GetMappedLineSpan()
: location.GetLineSpan();

public static Location EnsureMappedLocation(this Location location)
{
if (location is null || !GeneratedCodeRecognizer.IsRazorGeneratedFile(location.SourceTree))
{
return location;
}

var lineSpan = location.GetMappedLineSpan();

return Location.Create(lineSpan.Path, location.SourceSpan, lineSpan.Span);
}

public static int StartLine(this Location location) =>
location.GetLineSpan().StartLinePosition.Line;

public static int EndLine(this Location location) =>
location.GetLineSpan().EndLinePosition.Line;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,10 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

namespace SonarAnalyzer.Helpers
{
public static class LocationExtensions
{
public static Location EnsureMappedLocation(this Location location)
{
if (location is null || !GeneratedCodeRecognizer.IsRazorGeneratedFile(location.SourceTree))
{
return location;
}

var lineSpan = location.GetMappedLineSpan();
namespace SonarAnalyzer.Extensions;

return Location.Create(lineSpan.Path, location.SourceSpan, lineSpan.Span);
}
}
public static class SyntaxTokenExtensions
{
public static int Line(this SyntaxToken token) =>
token.GetLocation().StartLine();
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ private static Location CalculateLocationForLine(TextLine line, SyntaxTree tree,

private void AddStatementToLineCache(TStatementSyntax statement, MultiValueDictionary<int, TStatementSyntax> statementsByLines)
{
var startLine = statement.GetLocation().GetLineSpan().StartLinePosition.Line;
var startLine = statement.GetLocation().StartLine();
statementsByLines.AddWithKey(startLine, statement);

var lastToken = statement.GetLastToken();
var tokenBelonsTo = GetContainingStatement(lastToken);
if (tokenBelonsTo == statement)
{
var endLine = statement.GetLocation().GetLineSpan().EndLinePosition.Line;
var endLine = statement.GetLocation().EndLine();
statementsByLines.AddWithKey(endLine, statement);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,17 @@ protected override void Initialize(SonarAnalysisContext context)

private void CheckTokenComments(SonarSyntaxTreeReportingContext context, SyntaxToken token)
{
var tokenLine = token.GetLocation().GetLineSpan().StartLinePosition.Line;
var tokenLine = token.GetLocation().StartLine();

var comments = token.TrailingTrivia
.Where(tr => tr.IsKind(SyntaxKind.CommentTrivia));

foreach (var comment in comments)
{
var location = comment.GetLocation();
if (location.GetLineSpan().StartLinePosition.Line == tokenLine &&
!SafeRegex.IsMatch(comment.ToString(), LegalCommentPattern))
if (location.StartLine() == tokenLine && !SafeRegex.IsMatch(comment.ToString(), LegalCommentPattern))
{
context.ReportIssue(Diagnostic.Create(rule, location));
context.ReportIssue(rule, location);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protected override void VisitInvocations(SonarSyntaxNodeReportingContext context
var invocationLocation = invocation.GetLocation();
var secondaryLocation = objectCreation.GetLocation();

var diagnostic = invocationLocation.GetLineSpan().StartLinePosition.Line == secondaryLocation.GetLineSpan().StartLinePosition.Line
var diagnostic = invocationLocation.StartLine() == secondaryLocation.StartLine()
? Diagnostic.Create(Rule, invocationLocation)
: Rule.CreateDiagnostic(context.Compilation, invocationLocation, additionalLocations: new[] {secondaryLocation}, properties: null);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2024 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

namespace SonarAnalyzer.CSharp.Styling.Test.Rules;

[TestClass]
public class SeparateDeclarationsTest
{
[TestMethod]
public void SeparateDeclarations() =>
StylingVerifierBuilder.Create<SeparateDeclarations>().AddPaths("SeparateDeclarations.cs").WithConcurrentAnalysis(false).Verify();
}