Skip to content

Commit

Permalink
Node: added $start & $end positions (replaces $startLine & $endLine)
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Apr 28, 2024
1 parent 9ba3cef commit 319f77f
Show file tree
Hide file tree
Showing 4 changed files with 711 additions and 283 deletions.
4 changes: 2 additions & 2 deletions src/Neon/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ abstract class Node implements \IteratorAggregate
{
public ?int $startTokenPos = null;
public ?int $endTokenPos = null;
public ?int $startLine = null;
public ?int $endLine = null;
public ?Position $start = null;
public ?Position $end = null;


abstract public function toValue(): mixed;
Expand Down
22 changes: 3 additions & 19 deletions src/Neon/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,10 @@ final class Parser
{
private TokenStream $stream;

/** @var int[] */
private $posToLine = [];


public function parse(TokenStream $stream): Node
{
$this->stream = $stream;
$this->initLines();

while ($this->stream->tryConsume(Token::Newline));
$node = $this->parseBlock($this->stream->getIndentation());
Expand Down Expand Up @@ -240,22 +236,10 @@ private function checkArrayKey(Node $key, array &$arr): void
private function injectPos(Node $node, int $start = null, int $end = null): Node
{
$node->startTokenPos = $start ?? $this->stream->getIndex();
$node->startLine = $this->posToLine[$node->startTokenPos];
$node->start = $this->stream->tokens[$node->startTokenPos]->position;
$node->endTokenPos = $end ?? $node->startTokenPos;
$node->endLine = $this->posToLine[$node->endTokenPos + 1] ?? end($this->posToLine);
$token = $this->stream->tokens[$node->startTokenPos + 1] ?? $this->stream->tokens[$node->startTokenPos];
$node->end = $token->position;
return $node;
}


private function initLines(): void
{
$this->posToLine = [];
$line = 1;
foreach ($this->stream->tokens as $token) {
$this->posToLine[] = $line;
$line += substr_count($token->text, "\n");
}

$this->posToLine[] = $line;
}
}

0 comments on commit 319f77f

Please sign in to comment.