Skip to content

Commit 6912073

Browse files
committed
Include context in parse errors
1 parent 6a97e05 commit 6912073

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/ParserAbstract.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,10 +380,21 @@ protected function getErrorMessage(int $symbol, int $state, int $line): string
380380
{
381381
$expectedString = '';
382382
if ($expected = $this->getExpectedTokens($state)) {
383-
$expectedString = ': Expecting ' . implode(', ', $expected);
383+
$expectedString = ' Expecting ' . implode(', ', $expected);
384384
}
385385

386-
return "Parse error on line {$line}{$expectedString}, got {$this->symbolToName[$symbol]}";
386+
// get up to 22 chars of context starting 3 tokens before error
387+
$startPos = max(0, $this->tokenPos - 3);
388+
$context = '';
389+
for ($pos = $startPos; $pos <= $this->tokenPos; $pos++) {
390+
$context .= $this->tokens[$pos]->text;
391+
}
392+
if (strlen($context) > 22) {
393+
$context = '...' . substr($context, -22);
394+
}
395+
$context = str_replace(["\r\n", "\n"], '', $context);
396+
397+
return "Parse error on line {$line}: {$context}{$expectedString}, got {$this->symbolToName[$symbol]}";
387398
}
388399

389400
private function getNodeError(string $message, Node $node): string

tests/ParserTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,18 @@ public function testParse(): void
3131
$this->assertSame(file_get_contents('tests/test1.json'), $actual);
3232
}
3333

34+
public function testException(): void
35+
{
36+
try {
37+
$parser = (new ParserFactory())->create();
38+
$parser->parse("some\nlong\ncontext\n{{{foo}}");
39+
$this->fail('Failed to throw exception for invalid template');
40+
} catch (\Exception $e) {
41+
$expected = 'Parse error on line 4: ...longcontext{{{foo}} Expecting CLOSE_UNESCAPED, got CLOSE';
42+
$this->assertSame($expected, $e->getMessage());
43+
}
44+
}
45+
3446
/**
3547
* @return \Generator<array{0: SpecArr}>
3648
*/

0 commit comments

Comments
 (0)