-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathParser.php
More file actions
452 lines (364 loc) · 14.5 KB
/
Copy pathParser.php
File metadata and controls
452 lines (364 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php
/**
* @license http://opensource.org/licenses/mit-license.php MIT
* @link https://github.com/nicoSWD
* @author Nicolas Oelgart <hello@nico.es>
*/
declare(strict_types=1);
namespace nicoSWD\Rule\Parser;
use nicoSWD\Rule\AST\AdditionNode;
use nicoSWD\Rule\AST\ArrayNode;
use nicoSWD\Rule\AST\BoolNode;
use nicoSWD\Rule\AST\ComparisonNode;
use nicoSWD\Rule\AST\ComparisonOperator;
use nicoSWD\Rule\AST\DivisionNode;
use nicoSWD\Rule\AST\FloatNode;
use nicoSWD\Rule\AST\FunctionCallNode;
use nicoSWD\Rule\AST\IntegerNode;
use nicoSWD\Rule\AST\LogicalNode;
use nicoSWD\Rule\AST\LogicalOperator;
use nicoSWD\Rule\AST\MethodCallNode;
use nicoSWD\Rule\AST\ModuloNode;
use nicoSWD\Rule\AST\MultiplicationNode;
use nicoSWD\Rule\AST\Node;
use nicoSWD\Rule\AST\NotNode;
use nicoSWD\Rule\AST\NullNode;
use nicoSWD\Rule\AST\RegexNode;
use nicoSWD\Rule\AST\StringNode;
use nicoSWD\Rule\AST\SubtractionNode;
use nicoSWD\Rule\AST\UnaryMinusNode;
use nicoSWD\Rule\AST\VariableNode;
use nicoSWD\Rule\Lexer\Lexer;
use nicoSWD\Rule\TokenStream\Token\BaseToken;
use nicoSWD\Rule\TokenStream\Token\TokenKind;
use nicoSWD\Rule\TokenStream\TokenIterator;
/**
* Recursive descent parser that builds an AST from the token stream.
*
* Grammar (precedence from lowest to highest):
* expression -> logical_or
* logical_or -> logical_and ( "||" logical_and )*
* logical_and -> comparison ( "&&" comparison )*
* comparison -> additive ( comparison_op additive )?
* additive -> multiplicative ( ("+" | "-") multiplicative )*
* multiplicative -> unary ( ("*" | "/" | "%") unary )*
* unary -> "-" unary
* | "!" unary
* | primary
* primary -> "(" expression ")"
* | value
* value -> variable method_call*
* | function_call
* | string | integer | float | bool | null | regex
* | array_literal method_call*
*/
final readonly class Parser
{
public function __construct(
private Lexer $tokenizer,
) {
}
/** @throws Exception\ParserException */
public function parse(string $rule): Node
{
$tokenIterator = new TokenIterator($this->tokenizer->tokenize($rule));
if (!$tokenIterator->valid()) {
return new BoolNode(false);
}
$node = $this->parseExpression($tokenIterator);
// If there are remaining non-ignorable tokens, that's a syntax error
$this->skipIgnoredTokens($tokenIterator);
if ($tokenIterator->valid()) {
throw Exception\ParserException::unexpectedToken($tokenIterator->current());
}
return $node;
}
/** @throws Exception\ParserException */
private function parseExpression(TokenIterator $tokens): Node
{
return $this->parseLogicalOr($tokens);
}
/** @throws Exception\ParserException */
private function parseLogicalOr(TokenIterator $tokens): Node
{
$left = $this->parseLogicalAnd($tokens);
while ($this->peekToken($tokens)?->isOfKind(TokenKind::OR)) {
$this->consumeToken($tokens); // consume ||
$right = $this->parseLogicalAnd($tokens);
$left = new LogicalNode($left, $right, LogicalOperator::OR);
}
return $left;
}
/** @throws Exception\ParserException */
private function parseLogicalAnd(TokenIterator $tokens): Node
{
$left = $this->parseComparison($tokens);
while ($this->peekToken($tokens)?->isOfKind(TokenKind::AND)) {
$this->consumeToken($tokens); // consume &&
$right = $this->parseComparison($tokens);
$left = new LogicalNode($left, $right, LogicalOperator::AND);
}
return $left;
}
/** @throws Exception\ParserException */
private function parseComparison(TokenIterator $tokens): Node
{
$left = $this->parseAdditive($tokens);
$operatorToken = $this->peekToken($tokens);
if ($operatorToken !== null) {
$operator = $this->matchComparisonOperator($operatorToken);
if ($operator !== null) {
$this->consumeToken($tokens); // consume operator
$right = $this->parseAdditive($tokens);
return new ComparisonNode($left, $right, $operator);
}
}
return $left;
}
/** @throws Exception\ParserException */
private function parseAdditive(TokenIterator $tokens): Node
{
$left = $this->parseMultiplicative($tokens);
while (
($peeked = $this->peekToken($tokens)) !== null
&& ($peeked->isOfKind(TokenKind::PLUS) || $peeked->isOfKind(TokenKind::MINUS))
) {
$operator = $this->peekToken($tokens);
$this->consumeToken($tokens); // consume + or -
$right = $this->parseMultiplicative($tokens);
$left = match ($operator->getKind()) {
TokenKind::PLUS => new AdditionNode($left, $right),
TokenKind::MINUS => new SubtractionNode($left, $right),
default => throw new \RuntimeException('Unexpected additive operator'),
};
}
return $left;
}
/** @throws Exception\ParserException */
private function parseMultiplicative(TokenIterator $tokens): Node
{
$left = $this->parseUnary($tokens);
while (
($peeked = $this->peekToken($tokens)) !== null
&& ($peeked->isOfKind(TokenKind::MULTIPLY) || $peeked->isOfKind(TokenKind::DIVIDE) || $peeked->isOfKind(TokenKind::MODULO))
) {
$operator = $this->peekToken($tokens);
$this->consumeToken($tokens); // consume *, /, or %
$right = $this->parseUnary($tokens);
$left = match ($operator->getKind()) {
TokenKind::MULTIPLY => new MultiplicationNode($left, $right),
TokenKind::DIVIDE => new DivisionNode($left, $right),
TokenKind::MODULO => new ModuloNode($left, $right),
default => throw new \RuntimeException('Unexpected multiplicative operator'),
};
}
return $left;
}
/** @throws Exception\ParserException */
private function parseUnary(TokenIterator $tokens): Node
{
$this->skipIgnoredTokens($tokens);
if (!$tokens->valid()) {
throw Exception\ParserException::unexpectedEndOfString();
}
$token = $tokens->current();
// Unary minus: -expr
if ($token->isOfKind(TokenKind::MINUS)) {
$tokens->next();
$operand = $this->parseUnary($tokens);
return new UnaryMinusNode($operand);
}
// Logical NOT: !expr
if ($token->isOfKind(TokenKind::NOT)) {
$tokens->next();
$operand = $this->parseUnary($tokens);
return new NotNode($operand);
}
return $this->parsePrimary($tokens);
}
/** @throws Exception\ParserException */
private function parsePrimary(TokenIterator $tokens): Node
{
if (!$tokens->valid()) {
throw Exception\ParserException::unexpectedEndOfString();
}
$token = $tokens->current();
// Parenthesized expression
if ($token->isOfKind(TokenKind::OPENING_PARENTHESIS)) {
$tokens->next();
$node = $this->parseExpression($tokens);
$this->expectClosingParenthesis($tokens);
return $node;
}
// Array literal (may have method calls chained)
if ($token->isOfKind(TokenKind::OPENING_ARRAY)) {
$node = $this->parseArrayLiteral($tokens);
return $this->parseMethodChain($node, $tokens);
}
// Function call
if ($token->isOfKind(TokenKind::FUNCTION)) {
$node = $this->parseFunctionCall($tokens);
return $this->parseMethodChain($node, $tokens);
}
// Simple value tokens (advance past them)
$node = $this->parseSimpleValue($token);
if ($node !== null) {
$tokens->next();
// Check for method calls chained onto this value
return $this->parseMethodChain($node, $tokens);
}
throw Exception\ParserException::unexpectedToken($token);
}
private function parseSimpleValue(BaseToken $token): ?Node
{
return match ($token->getKind()) {
TokenKind::VARIABLE => new VariableNode($token->getOriginalValue(), $token->getOffset()),
TokenKind::ENCAPSED_STRING, TokenKind::STRING => new StringNode($token->getValue()),
TokenKind::INTEGER => new IntegerNode((int) $token->getValue()),
TokenKind::FLOAT => new FloatNode((float) $token->getValue()),
TokenKind::BOOL_TRUE => new BoolNode(true),
TokenKind::BOOL_FALSE => new BoolNode(false),
TokenKind::NULL => new NullNode(),
TokenKind::REGEX => new RegexNode($token->getValue(), $token),
default => null,
};
}
/** @throws Exception\ParserException */
private function parseFunctionCall(TokenIterator $tokens): FunctionCallNode
{
$token = $tokens->current();
$functionName = $token->getValue();
$offset = $token->getOffset();
// Move past the function token
$tokens->next();
$arguments = $this->parseParenthesizedArguments($tokens);
return new FunctionCallNode($functionName, $arguments, $offset);
}
/** @throws Exception\ParserException */
private function parseMethodChain(Node $object, TokenIterator $tokens): Node
{
$this->skipIgnoredTokens($tokens);
while ($tokens->valid() && $tokens->current()->isOfKind(TokenKind::METHOD)) {
$methodToken = $tokens->current();
$methodName = $methodToken->getValue();
$offset = $methodToken->getOffset();
$tokens->next();
$arguments = $this->parseParenthesizedArguments($tokens);
$object = new MethodCallNode($object, $methodName, $arguments, $offset);
$this->skipIgnoredTokens($tokens);
}
return $object;
}
/** @throws Exception\ParserException */
private function parseParenthesizedArguments(TokenIterator $tokens): array
{
// Consume the opening parenthesis
$this->skipIgnoredTokens($tokens);
if (!$tokens->valid() || !$tokens->current()->isOfKind(TokenKind::OPENING_PARENTHESIS)) {
throw Exception\ParserException::unexpectedToken($tokens->valid() ? $tokens->current() : null);
}
$tokens->next();
return $this->parseArguments($tokens);
}
/** @throws Exception\ParserException */
private function parseArguments(TokenIterator $tokens): array
{
return $this->parseCommaSeparatedList(
$tokens,
static fn (BaseToken $token): bool => $token->isOfKind(TokenKind::CLOSING_PARENTHESIS),
);
}
/** @throws Exception\ParserException */
private function parseArrayLiteral(TokenIterator $tokens): ArrayNode
{
// Consume the opening '['
$tokens->next();
$items = $this->parseCommaSeparatedList(
$tokens,
static fn (BaseToken $token): bool => $token->isOfKind(TokenKind::CLOSING_ARRAY),
);
return new ArrayNode($items);
}
/**
* @param callable(BaseToken): bool $isTerminator
* @return Node[]
* @throws Exception\ParserException
*/
private function parseCommaSeparatedList(TokenIterator $tokens, callable $isTerminator): array
{
$items = [];
$expectComma = false;
while ($tokens->valid()) {
$this->skipIgnoredTokens($tokens);
if (!$tokens->valid()) {
throw Exception\ParserException::unexpectedEndOfString();
}
$token = $tokens->current();
// Closing token ends the list
if ($isTerminator($token)) {
$tokens->next(); // consume the closing token
return $items;
}
if ($token->isOfKind(TokenKind::COMMA)) {
if (!$expectComma) {
throw Exception\ParserException::unexpectedComma($token);
}
$expectComma = false;
$tokens->next();
continue;
}
if ($expectComma) {
throw Exception\ParserException::unexpectedToken($token);
}
// Parse the item value (could be a complex expression)
$item = $this->parsePrimary($tokens);
$items[] = $item;
$expectComma = true;
}
throw Exception\ParserException::unexpectedEndOfString();
}
/** @throws Exception\ParserException */
private function expectClosingParenthesis(TokenIterator $tokens): void
{
$this->skipIgnoredTokens($tokens);
if (!$tokens->valid()) {
throw Exception\ParserException::unexpectedEndOfString();
}
$token = $tokens->current();
if (!$token->isOfKind(TokenKind::CLOSING_PARENTHESIS)) {
throw Exception\ParserException::unexpectedToken($token);
}
$tokens->next(); // consume ')'
}
private function matchComparisonOperator(BaseToken $token): ?ComparisonOperator
{
return match ($token->getKind()) {
TokenKind::EQUAL => ComparisonOperator::EQUAL,
TokenKind::EQUAL_STRICT => ComparisonOperator::EQUAL_STRICT,
TokenKind::NOT_EQUAL => ComparisonOperator::NOT_EQUAL,
TokenKind::NOT_EQUAL_STRICT => ComparisonOperator::NOT_EQUAL_STRICT,
TokenKind::LESS_THAN => ComparisonOperator::LESS_THAN,
TokenKind::GREATER => ComparisonOperator::GREATER_THAN,
TokenKind::LESS_THAN_EQUAL => ComparisonOperator::LESS_THAN_EQUAL,
TokenKind::GREATER_EQUAL => ComparisonOperator::GREATER_THAN_EQUAL,
TokenKind::IN => ComparisonOperator::IN,
TokenKind::NOT_IN => ComparisonOperator::NOT_IN,
default => null,
};
}
private function peekToken(TokenIterator $tokens): ?BaseToken
{
$this->skipIgnoredTokens($tokens);
return $tokens->valid() ? $tokens->current() : null;
}
private function consumeToken(TokenIterator $tokens): void
{
$tokens->next();
}
private function skipIgnoredTokens(TokenIterator $tokens): void
{
while ($tokens->valid() && $tokens->current()->canBeIgnored()) {
$tokens->next();
}
}
}