Skip to content

Commit 8fd2fd4

Browse files
committed
Compute token offsets once instead of rescanning from the first token
1 parent 2122125 commit 8fd2fd4

2 files changed

Lines changed: 28 additions & 4 deletions

File tree

‎src/Parser/TokenIterator.php‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ class TokenIterator
3131

3232
private ?string $newline = null;
3333

34+
/** @var list<int>|null */
35+
private ?array $offsets = null;
36+
3437
/**
3538
* @param list<array{string, int, int}> $tokens
3639
*/
@@ -81,12 +84,16 @@ public function currentTokenType(): int
8184

8285
public function currentTokenOffset(): int
8386
{
84-
$offset = 0;
85-
for ($i = 0; $i < $this->index; $i++) {
86-
$offset += strlen($this->tokens[$i][Lexer::VALUE_OFFSET]);
87+
if ($this->offsets === null) {
88+
$offset = 0;
89+
$this->offsets = [];
90+
foreach ($this->tokens as $token) {
91+
$this->offsets[] = $offset;
92+
$offset += strlen($token[Lexer::VALUE_OFFSET]);
93+
}
8794
}
8895

89-
return $offset;
96+
return $this->offsets[$this->index];
9097
}
9198

9299
public function currentTokenLine(): int

‎tests/PHPStan/Parser/TokenIteratorTest.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use PHPStan\PhpDocParser\Lexer\Lexer;
66
use PHPStan\PhpDocParser\ParserConfig;
77
use PHPUnit\Framework\TestCase;
8+
use function strlen;
9+
use function substr;
810
use const PHP_EOL;
911

1012
class TokenIteratorTest extends TestCase
@@ -57,4 +59,19 @@ public function testGetDetectedNewline(string $phpDoc, ?string $expectedNewline)
5759
$this->assertSame($expectedNewline, $tokens->getDetectedNewline());
5860
}
5961

62+
public function testCurrentTokenOffset(): void
63+
{
64+
$lexer = new Lexer(new ParserConfig([]));
65+
$phpDoc = "/**\n * @param array{size?: 'sm'|'md', icon: Icon} \$a\n */";
66+
$tokens = new TokenIterator($lexer->tokenize($phpDoc));
67+
68+
do {
69+
$this->assertSame($tokens->currentTokenValue(), substr($phpDoc, $tokens->currentTokenOffset(), strlen($tokens->currentTokenValue())));
70+
$this->assertSame(strlen($tokens->getContentBetween(0, $tokens->currentTokenIndex())), $tokens->currentTokenOffset());
71+
$tokens->next();
72+
} while (!$tokens->isCurrentTokenType(Lexer::TOKEN_END));
73+
74+
$this->assertSame(strlen($phpDoc), $tokens->currentTokenOffset());
75+
}
76+
6077
}

0 commit comments

Comments
 (0)