Repository navigation
Expand file tree
/
Copy pathSampleGenerator.php
More file actions
1598 lines (1357 loc) · 55.2 KB
/
Copy pathSampleGenerator.php
File metadata and controls
1598 lines (1357 loc) · 55.2 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
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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\Generator;
use PHPRegex\Generator\Exception\SampleGenerationException;
use PHPRegex\Parser\AbstractNodeVisitor;
use PHPRegex\Parser\Analysis\GroupNumberingCollector;
use PHPRegex\Parser\Analysis\LengthRangeCalculator;
use PHPRegex\Parser\Cache\StaticCaches;
use PHPRegex\Parser\Engine\LibraryPcre;
use PHPRegex\Parser\Engine\PcreEngine;
use PHPRegex\Parser\ErrorCode;
use PHPRegex\Parser\Exception\LexerException;
use PHPRegex\Parser\Exception\ParserException;
use PHPRegex\Parser\Hir\ClassSetProvider;
use PHPRegex\Parser\Node\AlternationNode;
use PHPRegex\Parser\Node\AnchorNode;
use PHPRegex\Parser\Node\AssertionNode;
use PHPRegex\Parser\Node\BackrefNode;
use PHPRegex\Parser\Node\CalloutNode;
use PHPRegex\Parser\Node\CharClassNode;
use PHPRegex\Parser\Node\CharLiteralNode;
use PHPRegex\Parser\Node\CharTypeNode;
use PHPRegex\Parser\Node\ClassSetOperationNode;
use PHPRegex\Parser\Node\CommentNode;
use PHPRegex\Parser\Node\ConditionalNode;
use PHPRegex\Parser\Node\ControlCharNode;
use PHPRegex\Parser\Node\DefineNode;
use PHPRegex\Parser\Node\DotNode;
use PHPRegex\Parser\Node\ExtendedCharClassNode;
use PHPRegex\Parser\Node\GroupNode;
use PHPRegex\Parser\Node\GroupType;
use PHPRegex\Parser\Node\KeepNode;
use PHPRegex\Parser\Node\LimitMatchNode;
use PHPRegex\Parser\Node\LiteralNode;
use PHPRegex\Parser\Node\NodeInterface;
use PHPRegex\Parser\Node\PcreVerbNode;
use PHPRegex\Parser\Node\PosixClassNode;
use PHPRegex\Parser\Node\QuantifierNode;
use PHPRegex\Parser\Node\RangeNode;
use PHPRegex\Parser\Node\RegexNode;
use PHPRegex\Parser\Node\ScriptRunNode;
use PHPRegex\Parser\Node\SequenceNode;
use PHPRegex\Parser\Node\SubroutineNode;
use PHPRegex\Parser\Node\UnicodePropNode;
use PHPRegex\Parser\Node\VersionConditionNode;
use PHPRegex\Parser\PcreTarget;
use PHPRegex\Parser\Printer\PatternPrinter;
use PHPRegex\Parser\RegexParser;
use PHPRegex\Parser\Text\Ascii;
/**
* A visitor that generates a random sample string that matches the AST.
*
* @extends AbstractNodeVisitor<string>
*/
final class SampleGenerator extends AbstractNodeVisitor
{
private const MAX_RECURSION_DEPTH = 2;
/**
* The longest sample built: past it, repeats of references or calls
* would outgrow any subject worth testing with.
*/
private const MAX_SAMPLE_LENGTH = 1048576;
/**
* How many times, for one sample, lookaheads nothing fits are drawn again.
*/
private const MAX_LOOKAHEAD_DRAWS = 32;
/**
* How many times the body of a scan is drawn to fit the group it reads.
*/
private const MAX_SCAN_DRAWS = 8;
/**
* Characters from the common scripts and categories, tried first.
*/
private const COMMON_CHARACTERS = "aZ09_ .,!+\t\n\x00\u{7f}éÀÿ×αΩЖжאب٣कক中あアク한ก\u{301}\u{200b}\u{2028}\u{a0}\u{3000}€∑«»¿\u{e000}\u{378}😀A\u{ff10}";
private ?int $seed = null;
private MersenneTwister $randomizer;
/**
* Stores generated text from capturing groups.
* Keyed by both numeric index and name (if available).
*
* @var array<int|string, string>
*/
private array $captures = [];
private int $groupCounter = 1;
private int $recursionDepth = 0;
private ?NodeInterface $rootPattern = null;
/**
* @var array<int, GroupNode>
*/
private array $groupIndexMap = [];
/**
* @var array<string, GroupNode>
*/
private array $namedGroupMap = [];
/**
* @var array<int, int>
*/
private array $groupNumbers = [];
/**
* @var array<string, array<int>> the numbers of the groups each name is given, as they open
*/
private array $groupNumbersByName = [];
/**
* @var list<GroupNode> the substring scans of the pattern
*/
private array $scans = [];
private int $lookaheadDraws = 0;
/**
* Whether a "(*ACCEPT)" ended what is being generated, up to the call or
* the assertion it stands in.
*/
private bool $accepted = false;
/**
* @var array<int, true> the groups being fitted to the scans that read them
*/
private array $fitting = [];
/**
* @var array<int, list<NodeInterface>> the bodies each group's capture is scanned with, by group number
*/
private array $scansByGroup = [];
private int $groupDefinitionCounter = 1;
private bool $unicode = false;
/**
* Whether the pattern ignores case, which changes what a set holds.
*/
private bool $caseless = false;
/**
* Whether "$" ends a line, under "m", rather than the subject.
*/
private bool $dollarEndsLine = false;
/**
* Whether a dot takes a newline, under "s".
*/
private bool $dotAll = false;
/**
* The text each sequence being generated holds so far, outermost first,
* held by reference: what stands before the node being generated.
*
* @var array<int, string>
*/
private array $textsBefore = [];
/**
* The groups the calls being generated run, innermost last: 0 for the
* whole pattern. "(?(R)" and its like read it.
*
* @var list<int>
*/
private array $calls = [];
/**
* The fewest characters the pattern still adds after the node being
* generated, which an alternative ending the subject leaves no room for.
*/
private int $textAhead = 0;
/**
* @var array<int, array{0: int, 1: int|null}> the fewest and most characters each node matches, by node id
*/
private array $lengthRanges = [];
/**
* Characters found to have a property, by the escape and the mode.
*
* @var array<string, list<string>>
*/
private static array $propertySamples = [];
/**
* @var array<int, string>
*/
private static array $codePointChunks = [];
/**
* @var array<int, string>
*/
private array $requiredPrefixes = [];
/**
* @var array<int, string>
*/
private array $requiredSuffixes = [];
/**
* The PCRE2 a sample is drawn for while generate() runs: each property
* is asked of the running engine as it spells what the target means.
* Null outside it, where a tree is read as the running engine reads it.
*/
private ?PcreTarget $target = null;
/**
* The parser of the calls that name none, built on the first of them.
*/
private ?RegexParser $parser = null;
/**
* @param int $maxRepetition Maximum repetitions for quantifiers like `*` or `+`
* @param PcreEngine $engine Asks the running engine what a class or a property holds
* @param int|null $seed Locks the random source, as setSeed() does: each sample starts again from it
*/
public function __construct(
private readonly int $maxRepetition = 3,
private readonly PcreEngine $engine = new PcreEngine(),
?int $seed = null
) {
$this->seed = $seed;
$this->resetRandomizer($seed);
}
public function setSeed(int $seed): void
{
$this->seed = $seed;
$this->resetRandomizer($seed);
}
public function resetSeed(): void
{
$this->seed = null;
$this->resetRandomizer();
}
/**
* A sample the running engine matches. Visiting the tree draws a sample
* from it alone, which an assertion, a condition or a backreference may
* make wrong; this draws again and checks each one with the engine.
*
* The engine reads the pattern as it spells what the target means: a
* property it reads otherwise is written as it reads the target's (see
* ClassSetProvider::spelledFor()). A pattern with a property it has no
* name for, as the target reads it, gets no sample: no character of
* the property can be drawn or checked.
*
* @param string $regex The delimited pattern
* @param RegexParser|null $parser Reads and judges the pattern; one for the running PHP, kept for the next call, when null
*
* @throws ParserException when the pattern does not parse (a delimiter, flag or syntax fault)
* @throws LexerException when the pattern does not tokenize
* @throws SampleGenerationException when the pattern parses but is invalid, as a call to a group that does not
* exist, holds a property the running engine cannot read as the target does,
* or no sample the running engine matches was found
*/
public function generate(string $regex, ?RegexParser $parser = null): string
{
$parser ??= $this->parser ??= RegexParser::create();
$ast = $parser->parse($regex);
// A pattern PCRE refuses, as a call to a group that does not exist,
// has no sample to draw.
$validation = $parser->validate($regex);
if (!$validation->isValid) {
throw new SampleGenerationException(\sprintf('No sample matching %s can be drawn: %s', $regex, (string) $validation->error), null, $validation->errorCode ?? ErrorCode::GenerateNoMatch);
}
$target = $parser->target();
$checked = ClassSetProvider::spelledFor($regex, $target);
if (null === $checked) {
throw new SampleGenerationException(\sprintf('No sample matching %s can be drawn: PCRE2 %s, which runs, has no name for a property of it as PCRE2 %s reads it.', $regex, PcreTarget::runtime()->pcreVersion, $target->pcreVersion), null, ErrorCode::GenerateNoMatch);
}
$this->target = $target;
try {
return $this->checkedSample($regex, $checked, $ast);
} finally {
$this->target = null;
}
}
#[\Override]
public function visitRegex(RegexNode $node): string
{
// Reset state for this run
$this->captures = [];
$this->groupCounter = 1;
$this->recursionDepth = 0;
$this->rootPattern = $node->pattern;
$this->groupIndexMap = [];
$this->namedGroupMap = [];
$this->groupNumbers = [];
$this->scans = [];
$this->lookaheadDraws = 0;
$this->accepted = false;
$this->groupDefinitionCounter = 1;
$this->requiredPrefixes = [];
$this->requiredSuffixes = [];
$this->collectGroups($node->pattern);
$this->numberGroupsAsPcre($node);
$this->caseless = str_contains($node->flags, 'i');
$this->dollarEndsLine = str_contains($node->flags, 'm');
$this->dotAll = str_contains($node->flags, 's');
$this->textsBefore = [];
$this->calls = [];
$this->textAhead = 0;
$this->lengthRanges = [];
$this->unicode = str_contains($node->flags, 'u')
|| 1 === LibraryPcre::match('/^(?:\(\*[A-Z_=0-9]+\))*\(\*UTF8?\)/', $node->source ?? '');
// Ensure we are seeded if the user expects it
if (null !== $this->seed) {
$this->resetRandomizer($this->seed);
}
// Note: Flags (like /i) are ignored, as we generate the sample
// from the literal pattern.
$sample = $node->pattern->accept($this);
return $this->applyLookaroundHints($sample);
}
#[\Override]
public function visitAlternation(AlternationNode $node): string
{
if (empty($node->alternatives)) {
return '';
}
// Pick one of the alternatives at random, among those that leave
// room for what the pattern still adds.
$alternatives = array_values(array_filter(
$node->alternatives,
fn (NodeInterface $alternative): bool => $this->textAhead <= $this->roomAfter($alternative),
));
if ([] === $alternatives) {
$alternatives = $node->alternatives;
}
$chosenAlt = $alternatives[$this->randomInt(0, \count($alternatives) - 1)];
return $chosenAlt->accept($this);
}
#[\Override]
public function visitSequence(SequenceNode $node): string
{
return $this->generateSequence($node->children);
}
#[\Override]
public function visitGroup(GroupNode $node): string
{
// "(?s)" sets its flags for the rest of the group it stands in,
// "(?s:...)" for its own content: the group around them ends them.
if (GroupType::InlineFlags === $node->type && $node->child instanceof LiteralNode && '' === $node->child->value) {
$this->applyFlags($node->flags ?? '');
return '';
}
$modes = [$this->caseless, $this->dotAll, $this->dollarEndsLine];
if (GroupType::InlineFlags === $node->type) {
$this->applyFlags($node->flags ?? '');
}
try {
return $this->generateGroup($node);
} finally {
[$this->caseless, $this->dotAll, $this->dollarEndsLine] = $modes;
}
}
#[\Override]
public function visitDot(DotNode $node): string
{
// Generate a random, simple, printable ASCII char, or a newline
// where "s" lets the dot take one.
$characters = ['a', 'b', 'c', '1', '2', '3', ' '];
return $this->getRandomChar($this->dotAll ? [...$characters, "\n"] : $characters);
}
#[\Override]
public function visitQuantifier(QuantifierNode $node): string
{
[$min, $max] = $this->parseQuantifierRange($node);
// What takes no text, optional, need not hold: it adds nothing. It
// stays in its sequence, where a call may name a group it holds.
if (0 === $min && 0 === $this->lengthRange($node->node)[1]) {
return '';
}
// Pick a random number of repetitions
// $min and $max are guaranteed to be in the correct order
// by parseQuantifierRange()
$repeats = ($min === $max) ? $min : $this->randomInt($min, $max);
$sample = '';
$ahead = $this->textAhead;
$each = $this->minLength($node->node);
for ($i = 0; $i < $repeats; $i++) {
$this->textAhead = $ahead + ($repeats - 1 - $i) * $each;
$sample .= $node->node->accept($this);
$this->textAhead = $ahead;
if ($this->accepted) {
break;
}
// References and calls can double a sample at each repeat.
if (\strlen($sample) > self::MAX_SAMPLE_LENGTH) {
throw new SampleGenerationException(\sprintf('No sample was built: it would pass %d bytes.', self::MAX_SAMPLE_LENGTH));
}
}
return $sample;
}
#[\Override]
public function visitLiteral(LiteralNode $node): string
{
return $node->value;
}
#[\Override]
public function visitCharType(CharTypeNode $node): string
{
return $this->generateForCharType($node->value);
}
#[\Override]
public function visitAnchor(AnchorNode $node): string
{
// Anchors do not generate text
return '';
}
#[\Override]
public function visitAssertion(AssertionNode $node): string
{
// Assertions do not generate text
return '';
}
#[\Override]
public function visitKeep(KeepNode $node): string
{
// \K does not generate text
return '';
}
#[\Override]
public function visitCharClass(CharClassNode $node): string
{
if ($node->isNegated) {
return $this->sampleForNegatedClass($node);
}
$parts = $node->expression instanceof AlternationNode ? $node->expression->alternatives : [$node->expression];
if (empty($parts)) {
// Only an AST built by hand holds one: "[]" opens a class whose first member is "]".
throw new SampleGenerationException('Cannot generate sample for empty character class');
}
// Pick one of the parts at random
$randomKey = $this->randomInt(0, \count($parts) - 1);
return $parts[$randomKey]->accept($this);
}
#[\Override]
public function visitRange(RangeNode $node): string
{
$first = $this->codePointOf($node->start);
$last = $this->codePointOf($node->end);
if (null === $first || null === $last || $first > $last) {
$sample = $node->start->accept($this);
return '' !== $sample ? $sample : $node->end->accept($this);
}
// A code point of the range, the surrogates aside, which UTF-8 cannot
// hold; without UTF mode, a byte.
$codePoint = $this->randomInt($first, $last);
if ($codePoint >= 0xD800 && $codePoint <= 0xDFFF) {
$codePoint = $first;
}
return $this->unicode ? (string) mb_chr($codePoint, 'UTF-8') : \chr($codePoint & 0xFF);
}
#[\Override]
public function visitBackref(BackrefNode $node): string
{
$ref = $node->ref;
// Check numeric reference first
if (Ascii::isDigit($ref)) {
$key = (int) $ref;
if (isset($this->captures[$key])) {
return $this->captures[$key];
}
}
// Check numeric reference with \
if (LibraryPcre::match('/^\\\\(\d++)$/', $ref, $matches)) {
$key = (int) $matches[1];
if (isset($this->captures[$key])) {
return $this->captures[$key];
}
}
// "\g1", "\g{1}", and relative "\g-1", "\g{-1}", "\g{+1}": relative
// ones count the groups opened before the reference.
if (LibraryPcre::match('/^\\\\g\{?([+-]?)(\d++)\}?$/', $ref, $matches)) {
$number = (int) $matches[2];
if ('' !== $matches[1]) {
$opened = \count(array_filter($this->groupIndexMap, static fn (GroupNode $group): bool => $group->startPosition < $node->startPosition));
$number = '-' === $matches[1] ? $opened - $number + 1 : $opened + $number;
}
return $this->captures[$number] ?? '';
}
// Check string/named reference (e.g. for (?&name) conditionals)
if (isset($this->captures[$ref])) {
return $this->captures[$ref];
}
// "\k<name>", "\k{name}", "\k'name'": several groups may share the
// name, and the reference matches the first of them that captured.
if (1 === LibraryPcre::match('/^\\\\k[<{\']([^>}\']++)[>}\']$/', $ref, $m)) {
foreach ($this->groupNumbersByName[$m[1]] ?? [] as $number) {
if (isset($this->captures[$number])) {
return $this->captures[$number];
}
}
return '';
}
// Backreference to a group that hasn't matched yet
// (or doesn't exist). In a real engine, this fails the match.
// For generation, we must return empty string.
return '';
}
#[\Override]
public function visitExtendedCharClass(ExtendedCharClassNode $node): string
{
// PCRE knows which characters are in the set, under "i" too: ask it,
// when it reads "(?[".
$written = $node->accept(PatternPrinter::asWritten());
$class = ClassSetProvider::spelledFor($written, $this->target) ?? $written;
$samples = $this->charactersWithProperty($this->caseless ? '(?i)'.$class : $class);
if ([] !== $samples) {
return $this->getRandomChar($samples);
}
return $node->expression->accept($this);
}
#[\Override]
public function visitClassSetOperation(ClassSetOperationNode $node): string
{
// A guess for an engine that cannot tell: a member of the left operand.
return $node->left?->accept($this) ?? '!';
}
#[\Override]
public function visitScriptRun(ScriptRunNode $node): string
{
return $node->content?->accept($this) ?? '';
}
#[\Override]
public function visitVersionCondition(VersionConditionNode $node): string
{
return '';
}
#[\Override]
public function visitControlChar(ControlCharNode $node): string
{
if ($node->codePoint < 0 || $node->codePoint > 0xFF) {
return '?';
}
return \chr($node->codePoint);
}
#[\Override]
public function visitCharLiteral(CharLiteralNode $node): string
{
if ($node->codePoint < 0 || $node->codePoint > 0x10FFFF) {
return '?';
}
// Without UTF mode, a character up to 255 is a byte.
if (!$this->unicode && $node->codePoint <= 0xFF) {
return \chr($node->codePoint);
}
try {
$char = mb_chr($node->codePoint, 'UTF-8');
if (false === $char) {
return '?';
}
return $char;
} catch (\Throwable) {
return '?';
}
}
#[\Override]
public function visitUnicodeProp(UnicodePropNode $node): string
{
// PCRE knows which characters have the property: ask it.
$escape = $node->hasBraces
? '\\p'.$node->prop
: ((\strlen($node->prop) > 1 || str_starts_with($node->prop, '^')) ? '\\p{'.$node->prop.'}' : '\\p'.$node->prop);
$samples = $this->charactersWithProperty(ClassSetProvider::spelledFor($escape, $this->target) ?? $escape);
if ([] !== $samples) {
return $this->getRandomChar($samples);
}
// Nothing encodable has it (the surrogates): a guess.
if (str_contains($node->prop, 'L')) { // 'L' (Letter)
return $this->getRandomChar(['a', 'b', 'c']);
}
if (str_contains($node->prop, 'N')) { // 'N' (Number)
return $this->getRandomChar(['1', '2', '3']);
}
if (str_contains($node->prop, 'P')) { // 'P' (Punctuation)
return $this->getRandomChar(['.', ',', '!']);
}
return $this->getRandomChar(['a', '1', '.']); // Generic fallback
}
#[\Override]
public function visitPosixClass(PosixClassNode $node): string
{
// PCRE knows the members, negated classes and UTF mode included.
$samples = $this->charactersWithProperty('[[:'.$node->class.':]]');
if ([] !== $samples) {
return $this->getRandomChar($samples);
}
return match (Ascii::lower($node->class)) {
'alpha' => $this->getRandomChar(['a', 'b', 'C', 'Z']),
'alnum' => $this->getRandomChar(['a', 'Z', '1', '9']),
'digit' => $this->getRandomChar(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']),
'xdigit' => $this->getRandomChar(['0', '9', 'a', 'f', 'A', 'F']),
'space' => $this->getRandomChar([' ', "\t", "\n"]),
'lower' => $this->getRandomChar(['a', 'b', 'c', 'z']),
'upper' => $this->getRandomChar(['A', 'B', 'C', 'Z']),
'punct' => $this->getRandomChar(['.', '!', ',', '?']),
'word' => $this->getRandomChar(['a', 'Z', '0', '9', '_']),
'blank' => $this->getRandomChar([' ', "\t"]),
'cntrl' => "\x00", // Control character
'graph', 'print' => $this->getRandomChar(['!', '@', '#']),
default => $this->getRandomChar(['a', '1', ' ']),
};
}
#[\Override]
public function visitComment(CommentNode $node): string
{
// Comments do not generate text
return '';
}
#[\Override]
public function visitConditional(ConditionalNode $node): string
{
if ($this->isConditionSatisfied($node->condition)) {
return $node->yes->accept($this);
}
return $node->no->accept($this);
}
#[\Override]
public function visitSubroutine(SubroutineNode $node): string
{
if (null === $this->rootPattern || $this->rootPattern instanceof SubroutineNode) {
throw new SampleGenerationException('Sample generation for subroutines is not supported.');
}
if ($this->recursionDepth >= self::MAX_RECURSION_DEPTH) {
return '';
}
$target = $this->resolveSubroutineTarget($node);
if (null === $target) {
throw new SampleGenerationException('Sample generation for subroutines is not supported.');
}
$this->recursionDepth++;
$this->calls[] = \in_array($node->reference, ['R', '0'], true) || !$target instanceof GroupNode
? 0
: $this->groupNumbers[spl_object_id($target)] ?? -1;
try {
return $this->acceptedIn($target instanceof GroupNode ? $target->child : $target, inPlace: true);
} finally {
array_pop($this->calls);
$this->recursionDepth--;
}
}
#[\Override]
public function visitPcreVerb(PcreVerbNode $node): string
{
// Verbs do not generate text
return '';
}
#[\Override]
public function visitDefine(DefineNode $node): string
{
// DEFINE blocks do not generate text, they only define subpatterns
return '';
}
#[\Override]
public function visitLimitMatch(LimitMatchNode $node): string
{
return '';
}
#[\Override]
public function visitCallout(CalloutNode $node): string
{
// Callouts do not match characters, so they generate no sample text.
return '';
}
/**
* A sample of the tree the engine matches, checked by the pattern as it
* spells it.
*
* @throws SampleGenerationException when no sample the running engine matches was found
*/
private function checkedSample(string $regex, string $checked, RegexNode $ast): string
{
// Generation is best-effort (lookaround hints, negated classes, ...):
// verify the sample against the real engine and retry a few times
// before settling for the last attempt. The engine checks it without
// the JIT, which crashes PHP on some pattern and subject pairs.
// Only a pattern this PHP cannot compile gets a sample nothing checks.
$compiles = null === $this->engine->compile($checked);
$attempts = [];
$gaveUp = 0;
$engineError = '';
// A condition with one valid branch in two misses once in 2^32 calls.
for ($attempt = 0; $attempt < 32; $attempt++) {
$sample = $ast->accept($this);
$match = $this->engine->match($checked, $sample);
// Verified, or a pattern this PCRE runtime cannot compile: what
// we have. A limit or an error it met checks nothing: another try.
if (true === $match->matched || !$compiles) {
return $sample;
}
if (false === $match->matched) {
$attempts[$sample] = true;
} else {
$gaveUp++;
$engineError = (string) $match->error;
// A sample that matches is found quickly: the samples the
// engine gives up on are costly misses, and eight end it.
if (8 === $gaveUp) {
break;
}
}
}
// An assertion on what surrounds the match, as "\b" or "(?!^)", may
// hold once the sample has text around it. A sample the engine gave
// up on is not tried again: with text around it, it gives up again.
foreach (array_keys($attempts) as $attempt) {
foreach (['a', ' ', "\n"] as $padding) {
foreach ([$padding.$attempt, $attempt.$padding, $padding.$attempt.$padding] as $padded) {
if (true === $this->engine->match($checked, $padded)->matched) {
return $padded;
}
}
}
}
if ($gaveUp > 0) {
throw new SampleGenerationException(\sprintf('No sample matching %s was found: the engine gave up checking %d of the samples (%s).', $regex, $gaveUp, $engineError));
}
throw new SampleGenerationException(\sprintf('No sample matching %s was found: the pattern may match nothing, or its assertions ask for more than the samples give.', $regex));
}
private function generateGroup(GroupNode $node): string
{
// Lookarounds are zero-width assertions and should not generate text
if (\in_array($node->type, [
GroupType::LookaheadPositive,
GroupType::LookaheadNegative,
GroupType::LookbehindPositive,
GroupType::LookbehindNegative,
GroupType::ScanSubstring,
], true)) {
if (GroupType::LookbehindPositive === $node->type) {
$prefix = $this->acceptedIn($node->child);
if ('' !== $prefix) {
$this->requiredPrefixes[] = $prefix;
}
} elseif (GroupType::LookaheadPositive === $node->type) {
$suffix = $this->acceptedIn($node->child);
if ('' !== $suffix) {
$this->requiredSuffixes[] = $suffix;
}
}
return '';
}
$result = $node->child->accept($this);
// Store the result if it's a capturing group
if (GroupType::Capturing === $node->type) {
$groupIndex = $this->groupNumbers[spl_object_id($node)] ?? $this->groupCounter++;
$result = $this->fitScans($groupIndex, $node, $result);
$this->captures[$groupIndex] = $result;
$this->groupCounter = max($this->groupCounter, $groupIndex + 1);
} elseif (GroupType::Named === $node->type) {
$groupIndex = $this->groupNumbers[spl_object_id($node)] ?? $this->groupCounter++;
$result = $this->fitScans($groupIndex, $node, $result);
$this->captures[$groupIndex] = $result;
if ($node->name) {
$this->captures[$node->name] = $result;
}
$this->groupCounter = max($this->groupCounter, $groupIndex + 1);
}
// For non-capturing, etc., just return the child's result
return $result;
}
/**
* The code point a range end stands for: a character, a byte without UTF
* mode, or an escape.
*/
private function codePointOf(NodeInterface $node): ?int
{
if ($node instanceof CharLiteralNode) {
return $node->codePoint >= 0 && $node->codePoint <= 0x10FFFF ? $node->codePoint : null;
}
if (!$node instanceof LiteralNode || '' === $node->value) {
return null;
}
$codePoint = $this->unicode ? mb_ord($node->value, 'UTF-8') : \ord($node->value[0]);
return false === $codePoint ? null : $codePoint;
}
/**
* Up to eight characters the escape "\p{...}", or an extended class,
* matches: common ones first, then the whole range, one chunk at a time;
* bytes without UTF mode. None when the engine refuses it.
*
* @return list<string>
*/
private function charactersWithProperty(string $escape): array
{
$key = ($this->unicode ? 'u' : 'b').$escape;
if (isset(self::$propertySamples[$key])) {
return self::$propertySamples[$key];
}
// A written class escapes its "/", so "/" delimits it.
$pattern = '/'.$escape.'/'.($this->unicode ? 'u' : '');
$found = [];
foreach ($this->unicode ? self::codePointChunks() : [implode('', array_map(\chr(...), range(0, 255)))] as $chunk) {
$matches = $this->engine->matchAll($pattern, $chunk);
if (null === $matches) {
break;
}
foreach ($matches as $character) {
$found[$character] = true;
if (\count($found) >= 8) {
break 2;
}
}
}
self::$propertySamples = StaticCaches::makeRoom(self::$propertySamples);
StaticCaches::register(self::class, self::clearCaches(...));
return self::$propertySamples[$key] = array_map(strval(...), array_keys($found));
}
/**
* The chunks are bounded by the code points, 272 of them; the property
* samples by StaticCaches::MAX_ENTRIES.
*/
private static function clearCaches(): void
{
self::$propertySamples = [];
self::$codePointChunks = [];
}
/**
* Common characters first, then every code point but the surrogates,
* 4096 at a time, built once.
*
* @return \Generator<int, string>
*/
private static function codePointChunks(): \Generator
{
yield self::COMMON_CHARACTERS;
for ($start = 0; $start <= 0x10FFFF; $start += 4096) {
if (!isset(self::$codePointChunks[$start])) {
$chunk = '';
for ($codePoint = $start; $codePoint < $start + 4096 && $codePoint <= 0x10FFFF; $codePoint++) {
if ($codePoint < 0xD800 || $codePoint > 0xDFFF) {
$chunk .= mb_chr($codePoint, 'UTF-8');
}
}
StaticCaches::register(self::class, self::clearCaches(...));
self::$codePointChunks[$start] = $chunk;
}
yield self::$codePointChunks[$start];
}
}
/**
* Picks a character that is actually outside the negated set by testing
* candidates against the compiled character class.
*/
private function sampleForNegatedClass(CharClassNode $node): string
{
$candidates = [
'a', 'b', 'c', 'd', 'e',
'A', 'B', 'C', 'D', 'E',
'0', '1', '2', '3', '4',
'!', '?', '_', '-', ' ', "\t", 'é', '☃',
];
try {
$written = $node->accept(PatternPrinter::asWritten());
} catch (\Throwable) {
return '!';
}
$compiled = ClassSetProvider::spelledFor($written, $this->target) ?? $written;
foreach (['/', '~', '#', '%', '@', ';'] as $delimiter) {
if (str_contains($compiled, $delimiter)) {
continue;
}
// The class as it reads where it stands: caseless under "i".
$classPattern = $delimiter.$compiled.$delimiter.($this->caseless ? 'i' : '').($this->unicode ? 'u' : '');
foreach ($candidates as $candidate) {
if (true === $this->engine->match($classPattern, $candidate)->matched) {
return $candidate;
}
}
break;
}