Skip to content

Commit

Permalink
[TASK] Add more context to exceptions
Browse files Browse the repository at this point in the history
* enhances `UnrecognizedToken` exception, see hoaproject#111
* enhances `UnexpectedToken` exception, see hoaproject#112

Fixes: hoaproject#111, hoaproject#112
  • Loading branch information
ohader committed Oct 6, 2020
1 parent 694a7fd commit 7b8ec32
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
17 changes: 14 additions & 3 deletions Llk/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,25 @@ public function lexMe($text, array $tokens)
$nextToken = $this->nextToken($offset);

if (null === $nextToken) {
$line = 1;
$column = $offset;
$offsetText = substr($text, 0, $offset);
$pointerSpacing = mb_strlen($offsetText);
$previousLineBreak = strrpos($offsetText, "\n");
if ($previousLineBreak !== false) {
$line = substr_count($offsetText, "\n") + 1;
$column = mb_strlen($offsetText) - $previousLineBreak - 1;
$pointerSpacing = $column;
}
throw new Compiler\Exception\UnrecognizedToken(
'Unrecognized token "%s" at line 1 and column %d:' .
'Unrecognized token "%s" at line %d and column %d:' .
"\n" . '%s' . "\n" .
str_repeat(' ', mb_strlen(substr($text, 0, $offset))) . '',
str_repeat(' ', $pointerSpacing) . '',
0,
[
mb_substr(substr($text, $offset), 0, 1),
$offset + 1,
$line,
$column + 1,
$text
],
1,
Expand Down
3 changes: 2 additions & 1 deletion Llk/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,12 @@ public function parse($text, $rule = null, $tree = true)
}

throw new Compiler\Exception\UnexpectedToken(
'Unexpected token "%s" (%s) at line %d and column %d:' .
'Unexpected token "%s" (%s:%s) at line %d and column %d:' .
"\n" . '%s' . "\n" . str_repeat(' ', $column - 1) . '',
0,
[
$token['value'],
$token['namespace'],
$token['token'],
$line,
$column,
Expand Down

0 comments on commit 7b8ec32

Please sign in to comment.