|
4 | 4 |
|
5 | 5 | namespace TypeLang\Parser; |
6 | 6 |
|
7 | | -use JetBrains\PhpStorm\Language; |
8 | 7 | use Phplrt\Contracts\Lexer\LexerInterface; |
9 | 8 | use Phplrt\Contracts\Lexer\TokenInterface; |
10 | 9 | use Phplrt\Contracts\Parser\ParserRuntimeExceptionInterface; |
@@ -128,11 +127,41 @@ public function __construct( |
128 | 127 | $this->stringPool = new \WeakMap(); |
129 | 128 | $this->integerPool = new \WeakMap(); |
130 | 129 |
|
131 | | - $this->builder = new Builder($grammar['reducers']); |
| 130 | + $this->builder = $this->createBuilder($grammar['reducers']); |
132 | 131 | $this->lexer = $this->createLexer($grammar); |
133 | 132 | $this->parser = $this->createParser($this->lexer, $grammar); |
134 | 133 | } |
135 | 134 |
|
| 135 | + /** |
| 136 | + * @param array<int<0, max>|non-empty-string, callable(Context, mixed):mixed> $reducers |
| 137 | + */ |
| 138 | + private function createBuilder(array $reducers): BuilderInterface |
| 139 | + { |
| 140 | + return new class($reducers) implements BuilderInterface { |
| 141 | + /** |
| 142 | + * @param array<int<0, max>|non-empty-string, callable(Context, mixed):mixed> $reducers |
| 143 | + */ |
| 144 | + public function __construct( |
| 145 | + private readonly array $reducers, |
| 146 | + ) {} |
| 147 | + |
| 148 | + public function build(Context $context, mixed $result): mixed |
| 149 | + { |
| 150 | + if (!isset($this->reducers[$context->state])) { |
| 151 | + return $result; |
| 152 | + } |
| 153 | + |
| 154 | + $result = ($this->reducers[$context->state])($context, $result); |
| 155 | + |
| 156 | + if ($result instanceof Node && $result->offset === 0) { |
| 157 | + $result->offset = $context->lastProcessedToken->getOffset(); |
| 158 | + } |
| 159 | + |
| 160 | + return $result; |
| 161 | + } |
| 162 | + }; |
| 163 | + } |
| 164 | + |
136 | 165 | /** |
137 | 166 | * @phpstan-param GrammarConfigArray $grammar |
138 | 167 | * |
@@ -164,7 +193,7 @@ private function createLexer(array $grammar): Lexer |
164 | 193 | ); |
165 | 194 | } |
166 | 195 |
|
167 | | - public function parse(#[Language('PHP')] mixed $source): TypeStatement |
| 196 | + public function parse(mixed $source): TypeStatement |
168 | 197 | { |
169 | 198 | $this->lastProcessedTokenOffset = 0; |
170 | 199 |
|
|
0 commit comments