|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Remorhaz\Lexer\Runtime\Token; |
|
6
|
|
|
|
|
7
|
|
|
use Iterator; |
|
8
|
|
|
use IteratorAggregate; |
|
9
|
|
|
use Remorhaz\Lexer\Runtime\IO\Exception; |
|
10
|
|
|
use Remorhaz\Lexer\Runtime\IO\LexemeInterface; |
|
11
|
|
|
use Remorhaz\Lexer\Runtime\IO\Symbol; |
|
12
|
|
|
use Remorhaz\Lexer\Runtime\IO\SymbolInterface; |
|
13
|
|
|
use Remorhaz\Lexer\Runtime\IO\SymbolReaderInterface; |
|
14
|
|
|
use Throwable; |
|
15
|
|
|
|
|
16
|
|
|
final class TokenInput implements IteratorAggregate, SymbolReaderInterface |
|
17
|
|
|
{ |
|
18
|
|
|
|
|
19
|
|
|
public const ATTRIBUTE_SYMBOL_CODE = 'symbol.code'; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var TokenReaderInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
private $tokenReader; |
|
25
|
|
|
|
|
26
|
10 |
|
public function __construct(TokenReaderInterface $tokenReader) |
|
27
|
|
|
{ |
|
28
|
10 |
|
$this->tokenReader = $tokenReader; |
|
29
|
10 |
|
} |
|
30
|
|
|
|
|
31
|
5 |
|
public function read(): SymbolInterface |
|
32
|
|
|
{ |
|
33
|
5 |
|
$token = $this->tokenReader->read(); |
|
34
|
5 |
|
$attribute = $token->getAttributes()->get(self::ATTRIBUTE_SYMBOL_CODE); |
|
35
|
|
|
try { |
|
36
|
5 |
|
return new Symbol($token->getOffset(), $attribute->asInteger(), $token->getLexeme()); |
|
37
|
1 |
|
} catch (Throwable $e) { |
|
38
|
1 |
|
throw new Exception\InvalidSymbolCodeException($attribute, $e); |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return int |
|
44
|
|
|
* @psalm-pure |
|
45
|
|
|
*/ |
|
46
|
3 |
|
public function getOffset(): int |
|
47
|
|
|
{ |
|
48
|
3 |
|
return $this->tokenReader->getOffset(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @return bool |
|
53
|
|
|
* @psalm-pure |
|
54
|
|
|
*/ |
|
55
|
5 |
|
public function isFinished(): bool |
|
56
|
|
|
{ |
|
57
|
5 |
|
return $this->tokenReader->isFinished(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @return LexemeInterface |
|
62
|
|
|
* @psalm-pure |
|
63
|
|
|
*/ |
|
64
|
1 |
|
public function getEmptyLexeme(): LexemeInterface |
|
65
|
|
|
{ |
|
66
|
1 |
|
return $this->tokenReader->getEmptyLexeme(); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @return Iterator |
|
71
|
|
|
* @psalm-return Iterator<int,SymbolInterface> |
|
72
|
|
|
*/ |
|
73
|
3 |
|
public function getIterator(): Iterator |
|
74
|
|
|
{ |
|
75
|
3 |
|
while (!$this->isFinished()) { |
|
76
|
2 |
|
yield $this->getOffset() => $this->read(); |
|
77
|
|
|
} |
|
78
|
3 |
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|