Skip to content

Commit

Permalink
MA0051 exclude local functions's trivia when skipping local functions (
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou authored Jul 27, 2023
1 parent 37c14b6 commit a888667
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
31 changes: 28 additions & 3 deletions src/Meziantou.Analyzer/Rules/MethodShouldNotBeTooLongAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,37 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context, SyntaxNode? n
var localFunctions = node.DescendantNodes(node => !node.IsKind(SyntaxKind.LocalFunctionStatement)).Where(node => node.IsKind(SyntaxKind.LocalFunctionStatement));
foreach (var localFunction in localFunctions)
{
var functionLocation = localFunction.GetLocation().GetLineSpan();
lines -= functionLocation.EndLinePosition.Line - functionLocation.StartLinePosition.Line;
var firstLine = -1;
var lastLine = -1;

if (localFunction.HasLeadingTrivia)
{
firstLine = localFunction.GetLeadingTrivia()[0].GetLocation().GetLineSpan().StartLinePosition.Line;
}

if (localFunction.HasTrailingTrivia)
{
lastLine = localFunction.GetTrailingTrivia()[^1].GetLocation().GetLineSpan().EndLinePosition.Line;
}

if (firstLine < 0 || lastLine < 0)
{
var functionLocation = localFunction.GetLocation().GetLineSpan();
if (firstLine < 0)
{
firstLine = functionLocation.StartLinePosition.Line;
}

if (lastLine < 0)
{
lastLine = functionLocation.EndLinePosition.Line;
}
}

lines -= lastLine - firstLine;
}
}


if (lines > maximumLines)
{
context.ReportDiagnostic(s_rule, reportNode, $"{lines} lines; maximum allowed: {maximumLines}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ await CreateProjectBuilder()
}

[Fact]
public async Task TooLong_SkipLocalFunction()
public async Task TooLong_SkipLocalFunction_False()
{
const string SourceCode = @"
public class Test
Expand All @@ -100,6 +100,7 @@ public class Test
var a = 0;
var b = 0;
var c = 0;
void A()
{
void B() { }
Expand All @@ -114,7 +115,7 @@ await CreateProjectBuilder()
}

[Fact]
public async Task ValidMethod_SkipLocalFunction()
public async Task ValidMethod_SkipLocalFunction_True()
{
const string SourceCode = @"
public class Test
Expand All @@ -124,6 +125,7 @@ void Method()
var a = 0;
var b = 0;
var c = 0;
void A()
{
void B() { }
Expand All @@ -136,7 +138,7 @@ await CreateProjectBuilder()
.AddAnalyzerConfiguration("MA0051.skip_local_functions", "true")
.ValidateAsync();
}

[Fact]
public async Task ValidMethod_Statements_SkipLocalFunction()
{
Expand Down

0 comments on commit a888667

Please sign in to comment.