Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions SourceGeneratorToolkit.Test/GeneratorBaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using ktsu.SourceGeneratorToolkit.Testing;

[TestClass]
Expand Down Expand Up @@ -73,6 +74,70 @@
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);

Check warning on line 126 in SourceGeneratorToolkit.Test/GeneratorBaseTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.HasCount' instead of 'Assert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_SourceGeneratorToolkit&issues=AaFY577VtBF26-B4JqEy&open=AaFY577VtBF26-B4JqEy&pullRequest=51
Assert.AreEqual(Location.None, result.Diagnostics[0].Location);
}

private static Diagnostic ParseFailure(string json)
{
GeneratorRunResult result = Harness.Run(
new ThingsGenerator(),
new Dictionary<string, string> { ["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()
{
Expand Down
82 changes: 81 additions & 1 deletion SourceGeneratorToolkit/MetadataFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -194,6 +195,85 @@ public Location FindLocation(string anchor, string needle)
}
}

/// <summary>
/// Finds where in the file a <see cref="JsonException"/> says the JSON went wrong.
/// </summary>
/// <param name="ex">The exception thrown while reading the file.</param>
/// <returns>
/// A location covering the character at the reported position, or <see cref="Location.None"/>
/// when the exception carries no position or there is no source text to locate it in.
/// </returns>
/// <remarks>
/// <see cref="JsonException.LineNumber"/> counts <c>\n</c> line feeds from zero, and
/// <see cref="JsonException.BytePositionInLine"/> 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.
/// </remarks>
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);
}

/// <summary>
/// Finds where a line starts, counting lines by <c>\n</c> line feeds as System.Text.Json does.
/// </summary>
/// <param name="lineNumber">The zero-based line number.</param>
/// <returns>The offset of the line's first character, or -1 when the file has fewer lines.</returns>
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;
}

/// <summary>
/// Counts the characters that make up the code point at an offset: two for a surrogate pair,
/// otherwise one.
/// </summary>
/// <param name="index">The offset of the code point's first character.</param>
/// <returns>The number of characters in the code point.</returns>
private int CharactersAt(int index) =>
char.IsHighSurrogate(Text[index]) && index + 1 < Text.Length && char.IsLowSurrogate(Text[index + 1]) ? 2 : 1;

/// <summary>
/// Counts the bytes UTF-8 uses for the code point at an offset.
/// </summary>
/// <param name="index">The offset of the code point's first character.</param>
/// <param name="characters">The number of characters in the code point.</param>
/// <returns>The code point's length in UTF-8.</returns>
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);
Expand Down
Loading