This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
update PL_stack_sp when we exit matcher_matches_sv()
[perl5.git] / t / op / smartmatch.t
1 #!./perl
2
3 BEGIN {
4     chdir 't' if -d 't';
5     require './test.pl';
6     set_up_inc('../lib');
7 }
8 use strict;
9 use warnings;
10 no warnings 'uninitialized';
11 no warnings 'experimental::smartmatch';
12
13 ++$|;
14
15 use Tie::Array;
16 use Tie::Hash;
17
18 # Predeclare vars used in the tests:
19 my @empty;
20 my %empty;
21 my @sparse; $sparse[2] = 2;
22
23 my $deep1 = []; push @$deep1, $deep1;
24 my $deep2 = []; push @$deep2, $deep2;
25
26 my @nums = (1..10);
27 tie my @tied_nums, 'Tie::StdArray';
28 @tied_nums =  (1..10);
29
30 my %hash = (foo => 17, bar => 23);
31 tie my %tied_hash, 'Tie::StdHash';
32 %tied_hash = %hash;
33
34 {
35     package Test::Object::NoOverload;
36     sub new { bless { key => 1 } }
37 }
38
39 {
40     package Test::Object::StringOverload;
41     use overload '""' => sub { "object" }, fallback => 1;
42     sub new { bless { key => 1 } }
43 }
44
45 {
46     package Test::Object::WithOverload;
47     sub new { bless { key => ($_[1] // 'magic') } }
48     use overload '~~' => sub {
49         my %hash = %{ $_[0] };
50         if ($_[2]) { # arguments reversed ?
51             return $_[1] eq reverse $hash{key};
52         }
53         else {
54             return $_[1] eq $hash{key};
55         }
56     };
57     use overload '""' => sub { "stringified" };
58     use overload 'eq' => sub {"$_[0]" eq "$_[1]"};
59 }
60
61 our $ov_obj = Test::Object::WithOverload->new;
62 our $ov_obj_2 = Test::Object::WithOverload->new("object");
63 our $obj = Test::Object::NoOverload->new;
64 our $str_obj = Test::Object::StringOverload->new;
65
66 my %refh;
67 unless (is_miniperl()) {
68     require Tie::RefHash;
69     tie %refh, 'Tie::RefHash';
70     $refh{$ov_obj} = 1;
71 }
72
73 my @keyandmore = qw(key and more);
74 my @fooormore = qw(foo or more);
75 my %keyandmore = map { $_ => 0 } @keyandmore;
76 my %fooormore = map { $_ => 0 } @fooormore;
77
78 # Load and run the tests
79 plan tests => 349+1;
80
81 while (<DATA>) {
82   SKIP: {
83     next if /^#/ || !/\S/;
84     chomp;
85     my ($yn, $left, $right, $note) = split /\t+/;
86
87     local $::TODO = $note =~ /TODO/;
88
89     die "Bad test spec: ($yn, $left, $right)" if $yn =~ /[^!@=]/;
90
91     my $tstr = "$left ~~ $right";
92
93     test_again:
94     my $res;
95     if ($note =~ /NOWARNINGS/) {
96         $res = eval "no warnings; $tstr";
97     }
98     else {
99         skip_if_miniperl("Doesn't work with miniperl", $yn =~ /=/ ? 2 : 1)
100             if $note =~ /MINISKIP/;
101         $res = eval $tstr;
102     }
103
104     chomp $@;
105
106     if ( $yn =~ /@/ ) {
107         ok( $@ ne '', "$tstr dies" )
108             and print "# \$\@ was: $@\n";
109     } else {
110         my $test_name = $tstr . ($yn =~ /!/ ? " does not match" : " matches");
111         if ( $@ ne '' ) {
112             fail($test_name);
113             print "# \$\@ was: $@\n";
114         } else {
115             ok( ($yn =~ /!/ xor $res), $test_name );
116         }
117     }
118
119     if ( $yn =~ s/=// ) {
120         $tstr = "$right ~~ $left";
121         goto test_again;
122     }
123   }
124 }
125
126 sub foo {}
127 sub bar {42}
128 sub gorch {42}
129 sub fatal {die "fatal sub\n"}
130
131 # to test constant folding
132 sub FALSE() { 0 }
133 sub TRUE() { 1 }
134 sub NOT_DEF() { undef }
135
136 {
137   # [perl #123860]
138   # this can but might not crash
139   # This can but might not crash
140   #
141   # The second smartmatch would leave a &PL_sv_no on the stack for
142   # each key it checked in %!, this could then cause various types of
143   # crash or assertion failure.
144   #
145   # This isn't guaranteed to crash, but if the stack issue is
146   # re-introduced it will probably crash in one of the many smoke
147   # builds.
148   fresh_perl_is('print (q(x) ~~ q(x)) | (/x/ ~~ %!)', "1",
149                 { switches => [ "-MErrno", "-M-warnings=experimental::smartmatch" ] },
150                  "don't fill the stack with rubbish");
151 }
152
153 # Prefix character :
154 #   - expected to match
155 # ! - expected to not match
156 # @ - expected to be a compilation failure
157 # = - expected to match symmetrically (runs test twice)
158 # Data types to test :
159 #   undef
160 #   Object-overloaded
161 #   Object
162 #   Coderef
163 #   Hash
164 #   Hashref
165 #   Array
166 #   Arrayref
167 #   Tied arrays and hashes
168 #   Arrays that reference themselves
169 #   Regex (// and qr//)
170 #   Range
171 #   Num
172 #   Str
173 # Other syntactic items of interest:
174 #   Constants
175 #   Values returned by a sub call
176 __DATA__
177 # Any ~~ undef
178 !       $ov_obj         undef
179 !       $obj            undef
180 !       sub {}          undef
181 !       %hash           undef
182 !       \%hash          undef
183 !       {}              undef
184 !       @nums           undef
185 !       \@nums          undef
186 !       []              undef
187 !       %tied_hash      undef
188 !       @tied_nums      undef
189 !       $deep1          undef
190 !       /foo/           undef
191 !       qr/foo/         undef
192 !       21..30          undef
193 !       189             undef
194 !       "foo"           undef
195 !       ""              undef
196 !       !1              undef
197         undef           undef
198         (my $u)         undef
199         NOT_DEF         undef
200         &NOT_DEF        undef
201
202 # Any ~~ object overloaded
203 !       \&fatal         $ov_obj
204         'cigam'         $ov_obj
205 !       'cigam on'      $ov_obj
206 !       ['cigam']       $ov_obj
207 !       ['stringified'] $ov_obj
208 !       { cigam => 1 }  $ov_obj
209 !       { stringified => 1 }    $ov_obj
210 !       $obj            $ov_obj
211 !       undef           $ov_obj
212
213 # regular object
214 @       $obj            $obj
215 @       $ov_obj         $obj
216 =@      \&fatal         $obj
217 @       \&FALSE         $obj
218 @       \&foo           $obj
219 @       sub { 1 }       $obj
220 @       sub { 0 }       $obj
221 @       %keyandmore     $obj
222 @       {"key" => 1}    $obj
223 @       @fooormore      $obj
224 @       ["key" => 1]    $obj
225 @       /key/           $obj
226 @       qr/key/         $obj
227 @       "key"           $obj
228 @       FALSE           $obj
229
230 # regular object with "" overload
231 @       $obj            $str_obj
232 =@      \&fatal         $str_obj
233 @       \&FALSE         $str_obj
234 @       \&foo           $str_obj
235 @       sub { 1 }       $str_obj
236 @       sub { 0 }       $str_obj
237 @       %keyandmore     $str_obj
238 @       {"object" => 1} $str_obj
239 @       @fooormore      $str_obj
240 @       ["object" => 1] $str_obj
241 @       /object/        $str_obj
242 @       qr/object/      $str_obj
243 @       "object"        $str_obj
244 @       FALSE           $str_obj
245 # Those will treat the $str_obj as a string because of fallback:
246
247 # object (overloaded or not) ~~ Any
248         $obj            qr/NoOverload/
249         $ov_obj         qr/^stringified$/
250 =       "$ov_obj"       "stringified"
251 =       "$str_obj"      "object"
252 !=      $ov_obj         "stringified"
253         $str_obj        "object"
254         $ov_obj         'magic'
255 !       $ov_obj         'not magic'
256
257 # ~~ Coderef
258         sub{0}          sub { ref $_[0] eq "CODE" }
259         %fooormore      sub { $_[0] =~ /^(foo|or|more)$/ }
260 !       %fooormore      sub { $_[0] =~ /^(foo|or|less)$/ }
261         \%fooormore     sub { $_[0] =~ /^(foo|or|more)$/ }
262 !       \%fooormore     sub { $_[0] =~ /^(foo|or|less)$/ }
263         +{%fooormore}   sub { $_[0] =~ /^(foo|or|more)$/ }
264 !       +{%fooormore}   sub { $_[0] =~ /^(foo|or|less)$/ }
265         @fooormore      sub { $_[0] =~ /^(foo|or|more)$/ }
266 !       @fooormore      sub { $_[0] =~ /^(foo|or|less)$/ }
267         \@fooormore     sub { $_[0] =~ /^(foo|or|more)$/ }
268 !       \@fooormore     sub { $_[0] =~ /^(foo|or|less)$/ }
269         [@fooormore]    sub { $_[0] =~ /^(foo|or|more)$/ }
270 !       [@fooormore]    sub { $_[0] =~ /^(foo|or|less)$/ }
271         %fooormore      sub{@_==1}
272         @fooormore      sub{@_==1}
273         "foo"           sub { $_[0] =~ /^(foo|or|more)$/ }
274 !       "more"          sub { $_[0] =~ /^(foo|or|less)$/ }
275         /fooormore/     sub{ref $_[0] eq 'Regexp'}
276         qr/fooormore/   sub{ref $_[0] eq 'Regexp'}
277         1               sub{shift}
278 !       0               sub{shift}
279 !       undef           sub{shift}
280         undef           sub{not shift}
281         NOT_DEF         sub{not shift}
282         &NOT_DEF        sub{not shift}
283         FALSE           sub{not shift}
284         [1]             \&bar
285         {a=>1}          \&bar
286         qr//            \&bar
287 !       [1]             \&foo
288 !       {a=>1}          \&foo
289         $obj            sub { ref($_[0]) =~ /NoOverload/ }
290         $ov_obj         sub { ref($_[0]) =~ /WithOverload/ }
291 # empty stuff matches, because the sub is never called:
292         []              \&foo
293         {}              \&foo
294         @empty          \&foo
295         %empty          \&foo
296 !       qr//            \&foo
297 !       undef           \&foo
298         undef           \&bar
299 @       undef           \&fatal
300 @       1               \&fatal
301 @       [1]             \&fatal
302 @       {a=>1}          \&fatal
303 @       "foo"           \&fatal
304 @       qr//            \&fatal
305 # sub is not called on empty hashes / arrays
306         []              \&fatal
307         +{}             \&fatal
308         @empty          \&fatal
309         %empty          \&fatal
310 # sub is not special on the left
311         sub {0}         qr/^CODE/
312         sub {0}         sub { ref shift eq "CODE" }
313
314 # HASH ref against:
315 #   - another hash ref
316         {}              {}
317 =!      {}              {1 => 2}
318         {1 => 2}        {1 => 2}
319         {1 => 2}        {1 => 3}
320 =!      {1 => 2}        {2 => 3}
321 =       \%main::        {map {$_ => 'x'} keys %main::}
322
323 #  - tied hash ref
324 =       \%hash          \%tied_hash
325         \%tied_hash     \%tied_hash
326 !=      {"a"=>"b"}      \%tied_hash
327 =       %hash           %tied_hash
328         %tied_hash      %tied_hash
329 !=      {"a"=>"b"}      %tied_hash
330         $ov_obj         %refh           MINISKIP
331 !       "$ov_obj"       %refh           MINISKIP
332         [$ov_obj]       %refh           MINISKIP
333 !       ["$ov_obj"]     %refh           MINISKIP
334         %refh           %refh           MINISKIP
335
336 #  - an array ref
337 #  (since this is symmetrical, tests as well hash~~array)
338 =       [keys %main::]  \%::
339 =       [qw[STDIN STDOUT]]      \%::
340 =!      []              \%::
341 =!      [""]            {}
342 =!      []              {}
343 =!      @empty          {}
344 =       [undef]         {"" => 1}
345 =       [""]            {"" => 1}
346 =       ["foo"]         { foo => 1 }
347 =       ["foo", "bar"]  { foo => 1 }
348 =       ["foo", "bar"]  \%hash
349 =       ["foo"]         \%hash
350 =!      ["quux"]        \%hash
351 =       [qw(foo quux)]  \%hash
352 =       @fooormore      { foo => 1, or => 2, more => 3 }
353 =       @fooormore      %fooormore
354 =       @fooormore      \%fooormore
355 =       \@fooormore     %fooormore
356
357 #  - a regex
358 =       qr/^(fo[ox])$/          {foo => 1}
359 =       /^(fo[ox])$/            %fooormore
360 =!      qr/[13579]$/            +{0..99}
361 =!      qr/a*/                  {}
362 =       qr/a*/                  {b=>2}
363 =       qr/B/i                  {b=>2}
364 =       /B/i                    {b=>2}
365 =!      qr/a+/                  {b=>2}
366 =       qr/^à/                 {"à"=>2}
367
368 #  - a scalar
369         "foo"           +{foo => 1, bar => 2}
370         "foo"           %fooormore
371 !       "baz"           +{foo => 1, bar => 2}
372 !       "boz"           %fooormore
373 !       1               +{foo => 1, bar => 2}
374 !       1               %fooormore
375         1               { 1 => 3 }
376         1.0             { 1 => 3 }
377 !       "1.0"           { 1 => 3 }
378 !       "1.0"           { 1.0 => 3 }
379         "1.0"           { "1.0" => 3 }
380         "à"            { "à" => "À" }
381
382 #  - undef
383 !       undef           { hop => 'zouu' }
384 !       undef           %hash
385 !       undef           +{"" => "empty key"}
386 !       undef           {}
387
388 # ARRAY ref against:
389 #  - another array ref
390         []                      []
391 =!      []                      [1]
392         [["foo"], ["bar"]]      [qr/o/, qr/a/]
393 !       [["foo"], ["bar"]]      [qr/ARRAY/, qr/ARRAY/]
394         ["foo", "bar"]          [qr/o/, qr/a/]
395 !       [qr/o/, qr/a/]          ["foo", "bar"]
396         ["foo", "bar"]          [["foo"], ["bar"]]
397 !       ["foo", "bar"]          [qr/o/, "foo"]
398         ["foo", undef, "bar"]   [qr/o/, undef, "bar"]
399 !       ["foo", undef, "bar"]   [qr/o/, "",    "bar"]
400 !       ["foo", "", "bar"]      [qr/o/, undef, "bar"]
401         $deep1                  $deep1
402         @$deep1                 @$deep1
403 !       $deep1                  $deep2
404
405 =       \@nums                  \@tied_nums
406 =       @nums                   \@tied_nums
407 =       \@nums                  @tied_nums
408 =       @nums                   @tied_nums
409
410 #  - an object
411 !       $obj            @fooormore
412         $obj            [sub{ref shift}]
413
414 #  - a regex
415 =       qr/x/           [qw(foo bar baz quux)]
416 =!      qr/y/           [qw(foo bar baz quux)]
417 =       /x/             [qw(foo bar baz quux)]
418 =!      /y/             [qw(foo bar baz quux)]
419 =       /FOO/i          @fooormore
420 =!      /bar/           @fooormore
421
422 # - a number
423         2               [qw(1.00 2.00)]
424         2               [qw(foo 2)]
425         2.0_0e+0        [qw(foo 2)]
426 !       2               [qw(1foo bar2)]
427
428 # - a string
429 !       "2"             [qw(1foo 2bar)]
430         "2bar"          [qw(1foo 2bar)]
431
432 # - undef
433         undef           [1, 2, undef, 4]
434 !       undef           [1, 2, [undef], 4]
435 !       undef           @fooormore
436         undef           @sparse
437         undef           [undef]
438 !       0               [undef]
439 !       ""              [undef]
440 !       undef           [0]
441 !       undef           [""]
442
443 # - nested arrays and ~~ distributivity
444         11              [[11]]
445 !       11              [[12]]
446         "foo"           [{foo => "bar"}]
447 !       "bar"           [{foo => "bar"}]
448
449 # Number against number
450         2               2
451         20              2_0
452 !       2               3
453         0               FALSE
454         3-2             TRUE
455 !       undef           0
456 !       (my $u)         0
457
458 # Number against string
459 =       2               "2"
460 =       2               "2.0"
461 !       2               "2bananas"
462 !=      2_3             "2_3"           NOWARNINGS
463         FALSE           "0"
464 !       undef           "0"
465 !       undef           ""
466
467 # Regex against string
468         "x"             qr/x/
469 !       "x"             qr/y/
470
471 # Regex against number
472         12345           qr/3/
473 !       12345           qr/7/
474
475 # array/hash against string
476         @fooormore      "".\@fooormore
477 !       @keyandmore     "".\@fooormore
478         %fooormore      "".\%fooormore
479 !       %keyandmore     "".\%fooormore
480
481 # Test the implicit referencing
482         7               @nums
483         @nums           \@nums
484 !       @nums           \\@nums
485         @nums           [1..10]
486 !       @nums           [0..9]
487
488         "foo"           %hash
489         /bar/           %hash
490         [qw(bar)]       %hash
491 !       [qw(a b c)]     %hash
492         %hash           %hash
493         %hash           +{%hash}
494         %hash           \%hash
495         %hash           %tied_hash
496         %tied_hash      %tied_hash
497         %hash           { foo => 5, bar => 10 }
498 !       %hash           { foo => 5, bar => 10, quux => 15 }
499
500         @nums           {  1, '',  2, '' }
501         @nums           {  1, '', 12, '' }
502 !       @nums           { 11, '', 12, '' }
503
504 # array slices
505         @nums[0..-1]    []
506         @nums[0..0]     [1]
507 !       @nums[0..1]     [0..2]
508         @nums[0..4]     [1..5]
509
510 !       undef           @nums[0..-1]
511         1               @nums[0..0]
512         2               @nums[0..1]
513 !       @nums[0..1]     2
514
515         @nums[0..1]     @nums[0..1]
516
517 # hash slices
518         @keyandmore{qw(not)}            [undef]
519         @keyandmore{qw(key)}            [0]
520
521         undef                           @keyandmore{qw(not)}
522         0                               @keyandmore{qw(key and more)}
523 !       2                               @keyandmore{qw(key and)}
524
525         @fooormore{qw(foo)}             @keyandmore{qw(key)}
526         @fooormore{qw(foo or more)}     @keyandmore{qw(key and more)}
527
528 # UNDEF
529 !       3               undef
530 !       1               undef
531 !       []              undef
532 !       {}              undef
533 !       \%::main        undef
534 !       [1,2]           undef
535 !       %hash           undef
536 !       @nums           undef
537 !       "foo"           undef
538 !       ""              undef
539 !       !1              undef
540 !       \&foo           undef
541 !       sub { }         undef