Show text line in error messages

This commit is contained in:
Deukhoofd 2018-11-17 14:20:43 +01:00
parent c013ed38c6
commit 0f45660a43
No known key found for this signature in database
GPG Key ID: B4C087AC81641654
4 changed files with 60 additions and 1 deletions

View File

@ -83,7 +83,14 @@ namespace Upsilon
public override string ToString() public override string ToString()
{ {
return $"{Message} at {Span.Start}\n{Diagnostics.ScriptString.GetSpan(Span)}"; var linePos = Diagnostics.ScriptString.GetLinePosition(Span.Start);
return $"{Message} at ({linePos.Line}, {linePos.Pos})\n{Diagnostics.ScriptString.GetSpan(Span)}";
}
public string GetDiagnosticPosition()
{
var linePos = Diagnostics.ScriptString.GetLinePosition(Span.Start);
return $"({linePos.Line},{linePos.Pos})";
} }
public string BeforeError(int i = 5) public string BeforeError(int i = 5)

View File

@ -5,10 +5,20 @@ namespace Upsilon.Text
public class SourceText public class SourceText
{ {
private readonly string _text; private readonly string _text;
private readonly SourceTextLine[] _lines;
public SourceText(string text) public SourceText(string text)
{ {
_text = text; _text = text;
var lines = text.Split('\n');
_lines = new SourceTextLine[lines.Length];
var linePos = 0;
for (var index = 0; index < lines.Length; index++)
{
var line = lines[index];
_lines[index] = new SourceTextLine(linePos, line.Length);
linePos += line.Length;
}
} }
public string GetSpan(int start, int length) public string GetSpan(int start, int length)
@ -24,6 +34,32 @@ namespace Upsilon.Text
return _text.Substring(start, length); return _text.Substring(start, length);
} }
public (int Line, int Pos) GetLinePosition(int spanPos)
{
var min = 0;
var max = _lines.Length - 1;
while (min <= max)
{
var mid = (min + max) / 2 ;
var midLine = _lines[mid];
if (midLine.Start <= spanPos && midLine.End > spanPos)
{
var pos = spanPos - midLine.Start;
return (mid, pos);
}
if (spanPos >= midLine.End)
{
min = mid + 1;
}
else if (spanPos < midLine.Start)
{
max = mid - 1;
}
}
var newPos = spanPos - _lines[min].Start;
return (min, newPos);
}
public string GetSpan(TextSpan span) public string GetSpan(TextSpan span)
{ {
return GetSpan(span.Start, span.Length); return GetSpan(span.Start, span.Length);

View File

@ -0,0 +1,15 @@
namespace Upsilon.Text
{
public struct SourceTextLine
{
public SourceTextLine(int start, int lineLength)
{
Start = start;
LineLength = lineLength;
}
public int Start { get; }
public int LineLength { get; }
public int End => Start + LineLength;
}
}

View File

@ -65,6 +65,7 @@ namespace Ycicle
Console.WriteLine(message.Message); Console.WriteLine(message.Message);
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(message.GetDiagnosticPosition() + " ");
Console.Write(message.BeforeError()); Console.Write(message.BeforeError());
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;