Skip to content

Fix ArgumentOutOfRangeException in GetContextualMessage for empty source #615 - #616

Merged
b3b00 merged 1 commit into
b3b00:devfrom
meichenberger78:me/#615
Aug 28, 2026
Merged

Fix ArgumentOutOfRangeException in GetContextualMessage for empty source #615#616
b3b00 merged 1 commit into
b3b00:devfrom
meichenberger78:me/#615

Conversation

@meichenberger78

Copy link
Copy Markdown
Contributor

Fixes #615

Problem

GetContextualMessage threw an ArgumentOutOfRangeException when the parsed source was empty, because the requested line index was out of range for the lines produced by GetLines().

       protected string GetContextualMessage(string fullSource, int line, int column, string message)
       {
           StringBuilder sb = new StringBuilder();
           sb.AppendLine(ErrorMessage);
           var theLine = fullSource.GetLines()[line];
           var tab = " ".Multiply(line.ToString().Length);
           sb.Append(tab).AppendLine(" |");
           sb.Append(line).Append(" |").AppendLine(theLine);
           sb.Append($"{tab} |").Append(" ".Multiply(column)).Append("^^^").AppendLine($" {message}");
           
           return sb.ToString();
      }

https://github.com/b3b00/csly/blob/dev/src/sly/parser/parser/ParseError.cs#L56

Fix

Added a bounds check before indexing into lines, falling back to an empty string when the line index is out of range.

      protected string GetContextualMessage(string fullSource, int line, int column, string message)
      {
          StringBuilder sb = new StringBuilder();
          sb.AppendLine(ErrorMessage);
          var lines = (fullSource ?? string.Empty).GetLines();
          var theLine = line >= 0 && line < lines.Count ? lines[line] : string.Empty;
          var tab = " ".Multiply(line.ToString().Length);
          sb.Append(tab).AppendLine(" |");
          sb.Append(line).Append(" |").AppendLine(theLine);
          sb.Append($"{tab} |").Append(" ".Multiply(column)).Append("^^^").AppendLine($" {message}");
          
          return sb.ToString();
      }

Testing

Added TestContextualErrorWithEmptySource, which parses an empty string and asserts that no exception is thrown and that a valid 4-line ContextualErrorMessage is produced.

@codesandbox

codesandbox Bot commented Aug 20, 2026

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

@sonarqubecloud

Copy link
Copy Markdown

@b3b00
b3b00 merged commit 39f1481 into b3b00:dev Aug 28, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ArgumentOutOfRangeException in GetContextualMessage when source is empty

2 participants