|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of Railt package. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
declare(strict_types=1); |
|
9
|
|
|
|
|
10
|
|
|
namespace Railt\Lexer\Driver; |
|
11
|
|
|
|
|
12
|
|
|
use Railt\Lexer\Definition\MultistateTokenDefinition; |
|
13
|
|
|
use Railt\Lexer\MultistateLexerInterface; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class MultistateLexer |
|
17
|
|
|
*/ |
|
18
|
|
|
abstract class MultistateLexer extends SimpleLexer implements MultistateLexerInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var int |
|
22
|
|
|
*/ |
|
23
|
|
|
protected const DEFAULT_STATE = 0x00; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var array|int[] |
|
27
|
|
|
*/ |
|
28
|
|
|
protected $states = []; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var array|int[] |
|
32
|
|
|
*/ |
|
33
|
|
|
protected $transitions = []; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param string $token |
|
37
|
|
|
* @param int $state |
|
38
|
|
|
* @param int|null $nextState |
|
39
|
|
|
* @return MultistateLexerInterface |
|
40
|
|
|
*/ |
|
41
|
|
|
public function state(string $token, int $state, int $nextState = null): MultistateLexerInterface |
|
42
|
|
|
{ |
|
43
|
|
|
$this->states[$token] = $state; |
|
44
|
|
|
|
|
45
|
|
|
if ($nextState !== null) { |
|
46
|
|
|
$this->transitions[$token] = $nextState; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return $this; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @return iterable |
|
54
|
|
|
*/ |
|
55
|
|
|
public function getTokenDefinitions(): iterable |
|
56
|
|
|
{ |
|
57
|
|
|
foreach ($this->tokens as $name => $pcre) { |
|
58
|
|
|
$keep = ! \in_array($name, $this->skipped, true); |
|
59
|
|
|
$state = $this->getTokenState($name); |
|
60
|
|
|
$next = $this->getNextState($name); |
|
61
|
|
|
|
|
62
|
|
|
yield new MultistateTokenDefinition($name, $pcre, $keep, $state, $next); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @param string $token |
|
68
|
|
|
* @return int |
|
69
|
|
|
*/ |
|
70
|
|
|
protected function getTokenState(string $token): int |
|
71
|
|
|
{ |
|
72
|
|
|
return $this->states[$token] ?? static::DEFAULT_STATE; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @param string $token |
|
77
|
|
|
* @return int |
|
78
|
|
|
*/ |
|
79
|
|
|
protected function getNextState(string $token): int |
|
80
|
|
|
{ |
|
81
|
|
|
return $this->transitions[$this->getTokenState($token)] ?? static::DEFAULT_STATE; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|