-
Notifications
You must be signed in to change notification settings - Fork 10
/
Parser.php
644 lines (537 loc) · 18.8 KB
/
Parser.php
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<?php
namespace QueryTranslator\Languages\Galach;
use QueryTranslator\Languages\Galach\Values\Node\Group;
use QueryTranslator\Languages\Galach\Values\Node\LogicalAnd;
use QueryTranslator\Languages\Galach\Values\Node\LogicalNot;
use QueryTranslator\Languages\Galach\Values\Node\LogicalOr;
use QueryTranslator\Languages\Galach\Values\Node\Mandatory;
use QueryTranslator\Languages\Galach\Values\Node\Prohibited;
use QueryTranslator\Languages\Galach\Values\Node\Query;
use QueryTranslator\Languages\Galach\Values\Node\Term;
use QueryTranslator\Parsing;
use QueryTranslator\Values\Correction;
use QueryTranslator\Values\Node;
use QueryTranslator\Values\SyntaxTree;
use QueryTranslator\Values\Token;
use QueryTranslator\Values\TokenSequence;
use SplStack;
/**
* Galach implementation of the Parsing interface.
*/
final class Parser implements Parsing
{
/**
* Parser ignored adjacent unary operator preceding another operator.
*/
const CORRECTION_ADJACENT_UNARY_OPERATOR_PRECEDING_OPERATOR_IGNORED = 0;
/**
* Parser ignored unary operator missing an operand.
*/
const CORRECTION_UNARY_OPERATOR_MISSING_OPERAND_IGNORED = 1;
/**
* Parser ignored binary operator missing left side operand.
*/
const CORRECTION_BINARY_OPERATOR_MISSING_LEFT_OPERAND_IGNORED = 2;
/**
* Parser ignored binary operator missing right side operand.
*/
const CORRECTION_BINARY_OPERATOR_MISSING_RIGHT_OPERAND_IGNORED = 3;
/**
* Parser ignored binary operator following another operator and connecting operators.
*/
const CORRECTION_BINARY_OPERATOR_FOLLOWING_OPERATOR_IGNORED = 4;
/**
* Parser ignored logical not operators preceding mandatory or prohibited operator.
*/
const CORRECTION_LOGICAL_NOT_OPERATORS_PRECEDING_PREFERENCE_IGNORED = 5;
/**
* Parser ignored empty group and connecting operators.
*/
const CORRECTION_EMPTY_GROUP_IGNORED = 6;
/**
* Parser ignored unmatched left side group delimiter.
*/
const CORRECTION_UNMATCHED_GROUP_LEFT_DELIMITER_IGNORED = 7;
/**
* Parser ignored unmatched right side group delimiter.
*/
const CORRECTION_UNMATCHED_GROUP_RIGHT_DELIMITER_IGNORED = 8;
/**
* Parser ignored bailout type token.
*
* @see \QueryTranslator\Languages\Galach\Tokenizer::TOKEN_BAILOUT
*/
const CORRECTION_BAILOUT_TOKEN_IGNORED = 9;
private static $tokenShortcuts = [
'operatorNot' => Tokenizer::TOKEN_LOGICAL_NOT | Tokenizer::TOKEN_LOGICAL_NOT_2,
'operatorPreference' => Tokenizer::TOKEN_MANDATORY | Tokenizer::TOKEN_PROHIBITED,
'operatorPrefix' => Tokenizer::TOKEN_MANDATORY | Tokenizer::TOKEN_PROHIBITED | Tokenizer::TOKEN_LOGICAL_NOT_2,
'operatorUnary' => Tokenizer::TOKEN_MANDATORY | Tokenizer::TOKEN_PROHIBITED | Tokenizer::TOKEN_LOGICAL_NOT | Tokenizer::TOKEN_LOGICAL_NOT_2,
'operatorBinary' => Tokenizer::TOKEN_LOGICAL_AND | Tokenizer::TOKEN_LOGICAL_OR,
'operator' => Tokenizer::TOKEN_LOGICAL_AND | Tokenizer::TOKEN_LOGICAL_OR | Tokenizer::TOKEN_MANDATORY | Tokenizer::TOKEN_PROHIBITED | Tokenizer::TOKEN_LOGICAL_NOT | Tokenizer::TOKEN_LOGICAL_NOT_2,
'groupDelimiter' => Tokenizer::TOKEN_GROUP_BEGIN | Tokenizer::TOKEN_GROUP_END,
'binaryOperatorAndWhitespace' => Tokenizer::TOKEN_LOGICAL_AND | Tokenizer::TOKEN_LOGICAL_OR | Tokenizer::TOKEN_WHITESPACE,
];
private static $shifts = [
Tokenizer::TOKEN_WHITESPACE => 'shiftWhitespace',
Tokenizer::TOKEN_TERM => 'shiftTerm',
Tokenizer::TOKEN_GROUP_BEGIN => 'shiftGroupBegin',
Tokenizer::TOKEN_GROUP_END => 'shiftGroupEnd',
Tokenizer::TOKEN_LOGICAL_AND => 'shiftBinaryOperator',
Tokenizer::TOKEN_LOGICAL_OR => 'shiftBinaryOperator',
Tokenizer::TOKEN_LOGICAL_NOT => 'shiftLogicalNot',
Tokenizer::TOKEN_LOGICAL_NOT_2 => 'shiftLogicalNot2',
Tokenizer::TOKEN_MANDATORY => 'shiftPreference',
Tokenizer::TOKEN_PROHIBITED => 'shiftPreference',
Tokenizer::TOKEN_BAILOUT => 'shiftBailout',
];
private static $nodeToReductionGroup = [
Group::class => 'group',
LogicalAnd::class => 'logicalAnd',
LogicalOr::class => 'logicalOr',
LogicalNot::class => 'unaryOperator',
Mandatory::class => 'unaryOperator',
Prohibited::class => 'unaryOperator',
Term::class => 'term',
];
private static $reductionGroups = [
'group' => [
'reduceGroup',
'reducePreference',
'reduceLogicalNot',
'reduceLogicalAnd',
'reduceLogicalOr',
],
'unaryOperator' => [
'reduceLogicalNot',
'reduceLogicalAnd',
'reduceLogicalOr',
],
'logicalOr' => [],
'logicalAnd' => [
'reduceLogicalOr',
],
'term' => [
'reducePreference',
'reduceLogicalNot',
'reduceLogicalAnd',
'reduceLogicalOr',
],
];
/**
* Input tokens.
*
* @var \QueryTranslator\Values\Token[]
*/
private $tokens;
/**
* Query stack.
*
* @var \SplStack
*/
private $stack;
/**
* An array of applied corrections.
*
* @var \QueryTranslator\Values\Correction[]
*/
private $corrections = [];
public function parse(TokenSequence $tokenSequence)
{
$this->init($tokenSequence->tokens);
while (!empty($this->tokens)) {
$node = $this->shift();
if ($node instanceof Node) {
$this->reduce($node);
}
}
$this->reduceQuery();
return new SyntaxTree($this->stack->top(), $tokenSequence, $this->corrections);
}
private function shift()
{
$token = array_shift($this->tokens);
$shift = self::$shifts[$token->type];
return $this->{$shift}($token);
}
private function reduce(Node $node)
{
$previousNode = null;
$reductionIndex = null;
while ($node instanceof Node) {
// Reset reduction index on first iteration or on Node change
if ($node !== $previousNode) {
$reductionIndex = 0;
}
// If there are no reductions to try, put the Node on the stack
// and continue shifting
$reduction = $this->getReduction($node, $reductionIndex);
if ($reduction === null) {
$this->stack->push($node);
break;
}
$previousNode = $node;
$node = $this->{$reduction}($node);
++$reductionIndex;
}
}
protected function shiftWhitespace()
{
if ($this->isTopStackToken(self::$tokenShortcuts['operatorPrefix'])) {
$this->addCorrection(
self::CORRECTION_UNARY_OPERATOR_MISSING_OPERAND_IGNORED,
$this->stack->pop()
);
}
}
protected function shiftPreference(Token $token)
{
return $this->shiftAdjacentUnaryOperator($token, self::$tokenShortcuts['operator']);
}
protected function shiftAdjacentUnaryOperator(Token $token, $tokenMask)
{
if ($this->isToken(reset($this->tokens), $tokenMask)) {
$this->addCorrection(
self::CORRECTION_ADJACENT_UNARY_OPERATOR_PRECEDING_OPERATOR_IGNORED,
$token
);
return null;
}
$this->stack->push($token);
}
protected function shiftLogicalNot(Token $token)
{
$this->stack->push($token);
}
protected function shiftLogicalNot2(Token $token)
{
$tokenMask = self::$tokenShortcuts['operator'] & ~Tokenizer::TOKEN_LOGICAL_NOT_2;
return $this->shiftAdjacentUnaryOperator($token, $tokenMask);
}
protected function shiftBinaryOperator(Token $token)
{
if ($this->stack->isEmpty() || $this->isTopStackToken(Tokenizer::TOKEN_GROUP_BEGIN)) {
$this->addCorrection(
self::CORRECTION_BINARY_OPERATOR_MISSING_LEFT_OPERAND_IGNORED,
$token
);
return null;
}
if ($this->isTopStackToken(self::$tokenShortcuts['operator'])) {
$this->ignoreBinaryOperatorFollowingOperator($token);
return null;
}
$this->stack->push($token);
}
private function ignoreBinaryOperatorFollowingOperator(Token $token)
{
$precedingOperators = $this->ignorePrecedingOperators(self::$tokenShortcuts['operator']);
$followingOperators = $this->ignoreFollowingOperators();
$this->addCorrection(
self::CORRECTION_BINARY_OPERATOR_FOLLOWING_OPERATOR_IGNORED,
...array_merge(
$precedingOperators,
[$token],
$followingOperators
)
);
}
protected function shiftTerm(Token $token)
{
return new Term($token);
}
protected function shiftGroupBegin(Token $token)
{
$this->stack->push($token);
}
protected function shiftGroupEnd(Token $token)
{
$this->stack->push($token);
return new Group();
}
protected function shiftBailout(Token $token)
{
$this->addCorrection(self::CORRECTION_BAILOUT_TOKEN_IGNORED, $token);
}
protected function reducePreference(Node $node)
{
if (!$this->isTopStackToken(self::$tokenShortcuts['operatorPreference'])) {
return $node;
}
$token = $this->stack->pop();
if ($this->isToken($token, Tokenizer::TOKEN_MANDATORY)) {
return new Mandatory($node, $token);
}
return new Prohibited($node, $token);
}
protected function reduceLogicalNot(Node $node)
{
if (!$this->isTopStackToken(self::$tokenShortcuts['operatorNot'])) {
return $node;
}
if ($node instanceof Mandatory || $node instanceof Prohibited) {
$this->ignoreLogicalNotOperatorsPrecedingPreferenceOperator();
return $node;
}
return new LogicalNot($node, $this->stack->pop());
}
public function ignoreLogicalNotOperatorsPrecedingPreferenceOperator()
{
$precedingOperators = $this->ignorePrecedingOperators(self::$tokenShortcuts['operatorNot']);
if (!empty($precedingOperators)) {
$this->addCorrection(
self::CORRECTION_LOGICAL_NOT_OPERATORS_PRECEDING_PREFERENCE_IGNORED,
...$precedingOperators
);
}
}
protected function reduceLogicalAnd(Node $node)
{
if ($this->stack->count() <= 1 || !$this->isTopStackToken(Tokenizer::TOKEN_LOGICAL_AND)) {
return $node;
}
$token = $this->stack->pop();
$leftOperand = $this->stack->pop();
return new LogicalAnd($leftOperand, $node, $token);
}
/**
* Reduce logical OR.
*
* @param \QueryTranslator\Values\Node $node
* @param bool $inGroup Reduce inside a group
*
* @return null|\QueryTranslator\Languages\Galach\Values\Node\LogicalOr|\QueryTranslator\Values\Node
*/
protected function reduceLogicalOr(Node $node, $inGroup = false)
{
if ($this->stack->count() <= 1 || !$this->isTopStackToken(Tokenizer::TOKEN_LOGICAL_OR)) {
return $node;
}
// If inside a group don't look for following logical AND
if (!$inGroup) {
$this->popWhitespace();
// If the next token is logical AND, put the node on stack
// as that has precedence over logical OR
if ($this->isToken(reset($this->tokens), Tokenizer::TOKEN_LOGICAL_AND)) {
$this->stack->push($node);
return null;
}
}
$token = $this->stack->pop();
$leftOperand = $this->stack->pop();
return new LogicalOr($leftOperand, $node, $token);
}
protected function reduceGroup(Group $group)
{
$rightDelimiter = $this->stack->pop();
// Pop dangling tokens
$this->popTokens(~Tokenizer::TOKEN_GROUP_BEGIN);
if ($this->isTopStackToken(Tokenizer::TOKEN_GROUP_BEGIN)) {
$leftDelimiter = $this->stack->pop();
$this->ignoreEmptyGroup($leftDelimiter, $rightDelimiter);
$this->reduceRemainingLogicalOr(true);
return null;
}
$this->reduceRemainingLogicalOr(true);
$group->nodes = $this->collectTopStackNodes();
$group->tokenLeft = $this->stack->pop();
$group->tokenRight = $rightDelimiter;
return $group;
}
/**
* Collect all Nodes from the top of the stack.
*
* @return \QueryTranslator\Values\Node[]
*/
private function collectTopStackNodes()
{
$nodes = [];
while (!$this->stack->isEmpty() && $this->stack->top() instanceof Node) {
array_unshift($nodes, $this->stack->pop());
}
return $nodes;
}
private function ignoreEmptyGroup(Token $leftDelimiter, Token $rightDelimiter)
{
$precedingOperators = $this->ignorePrecedingOperators(self::$tokenShortcuts['operator']);
$followingOperators = $this->ignoreFollowingOperators();
$this->addCorrection(
self::CORRECTION_EMPTY_GROUP_IGNORED,
...array_merge(
$precedingOperators,
[$leftDelimiter, $rightDelimiter],
$followingOperators
)
);
}
/**
* Initialize the parser with given array of $tokens.
*
* @param \QueryTranslator\Values\Token[] $tokens
*/
private function init(array $tokens)
{
$this->corrections = [];
$this->tokens = $tokens;
$this->cleanupGroupDelimiters($this->tokens);
$this->stack = new SplStack();
}
private function getReduction(Node $node, $reductionIndex)
{
$reductionGroup = self::$nodeToReductionGroup[get_class($node)];
if (isset(self::$reductionGroups[$reductionGroup][$reductionIndex])) {
return self::$reductionGroups[$reductionGroup][$reductionIndex];
}
return null;
}
private function reduceQuery()
{
$this->popTokens();
$this->reduceRemainingLogicalOr();
$nodes = [];
while (!$this->stack->isEmpty()) {
array_unshift($nodes, $this->stack->pop());
}
$this->stack->push(new Query($nodes));
}
/**
* Check if the given $token is an instance of Token.
*
* Optionally also checks given Token $typeMask.
*
* @param mixed $token
* @param int $typeMask
*
* @return bool
*/
private function isToken($token, $typeMask = null)
{
if (!$token instanceof Token) {
return false;
}
if (null === $typeMask || $token->type & $typeMask) {
return true;
}
return false;
}
private function isTopStackToken($type = null)
{
return !$this->stack->isEmpty() && $this->isToken($this->stack->top(), $type);
}
/**
* Remove whitespace Tokens from the beginning of the token array.
*/
private function popWhitespace()
{
while ($this->isToken(reset($this->tokens), Tokenizer::TOKEN_WHITESPACE)) {
array_shift($this->tokens);
}
}
/**
* Remove all Tokens from the top of the query stack and log Corrections as necessary.
*
* Optionally also checks that Token matches given $typeMask.
*
* @param int $typeMask
*/
private function popTokens($typeMask = null)
{
while ($this->isTopStackToken($typeMask)) {
$token = $this->stack->pop();
if ($token->type & self::$tokenShortcuts['operatorUnary']) {
$this->addCorrection(
self::CORRECTION_UNARY_OPERATOR_MISSING_OPERAND_IGNORED,
$token
);
} else {
$this->addCorrection(
self::CORRECTION_BINARY_OPERATOR_MISSING_RIGHT_OPERAND_IGNORED,
$token
);
}
}
}
private function ignorePrecedingOperators($type)
{
$tokens = [];
while ($this->isTopStackToken($type)) {
array_unshift($tokens, $this->stack->pop());
}
return $tokens;
}
private function ignoreFollowingOperators()
{
$tokenMask = self::$tokenShortcuts['binaryOperatorAndWhitespace'];
$tokens = [];
while ($this->isToken(reset($this->tokens), $tokenMask)) {
$token = array_shift($this->tokens);
if ($token->type & self::$tokenShortcuts['operatorBinary']) {
$tokens[] = $token;
}
}
return $tokens;
}
/**
* Reduce logical OR possibly remaining after reaching end of group or query.
*
* @param bool $inGroup Reduce inside a group
*/
private function reduceRemainingLogicalOr($inGroup = false)
{
if (!$this->stack->isEmpty() && !$this->isTopStackToken()) {
$node = $this->reduceLogicalOr($this->stack->pop(), $inGroup);
$this->stack->push($node);
}
}
/**
* Clean up group delimiter tokens, removing unmatched left and right delimiter.
*
* Closest group delimiters will be matched first, unmatched remainder is removed.
*
* @param \QueryTranslator\Values\Token[] $tokens
*/
private function cleanupGroupDelimiters(array &$tokens)
{
$indexes = $this->getUnmatchedGroupDelimiterIndexes($tokens);
while (!empty($indexes)) {
$lastIndex = array_pop($indexes);
$token = $tokens[$lastIndex];
unset($tokens[$lastIndex]);
if ($token->type === Tokenizer::TOKEN_GROUP_BEGIN) {
$this->addCorrection(
self::CORRECTION_UNMATCHED_GROUP_LEFT_DELIMITER_IGNORED,
$token
);
} else {
$this->addCorrection(
self::CORRECTION_UNMATCHED_GROUP_RIGHT_DELIMITER_IGNORED,
$token
);
}
}
}
private function getUnmatchedGroupDelimiterIndexes(array &$tokens)
{
$trackLeft = [];
$trackRight = [];
foreach ($tokens as $index => $token) {
if (!$this->isToken($token, self::$tokenShortcuts['groupDelimiter'])) {
continue;
}
if ($this->isToken($token, Tokenizer::TOKEN_GROUP_BEGIN)) {
$trackLeft[] = $index;
continue;
}
if (empty($trackLeft)) {
$trackRight[] = $index;
} else {
array_pop($trackLeft);
}
}
return array_merge($trackLeft, $trackRight);
}
private function addCorrection($type, Token ...$tokens)
{
$this->corrections[] = new Correction($type, ...$tokens);
}
}