Skip to content

Commit

Permalink
TokenStream: refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Apr 28, 2024
1 parent 26a9691 commit 93c34a4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
6 changes: 6 additions & 0 deletions src/Neon/Token.php
Expand Up @@ -27,4 +27,10 @@ public function __construct(
public string $text,
) {
}


public function is(int|string ...$kind): bool
{
return in_array($this->type, $kind, strict: true);
}
}
18 changes: 12 additions & 6 deletions src/Neon/TokenStream.php
Expand Up @@ -35,21 +35,27 @@ public function seek(int $index): void
}


public function is(int|string ...$types): bool
/**
* Tells whether the token at current position is of given kind.
*/
public function is(int|string ...$kind): bool
{
while (in_array($this->tokens[$this->index]->type, [Token::Comment, Token::Whitespace], strict: true)) {
while ($this->tokens[$this->index]->is(Token::Comment, Token::Whitespace)) {
$this->index++;
}

return $types
? in_array($this->tokens[$this->index]->type, $types, strict: true)
return $kind
? $this->tokens[$this->index]->is(...$kind)
: $this->tokens[$this->index]->type !== Token::End;
}


public function tryConsume(int|string ...$types): ?Token
/**
* Consumes the current token of given kind or returns null.
*/
public function tryConsume(int|string ...$kind): ?Token
{
return $this->is(...$types)
return $this->is(...$kind)
? $this->tokens[$this->index++]
: null;
}
Expand Down

0 comments on commit 93c34a4

Please sign in to comment.