1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Remorhaz\Lexer\Runtime\IO; |
6
|
|
|
|
7
|
|
|
use function array_key_last; |
8
|
|
|
use function array_reduce; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @psalm-immutable |
12
|
|
|
*/ |
13
|
|
|
final class Lexeme implements LexemeInterface |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var SymbolInterface[] |
18
|
|
|
* @psalm-var array<int, SymbolInterface> |
19
|
|
|
*/ |
20
|
|
|
private $symbols; |
21
|
|
|
|
22
|
5 |
|
public function __construct(SymbolInterface ...$symbols) |
23
|
|
|
{ |
24
|
5 |
|
if (empty($symbols)) { |
25
|
1 |
|
throw new Exception\EmptyLexemeException(); |
26
|
|
|
} |
27
|
4 |
|
$this->symbols = $symbols; |
28
|
4 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @return SymbolInterface[] |
32
|
|
|
* @psalm-return array<int, SymbolInterface> |
33
|
|
|
* @psalm-pure |
34
|
|
|
*/ |
35
|
2 |
|
public function getSymbols(): array |
36
|
|
|
{ |
37
|
2 |
|
return $this->symbols; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return int[] |
42
|
|
|
* @psalm-return array<int, int> |
43
|
|
|
* @psalm-pure |
44
|
|
|
*/ |
45
|
1 |
|
public function getStartOffsets(): array |
46
|
|
|
{ |
47
|
|
|
return $this |
48
|
1 |
|
->symbols[0] |
49
|
1 |
|
->getLexeme() |
50
|
1 |
|
->getStartOffsets(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return int[] |
55
|
|
|
* @psalm-return array<int,int> |
56
|
|
|
* @psalm-pure |
57
|
|
|
*/ |
58
|
1 |
|
public function getFinishOffsets(): array |
59
|
|
|
{ |
60
|
|
|
/** @var int $index */ |
61
|
1 |
|
$index = array_key_last($this->symbols); |
62
|
|
|
|
63
|
|
|
return $this |
64
|
1 |
|
->symbols[$index] |
65
|
1 |
|
->getLexeme() |
66
|
1 |
|
->getFinishOffsets(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return LexemeInterface |
71
|
|
|
* @psalm-pure |
72
|
|
|
*/ |
73
|
1 |
|
public function getConstituentLexeme(): LexemeInterface |
74
|
|
|
{ |
75
|
1 |
|
return new Lexeme(...array_reduce($this->symbols, [$this, 'appendConstituentSymbols'], [])); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param SymbolInterface[] $buffer |
80
|
|
|
* @psalm-param array<int,SymbolInterface> $buffer |
81
|
|
|
* @param SymbolInterface $symbol |
82
|
|
|
* @return SymbolInterface[] |
83
|
|
|
* @psalm-return array<int,SymbolInterface> |
84
|
|
|
*/ |
85
|
1 |
|
private function appendConstituentSymbols(array $buffer, SymbolInterface $symbol): array |
86
|
|
|
{ |
87
|
1 |
|
return array_merge($buffer, $symbol->getLexeme()->getConstituentLexeme()->getSymbols()); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|