This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
66fe6f34fd5b34a56bb42b2f44c4f28b8a90975b
[perl5.git] / t / re / pat.t
1 #!./perl
2 #
3 # This is a home for regular expression tests that don't fit into
4 # the format supported by re/regexp.t.  If you want to add a test
5 # that does fit that format, add it to re/re_tests, not here.
6
7 use strict;
8 use warnings;
9 use 5.010;
10
11 sub run_tests;
12
13 $| = 1;
14
15
16 BEGIN {
17     chdir 't' if -d 't';
18     require Config; import Config;
19     require './test.pl'; require './charset_tools.pl';
20     require './loc_tools.pl';
21     set_up_inc('../lib', '.', '../ext/re');
22 }
23     skip_all('no re module') unless defined &DynaLoader::boot_DynaLoader;
24     skip_all_without_unicode_tables();
25
26 plan tests => 844;  # Update this when adding/deleting tests.
27
28 run_tests() unless caller;
29
30 #
31 # Tests start here.
32 #
33 sub run_tests {
34
35     {
36         my $x = "abc\ndef\n";
37         (my $x_pretty = $x) =~ s/\n/\\n/g;
38
39         ok $x =~ /^abc/,  qq ["$x_pretty" =~ /^abc/];
40         ok $x !~ /^def/,  qq ["$x_pretty" !~ /^def/];
41
42         # used to be a test for $*
43         ok $x =~ /^def/m, qq ["$x_pretty" =~ /^def/m];
44
45         ok(!($x =~ /^xxx/), qq ["$x_pretty" =~ /^xxx/]);
46         ok(!($x !~ /^abc/), qq ["$x_pretty" !~ /^abc/]);
47
48          ok $x =~ /def/, qq ["$x_pretty" =~ /def/];
49         ok(!($x !~ /def/), qq ["$x_pretty" !~ /def/]);
50
51          ok $x !~ /.def/, qq ["$x_pretty" !~ /.def/];
52         ok(!($x =~ /.def/), qq ["$x_pretty" =~ /.def/]);
53
54          ok $x =~ /\ndef/, qq ["$x_pretty" =~ /\\ndef/];
55         ok(!($x !~ /\ndef/), qq ["$x_pretty" !~ /\\ndef/]);
56     }
57
58     {
59         $_ = '123';
60         ok /^([0-9][0-9]*)/, qq [\$_ = '$_'; /^([0-9][0-9]*)/];
61     }
62
63     {
64         $_ = 'aaabbbccc';
65          ok /(a*b*)(c*)/ && $1 eq 'aaabbb' && $2 eq 'ccc',
66                                              qq [\$_ = '$_'; /(a*b*)(c*)/];
67          ok /(a+b+c+)/ && $1 eq 'aaabbbccc', qq [\$_ = '$_'; /(a+b+c+)/];
68         unlike($_, qr/a+b?c+/, qq [\$_ = '$_'; /a+b?c+/]);
69
70         $_ = 'aaabccc';
71          ok /a+b?c+/, qq [\$_ = '$_'; /a+b?c+/];
72          ok /a*b?c*/, qq [\$_ = '$_'; /a*b?c*/];
73
74         $_ = 'aaaccc';
75          ok /a*b?c*/, qq [\$_ = '$_'; /a*b?c*/];
76         unlike($_, qr/a*b+c*/, qq [\$_ = '$_'; /a*b+c*/]);
77
78         $_ = 'abcdef';
79          ok /bcd|xyz/, qq [\$_ = '$_'; /bcd|xyz/];
80          ok /xyz|bcd/, qq [\$_ = '$_'; /xyz|bcd/];
81          ok m|bc/*d|,  qq [\$_ = '$_'; m|bc/*d|];
82          ok /^$_$/,    qq [\$_ = '$_'; /^\$_\$/];
83     }
84
85     {
86         # used to be a test for $*
87         ok "ab\ncd\n" =~ /^cd/m, q ["ab\ncd\n" =~ /^cd/m];
88     }
89
90     {
91         our %XXX = map {($_ => $_)} 123, 234, 345;
92
93         our @XXX = ('ok 1','not ok 1', 'ok 2','not ok 2','not ok 3');
94         while ($_ = shift(@XXX)) {
95             my $e = index ($_, 'not') >= 0 ? '' : 1;
96             my $r = m?(.*)?;
97             is($r, $e, "?(.*)?");
98             /not/ && reset;
99             if (/not ok 2/) {
100                 if ($^O eq 'VMS') {
101                     $_ = shift(@XXX);
102                 }
103                 else {
104                     reset 'X';
105                 }
106             }
107         }
108
109         SKIP: {
110             if ($^O eq 'VMS') {
111                 skip "Reset 'X'", 1;
112             }
113             ok !keys %XXX, "%XXX is empty";
114         }
115
116     }
117
118     {
119         my $message = "Test empty pattern";
120         my $xyz = 'xyz';
121         my $cde = 'cde';
122
123         $cde =~ /[^ab]*/;
124         $xyz =~ //;
125         is($&, $xyz, $message);
126
127         my $foo = '[^ab]*';
128         $cde =~ /$foo/;
129         $xyz =~ //;
130         is($&, $xyz, $message);
131
132         $cde =~ /$foo/;
133         my $null;
134         no warnings 'uninitialized';
135         $xyz =~ /$null/;
136         is($&, $xyz, $message);
137
138         $null = "";
139         $xyz =~ /$null/;
140         is($&, $xyz, $message);
141
142         # each entry: regexp, match string, $&, //o match success
143         my @tests =
144           (
145            [ "", "xy", "x", 1 ],
146            [ "y", "yz", "y", !1 ],
147           );
148         for my $test (@tests) {
149             my ($re, $str, $matched, $omatch) = @$test;
150             $xyz =~ /x/o;
151             ok($str =~ /$re/, "$str matches /$re/");
152             is($&, $matched, "on $matched");
153             $xyz =~ /x/o;
154             is($str =~ /$re/o, $omatch, "$str matches /$re/o (or not)");
155         }
156     }
157
158     {
159         my $message = q !Check $`, $&, $'!;
160         $_ = 'abcdefghi';
161         /def/;        # optimized up to cmd
162         is("$`:$&:$'", 'abc:def:ghi', $message);
163
164         no warnings 'void';
165         /cde/ + 0;    # optimized only to spat
166         is("$`:$&:$'", 'ab:cde:fghi', $message);
167
168         /[d][e][f]/;    # not optimized
169         is("$`:$&:$'", 'abc:def:ghi', $message);
170     }
171
172     {
173         $_ = 'now is the {time for all} good men to come to.';
174         / \{([^}]*)}/;
175         is($1, 'time for all', "Match braces");
176     }
177
178     {
179         my $message = "{N,M} quantifier";
180         $_ = 'xxx {3,4}  yyy   zzz';
181         ok(/( {3,4})/, $message);
182         is($1, '   ', $message);
183         unlike($_, qr/( {4,})/, $message);
184         ok(/( {2,3}.)/, $message);
185         is($1, '  y', $message);
186         ok(/(y{2,3}.)/, $message);
187         is($1, 'yyy ', $message);
188         unlike($_, qr/x {3,4}/, $message);
189         unlike($_, qr/^xxx {3,4}/, $message);
190     }
191
192     {
193         my $message = "Test /g";
194         local $" = ":";
195         $_ = "now is the time for all good men to come to.";
196         my @words = /(\w+)/g;
197         my $exp   = "now:is:the:time:for:all:good:men:to:come:to";
198
199         is("@words", $exp, $message);
200
201         @words = ();
202         while (/\w+/g) {
203             push (@words, $&);
204         }
205         is("@words", $exp, $message);
206
207         @words = ();
208         pos = 0;
209         while (/to/g) {
210             push(@words, $&);
211         }
212         is("@words", "to:to", $message);
213
214         pos $_ = 0;
215         @words = /to/g;
216         is("@words", "to:to", $message);
217     }
218
219     {
220         $_ = "abcdefghi";
221
222         my $pat1 = 'def';
223         my $pat2 = '^def';
224         my $pat3 = '.def.';
225         my $pat4 = 'abc';
226         my $pat5 = '^abc';
227         my $pat6 = 'abc$';
228         my $pat7 = 'ghi';
229         my $pat8 = '\w*ghi';
230         my $pat9 = 'ghi$';
231
232         my $t1 = my $t2 = my $t3 = my $t4 = my $t5 =
233         my $t6 = my $t7 = my $t8 = my $t9 = 0;
234
235         for my $iter (1 .. 5) {
236             $t1++ if /$pat1/o;
237             $t2++ if /$pat2/o;
238             $t3++ if /$pat3/o;
239             $t4++ if /$pat4/o;
240             $t5++ if /$pat5/o;
241             $t6++ if /$pat6/o;
242             $t7++ if /$pat7/o;
243             $t8++ if /$pat8/o;
244             $t9++ if /$pat9/o;
245         }
246         my $x = "$t1$t2$t3$t4$t5$t6$t7$t8$t9";
247         is($x, '505550555', "Test /o");
248     }
249
250     {
251         my $xyz = 'xyz';
252         ok "abc" =~ /^abc$|$xyz/, "| after \$";
253
254         # perl 4.009 says "unmatched ()"
255         my $message = '$ inside ()';
256
257         my $result;
258         eval '"abc" =~ /a(bc$)|$xyz/; $result = "$&:$1"';
259         is($@, "", $message);
260         is($result, "abc:bc", $message);
261     }
262
263     {
264         my $message = "Scalar /g";
265         $_ = "abcfooabcbar";
266
267         ok( /abc/g && $` eq "", $message);
268         ok( /abc/g && $` eq "abcfoo", $message);
269         ok(!/abc/g, $message);
270
271         $message = "Scalar /gi";
272         pos = 0;
273         ok( /ABC/gi && $` eq "", $message);
274         ok( /ABC/gi && $` eq "abcfoo", $message);
275         ok(!/ABC/gi, $message);
276
277         $message = "Scalar /g";
278         pos = 0;
279         ok( /abc/g && $' eq "fooabcbar", $message);
280         ok( /abc/g && $' eq "bar", $message);
281
282         $_ .= '';
283         my @x = /abc/g;
284         is(@x, 2, "/g reset after assignment");
285     }
286
287     {
288         my $message = '/g, \G and pos';
289         $_ = "abdc";
290         pos $_ = 2;
291         /\Gc/gc;
292         is(pos $_, 2, $message);
293         /\Gc/g;
294         is(pos $_, undef, $message);
295     }
296
297     {
298         my $message = '(?{ })';
299         our $out = 1;
300         'abc' =~ m'a(?{ $out = 2 })b';
301         is($out, 2, $message);
302
303         $out = 1;
304         'abc' =~ m'a(?{ $out = 3 })c';
305         is($out, 1, $message);
306     }
307
308     {
309         $_ = 'foobar1 bar2 foobar3 barfoobar5 foobar6';
310         my @out = /(?<!foo)bar./g;
311         is("@out", 'bar2 barf', "Negative lookbehind");
312     }
313
314     {
315         my $message = "REG_INFTY tests";
316         # Tests which depend on REG_INFTY
317
318         #  Defaults assumed if this fails
319         eval { require Config; };
320         $::reg_infty   = $Config::Config{reg_infty} // 32767;
321         $::reg_infty_m = $::reg_infty - 1;
322         $::reg_infty_p = $::reg_infty + 1;
323         $::reg_infty_m = $::reg_infty_m;   # Suppress warning.
324
325         # As well as failing if the pattern matches do unexpected things, the
326         # next three tests will fail if you should have picked up a lower-than-
327         # default value for $reg_infty from Config.pm, but have not.
328
329         is(eval q{('aaa' =~ /(a{1,$::reg_infty_m})/)[0]}, 'aaa', $message);
330         is($@, '', $message);
331         is(eval q{('a' x $::reg_infty_m) =~ /a{$::reg_infty_m}/}, 1, $message);
332         is($@, '', $message);
333         isnt(q{('a' x ($::reg_infty_m - 1)) !~ /a{$::reg_infty_m}/}, 1, $message);
334         is($@, '', $message);
335
336         eval "'aaa' =~ /a{1,$::reg_infty}/";
337         like($@, qr/^\QQuantifier in {,} bigger than/, $message);
338         eval "'aaa' =~ /a{1,$::reg_infty_p}/";
339         like($@, qr/^\QQuantifier in {,} bigger than/, $message);
340     }
341
342     {
343         # Poke a couple more parse failures
344         my $context = 'x' x 256;
345         eval qq("${context}y" =~ /(?<=$context)y/);
346         ok $@ =~ /^\QLookbehind longer than 255 not/, "Lookbehind limit";
347     }
348
349     {
350         # Long Monsters
351         for my $l (125, 140, 250, 270, 300000, 30) { # Ordered to free memory
352             my $a = 'a' x $l;
353             my $message = "Long monster, length = $l";
354             like("ba$a=", qr/a$a=/, $message);
355             unlike("b$a=", qr/a$a=/, $message);
356             like("b$a=", qr/ba+=/, $message);
357
358             like("ba$a=", qr/b(?:a|b)+=/, $message);
359         }
360     }
361
362     {
363         # 20000 nodes, each taking 3 words per string, and 1 per branch
364         my $long_constant_len = join '|', 12120 .. 32645;
365         my $long_var_len = join '|', 8120 .. 28645;
366         my %ans = ( 'ax13876y25677lbc' => 1,
367                     'ax13876y25677mcb' => 0, # not b.
368                     'ax13876y35677nbc' => 0, # Num too big
369                     'ax13876y25677y21378obc' => 1,
370                     'ax13876y25677y21378zbc' => 0,    # Not followed by [k-o]
371                     'ax13876y25677y21378y21378kbc' => 1,
372                     'ax13876y25677y21378y21378kcb' => 0, # Not b.
373                     'ax13876y25677y21378y21378y21378kbc' => 0, # 5 runs
374                   );
375
376         for (keys %ans) {
377             my $message = "20000 nodes, const-len '$_'";
378             ok !($ans{$_} xor /a(?=([yx]($long_constant_len)){2,4}[k-o]).*b./o), $message;
379
380             $message = "20000 nodes, var-len '$_'";
381             ok !($ans{$_} xor /a(?=([yx]($long_var_len)){2,4}[k-o]).*b./o,), $message;
382         }
383     }
384
385     {
386         my $message = "Complicated backtracking";
387         $_ = " a (bla()) and x(y b((l)u((e))) and b(l(e)e)e";
388         my $expect = "(bla()) ((l)u((e))) (l(e)e)";
389
390         our $c;
391         sub matchit {
392           m/
393              (
394                \(
395                (?{ $c = 1 })    # Initialize
396                (?:
397                  (?(?{ $c == 0 })   # PREVIOUS iteration was OK, stop the loop
398                    (?!
399                    )        # Fail: will unwind one iteration back
400                  )
401                  (?:
402                    [^()]+        # Match a big chunk
403                    (?=
404                      [()]
405                    )        # Do not try to match subchunks
406                  |
407                    \(
408                    (?{ ++$c })
409                  |
410                    \)
411                    (?{ --$c })
412                  )
413                )+        # This may not match with different subblocks
414              )
415              (?(?{ $c != 0 })
416                (?!
417                )        # Fail
418              )            # Otherwise the chunk 1 may succeed with $c>0
419            /xg;
420         }
421
422         my @ans = ();
423         my $res;
424         push @ans, $res while $res = matchit;
425         is("@ans", "1 1 1", $message);
426
427         @ans = matchit;
428         is("@ans", $expect, $message);
429
430         $message = "Recursion with (??{ })";
431         our $matched;
432         $matched = qr/\((?:(?>[^()]+)|(??{$matched}))*\)/;
433
434         @ans = my @ans1 = ();
435         push (@ans, $res), push (@ans1, $&) while $res = m/$matched/g;
436
437         is("@ans", "1 1 1", $message);
438         is("@ans1", $expect, $message);
439
440         @ans = m/$matched/g;
441         is("@ans", $expect, $message);
442
443     }
444
445     {
446         ok "abc" =~ /^(??{"a"})b/, '"abc" =~ /^(??{"a"})b/';
447     }
448
449     {
450         my @ans = ('a/b' =~ m%(.*/)?(.*)%);    # Stack may be bad
451         is("@ans", 'a/ b', "Stack may be bad");
452     }
453
454     {
455         my $message = "Eval-group not allowed at runtime";
456         my $code = '{$blah = 45}';
457         our $blah = 12;
458         eval { /(?$code)/ };
459         ok($@ && $@ =~ /not allowed at runtime/ && $blah == 12, $message);
460
461         $blah = 12;
462         my $res = eval { "xx" =~ /(?$code)/o };
463         {
464             no warnings 'uninitialized';
465             chomp $@; my $message = "$message '$@', '$res', '$blah'";
466             ok($@ && $@ =~ /not allowed at runtime/ && $blah == 12, $message);
467         }
468
469         $code = '=xx';
470         $blah = 12;
471         $res = eval { "xx" =~ /(?$code)/o };
472         {
473             no warnings 'uninitialized';
474             my $message = "$message '$@', '$res', '$blah'";
475             ok(!$@ && $res, $message);
476         }
477
478         $code = '{$blah = 45}';
479         $blah = 12;
480         eval "/(?$code)/";
481         is($blah, 45, $message);
482
483         $blah = 12;
484         /(?{$blah = 45})/;
485         is($blah, 45, $message);
486     }
487
488     {
489         my $message = "Pos checks";
490         my $x = 'banana';
491         $x =~ /.a/g;
492         is(pos $x, 2, $message);
493
494         $x =~ /.z/gc;
495         is(pos $x, 2, $message);
496
497         sub f {
498             my $p = $_[0];
499             return $p;
500         }
501
502         $x =~ /.a/g;
503         is(f (pos $x), 4, $message);
504     }
505
506     {
507         my $message = 'Checking $^R';
508         our $x = $^R = 67;
509         'foot' =~ /foo(?{$x = 12; 75})[t]/;
510         is($^R, 75, $message);
511
512         $x = $^R = 67;
513         'foot' =~ /foo(?{$x = 12; 75})[xy]/;
514         ok($^R eq '67' && $x eq '12', $message);
515
516         $x = $^R = 67;
517         'foot' =~ /foo(?{ $^R + 12 })((?{ $x = 12; $^R + 17 })[xy])?/;
518         ok($^R eq '79' && $x eq '12', $message);
519     }
520
521     {
522         is(qr/\b\v$/i,    '(?^i:\b\v$)', 'qr/\b\v$/i');
523         is(qr/\b\v$/s,    '(?^s:\b\v$)', 'qr/\b\v$/s');
524         is(qr/\b\v$/m,    '(?^m:\b\v$)', 'qr/\b\v$/m');
525         is(qr/\b\v$/x,    '(?^x:\b\v$)', 'qr/\b\v$/x');
526         is(qr/\b\v$/xism, '(?^msix:\b\v$)',  'qr/\b\v$/xism');
527         is(qr/\b\v$/,     '(?^:\b\v$)', 'qr/\b\v$/');
528     }
529
530     {   # Test that charset modifier work, and are interpolated
531         is(qr/\b\v$/, '(?^:\b\v$)', 'Verify no locale, no unicode_strings gives default modifier');
532         is(qr/(?l:\b\v$)/, '(?^:(?l:\b\v$))', 'Verify infix l modifier compiles');
533         is(qr/(?u:\b\v$)/, '(?^:(?u:\b\v$))', 'Verify infix u modifier compiles');
534         is(qr/(?l)\b\v$/, '(?^:(?l)\b\v$)', 'Verify (?l) compiles');
535         is(qr/(?u)\b\v$/, '(?^:(?u)\b\v$)', 'Verify (?u) compiles');
536
537         my $dual = qr/\b\v$/;
538         my $locale;
539
540       SKIP: {
541             skip 'Locales not available', 1 unless locales_enabled('LC_CTYPE');
542
543             use locale;
544             $locale = qr/\b\v$/;
545             is($locale,    '(?^l:\b\v$)', 'Verify has l modifier when compiled under use locale');
546             no locale;
547         }
548
549         use feature 'unicode_strings';
550         my $unicode = qr/\b\v$/;
551         is($unicode,    '(?^u:\b\v$)', 'Verify has u modifier when compiled under unicode_strings');
552         is(qr/abc$dual/,    '(?^u:abc(?^:\b\v$))', 'Verify retains d meaning when interpolated under locale');
553
554       SKIP: {
555             skip 'Locales not available', 1 unless locales_enabled('LC_CTYPE');
556
557             is(qr/abc$locale/,    '(?^u:abc(?^l:\b\v$))', 'Verify retains l when interpolated under unicode_strings');
558         }
559
560         no feature 'unicode_strings';
561       SKIP: {
562             skip 'Locales not available', 1 unless locales_enabled('LC_CTYPE');
563             is(qr/abc$locale/,    '(?^:abc(?^l:\b\v$))', 'Verify retains l when interpolated outside locale and unicode strings');
564         }
565
566         is(qr/def$unicode/,    '(?^:def(?^u:\b\v$))', 'Verify retains u when interpolated outside locale and unicode strings');
567
568       SKIP: {
569             skip 'Locales not available', 2 unless locales_enabled('LC_CTYPE');
570
571              use locale;
572             is(qr/abc$dual/,    '(?^l:abc(?^:\b\v$))', 'Verify retains d meaning when interpolated under locale');
573             is(qr/abc$unicode/,    '(?^l:abc(?^u:\b\v$))', 'Verify retains u when interpolated under locale');
574         }
575     }
576
577     {
578         my $message = "Look around";
579         $_ = 'xabcx';
580         foreach my $ans ('', 'c') {
581             ok(/(?<=(?=a)..)((?=c)|.)/g, $message);
582             is($1, $ans, $message);
583         }
584     }
585
586     {
587         my $message = "Empty clause";
588         $_ = 'a';
589         foreach my $ans ('', 'a', '') {
590             ok(/^|a|$/g, $message);
591             is($&, $ans, $message);
592         }
593     }
594
595     {
596         sub prefixify {
597         my $message = "Prefixify";
598             {
599                 my ($v, $a, $b, $res) = @_;
600                 ok($v =~ s/\Q$a\E/$b/, $message);
601                 is($v, $res, $message);
602             }
603         }
604
605         prefixify ('/a/b/lib/arch', "/a/b/lib", 'X/lib', 'X/lib/arch');
606         prefixify ('/a/b/man/arch', "/a/b/man", 'X/man', 'X/man/arch');
607     }
608
609     {
610         $_ = 'var="foo"';
611         /(\")/;
612         ok $1 && /$1/, "Capture a quote";
613     }
614
615     {
616         no warnings 'closure';
617         my $message = '(?{ $var } refers to package vars';
618         package aa;
619         our $c = 2;
620         $::c = 3;
621         '' =~ /(?{ $c = 4 })/;
622         main::is($c, 4, $message);
623         main::is($::c, 3, $message);
624     }
625
626     {
627         is(eval 'q(a:[b]:) =~ /[x[:foo:]]/', undef);
628         like ($@, qr/POSIX class \[:[^:]+:\] unknown in regex/,
629               'POSIX class [: :] must have valid name');
630
631         for my $d (qw [= .]) {
632             is(eval "/[[${d}foo${d}]]/", undef);
633             like ($@, qr/\QPOSIX syntax [$d $d] is reserved for future extensions/,
634                   "POSIX syntax [[$d $d]] is an error");
635         }
636     }
637
638     {
639         # test if failure of patterns returns empty list
640         my $message = "Failed pattern returns empty list";
641         $_ = 'aaa';
642         @_ = /bbb/;
643         is("@_", "", $message);
644
645         @_ = /bbb/g;
646         is("@_", "", $message);
647
648         @_ = /(bbb)/;
649         is("@_", "", $message);
650
651         @_ = /(bbb)/g;
652         is("@_", "", $message);
653     }
654
655     {
656         my $message = '@- and @+ and @{^CAPTURE} tests';
657
658         $_= "ace";
659         /c(?=.$)/;
660         is($#{^CAPTURE}, -1, $message);
661         is($#+, 0, $message);
662         is($#-, 0, $message);
663         is($+ [0], 2, $message);
664         is($- [0], 1, $message);
665         ok(!defined $+ [1] && !defined $- [1] &&
666            !defined $+ [2] && !defined $- [2], $message);
667
668         /a(c)(e)/;
669         is($#{^CAPTURE}, 1, $message); # one less than $#-
670         is($#+, 2, $message);
671         is($#-, 2, $message);
672         is($+ [0], 3, $message);
673         is($- [0], 0, $message);
674         is(${^CAPTURE}[0], "c", $message);
675         is($+ [1], 2, $message);
676         is($- [1], 1, $message);
677         is(${^CAPTURE}[1], "e", $message);
678         is($+ [2], 3, $message);
679         is($- [2], 2, $message);
680         ok(!defined $+ [3] && !defined $- [3] &&
681            !defined ${^CAPTURE}[2] && !defined ${^CAPTURE}[3] &&
682            !defined $+ [4] && !defined $- [4], $message);
683
684         # Exists has a special check for @-/@+ - bug 45147
685         ok(exists $-[0], $message);
686         ok(exists $+[0], $message);
687         ok(exists ${^CAPTURE}[0], $message);
688         ok(exists ${^CAPTURE}[1], $message);
689         ok(exists $-[2], $message);
690         ok(exists $+[2], $message);
691         ok(!exists ${^CAPTURE}[2], $message);
692         ok(!exists $-[3], $message);
693         ok(!exists $+[3], $message);
694         ok(exists ${^CAPTURE}[-1], $message);
695         ok(exists ${^CAPTURE}[-2], $message);
696         ok(exists $-[-1], $message);
697         ok(exists $+[-1], $message);
698         ok(exists $-[-3], $message);
699         ok(exists $+[-3], $message);
700         ok(!exists $-[-4], $message);
701         ok(!exists $+[-4], $message);
702         ok(!exists ${^CAPTURE}[-3], $message);
703
704
705         /.(c)(b)?(e)/;
706         is($#{^CAPTURE}, 2, $message); # one less than $#-
707         is($#+, 3, $message);
708         is($#-, 3, $message);
709         is(${^CAPTURE}[0], "c", $message);
710         is(${^CAPTURE}[2], "e", $message . "[$1 $3]");
711         is($+ [1], 2, $message);
712         is($- [1], 1, $message);
713         is($+ [3], 3, $message);
714         is($- [3], 2, $message);
715         ok(!defined $+ [2] && !defined $- [2] &&
716            !defined $+ [4] && !defined $- [4] &&
717            !defined ${^CAPTURE}[1], $message);
718
719         /.(c)/;
720         is($#{^CAPTURE}, 0, $message); # one less than $#-
721         is($#+, 1, $message);
722         is($#-, 1, $message);
723         is(${^CAPTURE}[0], "c", $message);
724         is($+ [0], 2, $message);
725         is($- [0], 0, $message);
726         is($+ [1], 2, $message);
727         is($- [1], 1, $message);
728         ok(!defined $+ [2] && !defined $- [2] &&
729            !defined $+ [3] && !defined $- [3] &&
730            !defined ${^CAPTURE}[1], $message);
731
732         /.(c)(ba*)?/;
733         is($#{^CAPTURE}, 0, $message); # one less than $#-
734         is($#+, 2, $message);
735         is($#-, 1, $message);
736
737         # Check that values don’t stick
738         "     "=~/()()()(.)(..)/;
739         my($m,$p,$q) = (\$-[5], \$+[5], \${^CAPTURE}[4]);
740         () = "$$_" for $m, $p, $q; # FETCH (or eqv.)
741         " " =~ /()/;
742         is $$m, undef, 'values do not stick to @- elements';
743         is $$p, undef, 'values do not stick to @+ elements';
744         is $$q, undef, 'values do not stick to @{^CAPTURE} elements';
745     }
746
747     foreach ('$+[0] = 13', '$-[0] = 13', '@+ = (7, 6, 5)',
748              '${^CAPTURE}[0] = 13',
749              '@- = qw (foo bar)', '$^N = 42') {
750         is(eval $_, undef);
751         like($@, qr/^Modification of a read-only value attempted/,
752              '$^N, @- and @+ are read-only');
753     }
754
755     {
756         my $message = '\G testing';
757         $_ = 'aaa';
758         pos = 1;
759         my @a = /\Ga/g;
760         is("@a", "a a", $message);
761
762         my $str = 'abcde';
763         pos $str = 2;
764         unlike($str, qr/^\G/, $message);
765         unlike($str, qr/^.\G/, $message);
766         like($str, qr/^..\G/, $message);
767         unlike($str, qr/^...\G/, $message);
768         ok($str =~ /\G../ && $& eq 'cd', $message);
769         ok($str =~ /.\G./ && $& eq 'bc', $message);
770
771     }
772
773     {
774         my $message = '\G and intuit and anchoring';
775         $_ = "abcdef";
776         pos = 0;
777         ok($_ =~ /\Gabc/, $message);
778         ok($_ =~ /^\Gabc/, $message);
779
780         pos = 3;
781         ok($_ =~ /\Gdef/, $message);
782         pos = 3;
783         ok($_ =~ /\Gdef$/, $message);
784         pos = 3;
785         ok($_ =~ /abc\Gdef$/, $message);
786         pos = 3;
787         ok($_ =~ /^abc\Gdef$/, $message);
788         pos = 3;
789         ok($_ =~ /c\Gd/, $message);
790         pos = 3;
791         ok($_ =~ /..\GX?def/, $message);
792     }
793
794     {
795         my $s = '123';
796         pos($s) = 1;
797         my @a = $s =~ /(\d)\G/g; # this infinitely looped up till 5.19.1
798         is("@a", "1", '\G looping');
799     }
800
801
802     {
803         my $message = 'pos inside (?{ })';
804         my $str = 'abcde';
805         our ($foo, $bar);
806         like($str, qr/b(?{$foo = $_; $bar = pos})c/, $message);
807         is($foo, $str, $message);
808         is($bar, 2, $message);
809         is(pos $str, undef, $message);
810
811         undef $foo;
812         undef $bar;
813         pos $str = undef;
814         ok($str =~ /b(?{$foo = $_; $bar = pos})c/g, $message);
815         is($foo, $str, $message);
816         is($bar, 2, $message);
817         is(pos $str, 3, $message);
818
819         $_ = $str;
820         undef $foo;
821         undef $bar;
822         like($_, qr/b(?{$foo = $_; $bar = pos})c/, $message);
823         is($foo, $str, $message);
824         is($bar, 2, $message);
825
826         undef $foo;
827         undef $bar;
828         ok(/b(?{$foo = $_; $bar = pos})c/g, $message);
829         is($foo, $str, $message);
830         is($bar, 2, $message);
831         is(pos, 3, $message);
832
833         undef $foo;
834         undef $bar;
835         pos = undef;
836         1 while /b(?{$foo = $_; $bar = pos})c/g;
837         is($foo, $str, $message);
838         is($bar, 2, $message);
839         is(pos, undef, $message);
840
841         undef $foo;
842         undef $bar;
843         $_ = 'abcde|abcde';
844         ok(s/b(?{$foo = $_; $bar = pos})c/x/g, $message);
845         is($foo, 'abcde|abcde', $message);
846         is($bar, 8, $message);
847         is($_, 'axde|axde', $message);
848
849         # List context:
850         $_ = 'abcde|abcde';
851         our @res;
852         () = /([ace]).(?{push @res, $1,$2})([ce])(?{push @res, $1,$2})/g;
853         @res = map {defined $_ ? "'$_'" : 'undef'} @res;
854         is("@res", "'a' undef 'a' 'c' 'e' undef 'a' undef 'a' 'c'", $message);
855
856         @res = ();
857         () = /([ace]).(?{push @res, $`,$&,$'})([ce])(?{push @res, $`,$&,$'})/g;
858         @res = map {defined $_ ? "'$_'" : 'undef'} @res;
859         is("@res", "'' 'ab' 'cde|abcde' " .
860                      "'' 'abc' 'de|abcde' " .
861                      "'abcd' 'e|' 'abcde' " .
862                      "'abcde|' 'ab' 'cde' " .
863                      "'abcde|' 'abc' 'de'", $message);
864     }
865
866     {
867         my $message = '\G anchor checks';
868         my $foo = 'aabbccddeeffgg';
869         pos ($foo) = 1;
870
871         ok($foo =~ /.\G(..)/g, $message);
872         is($1, 'ab', $message);
873
874         pos ($foo) += 1;
875         ok($foo =~ /.\G(..)/g, $message);
876         is($1, 'cc', $message);
877
878         pos ($foo) += 1;
879         ok($foo =~ /.\G(..)/g, $message);
880         is($1, 'de', $message);
881
882         ok($foo =~ /\Gef/g, $message);
883
884         undef pos $foo;
885         ok($foo =~ /\G(..)/g, $message);
886         is($1, 'aa', $message);
887
888         ok($foo =~ /\G(..)/g, $message);
889         is($1, 'bb', $message);
890
891         pos ($foo) = 5;
892         ok($foo =~ /\G(..)/g, $message);
893         is($1, 'cd', $message);
894     }
895
896     {
897         my $message = 'basic \G floating checks';
898         my $foo = 'aabbccddeeffgg';
899         pos ($foo) = 1;
900
901         ok($foo =~ /a+\G(..)/g, "$message: a+\\G");
902         is($1, 'ab', "$message: ab");
903
904         pos ($foo) += 1;
905         ok($foo =~ /b+\G(..)/g, "$message: b+\\G");
906         is($1, 'cc', "$message: cc");
907
908         pos ($foo) += 1;
909         ok($foo =~ /d+\G(..)/g, "$message: d+\\G");
910         is($1, 'de', "$message: de");
911
912         ok($foo =~ /\Gef/g, "$message: \\Gef");
913
914         pos ($foo) = 1;
915
916         ok($foo =~ /(?=a+\G)(..)/g, "$message: (?a+\\G)");
917         is($1, 'aa', "$message: aa");
918
919         pos ($foo) = 2;
920
921         ok($foo =~ /a(?=a+\G)(..)/g, "$message: a(?=a+\\G)");
922         is($1, 'ab', "$message: ab");
923
924     }
925
926     {
927         $_ = '123x123';
928         my @res = /(\d*|x)/g;
929         local $" = '|';
930         is("@res", "123||x|123|", "0 match in alternation");
931     }
932
933     {
934         my $message = "Match against temporaries (created via pp_helem())" .
935                          " is safe";
936         ok({foo => "bar\n" . $^X} -> {foo} =~ /^(.*)\n/g, $message);
937         is($1, "bar", $message);
938     }
939
940     {
941         my $message = 'package $i inside (?{ }), ' .
942                          'saved substrings and changing $_';
943         our @a = qw [foo bar];
944         our @b = ();
945         s/(\w)(?{push @b, $1})/,$1,/g for @a;
946         is("@b", "f o o b a r", $message);
947         is("@a", ",f,,o,,o, ,b,,a,,r,", $message);
948
949         $message = 'lexical $i inside (?{ }), ' .
950                          'saved substrings and changing $_';
951         no warnings 'closure';
952         my @c = qw [foo bar];
953         my @d = ();
954         s/(\w)(?{push @d, $1})/,$1,/g for @c;
955         is("@d", "f o o b a r", $message);
956         is("@c", ",f,,o,,o, ,b,,a,,r,", $message);
957     }
958
959     {
960         my $message = 'Brackets';
961         our $brackets;
962         $brackets = qr {
963             {  (?> [^{}]+ | (??{ $brackets }) )* }
964         }x;
965
966         ok("{{}" =~ $brackets, $message);
967         is($&, "{}", $message);
968         ok("something { long { and } hairy" =~ $brackets, $message);
969         is($&, "{ and }", $message);
970         ok("something { long { and } hairy" =~ m/((??{ $brackets }))/, $message);
971         is($&, "{ and }", $message);
972     }
973
974     {
975         $_ = "a-a\nxbb";
976         pos = 1;
977         ok(!m/^-.*bb/mg, '$_ = "a-a\nxbb"; m/^-.*bb/mg');
978     }
979
980     {
981         my $message = '\G anchor checks';
982         my $text = "aaXbXcc";
983         pos ($text) = 0;
984         ok($text !~ /\GXb*X/g, $message);
985     }
986
987     {
988         $_ = "xA\n" x 500;
989         unlike($_, qr/^\s*A/m, '$_ = "xA\n" x 500; /^\s*A/m"');
990
991         my $text = "abc dbf";
992         my @res = ($text =~ /.*?(b).*?\b/g);
993         is("@res", "b b", '\b is not special');
994     }
995
996     {
997         my $message = '\S, [\S], \s, [\s]';
998         my @a = map chr, 0 .. 255;
999         my @b = grep m/\S/, @a;
1000         my @c = grep m/[^\s]/, @a;
1001         is("@b", "@c", $message);
1002
1003         @b = grep /\S/, @a;
1004         @c = grep /[\S]/, @a;
1005         is("@b", "@c", $message);
1006
1007         @b = grep /\s/, @a;
1008         @c = grep /[^\S]/, @a;
1009         is("@b", "@c", $message);
1010
1011         @b = grep /\s/, @a;
1012         @c = grep /[\s]/, @a;
1013         is("@b", "@c", $message);
1014
1015         # Test an inverted posix class with a char also in the class.
1016         my $nbsp = chr utf8::unicode_to_native(0xA0);
1017         my $non_s = chr utf8::unicode_to_native(0xA1);
1018         my $pat_string = "[^\\S ]";
1019         unlike(" ", qr/$pat_string/, "Verify ' ' !~ /$pat_string/");
1020         like("\t", qr/$pat_string/, "Verify '\\t =~ /$pat_string/");
1021         unlike($nbsp, qr/$pat_string/, "Verify non-utf8-NBSP !~ /$pat_string/");
1022         utf8::upgrade($nbsp);
1023         like($nbsp, qr/$pat_string/, "Verify utf8-NBSP =~ /$pat_string/");
1024         unlike($non_s, qr/$pat_string/, "Verify non-utf8-inverted-bang !~ /$pat_string/");
1025         utf8::upgrade($non_s);
1026         unlike($non_s, qr/$pat_string/, "Verify utf8-inverted-bang !~ /$pat_string/");
1027     }
1028     {
1029         my $message = '\D, [\D], \d, [\d]';
1030         my @a = map chr, 0 .. 255;
1031         my @b = grep /\D/, @a;
1032         my @c = grep /[^\d]/, @a;
1033         is("@b", "@c", $message);
1034
1035         @b = grep /\D/, @a;
1036         @c = grep /[\D]/, @a;
1037         is("@b", "@c", $message);
1038
1039         @b = grep /\d/, @a;
1040         @c = grep /[^\D]/, @a;
1041         is("@b", "@c", $message);
1042
1043         @b = grep /\d/, @a;
1044         @c = grep /[\d]/, @a;
1045         is("@b", "@c", $message);
1046     }
1047     {
1048         my $message = '\W, [\W], \w, [\w]';
1049         my @a = map chr, 0 .. 255;
1050         my @b = grep /\W/, @a;
1051         my @c = grep /[^\w]/, @a;
1052         is("@b", "@c", $message);
1053
1054         @b = grep /\W/, @a;
1055         @c = grep /[\W]/, @a;
1056         is("@b", "@c", $message);
1057
1058         @b = grep /\w/, @a;
1059         @c = grep /[^\W]/, @a;
1060         is("@b", "@c", $message);
1061
1062         @b = grep /\w/, @a;
1063         @c = grep /[\w]/, @a;
1064         is("@b", "@c", $message);
1065     }
1066
1067     {
1068         # see if backtracking optimization works correctly
1069         my $message = 'Backtrack optimization';
1070         like("\n\n", qr/\n   $ \n/x, $message);
1071         like("\n\n", qr/\n*  $ \n/x, $message);
1072         like("\n\n", qr/\n+  $ \n/x, $message);
1073         like("\n\n", qr/\n?  $ \n/x, $message);
1074         like("\n\n", qr/\n*? $ \n/x, $message);
1075         like("\n\n", qr/\n+? $ \n/x, $message);
1076         like("\n\n", qr/\n?? $ \n/x, $message);
1077         unlike("\n\n", qr/\n*+ $ \n/x, $message);
1078         unlike("\n\n", qr/\n++ $ \n/x, $message);
1079         like("\n\n", qr/\n?+ $ \n/x, $message);
1080     }
1081
1082     {
1083         package S;
1084         use overload '""' => sub {'Object S'};
1085         sub new {bless []}
1086
1087         my $message  = "Ref stringification";
1088       ::ok(do { \my $v} =~ /^SCALAR/,   "Scalar ref stringification") or diag($message);
1089       ::ok(do {\\my $v} =~ /^REF/,      "Ref ref stringification") or diag($message);
1090       ::ok([]           =~ /^ARRAY/,    "Array ref stringification") or diag($message);
1091       ::ok({}           =~ /^HASH/,     "Hash ref stringification") or diag($message);
1092       ::ok('S' -> new   =~ /^Object S/, "Object stringification") or diag($message);
1093     }
1094
1095     {
1096         my $message = "Test result of match used as match";
1097         ok('a1b' =~ ('xyz' =~ /y/), $message);
1098         is($`, 'a', $message);
1099         ok('a1b' =~ ('xyz' =~ /t/), $message);
1100         is($`, 'a', $message);
1101     }
1102
1103     {
1104         my $message = '"1" is not \s';
1105         warning_is(sub {unlike("1\n" x 102, qr/^\s*\n/m, $message)},
1106                    undef, "$message (did not warn)");
1107     }
1108
1109     {
1110         my $message = '\s, [[:space:]] and [[:blank:]]';
1111         my %space = (spc   => " ",
1112                      tab   => "\t",
1113                      cr    => "\r",
1114                      lf    => "\n",
1115                      ff    => "\f",
1116         # There's no \v but the vertical tabulator seems miraculously
1117         # be 11 both in ASCII and EBCDIC.
1118                      vt    => chr(11),
1119                      false => "space");
1120
1121         my @space0 = sort grep {$space {$_} =~ /\s/         } keys %space;
1122         my @space1 = sort grep {$space {$_} =~ /[[:space:]]/} keys %space;
1123         my @space2 = sort grep {$space {$_} =~ /[[:blank:]]/} keys %space;
1124
1125         is("@space0", "cr ff lf spc tab vt", $message);
1126         is("@space1", "cr ff lf spc tab vt", $message);
1127         is("@space2", "spc tab", $message);
1128     }
1129
1130     {
1131         my $n= 50;
1132         # this must be a high number and go from 0 to N, as the bug we are looking for doesn't
1133         # seem to be predictable. Slight changes to the test make it fail earlier or later.
1134         foreach my $i (0 .. $n)
1135         {
1136             my $str= "\n" x $i;
1137             ok $str=~/.*\z/, "implicit MBOL check string disable does not break things length=$i";
1138         }
1139     }
1140     {
1141         # we are actually testing that we dont die when executing these patterns
1142         use utf8;
1143         my $e = "Böck";
1144         ok(utf8::is_utf8($e),"got a unicode string - rt75680");
1145
1146         ok($e !~ m/.*?[x]$/, "unicode string against /.*?[x]\$/ - rt75680");
1147         ok($e !~ m/.*?\p{Space}$/i, "unicode string against /.*?\\p{space}\$/i - rt75680");
1148         ok($e !~ m/.*?[xyz]$/, "unicode string against /.*?[xyz]\$/ - rt75680");
1149         ok($e !~ m/(.*?)[,\p{isSpace}]+((?:\p{isAlpha}[\p{isSpace}\.]{1,2})+)\p{isSpace}*$/, "unicode string against big pattern - rt75680");
1150     }
1151     {
1152         # we are actually testing that we dont die when executing these patterns
1153         my $e = "B" . uni_to_native("\x{f6}") . "ck";
1154         ok(!utf8::is_utf8($e), "got a latin string - rt75680");
1155
1156         ok($e !~ m/.*?[x]$/, "latin string against /.*?[x]\$/ - rt75680");
1157         ok($e !~ m/.*?\p{Space}$/i, "latin string against /.*?\\p{space}\$/i - rt75680");
1158         ok($e !~ m/.*?[xyz]$/,"latin string against /.*?[xyz]\$/ - rt75680");
1159         ok($e !~ m/(.*?)[,\p{isSpace}]+((?:\p{isAlpha}[\p{isSpace}\.]{1,2})+)\p{isSpace}*$/,"latin string against big pattern - rt75680");
1160     }
1161
1162     {
1163         #
1164         # Tests for bug 77414.
1165         #
1166
1167         my $message = '\p property after empty * match';
1168         {
1169             like("1", qr/\s*\pN/, $message);
1170             like("-", qr/\s*\p{Dash}/, $message);
1171             like(" ", qr/\w*\p{Blank}/, $message);
1172         }
1173
1174         like("1", qr/\s*\pN+/, $message);
1175         like("-", qr/\s*\p{Dash}{1}/, $message);
1176         like(" ", qr/\w*\p{Blank}{1,4}/, $message);
1177
1178     }
1179
1180     {   # Some constructs with Latin1 characters cause a utf8 string not
1181         # to match itself in non-utf8
1182         my $c = uni_to_native("\xc0");
1183         my $pattern = my $utf8_pattern = qr/(($c)+,?)/;
1184         utf8::upgrade($utf8_pattern);
1185         ok $c =~ $pattern, "\\xc0 =~ $pattern; Neither pattern nor target utf8";
1186         ok $c =~ /$pattern/i, "\\xc0 =~ /$pattern/i; Neither pattern nor target utf8";
1187         ok $c =~ $utf8_pattern, "\\xc0 =~ $pattern; pattern utf8, target not";
1188         ok $c =~ /$utf8_pattern/i, "\\xc0 =~ /$pattern/i; pattern utf8, target not";
1189         utf8::upgrade($c);
1190         ok $c =~ $pattern, "\\xc0 =~ $pattern; target utf8, pattern not";
1191         ok $c =~ /$pattern/i, "\\xc0 =~ /$pattern/i; target utf8, pattern not";
1192         ok $c =~ $utf8_pattern, "\\xc0 =~ $pattern; Both target and pattern utf8";
1193         ok $c =~ /$utf8_pattern/i, "\\xc0 =~ /$pattern/i; Both target and pattern utf8";
1194     }
1195
1196     {   # Make sure can override the formatting
1197         use feature 'unicode_strings';
1198         ok uni_to_native("\xc0") =~ /\w/, 'Under unicode_strings: "\xc0" =~ /\w/';
1199         ok uni_to_native("\xc0") !~ /(?d:\w)/, 'Under unicode_strings: "\xc0" !~ /(?d:\w)/';
1200     }
1201
1202     {
1203         my $str= "\x{100}";
1204         chop $str;
1205         my $qr= qr/$str/;
1206         is("$qr", "(?^:)", "Empty pattern qr// stringifies to (?^:) with unicode flag enabled - Bug #80212");
1207         $str= "";
1208         $qr= qr/$str/;
1209         is("$qr", "(?^:)", "Empty pattern qr// stringifies to (?^:) with unicode flag disabled - Bug #80212");
1210
1211     }
1212
1213     {
1214         local $::TODO = "[perl #38133]";
1215
1216         "A" =~ /(((?:A))?)+/;
1217         my $first = $2;
1218
1219         "A" =~ /(((A))?)+/;
1220         my $second = $2;
1221
1222         is($first, $second);
1223     }
1224
1225     {
1226         # RT #3516: \G in a m//g expression causes problems
1227         my $count = 0;
1228         while ("abc" =~ m/(\G[ac])?/g) {
1229             last if $count++ > 10;
1230         }
1231         ok($count < 10, 'RT #3516 A');
1232
1233         $count = 0;
1234         while ("abc" =~ m/(\G|.)[ac]/g) {
1235             last if $count++ > 10;
1236         }
1237         ok($count < 10, 'RT #3516 B');
1238
1239         $count = 0;
1240         while ("abc" =~ m/(\G?[ac])?/g) {
1241             last if $count++ > 10;
1242         }
1243         ok($count < 10, 'RT #3516 C');
1244     }
1245     {
1246         # RT #84294: Is this a bug in the simple Perl regex?
1247         #          : Nested buffers and (?{...}) dont play nicely on partial matches
1248         our @got= ();
1249         ok("ab" =~ /((\w+)(?{ push @got, $2 })){2}/,"RT #84294: Pattern should match");
1250         my $want= "'ab', 'a', 'b'";
1251         my $got= join(", ", map { defined($_) ? "'$_'" : "undef" } @got);
1252         is($got,$want,'RT #84294: check that "ab" =~ /((\w+)(?{ push @got, $2 })){2}/ leaves @got in the correct state');
1253     }
1254
1255     {
1256         # Suppress warnings, as the non-unicode one comes out even if turn off
1257         # warnings here (because the execution is done in another scope).
1258         local $SIG{__WARN__} = sub {};
1259         my $str = "\x{110000}";
1260
1261         unlike($str, qr/\p{ASCII_Hex_Digit=True}/, "Non-Unicode doesn't match \\p{AHEX=True}");
1262         like($str, qr/\p{ASCII_Hex_Digit=False}/, "Non-Unicode matches \\p{AHEX=False}");
1263         like($str, qr/\P{ASCII_Hex_Digit=True}/, "Non-Unicode matches \\P{AHEX=True}");
1264         unlike($str, qr/\P{ASCII_Hex_Digit=False}/, "Non-Unicode matches \\P{AHEX=FALSE}");
1265     }
1266
1267     {
1268         # Test that IDstart works, but because the author (khw) knows
1269         # regexes much better than the rest of the core, it is being done here
1270         # in the context of a regex which relies on buffer names beginng with
1271         # IDStarts.
1272         use utf8;
1273         my $str = "abc";
1274         like($str, qr/(?<a>abc)/, "'a' is legal IDStart");
1275         like($str, qr/(?<_>abc)/, "'_' is legal IDStart");
1276         like($str, qr/(?<ß>abc)/, "U+00DF is legal IDStart");
1277         like($str, qr/(?<â„•>abc)/, "U+2115' is legal IDStart");
1278
1279         # This test works on Unicode 6.0 in which U+2118 and U+212E are legal
1280         # IDStarts there, but are not Word characters, and therefore Perl
1281         # doesn't allow them to be IDStarts.  But there is no guarantee that
1282         # Unicode won't change things around in the future so that at some
1283         # future Unicode revision these tests would need to be revised.
1284         foreach my $char ("%", "×", chr(0x2118), chr(0x212E)) {
1285             my $prog = <<"EOP";
1286 use utf8;;
1287 "abc" =~ qr/(?<$char>abc)/;
1288 EOP
1289             utf8::encode($prog);
1290             fresh_perl_like($prog, qr!Group name must start with a non-digit word character!, {},
1291                         sprintf("'U+%04X not legal IDFirst'", ord($char)));
1292         }
1293     }
1294
1295     { # [perl #101710]
1296         my $pat = "b";
1297         utf8::upgrade($pat);
1298         like("\xffb", qr/$pat/i, "/i: utf8 pattern, non-utf8 string, latin1-char preceding matching char in string");
1299     }
1300
1301     { # Crash with @a =~ // warning
1302         local $SIG{__WARN__} = sub {
1303              pass 'no crash for @a =~ // warning'
1304         };
1305         eval ' sub { my @a =~ // } ';
1306     }
1307
1308     { # Concat overloading and qr// thingies
1309         my @refs;
1310         my $qr = qr//;
1311         package Cat {
1312             require overload;
1313             overload->import(
1314                 '""' => sub { ${$_[0]} },
1315                 '.' => sub {
1316                     push @refs, ref $_[1] if ref $_[1];
1317                     bless $_[2] ? \"$_[1]${$_[0]}" : \"${$_[0]}$_[1]"
1318                 }
1319             );
1320         }
1321         my $s = "foo";
1322         my $o = bless \$s, Cat::;
1323         /$o$qr/;
1324         is "@refs", "Regexp", '/$o$qr/ passes qr ref to cat overload meth';
1325     }
1326
1327     {
1328         my $count=0;
1329         my $str="\n";
1330         $count++ while $str=~/.*/g;
1331         is $count, 2, 'test that ANCH_MBOL works properly. We should get 2 from $count++ while "\n"=~/.*/g';
1332         my $class_count= 0;
1333         $class_count++ while $str=~/[^\n]*/g;
1334         is $class_count, $count, 'while "\n"=~/.*/g and while "\n"=~/[^\n]*/g should behave the same';
1335         my $anch_count= 0;
1336         $anch_count++ while $str=~/^.*/mg;
1337         is $anch_count, 1, 'while "\n"=~/^.*/mg should match only once';
1338     }
1339
1340     { # [perl #111174]
1341         use re '/u';
1342         my $A_grave = uni_to_native("\xc0");
1343         like uni_to_native("\xe0"), qr/(?i:$A_grave)/, "(?i: shouldn't lose the passed in /u";
1344         use re '/a';
1345         unlike "\x{100}", qr/(?i:\w)/, "(?i: shouldn't lose the passed in /a";
1346         use re '/aa';
1347         unlike 'k', qr/(?i:\N{KELVIN SIGN})/, "(?i: shouldn't lose the passed in /aa";
1348     }
1349
1350     {
1351         # the test for whether the pattern should be re-compiled should
1352         # consider the UTF8ness of the previous and current pattern
1353         # string, as well as the physical bytes of the pattern string
1354
1355         for my $s (byte_utf8a_to_utf8n("\xc4\x80"), "\x{100}") {
1356             ok($s =~ /^$s$/, "re-compile check is UTF8-aware");
1357         }
1358     }
1359
1360     #  #113682 more overloading and qr//
1361     # when doing /foo$overloaded/, if $overloaded returns
1362     # a qr/(?{})/ via qr or "" overloading, then 'use re 'eval'
1363     # shouldn't be required. Via '.', it still is.
1364     {
1365         package Qr0;
1366         use overload 'qr' => sub { qr/(??{50})/ };
1367
1368         package Qr1;
1369         use overload '""' => sub { qr/(??{51})/ };
1370
1371         package Qr2;
1372         use overload '.'  => sub { $_[1] . qr/(??{52})/ };
1373
1374         package Qr3;
1375         use overload '""' => sub { qr/(??{7})/ },
1376                      '.'  => sub { $_[1] . qr/(??{53})/ };
1377
1378         package Qr_indirect;
1379         use overload '""'  => sub { $_[0][0] };
1380
1381         package main;
1382
1383         for my $i (0..3) {
1384             my $o = bless [], "Qr$i";
1385             if ((0,0,1,1)[$i]) {
1386                 eval { "A5$i" =~ /^A$o$/ };
1387                 like($@, qr/Eval-group not allowed/, "Qr$i");
1388                 eval { "5$i" =~ /$o/ };
1389                 like($@, ($i == 3 ? qr/^$/ : qr/no method found,/),
1390                         "Qr$i bare");
1391                 {
1392                     use re 'eval';
1393                     ok("A5$i" =~ /^A$o$/, "Qr$i - with use re eval");
1394                     eval { "5$i" =~ /$o/ };
1395                     like($@, ($i == 3 ? qr/^$/ : qr/no method found,/),
1396                             "Qr$i bare - with use re eval");
1397                 }
1398             }
1399             else {
1400                 ok("A5$i" =~ /^A$o$/, "Qr$i");
1401                 ok("5$i" =~ /$o/, "Qr$i bare");
1402             }
1403         }
1404
1405         my $o = bless [ bless [], "Qr1" ], 'Qr_indirect';
1406         ok("A51" =~ /^A$o/, "Qr_indirect");
1407         ok("51" =~ /$o/, "Qr_indirect bare");
1408     }
1409
1410     {   # Various flags weren't being set when a [] is optimized into an
1411         # EXACTish node
1412         ;
1413         ;
1414         my $sharp_s = uni_to_native("\xdf");
1415         ok("\x{017F}\x{017F}" =~ qr/^[$sharp_s]?$/i, "[] to EXACTish optimization");
1416     }
1417
1418     {
1419         for my $char (":", uni_to_native("\x{f7}"), "\x{2010}") {
1420             my $utf8_char = $char;
1421             utf8::upgrade($utf8_char);
1422             my $display = $char;
1423             $display = display($display);
1424             my $utf8_display = "utf8::upgrade(\"$display\")";
1425
1426             like($char, qr/^$char?$/, "\"$display\" =~ /^$display?\$/");
1427             like($char, qr/^$utf8_char?$/, "my \$p = \"$display\"; utf8::upgrade(\$p); \"$display\" =~ /^\$p?\$/");
1428             like($utf8_char, qr/^$char?$/, "my \$c = \"$display\"; utf8::upgrade(\$c); \"\$c\" =~ /^$display?\$/");
1429             like($utf8_char, qr/^$utf8_char?$/, "my \$c = \"$display\"; utf8::upgrade(\$c); my \$p = \"$display\"; utf8::upgrade(\$p); \"\$c\" =~ /^\$p?\$/");
1430         }
1431     }
1432
1433     {
1434         # #116148: Pattern utf8ness sticks around globally
1435         # the utf8 in the first match was sticking around for the second
1436         # match
1437
1438         use feature 'unicode_strings';
1439
1440         my $x = "\x{263a}";
1441         $x =~ /$x/;
1442
1443         my $text = "Perl";
1444         ok("Perl" =~ /P.*$/i, '#116148');
1445     }
1446
1447     { # 118297: Mixing up- and down-graded strings in regex
1448         utf8::upgrade(my $u = "\x{e5}");
1449         utf8::downgrade(my $d = "\x{e5}");
1450         my $warned;
1451         local $SIG{__WARN__} = sub { $warned++ if $_[0] =~ /\AMalformed UTF-8/ };
1452         my $re = qr/$u$d/;
1453         ok(!$warned, "no warnings when interpolating mixed up-/downgraded strings in pattern");
1454         my $c = "\x{e5}\x{e5}";
1455         utf8::downgrade($c);
1456         like($c, $re, "mixed up-/downgraded pattern matches downgraded string");
1457         utf8::upgrade($c);
1458         like($c, $re, "mixed up-/downgraded pattern matches upgraded string");
1459     }
1460
1461     {
1462         # if we have 87 capture buffers defined then \87 should refer to the 87th.
1463         # test that this is true for 1..100
1464         # Note that this test causes the engine to recurse at runtime, and
1465         # hence use a lot of C stack.
1466         for my $i (1..100) {
1467             my $capture= "a";
1468             $capture= "($capture)" for 1 .. $i;
1469             for my $mid ("","b") {
1470                 my $str= "a${mid}a";
1471                 my $backref= "\\$i";
1472                 eval {
1473                     ok($str=~/$capture$mid$backref/,"\\$i works with $i buffers '$str'=~/...$mid$backref/");
1474                     1;
1475                 } or do {
1476                     is("$@","","\\$i works with $i buffers works with $i buffers '$str'=~/...$mid$backref/");
1477                 };
1478             }
1479         }
1480     }
1481
1482     # this mixture of readonly (not COWable) and COWable strings
1483     # messed up the capture buffers under COW. The actual test results
1484     # are incidental; the issue is was an AddressSanitizer failure
1485     {
1486         my $c ='AB';
1487         my $res = '';
1488         for ($c, 'C', $c, 'DE') {
1489             ok(/(.)/, "COWable match");
1490             $res .= $1;
1491         }
1492         is($res, "ACAD");
1493     }
1494
1495
1496     {
1497         # RT #45667
1498         # /[#$x]/x didn't interpolate the var $x.
1499         my $b = 'cd';
1500         my $s = 'abcd$%#&';
1501         $s =~ s/[a#$b%]/X/g;
1502         is ($s, 'XbXX$XX&', 'RT #45667 without /x');
1503         $s = 'abcd$%#&';
1504         $s =~ s/[a#$b%]/X/gx;
1505         is ($s, 'XbXX$XX&', 'RT #45667 with /x');
1506     }
1507
1508     {
1509         no warnings "uninitialized";
1510         my @a;
1511         $a[1]++;
1512         /@a/;
1513         pass('no crash with /@a/ when array has nonexistent elems');
1514     }
1515
1516     {
1517         is runperl(prog => 'delete $::{qq-\cR-}; //; print qq-ok\n-'),
1518            "ok\n",
1519            'deleting *^R does not result in crashes';
1520         no warnings 'once';
1521         *^R = *caretRglobwithnoscalar;
1522         "" =~ /(?{42})/;
1523         is $^R, 42, 'assigning to *^R does not result in a crash';
1524         is runperl(
1525              stderr => 1,
1526              prog => 'eval q|'
1527                     .' q-..- =~ /(??{undef *^R;q--})(?{42})/; '
1528                     .' print qq-$^R\n-'
1529                     .'|'
1530            ),
1531            "42\n",
1532            'undefining *^R within (??{}) does not result in a crash';
1533     }
1534
1535     SKIP: {   # Test literal range end point special handling
1536         unless ($::IS_EBCDIC) {
1537             skip "Valid only for EBCDIC", 24;
1538         }
1539
1540         like("\x89", qr/[i-j]/, '"\x89" should match [i-j]');
1541         unlike("\x8A", qr/[i-j]/, '"\x8A" shouldnt match [i-j]');
1542         unlike("\x90", qr/[i-j]/, '"\x90" shouldnt match [i-j]');
1543         like("\x91", qr/[i-j]/, '"\x91" should match [i-j]');
1544
1545         like("\x89", qr/[i-\N{LATIN SMALL LETTER J}]/, '"\x89" should match [i-\N{LATIN SMALL LETTER J}]');
1546         unlike("\x8A", qr/[i-\N{LATIN SMALL LETTER J}]/, '"\x8A" shouldnt match [i-\N{LATIN SMALL LETTER J}]');
1547         unlike("\x90", qr/[i-\N{LATIN SMALL LETTER J}]/, '"\x90" shouldnt match [i-\N{LATIN SMALL LETTER J}]');
1548         like("\x91", qr/[i-\N{LATIN SMALL LETTER J}]/, '"\x91" should match [i-\N{LATIN SMALL LETTER J}]');
1549
1550         like("\x89", qr/[i-\N{U+6A}]/, '"\x89" should match [i-\N{U+6A}]');
1551         unlike("\x8A", qr/[i-\N{U+6A}]/, '"\x8A" shouldnt match [i-\N{U+6A}]');
1552         unlike("\x90", qr/[i-\N{U+6A}]/, '"\x90" shouldnt match [i-\N{U+6A}]');
1553         like("\x91", qr/[i-\N{U+6A}]/, '"\x91" should match [i-\N{U+6A}]');
1554
1555         like("\x89", qr/[\N{U+69}-\N{U+6A}]/, '"\x89" should match [\N{U+69}-\N{U+6A}]');
1556         unlike("\x8A", qr/[\N{U+69}-\N{U+6A}]/, '"\x8A" shouldnt match [\N{U+69}-\N{U+6A}]');
1557         unlike("\x90", qr/[\N{U+69}-\N{U+6A}]/, '"\x90" shouldnt match [\N{U+69}-\N{U+6A}]');
1558         like("\x91", qr/[\N{U+69}-\N{U+6A}]/, '"\x91" should match [\N{U+69}-\N{U+6A}]');
1559
1560         like("\x89", qr/[i-\x{91}]/, '"\x89" should match [i-\x{91}]');
1561         like("\x8A", qr/[i-\x{91}]/, '"\x8A" should match [i-\x{91}]');
1562         like("\x90", qr/[i-\x{91}]/, '"\x90" should match [i-\x{91}]');
1563         like("\x91", qr/[i-\x{91}]/, '"\x91" should match [i-\x{91}]');
1564
1565         # Need to use eval, because tries to compile on ASCII platforms even
1566         # though the tests are skipped, and fails because 0x89-j is an illegal
1567         # range there.
1568         like("\x89", eval 'qr/[\x{89}-j]/', '"\x89" should match [\x{89}-j]');
1569         like("\x8A", eval 'qr/[\x{89}-j]/', '"\x8A" should match [\x{89}-j]');
1570         like("\x90", eval 'qr/[\x{89}-j]/', '"\x90" should match [\x{89}-j]');
1571         like("\x91", eval 'qr/[\x{89}-j]/', '"\x91" should match [\x{89}-j]');
1572     }
1573
1574     # These are based on looking at the code in regcomp.c
1575     # We don't look for specific code, just the existence of an SSC
1576     foreach my $re (qw(     qr/a?c/
1577                             qr/a?c/i
1578                             qr/[ab]?c/
1579                             qr/\R?c/
1580                             qr/\d?c/d
1581                             qr/\w?c/l
1582                             qr/\s?c/a
1583                             qr/[[:lower:]]?c/u
1584     )) {
1585       SKIP: {
1586         skip "no re-debug under miniperl" if is_miniperl;
1587         my $prog = <<"EOP";
1588 use re qw(Debug COMPILE);
1589 $re;
1590 EOP
1591         fresh_perl_like($prog, qr/synthetic stclass/, { stderr=>1 }, "$re generates a synthetic start class");
1592       }
1593     }
1594
1595     {
1596         like "\x{AA}", qr/a?[\W_]/d, "\\W with /d synthetic start class works";
1597     }
1598
1599     SKIP: {
1600         skip("Tests are ASCII-centric, some would fail on EBCDIC", 12) if $::IS_EBCDIC;
1601
1602         # Verify that the very last Latin-1 U+00FF
1603         # (LATIN SMALL LETTER Y WITH DIAERESIS)
1604         # and its UPPER counterpart (U+0178 which is pure Unicode),
1605         # and likewise for the very first pure Unicode
1606         # (LATIN CAPITAL LETTER A WITH MACRON) fold-match properly,
1607         # and there are no off-by-one logic errors in the transition zone.
1608
1609         ok("\xFF" =~ /\xFF/i, "Y WITH DIAERESIS l =~ l");
1610         ok("\xFF" =~ /\x{178}/i, "Y WITH DIAERESIS l =~ u");
1611         ok("\x{178}" =~ /\xFF/i, "Y WITH DIAERESIS u =~ l");
1612         ok("\x{178}" =~ /\x{178}/i, "Y WITH DIAERESIS u =~ u");
1613
1614         # U+00FF with U+05D0 (non-casing Hebrew letter).
1615         ok("\xFF\x{5D0}" =~ /\xFF\x{5D0}/i, "Y WITH DIAERESIS l =~ l");
1616         ok("\xFF\x{5D0}" =~ /\x{178}\x{5D0}/i, "Y WITH DIAERESIS l =~ u");
1617         ok("\x{178}\x{5D0}" =~ /\xFF\x{5D0}/i, "Y WITH DIAERESIS u =~ l");
1618         ok("\x{178}\x{5D0}" =~ /\x{178}\x{5D0}/i, "Y WITH DIAERESIS u =~ u");
1619
1620         # U+0100.
1621         ok("\x{100}" =~ /\x{100}/i, "A WITH MACRON u =~ u");
1622         ok("\x{100}" =~ /\x{101}/i, "A WITH MACRON u =~ l");
1623         ok("\x{101}" =~ /\x{100}/i, "A WITH MACRON l =~ u");
1624         ok("\x{101}" =~ /\x{101}/i, "A WITH MACRON l =~ l");
1625     }
1626
1627     {
1628         use utf8;
1629         ok("abc" =~ /a\85b\85c/x, "NEL is white-space under /x");
1630     }
1631
1632     {
1633         ok('a(b)c' =~ qr(a\(b\)c), "'\\(' is a literal in qr(...)");
1634         ok('a[b]c' =~ qr[a\[b\]c], "'\\[' is a literal in qr[...]");
1635         ok('a{3}c' =~ qr{a\{3\}c},  # Only failed when { could be a meta
1636               "'\\{' is a literal in qr{...}, where it could be a quantifier");
1637
1638         # This one is for completeness
1639         ok('a<b>c' =~ qr<a\<b\>c>, "'\\<' is a literal in qr<...>)");
1640     }
1641
1642     {   # Was getting optimized into EXACT (non-folding node)
1643         my $x = qr/[x]/i;
1644         utf8::upgrade($x);
1645         like("X", qr/$x/, "UTF-8 of /[x]/i matches upper case");
1646     }
1647
1648     {   # make sure we get an error when \p{} cannot load Unicode tables
1649         fresh_perl_like(<<'        prog that cannot load uni tables',
1650             BEGIN {
1651                 @INC = '../lib';
1652                 require utf8; require 'utf8_heavy.pl';
1653                 @INC = ();
1654             }
1655             $name = 'A B';
1656             if ($name =~ /(\p{IsUpper}) (\p{IsUpper})/){
1657                 print "It's good! >$1< >$2<\n";
1658             } else {
1659                 print "It's not good...\n";
1660             }
1661         prog that cannot load uni tables
1662                   qr/^Can't locate unicore\/Heavy\.pl(?x:
1663                    )|^Can't find Unicode property definition/,
1664                   undef,
1665                  '\p{} should not fail silently when uni tables evanesce');
1666     }
1667
1668     {   # Special handling of literal-ended ranges in [...] was breaking this
1669         use utf8;
1670         like("ÿ", qr/[ÿ-ÿ]/, "\"ÿ\" should match [ÿ-ÿ]");
1671     }
1672
1673     {   # [perl #123539]
1674         like("TffffffffffffTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT5TTTTTTTTTTTTTTTTTTTTTTTTT3TTgTTTTTTTTTTTTTTTTTTTTT2TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHiHHHHHHHfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&ffff", qr/TffffffffffffTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT5TTTTTTTTTTTTTTTTTTTTTTTTT3TTgTTTTTTTTTTTTTTTTTTTTT2TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHiHHHHHHHfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&ffff/il, "");
1675         like("TffffffffffffT\x{100}TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT5TTTTTTTTTTTTTTTTTTTTTTTTT3TTgTTTTTTTTTTTTTTTTTTTTT2TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHiHHHHHHHfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&ffff", qr/TffffffffffffT\x{100}TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT5TTTTTTTTTTTTTTTTTTTTTTTTT3TTgTTTTTTTTTTTTTTTTTTTTT2TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHiHHHHHHHfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&ffff/il, "");
1676     }
1677
1678         {       # [perl #123604]
1679                 my($s, $x, @x) = ('abc', 'a', 'd');
1680                 my $long = 'b' x 2000;
1681                 my $eval = q{$s =~ m{$x[bbb]c} ? 1 : 0};
1682                 $eval =~ s{bbb}{$long};
1683                 my $match = eval $eval;
1684                 ok(1, "did not crash");
1685                 ok($match, "[bbb...] resolved as character class, not subscript");
1686         }
1687
1688         {       # [perl #123755]
1689                 for my $pat ('(??', '(?P', '(?i-') {
1690                         eval qq{ qr/$pat/ };
1691                         ok(1, "qr/$pat/ did not crash");
1692                         eval qq{ qr/${pat}\x{123}/ };
1693                         my $e = $@;
1694                         like($e, qr{\x{123}},
1695                                 "qr/${pat}x/ shows x in error even if it's a wide character");
1696                 }
1697         }
1698
1699         {
1700                 # Expect one of these sizes to cause overflow and wrap to negative
1701                 for my $bits (32, 64) {
1702                         my $wrapneg = 2 ** ($bits - 2) * 3;
1703                         for my $sign ('', '-') {
1704                                 my $pat = sprintf "qr/(?%s%u)/", $sign, $wrapneg;
1705                                 eval $pat;
1706                                 ok(1, "big backref $pat did not crash");
1707                         }
1708                 }
1709         }
1710         {
1711             # Test that we handle qr/\8888888/ and variants without an infinite loop,
1712             # we use a test within a test so we can todo it, and make sure we don't
1713             # infinite loop our tests.
1714             # NOTE - Do not put quotes in the code!
1715             # NOTE - We have to triple escape the backref in the pattern below.
1716             my $code='
1717                 BEGIN{require q(./test.pl);}
1718                 watchdog(3);
1719                 for my $len (1 .. 20) {
1720                     my $eights= q(8) x $len;
1721                     eval qq{ qr/\\\\$eights/ };
1722                 }
1723                 print q(No infinite loop here!);
1724             ';
1725             fresh_perl_is($code, "No infinite loop here!", {},
1726                 "test that we handle things like m/\\888888888/ without infinite loops" );
1727         }
1728
1729         {   # Test that we handle some malformed UTF-8 without looping [perl
1730             # #123562]
1731
1732             my $code='
1733                 BEGIN{require q(./test.pl);}
1734                 use Encode qw(_utf8_on);
1735                 # \x80 and \x41 are continuation bytes in their respective
1736                 # character sets
1737                 my $malformed = (ord("A") == 65) ? "a\x80\n" : "a\x41\n";
1738                 utf8::downgrade($malformed);
1739                 _utf8_on($malformed);
1740                 watchdog(3);
1741                 $malformed =~ /(\n\r|\r)$/;
1742                 print q(No infinite loop here!);
1743             ';
1744             fresh_perl_like($code, qr/Malformed UTF-8 character/, {},
1745                 "test that we handle some UTF-8 malformations without looping" );
1746         }
1747
1748         {
1749                 # [perl #123843] hits SEGV trying to compile this pattern
1750                 my $match;
1751                 eval q{ ($match) = ("xxyxxyxy" =~ m{(x+(y(?1))*)}) };
1752                 ok(1, "compiled GOSUB in CURLYM ok");
1753                 is($match, 'xxyxxyx', "matched GOSUB in CURLYM");
1754         }
1755
1756         {
1757                 # [perl #123852] doesn't avoid all the capture-related work with
1758                 # //n, leading to possible memory corruption
1759                 eval q{ qr{()(?1)}n };
1760                 my $error = $@;
1761                 ok(1, "qr{()(?1)}n didn't crash");
1762                 like($error, qr{Reference to nonexistent group},
1763                                 'gave appropriate error for qr{()(?1)}n');
1764         }
1765
1766         {
1767             # [perl #126406] panic with unmatchable quantifier
1768             my $code='
1769                 no warnings "regexp";
1770                 "" =~ m/(.0\N{6,0}0\N{6,0}000000000000000000000000000000000)/;
1771             ';
1772             fresh_perl_is($code, "", {},
1773                             "perl [#126406] panic");
1774         }
1775         {
1776             my $bug="[perl #126182]"; # test for infinite pattern recursion
1777             for my $tuple (
1778                     [ 'q(a)=~/(.(?2))((?<=(?=(?1)).))/', "died", "look ahead left recursion fails fast" ],
1779                     [ 'q(aa)=~/(?R)a/', "died", "left-recursion fails fast", ],
1780                     [ 'q(bbaa)=~/(?&x)(?(DEFINE)(?<x>(?&y)*a)(?<y>(?&x)*b))/',
1781                         "died", "inter-cyclic optional left recursion dies" ],
1782                     [ 'q(abc) =~ /a((?1)?)c/', "died", "optional left recursion dies" ],
1783                     [ 'q(abc) =~ /a((?1)??)c/', "died", "min mod left recursion dies" ],
1784                     [ 'q(abc) =~ /a((?1)*)c/', "died", "* left recursion dies" ],
1785                     [ 'q(abc) =~ /a((?1)+)c/', "died", "+ left recursion dies" ],
1786                     [ 'q(abc) =~ /a((?1){0,3})c/', "died", "{0,3} left recursion fails fast" ],
1787
1788                     [ 'q(aaabbb)=~/a(?R)?b/', "matched", "optional self recursion works" ],
1789                     [ '"((5maa-maa)(maa-3maa))" =~ /(\\\\((?:[^()]++|(?0))*+\\\\))/', "matched",
1790                         "recursion and possessive captures", "((5maa-maa)(maa-3maa))"],
1791                     [ '"((5maa-maa)(maa-3maa))" =~ /(\\\\((?:[^()]++|(?1))*+\\\\))/', "matched",
1792                         "recursion and possessive captures", "((5maa-maa)(maa-3maa))"],
1793                     [ '"((5maa-maa)(maa-3maa))" =~ /(\\\\((?:[^()]+|(?0))*\\\\))/', "matched",
1794                         "recursion and possessive captures", "((5maa-maa)(maa-3maa))"],
1795                     [ '"((5maa-maa)(maa-3maa))" =~ /(\\\\((?:[^()]+|(?1))*\\\\))/', "matched",
1796                         "recursion and possessive captures", "((5maa-maa)(maa-3maa))"],
1797             ) {
1798                 my ($expr, $expect, $test_name, $cap1)= @$tuple;
1799                 # avoid quotes in this code!
1800                 my $code='
1801                     BEGIN{require q(./test.pl);}
1802                     watchdog(3);
1803                     my $status= eval(q{ !(' . $expr . ') ? q(failed) : ' .
1804                         ($cap1 ? '($1 ne q['.$cap1.']) ? qq(badmatch:$1) : ' : '') .
1805                         ' q(matched) })
1806                                 || ( ( $@ =~ /Infinite recursion/ ) ? qq(died) : q(strange-death) );
1807                     print $status;
1808                 ';
1809                 fresh_perl_is($code, $expect, {}, "$bug - $test_name" );
1810             }
1811         }
1812         {
1813             fresh_perl_is('
1814                 BEGIN{require q(test.pl);}
1815                 watchdog(3);
1816                 $SIG{ALRM} = sub {print "Timeout\n"; exit(1)};
1817                 alarm 1;
1818                 $_ = "a" x 1000 . "b" x 1000 . "c" x 1000;
1819                 /.*a.*b.*c.*[de]/;
1820             ',"Timeout",{},"Test Perl 73464")
1821         }
1822
1823         {   # [perl #128686], crashed the the interpreter
1824             my $AE = chr utf8::unicode_to_native(0xC6);
1825             my $ae = chr utf8::unicode_to_native(0xE6);
1826             my $re = qr/[$ae\s]/i;
1827             ok($AE !~ $re, '/[\xE6\s]/i doesn\'t match \xC6 when not in UTF-8');
1828             utf8::upgrade $AE;
1829             ok($AE =~ $re, '/[\xE6\s]/i matches \xC6 when in UTF-8');
1830         }
1831
1832         {
1833             is(0+("\n" =~ m'\n'), 1, q|m'\n' should interpolate escapes|);
1834         }
1835
1836         {
1837             my $str = "a\xB6";
1838             ok( $str =~ m{^(a|a\x{b6})$}, "fix [perl #129950] - latin1 case" );
1839             utf8::upgrade($str);
1840             ok( $str =~ m{^(a|a\x{b6})$}, "fix [perl #129950] - utf8 case" );
1841         }
1842         {
1843             my $got= run_perl( switches => [ '-l' ], prog => <<'EOF_CODE' );
1844             my $died= !eval {
1845                 $_=qq(ab);
1846                 print;
1847                 my $p=qr/(?{ s!!x! })/;
1848                 /$p/;
1849                 print;
1850                 /a/;
1851                 /$p/;
1852                 print;
1853                 /b/;
1854                 /$p/;
1855                 print;
1856                 //;
1857                 1;
1858             };
1859             $error = $died ? ($@ || qq(Zombie)) : qq(none);
1860             print $died ? qq(died) : qq(lived);
1861             print qq(Error: $@);
1862 EOF_CODE
1863             my @got= split /\n/, $got;
1864             is($got[0],"ab","empty pattern in regex codeblock: got expected start string");
1865             is($got[1],"xab",
1866                 "empty pattern in regex codeblock: first subst with no last-match worked right");
1867             is($got[2],"xxb","empty pattern in regex codeblock: second subst worked right");
1868             is($got[3],"xxx","empty pattern in regex codeblock: third subst worked right");
1869             is($got[4],"died","empty pattern in regex codeblock: died as expected");
1870             like($got[5],qr/Error: Infinite recursion via empty pattern/,
1871            "empty pattern in regex codeblock: produced the right exception message" );
1872         }
1873     {
1874         # [perl #130495] /x comment skipping stopped a byte short, leading
1875         # to assertion failure or 'malformed utf-8 character" warning
1876         fresh_perl_is(
1877             "use utf8; m{a#\x{124}}x", '', {wide_chars => 1},
1878             '[perl #130495] utf-8 character at end of /x comment should not misparse',
1879         );
1880     }
1881     {
1882         # [perl #130522] causes out-of-bounds read detected by clang with
1883         # address=sanitized when length of the STCLASS string is greater than
1884         # length of target string.
1885         my $re = qr{(?=\0z)\0?z?$}i;
1886         my($yes, $no) = (1, "");
1887         for my $test (
1888             [ $no,  undef,   '<undef>' ],
1889             [ $no,  '',      '' ],
1890             [ $no,  "\0",    '\0' ],
1891             [ $yes, "\0z",   '\0z' ],
1892             [ $no,  "\0z\0", '\0z\0' ],
1893             [ $yes, "\0z\n", '\0z\n' ],
1894         ) {
1895             my($result, $target, $disp) = @$test;
1896             no warnings qw/uninitialized/;
1897             is($target =~ $re, $result, "[perl #130522] with target '$disp'");
1898         }
1899     }
1900     {
1901         # [perl #129377] backref to an unmatched capture should not cause
1902         # reading before start of string.
1903         SKIP: {
1904             skip "no re-debug under miniperl" if is_miniperl;
1905             my $prog = <<'EOP';
1906 use re qw(Debug EXECUTE);
1907 "x" =~ m{ () y | () \1 }x;
1908 EOP
1909             fresh_perl_like($prog, qr{
1910                 \A (?! .* ^ \s+ - )
1911             }msx, { stderr => 1 }, "Offsets in debug output are not negative");
1912         }
1913     }
1914     {
1915         # buffer overflow
1916         fresh_perl_is("BEGIN{\$^H=0x200000}\ns/[(?{//xx",
1917                       "Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE (?{/ at (eval 1) line 1.\n",
1918                       {}, "buffer overflow for regexp component");
1919     }
1920     {
1921         # [perl #129281] buffer write overflow, detected by ASAN, valgrind
1922         fresh_perl_is('/0(?0)|^*0(?0)|^*(^*())0|/', '', {}, "don't bump whilem_c too much");
1923     }
1924
1925     {
1926         # RT #131575 intuit skipping back from the end to find the highest
1927         # possible start point, was potentially hopping back beyond pos()
1928         # and crashing by calling fbm_instr with a negative length
1929
1930         my $text = "=t=\x{5000}";
1931         pos($text) = 3;
1932         ok(scalar($text !~ m{(~*=[a-z]=)}g), "RT #131575");
1933     }
1934     {
1935         fresh_perl_is('"AA" =~ m/AA{1,0}/','',{},"handle OPFAIL insert properly");
1936     }
1937
1938 } # End of sub run_tests
1939
1940 1;
1941
1942 #
1943 # ex: set ts=8 sts=4 sw=4 et:
1944 #