1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Remorhaz\UniLex\RegExp\FSM; |
6
|
|
|
|
7
|
|
|
use Remorhaz\IntRangeSets\RangeSetInterface; |
8
|
|
|
use Remorhaz\UniLex\Exception; |
9
|
|
|
|
10
|
|
|
class SymbolTable |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var RangeSetInterface[] |
14
|
|
|
*/ |
15
|
|
|
private $rangeSetList = []; |
16
|
|
|
|
17
|
|
|
private $nextSymbol = 0; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param RangeSetInterface $rangeSet |
21
|
|
|
* @return int |
22
|
|
|
*/ |
23
|
|
|
public function addSymbol(RangeSetInterface $rangeSet): int |
24
|
|
|
{ |
25
|
|
|
$symbolId = $this->nextSymbol++; |
26
|
|
|
$this->rangeSetList[$symbolId] = $rangeSet; |
27
|
|
|
return $symbolId; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param int $symbolId |
32
|
|
|
* @param RangeSetInterface $rangeSet |
33
|
|
|
* @throws Exception |
34
|
|
|
*/ |
35
|
|
|
public function importSymbol(int $symbolId, RangeSetInterface $rangeSet): void |
36
|
|
|
{ |
37
|
|
|
if (isset($this->rangeSetList[$symbolId])) { |
38
|
|
|
throw new Exception("Symbol {$symbolId} already defined in symbol table"); |
39
|
|
|
} |
40
|
|
|
$this->rangeSetList[$symbolId] = $rangeSet; |
41
|
|
|
$this->nextSymbol = max(array_keys($this->rangeSetList)); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param int $symbolId |
46
|
|
|
* @param RangeSetInterface $rangeSet |
47
|
|
|
* @return SymbolTable |
48
|
|
|
* @throws Exception |
49
|
|
|
*/ |
50
|
|
|
public function replaceSymbol(int $symbolId, RangeSetInterface $rangeSet): self |
51
|
|
|
{ |
52
|
|
|
if (!isset($this->rangeSetList[$symbolId])) { |
53
|
|
|
throw new Exception("Symbol {$symbolId} is not defined in symbol table"); |
54
|
|
|
} |
55
|
|
|
$this->rangeSetList[$symbolId] = $rangeSet; |
56
|
|
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param int $symbolId |
61
|
|
|
* @return RangeSetInterface |
62
|
|
|
* @throws Exception |
63
|
|
|
*/ |
64
|
|
|
public function getRangeSet(int $symbolId): RangeSetInterface |
65
|
|
|
{ |
66
|
|
|
if (!isset($this->rangeSetList[$symbolId])) { |
67
|
|
|
throw new Exception("Symbol {$symbolId} is not defined in symbol table"); |
68
|
|
|
} |
69
|
|
|
return $this->rangeSetList[$symbolId]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return RangeSetInterface[] |
74
|
|
|
*/ |
75
|
|
|
public function getRangeSetList(): array |
76
|
|
|
{ |
77
|
|
|
return $this->rangeSetList; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return int[] |
82
|
|
|
*/ |
83
|
|
|
public function getSymbolList(): array |
84
|
|
|
{ |
85
|
|
|
return array_keys($this->rangeSetList); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|