1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Remorhaz\UniLex\Parser\LL1\Lookup; |
6
|
|
|
|
7
|
|
|
abstract class Set |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var array |
11
|
|
|
*/ |
12
|
|
|
private $tokenMap = []; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* This counter increases each time changes are made to set. |
16
|
|
|
* |
17
|
|
|
* @var int |
18
|
|
|
*/ |
19
|
|
|
private $changeCount = 0; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Adds list of tokens to the set. |
23
|
|
|
* |
24
|
|
|
* @param int $symbolId |
25
|
|
|
* @param int ...$tokenIdList |
26
|
|
|
*/ |
27
|
|
|
public function addToken(int $symbolId, int ...$tokenIdList): void |
28
|
|
|
{ |
29
|
|
|
if (empty($tokenIdList)) { |
30
|
|
|
return; |
31
|
|
|
} |
32
|
|
|
if (!isset($this->tokenMap[$symbolId])) { |
33
|
|
|
$this->tokenMap[$symbolId] = $tokenIdList; |
34
|
|
|
$this->increaseChangeCount(count($tokenIdList)); |
35
|
|
|
return; |
36
|
|
|
} |
37
|
|
|
$newTokenIdList = array_diff($tokenIdList, $this->tokenMap[$symbolId]); |
38
|
|
|
if (empty($newTokenIdList)) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
$this->tokenMap[$symbolId] = array_merge($this->tokenMap[$symbolId], $newTokenIdList); |
42
|
|
|
$this->increaseChangeCount(count($newTokenIdList)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function increaseChangeCount(int $amount = 1): void |
46
|
|
|
{ |
47
|
|
|
$this->changeCount += $amount; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function getTokens(int $symbolId): array |
51
|
|
|
{ |
52
|
|
|
return $this->tokenMap[$symbolId] ?? []; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Returns amount of changes since last reset. |
57
|
|
|
* |
58
|
|
|
* @return int |
59
|
|
|
*/ |
60
|
|
|
public function getChangeCount(): int |
61
|
|
|
{ |
62
|
|
|
return $this->changeCount; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Resets changes counter. |
67
|
|
|
*/ |
68
|
|
|
public function resetChangeCount(): void |
69
|
|
|
{ |
70
|
|
|
$this->changeCount = 0; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Merges token sets. |
75
|
|
|
* |
76
|
|
|
* @param int $targetSymbolId |
77
|
|
|
* @param int $sourceSymbolId |
78
|
|
|
*/ |
79
|
|
|
public function mergeTokens(int $targetSymbolId, int $sourceSymbolId): void |
80
|
|
|
{ |
81
|
|
|
$this->addToken($targetSymbolId, ...$this->getTokens($sourceSymbolId)); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|