From 6d92dd9e4193f4b35eefa7f712dc83b4129b5b50 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 18 Sep 2024 21:23:30 +1000 Subject: [PATCH] Update LocationConverter.cs --- .../Converters/LocationConverter.cs | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/src/Verify.SourceGenerators/Converters/LocationConverter.cs b/src/Verify.SourceGenerators/Converters/LocationConverter.cs index 7f08bf1..7124e66 100644 --- a/src/Verify.SourceGenerators/Converters/LocationConverter.cs +++ b/src/Verify.SourceGenerators/Converters/LocationConverter.cs @@ -7,31 +7,41 @@ public override void Write(VerifyJsonWriter writer, Location value) { var lineSpan = value.GetMappedLineSpan(); + WriteSourceTree(writer, value, lineSpan); + + writer.Serialize(lineSpan); + } + + static void WriteSourceTree(VerifyJsonWriter writer, Location value, FileLinePositionSpan lineSpan) + { // Pretty-print the error with the source code snippet. - if (value.SourceTree is { } source) + if (value.SourceTree is not { } source) { - var comment = new StringBuilder().AppendLine(); - var lines = source.GetText().Lines; - var startLine = Math.Max(lineSpan.StartLinePosition.Line - contextLines, 0); - var endLine = Math.Min(lineSpan.EndLinePosition.Line + contextLines, lines.Count - 1); - for (var lineIdx = startLine; lineIdx <= endLine; lineIdx++) + return; + } + + var comment = new StringBuilder(); + comment.AppendLine(); + var lines = source.GetText().Lines; + var startLine = Math.Max(lineSpan.StartLinePosition.Line - contextLines, 0); + var endLine = Math.Min(lineSpan.EndLinePosition.Line + contextLines, lines.Count - 1); + for (var index = startLine; index <= endLine; index++) + { + var line = lines[index]; + // print the source line + comment.AppendLine(line.ToString()); + // print squiggly line highlighting the location + if (line.Span.Intersection(value.SourceSpan) is not { } intersection) { - var line = lines[lineIdx]; - // print the source line - comment.AppendLine(line.ToString()); - // print squiggly line highlighting the location - if (line.Span.Intersection(value.SourceSpan) is { } intersection) - { - comment - .Append(' ', intersection.Start - line.Start) - .Append('^', intersection.Length) - .AppendLine(); - } + continue; } - writer.WriteComment(comment.ToString()); - writer.WriteWhitespace("\n"); + + comment.Append(' ', intersection.Start - line.Start); + comment.Append('^', intersection.Length); + comment.AppendLine(); } - writer.Serialize(lineSpan); + writer.WriteComment(comment.ToString()); + writer.WriteWhitespace("\n"); } -} +} \ No newline at end of file