Skip to content

Commit

Permalink
Razor mappings: Ensure we check if the mapped span is valid (#9305)
Browse files Browse the repository at this point in the history
  • Loading branch information
costin-zaharia-sonarsource authored May 21, 2024
1 parent 1d041d4 commit c225c8e
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions analyzers/src/SonarAnalyzer.Common/Metrics/MetricsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,13 @@ public abstract class MetricsBase
public ISet<int> CodeLines =>
tree.GetRoot()
.DescendantTokens()
.Where(x => !IsEndOfFile(x))
.Select(x => x.GetLocation().GetMappedLineSpan())
.Where(IsInSameFile)
.Select(GetMappedLineSpan)
.Where(x => x is not null)
.SelectMany(
x =>
{
var start = x.StartLinePosition.GetLineNumberToReport();
var end = x.EndLinePosition.GetLineNumberToReport();
var start = x.Value.StartLinePosition.GetLineNumberToReport();
var end = x.Value.EndLinePosition.GetLineNumberToReport();
return Enumerable.Range(start, end - start + 1);
})
.ToHashSet();
Expand Down Expand Up @@ -119,6 +118,14 @@ protected bool IsInSameFile(FileLinePositionSpan span) =>
private IEnumerable<SyntaxNode> FunctionNodes =>
tree.GetRoot().DescendantNodes().Where(IsFunction);

private FileLinePositionSpan? GetMappedLineSpan(SyntaxToken token) =>
!IsEndOfFile(token)
&& token.GetLocation().GetMappedLineSpan() is { IsValid: true } mappedLineSpan
&& (!GeneratedCodeRecognizer.IsRazor(token.SyntaxTree) || mappedLineSpan.HasMappedPath)
&& IsInSameFile(mappedLineSpan)
? mappedLineSpan
: null;

private static void CategorizeLines(string line, int lineNumber, ISet<int> noSonar, ISet<int> nonBlank)
{
if (line.Contains("NOSONAR"))
Expand Down

0 comments on commit c225c8e

Please sign in to comment.