diff --git a/SourceGeneratorToolkit.Test/GeneratorBaseTests.cs b/SourceGeneratorToolkit.Test/GeneratorBaseTests.cs index b6104ee..38ba293 100644 --- a/SourceGeneratorToolkit.Test/GeneratorBaseTests.cs +++ b/SourceGeneratorToolkit.Test/GeneratorBaseTests.cs @@ -8,6 +8,7 @@ namespace ktsu.SourceGeneratorToolkit.Test; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Text; using ktsu.SourceGeneratorToolkit.Testing; [TestClass] @@ -73,6 +74,70 @@ public void AMalformedMetadataFileIsReportedRatherThanSwallowed() Assert.AreEqual(DiagnosticSeverity.Error, result.Diagnostics[0].Severity); } + [TestMethod] + [DataRow("\n", DisplayName = "LF")] + [DataRow("\r\n", DisplayName = "CRLF")] + public void AMalformedMetadataFileIsReportedAtTheBadLine(string newLine) + { + string json = string.Join(newLine, "{", " \"things\":", " [1,,2]", "}"); + + Diagnostic diagnostic = ParseFailure(json); + + FileLinePositionSpan span = diagnostic.Location.GetLineSpan(); + Assert.AreEqual(LocationKind.ExternalFile, diagnostic.Location.Kind); + Assert.AreEqual("things.json", Path.GetFileName(span.Path)); + Assert.AreEqual(2, span.StartLinePosition.Line); + + // System.Text.Json reports the position it had reached, which is the first comma of the pair. + Assert.AreEqual(json.Split('\n')[2].IndexOf(",,", StringComparison.Ordinal), span.StartLinePosition.Character); + } + + [TestMethod] + public void AParseFailureAfterMultiByteCharactersIsLocatedByCharacterNotByte() + { + // "é" is one character and two UTF-8 bytes, and "😀" is two characters (a surrogate pair) and + // four bytes. The ASCII twin has the same characters in the same places, so the two failures + // must land on the same character even though the byte positions differ. + LinePosition multiByte = ParseFailure("{\n \"things\": [\"é😀\",,1]\n}").Location.GetLineSpan().StartLinePosition; + LinePosition ascii = ParseFailure("{\n \"things\": [\"abc\",,1]\n}").Location.GetLineSpan().StartLinePosition; + + Assert.AreEqual(1, multiByte.Line); + Assert.AreEqual(ascii, multiByte); + } + + [TestMethod] + public void AParseFailureAtTheEndOfTheFileIsLocatedAtTheEnd() + { + string json = "{\n \"things\": ["; + + Diagnostic diagnostic = ParseFailure(json); + + FileLinePositionSpan span = diagnostic.Location.GetLineSpan(); + Assert.AreEqual("things.json", Path.GetFileName(span.Path)); + Assert.AreEqual(1, span.StartLinePosition.Line); + Assert.IsLessThanOrEqualTo(json.Split('\n')[1].Length, span.StartLinePosition.Character); + } + + [TestMethod] + public void AShapeFailureWithNoPositionIsStillReportedWithoutALocation() + { + GeneratorRunResult result = Harness.Run(new UnsupportedShapeGenerator()); + + Assert.AreEqual(1, result.Diagnostics.Length); + Assert.AreEqual(Location.None, result.Diagnostics[0].Location); + } + + private static Diagnostic ParseFailure(string json) + { + GeneratorRunResult result = Harness.Run( + new ThingsGenerator(), + new Dictionary { ["things.json"] = json }); + + Assert.AreEqual(1, result.Diagnostics.Length); + Assert.AreEqual(TestDiagnostics.MetadataParseFailed.Id, result.Diagnostics[0].Id); + return result.Diagnostics[0]; + } + [TestMethod] public void AMalformedSecondMetadataFileIsAlsoReported() { diff --git a/SourceGeneratorToolkit/MetadataFile.cs b/SourceGeneratorToolkit/MetadataFile.cs index f263e9f..02ccee2 100644 --- a/SourceGeneratorToolkit/MetadataFile.cs +++ b/SourceGeneratorToolkit/MetadataFile.cs @@ -164,7 +164,8 @@ public Location FindLocation(string anchor, string needle) } catch (JsonException ex) { - return ParseFailed(ex); + context.ReportAt(parseFailed, LocationOf(ex), FileName, ex.Message); + return null; } catch (NotSupportedException ex) { @@ -194,6 +195,85 @@ public Location FindLocation(string anchor, string needle) } } + /// + /// Finds where in the file a says the JSON went wrong. + /// + /// The exception thrown while reading the file. + /// + /// A location covering the character at the reported position, or + /// when the exception carries no position or there is no source text to locate it in. + /// + /// + /// counts \n line feeds from zero, and + /// counts UTF-8 bytes rather than characters, so + /// the position is walked through the line a character at a time. It is clamped to the line, so + /// a position past its end points at the end of the line. + /// + private Location LocationOf(JsonException ex) + { + if (sourceText is null || ex.LineNumber is not long lineNumber || lineNumber < 0) + { + return Location.None; + } + + int index = LineStart(lineNumber); + if (index < 0) + { + return Location.None; + } + + long bytes = ex.BytePositionInLine ?? 0; + while (bytes > 0 && index < Text.Length && Text[index] is not '\r' and not '\n') + { + int width = CharactersAt(index); + bytes -= Utf8Bytes(index, width); + index += width; + } + + int length = index < Text.Length && Text[index] is not '\r' and not '\n' ? 1 : 0; + return LocationAt(index, length); + } + + /// + /// Finds where a line starts, counting lines by \n line feeds as System.Text.Json does. + /// + /// The zero-based line number. + /// The offset of the line's first character, or -1 when the file has fewer lines. + private int LineStart(long lineNumber) + { + int index = 0; + for (long line = 0; line < lineNumber && index >= 0; line++) + { + int lineFeed = Text.IndexOf('\n', index); + index = lineFeed < 0 ? -1 : lineFeed + 1; + } + + return index; + } + + /// + /// Counts the characters that make up the code point at an offset: two for a surrogate pair, + /// otherwise one. + /// + /// The offset of the code point's first character. + /// The number of characters in the code point. + private int CharactersAt(int index) => + char.IsHighSurrogate(Text[index]) && index + 1 < Text.Length && char.IsLowSurrogate(Text[index + 1]) ? 2 : 1; + + /// + /// Counts the bytes UTF-8 uses for the code point at an offset. + /// + /// The offset of the code point's first character. + /// The number of characters in the code point. + /// The code point's length in UTF-8. + private int Utf8Bytes(int index, int characters) => + characters == 2 ? 4 : Text[index] switch + { + < '\u0080' => 1, + < '\u0800' => 2, + _ => 3, + }; + private Location LocationAt(int index, int length) { TextSpan span = new(index, length);