|
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\Compiler\Grammar\PP2; |
|
11
|
|
|
|
|
12
|
|
|
use Railt\Compiler\Reader\Result; |
|
13
|
|
|
use Railt\Io\Readable; |
|
14
|
|
|
use Railt\Lexer\TokenInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class Parser |
|
18
|
|
|
*/ |
|
19
|
|
|
class Parser |
|
20
|
|
|
{ |
|
21
|
|
|
private const STATE_CONFIGURE = 0x00; |
|
22
|
|
|
private const STATE_TOKEN = 0x01; |
|
23
|
|
|
private const STATE_PRODUCTIONS = 0x02; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var array|ResolverInterface[] |
|
27
|
|
|
*/ |
|
28
|
|
|
private $resolvers; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Parser constructor. |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct() |
|
34
|
|
|
{ |
|
35
|
|
|
$tokens = new TokenResolver(); |
|
36
|
|
|
$pragmas = new PragmaResolver(); |
|
37
|
|
|
$rules = new RuleResolver($tokens); |
|
38
|
|
|
|
|
39
|
|
|
$this->resolvers = [ |
|
40
|
|
|
self::STATE_TOKEN => $tokens, |
|
41
|
|
|
self::STATE_CONFIGURE => $pragmas, |
|
42
|
|
|
self::STATE_PRODUCTIONS => $rules, |
|
43
|
|
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @param Readable $file |
|
48
|
|
|
* @param TokenInterface $token |
|
49
|
|
|
*/ |
|
50
|
|
|
public function process(Readable $file, TokenInterface $token): void |
|
51
|
|
|
{ |
|
52
|
|
|
$this->resolvers[$this->getState($token)]->resolve($file, $token); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @param TokenInterface $token |
|
57
|
|
|
* @return int |
|
58
|
|
|
*/ |
|
59
|
|
|
private function getState(TokenInterface $token): int |
|
60
|
|
|
{ |
|
61
|
|
|
switch ($token->name()) { |
|
62
|
|
|
case 'T_PRAGMA': |
|
63
|
|
|
return self::STATE_CONFIGURE; |
|
64
|
|
|
case 'T_TOKEN': |
|
65
|
|
|
case 'T_SKIP': |
|
66
|
|
|
return self::STATE_TOKEN; |
|
67
|
|
|
default: |
|
68
|
|
|
return self::STATE_PRODUCTIONS; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @return Result |
|
74
|
|
|
*/ |
|
75
|
|
|
public function getResult(): Result |
|
76
|
|
|
{ |
|
77
|
|
|
return new Result( |
|
78
|
|
|
$this->resolvers[self::STATE_CONFIGURE], |
|
79
|
|
|
$this->resolvers[self::STATE_TOKEN], |
|
80
|
|
|
$this->resolvers[self::STATE_PRODUCTIONS] |
|
81
|
|
|
); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|