Repository navigation
Expand file tree
/
Copy pathAlternationRewrites.php
More file actions
293 lines (253 loc) · 9.15 KB
/
Copy pathAlternationRewrites.php
File metadata and controls
293 lines (253 loc) · 9.15 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
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Optimizer;
use PHPRegex\Parser\Node\AlternationNode;
use PHPRegex\Parser\Node\GroupNode;
use PHPRegex\Parser\Node\GroupType;
use PHPRegex\Parser\Node\LiteralNode;
use PHPRegex\Parser\Node\NodeInterface;
use PHPRegex\Parser\Node\QuantifierNode;
use PHPRegex\Parser\Node\QuantifierType;
use PHPRegex\Parser\Node\SequenceNode;
/**
* The alternations of a pattern for Rewriter: an alternative written twice
* removed, and the start or the end the literal alternatives share factored
* out, "ab|ac" written "a(?:b|c)".
*
* It shares the rewriter's RewriteState, and reads the alternatives the
* rewriter has already rewritten.
*
* @internal
*/
final class AlternationRewrites
{
public function __construct(private readonly RewriteState $state) {}
/**
* @param array<NodeInterface> $alts
*
* @return array<NodeInterface>
*/
public function deduplicateAlternation(array $alts): array
{
$seen = [];
$unique = [];
foreach ($alts as $alt) {
// An alternative holding a group is a group of its own number,
// however it is spelled: "(a)|(a)" keeps its group 2.
$key = $this->state->spelling($alt);
if (!isset($seen[$key]) || self::holdsGroup($alt)) {
$seen[$key] = true;
$unique[] = $alt;
}
}
return $unique;
}
/**
* Factors the start the literal branches share out of an alternation:
* "ab|ac" is "a(?:b|c)". It works on the strings the literals stand for,
* never on their spelling: "\r\n|\r" share "\r", not a backslash.
*
* @param array<NodeInterface> $alts
*
* @return array<NodeInterface>
*/
public function factorizeAlternation(array $alts): array
{
$literals = self::literalBranches($alts);
if (null === $literals) {
return $alts;
}
$values = array_map(static fn (LiteralNode $literal): string => $literal->value, $literals);
$prefix = self::sharedStart($values);
if ('' === $prefix) {
return $alts;
}
$rests = [];
foreach ($literals as $alt) {
$rest = substr($alt->value, \strlen($prefix));
$rests[] = '' === $rest ? null : new LiteralNode($rest, $alt->startPosition, $alt->endPosition);
}
$first = $literals[0];
$last = $literals[\count($literals) - 1];
if ([] === array_filter($rests)) {
// Every branch is the same string: one is enough.
return [new LiteralNode($prefix, $first->startPosition, $first->endPosition)];
}
$group = $this->optionalGroup($rests);
if (null === $group) {
return $alts;
}
return [new SequenceNode([new LiteralNode($prefix, $first->startPosition, $first->startPosition), $group], $first->startPosition, $last->endPosition)];
}
/**
* Factors the end the literal branches share out of an alternation:
* "abc|xbc" is "(?:a|x)bc".
*
* @param array<NodeInterface> $alts
*
* @return array<NodeInterface>
*/
public function factorizeSuffix(array $alts): array
{
$literals = self::literalBranches($alts);
if (null === $literals) {
return $alts;
}
$values = array_map(static fn (LiteralNode $literal): string => $literal->value, $literals);
$suffix = self::sharedEnd($values);
if (\strlen($suffix) < 2) {
return $alts;
}
$rests = [];
foreach ($literals as $alt) {
$rest = substr($alt->value, 0, -\strlen($suffix));
$rests[] = '' === $rest ? null : new LiteralNode($rest, $alt->startPosition, $alt->endPosition);
}
$first = $literals[0];
$last = $literals[\count($literals) - 1];
if ([] === array_filter($rests)) {
return [new LiteralNode($suffix, $first->startPosition, $first->endPosition)];
}
$group = $this->optionalGroup($rests);
if (null === $group) {
return $alts;
}
return [new SequenceNode([$group, new LiteralNode($suffix, $last->endPosition, $last->endPosition)], $first->startPosition, $last->endPosition)];
}
private static function holdsGroup(NodeInterface $node): bool
{
if ($node instanceof GroupNode && \in_array($node->type, [GroupType::Capturing, GroupType::Named, GroupType::BranchReset], true)) {
return true;
}
foreach ($node->getChildren() as $child) {
if (self::holdsGroup($child)) {
return true;
}
}
return false;
}
/**
* The branches left once the shared part is gone, as one group, optional
* when one of them is empty; null when no group keeps their order.
*
* @param non-empty-list<LiteralNode|null> $rests at least one not null
*/
private function optionalGroup(array $rests): ?NodeInterface
{
$emptyBranch = self::emptyBranchQuantifier($rests);
// An inline flag may turn "U" on or off around the group, which
// swaps what "?" and "??" mean: the alternation stays as written.
if (false === $emptyBranch || (null !== $emptyBranch && $this->state->inlineFlags)) {
return null;
}
// Under "U" the spellings swap: "?" is lazy, "??" greedy.
if (null !== $emptyBranch && $this->state->lazyByDefault) {
$emptyBranch = QuantifierType::Greedy === $emptyBranch ? QuantifierType::Lazy : QuantifierType::Greedy;
}
$kept = array_values(array_filter($rests, static fn (?LiteralNode $rest): bool => null !== $rest));
$first = $kept[0];
$last = $kept[\count($kept) - 1];
$group = new GroupNode(1 === \count($kept) ? $first : new AlternationNode($kept, $first->startPosition, $last->endPosition), GroupType::NonCapturing);
return null === $emptyBranch ? $group : new QuantifierNode($group, '?', $emptyBranch, $first->startPosition, $last->endPosition);
}
/**
* The branches, when every one is a plain literal.
*
* @param array<NodeInterface> $alts
*
* @return non-empty-list<LiteralNode>|null
*/
private static function literalBranches(array $alts): ?array
{
if (\count($alts) < 2) {
return null;
}
$literals = [];
foreach ($alts as $alt) {
if (!$alt instanceof LiteralNode || $alt->isRaw) {
return null;
}
$literals[] = $alt;
}
return $literals;
}
/**
* The longest start every string shares, cut back to whole characters
* when they are all UTF-8.
*
* @param list<string> $values
*/
private static function sharedStart(array $values): string
{
$prefix = $values[0];
foreach ($values as $value) {
$length = 0;
$limit = min(\strlen($prefix), \strlen($value));
while ($length < $limit && $prefix[$length] === $value[$length]) {
$length++;
}
$prefix = substr($prefix, 0, $length);
}
if (self::allUtf8($values)) {
while ('' !== $prefix && !mb_check_encoding($prefix, 'UTF-8')) {
$prefix = substr($prefix, 0, -1);
}
}
return $prefix;
}
/**
* The longest end every string shares, cut back to whole characters
* when they are all UTF-8.
*
* @param list<string> $values
*/
private static function sharedEnd(array $values): string
{
$suffix = strrev(self::sharedStart(array_map(strrev(...), $values)));
if (self::allUtf8($values)) {
while ('' !== $suffix && !mb_check_encoding($suffix, 'UTF-8')) {
$suffix = substr($suffix, 1);
}
}
return $suffix;
}
/**
* @param list<string> $values
*/
private static function allUtf8(array $values): bool
{
foreach ($values as $value) {
if (!mb_check_encoding($value, 'UTF-8')) {
return false;
}
}
return true;
}
/**
* How the branches left once the shared part is factored out keep the
* order PCRE tries them in: an empty branch tried first makes them a lazy
* option, "a|ab" is "a(?:b)??"; tried last, a greedy one, "ab|a" is
* "a(?:b)?". Null when no branch is empty, false when the empty one sits
* in the middle, where no quantifier keeps the order.
*
* @param array<NodeInterface|null> $branches
*/
private static function emptyBranchQuantifier(array $branches): QuantifierType|false|null
{
$empty = array_search(null, $branches, true);
return match ($empty) {
false => null,
0 => QuantifierType::Lazy,
\count($branches) - 1 => QuantifierType::Greedy,
default => false,
};
}
}