This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
f51884d39fd766d703e553eda2db8000214c9583
[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   local $::TODO = "not yet fixed...";
140   # This can but might not crash
141   #
142   # The second smartmatch would leave a &PL_sv_no on the stack for
143   # each key it checked in %!, this could then cause various types of
144   # crash or assertion failure.
145   #
146   # This isn't guaranteed to crash, but if the stack issue is
147   # re-introduced it will probably crash in one of the many smoke
148   # builds.
149   fresh_perl_is('print (q(x) ~~ q(x)) | (/x/ ~~ %!)', "1",
150                 { switches => [ "-MErrno", "-M-warnings=experimental::smartmatch" ] },
151                  "don't fill the stack with rubbish");
152 }
153
154 # Prefix character :
155 #   - expected to match
156 # ! - expected to not match
157 # @ - expected to be a compilation failure
158 # = - expected to match symmetrically (runs test twice)
159 # Data types to test :
160 #   undef
161 #   Object-overloaded
162 #   Object
163 #   Coderef
164 #   Hash
165 #   Hashref
166 #   Array
167 #   Arrayref
168 #   Tied arrays and hashes
169 #   Arrays that reference themselves
170 #   Regex (// and qr//)
171 #   Range
172 #   Num
173 #   Str
174 # Other syntactic items of interest:
175 #   Constants
176 #   Values returned by a sub call
177 __DATA__
178 # Any ~~ undef
179 !       $ov_obj         undef
180 !       $obj            undef
181 !       sub {}          undef
182 !       %hash           undef
183 !       \%hash          undef
184 !       {}              undef
185 !       @nums           undef
186 !       \@nums          undef
187 !       []              undef
188 !       %tied_hash      undef
189 !       @tied_nums      undef
190 !       $deep1          undef
191 !       /foo/           undef
192 !       qr/foo/         undef
193 !       21..30          undef
194 !       189             undef
195 !       "foo"           undef
196 !       ""              undef
197 !       !1              undef
198         undef           undef
199         (my $u)         undef
200         NOT_DEF         undef
201         &NOT_DEF        undef
202
203 # Any ~~ object overloaded
204 !       \&fatal         $ov_obj
205         'cigam'         $ov_obj
206 !       'cigam on'      $ov_obj
207 !       ['cigam']       $ov_obj
208 !       ['stringified'] $ov_obj
209 !       { cigam => 1 }  $ov_obj
210 !       { stringified => 1 }    $ov_obj
211 !       $obj            $ov_obj
212 !       undef           $ov_obj
213
214 # regular object
215 @       $obj            $obj
216 @       $ov_obj         $obj
217 =@      \&fatal         $obj
218 @       \&FALSE         $obj
219 @       \&foo           $obj
220 @       sub { 1 }       $obj
221 @       sub { 0 }       $obj
222 @       %keyandmore     $obj
223 @       {"key" => 1}    $obj
224 @       @fooormore      $obj
225 @       ["key" => 1]    $obj
226 @       /key/           $obj
227 @       qr/key/         $obj
228 @       "key"           $obj
229 @       FALSE           $obj
230
231 # regular object with "" overload
232 @       $obj            $str_obj
233 =@      \&fatal         $str_obj
234 @       \&FALSE         $str_obj
235 @       \&foo           $str_obj
236 @       sub { 1 }       $str_obj
237 @       sub { 0 }       $str_obj
238 @       %keyandmore     $str_obj
239 @       {"object" => 1} $str_obj
240 @       @fooormore      $str_obj
241 @       ["object" => 1] $str_obj
242 @       /object/        $str_obj
243 @       qr/object/      $str_obj
244 @       "object"        $str_obj
245 @       FALSE           $str_obj
246 # Those will treat the $str_obj as a string because of fallback:
247
248 # object (overloaded or not) ~~ Any
249         $obj            qr/NoOverload/
250         $ov_obj         qr/^stringified$/
251 =       "$ov_obj"       "stringified"
252 =       "$str_obj"      "object"
253 !=      $ov_obj         "stringified"
254         $str_obj        "object"
255         $ov_obj         'magic'
256 !       $ov_obj         'not magic'
257
258 # ~~ Coderef
259         sub{0}          sub { ref $_[0] eq "CODE" }
260         %fooormore      sub { $_[0] =~ /^(foo|or|more)$/ }
261 !       %fooormore      sub { $_[0] =~ /^(foo|or|less)$/ }
262         \%fooormore     sub { $_[0] =~ /^(foo|or|more)$/ }
263 !       \%fooormore     sub { $_[0] =~ /^(foo|or|less)$/ }
264         +{%fooormore}   sub { $_[0] =~ /^(foo|or|more)$/ }
265 !       +{%fooormore}   sub { $_[0] =~ /^(foo|or|less)$/ }
266         @fooormore      sub { $_[0] =~ /^(foo|or|more)$/ }
267 !       @fooormore      sub { $_[0] =~ /^(foo|or|less)$/ }
268         \@fooormore     sub { $_[0] =~ /^(foo|or|more)$/ }
269 !       \@fooormore     sub { $_[0] =~ /^(foo|or|less)$/ }
270         [@fooormore]    sub { $_[0] =~ /^(foo|or|more)$/ }
271 !       [@fooormore]    sub { $_[0] =~ /^(foo|or|less)$/ }
272         %fooormore      sub{@_==1}
273         @fooormore      sub{@_==1}
274         "foo"           sub { $_[0] =~ /^(foo|or|more)$/ }
275 !       "more"          sub { $_[0] =~ /^(foo|or|less)$/ }
276         /fooormore/     sub{ref $_[0] eq 'Regexp'}
277         qr/fooormore/   sub{ref $_[0] eq 'Regexp'}
278         1               sub{shift}
279 !       0               sub{shift}
280 !       undef           sub{shift}
281         undef           sub{not shift}
282         NOT_DEF         sub{not shift}
283         &NOT_DEF        sub{not shift}
284         FALSE           sub{not shift}
285         [1]             \&bar
286         {a=>1}          \&bar
287         qr//            \&bar
288 !       [1]             \&foo
289 !       {a=>1}          \&foo
290         $obj            sub { ref($_[0]) =~ /NoOverload/ }
291         $ov_obj         sub { ref($_[0]) =~ /WithOverload/ }
292 # empty stuff matches, because the sub is never called:
293         []              \&foo
294         {}              \&foo
295         @empty          \&foo
296         %empty          \&foo
297 !       qr//            \&foo
298 !       undef           \&foo
299         undef           \&bar
300 @       undef           \&fatal
301 @       1               \&fatal
302 @       [1]             \&fatal
303 @       {a=>1}          \&fatal
304 @       "foo"           \&fatal
305 @       qr//            \&fatal
306 # sub is not called on empty hashes / arrays
307         []              \&fatal
308         +{}             \&fatal
309         @empty          \&fatal
310         %empty          \&fatal
311 # sub is not special on the left
312         sub {0}         qr/^CODE/
313         sub {0}         sub { ref shift eq "CODE" }
314
315 # HASH ref against:
316 #   - another hash ref
317         {}              {}
318 =!      {}              {1 => 2}
319         {1 => 2}        {1 => 2}
320         {1 => 2}        {1 => 3}
321 =!      {1 => 2}        {2 => 3}
322 =       \%main::        {map {$_ => 'x'} keys %main::}
323
324 #  - tied hash ref
325 =       \%hash          \%tied_hash
326         \%tied_hash     \%tied_hash
327 !=      {"a"=>"b"}      \%tied_hash
328 =       %hash           %tied_hash
329         %tied_hash      %tied_hash
330 !=      {"a"=>"b"}      %tied_hash
331         $ov_obj         %refh           MINISKIP
332 !       "$ov_obj"       %refh           MINISKIP
333         [$ov_obj]       %refh           MINISKIP
334 !       ["$ov_obj"]     %refh           MINISKIP
335         %refh           %refh           MINISKIP
336
337 #  - an array ref
338 #  (since this is symmetrical, tests as well hash~~array)
339 =       [keys %main::]  \%::
340 =       [qw[STDIN STDOUT]]      \%::
341 =!      []              \%::
342 =!      [""]            {}
343 =!      []              {}
344 =!      @empty          {}
345 =       [undef]         {"" => 1}
346 =       [""]            {"" => 1}
347 =       ["foo"]         { foo => 1 }
348 =       ["foo", "bar"]  { foo => 1 }
349 =       ["foo", "bar"]  \%hash
350 =       ["foo"]         \%hash
351 =!      ["quux"]        \%hash
352 =       [qw(foo quux)]  \%hash
353 =       @fooormore      { foo => 1, or => 2, more => 3 }
354 =       @fooormore      %fooormore
355 =       @fooormore      \%fooormore
356 =       \@fooormore     %fooormore
357
358 #  - a regex
359 =       qr/^(fo[ox])$/          {foo => 1}
360 =       /^(fo[ox])$/            %fooormore
361 =!      qr/[13579]$/            +{0..99}
362 =!      qr/a*/                  {}
363 =       qr/a*/                  {b=>2}
364 =       qr/B/i                  {b=>2}
365 =       /B/i                    {b=>2}
366 =!      qr/a+/                  {b=>2}
367 =       qr/^à/                 {"à"=>2}
368
369 #  - a scalar
370         "foo"           +{foo => 1, bar => 2}
371         "foo"           %fooormore
372 !       "baz"           +{foo => 1, bar => 2}
373 !       "boz"           %fooormore
374 !       1               +{foo => 1, bar => 2}
375 !       1               %fooormore
376         1               { 1 => 3 }
377         1.0             { 1 => 3 }
378 !       "1.0"           { 1 => 3 }
379 !       "1.0"           { 1.0 => 3 }
380         "1.0"           { "1.0" => 3 }
381         "à"            { "à" => "À" }
382
383 #  - undef
384 !       undef           { hop => 'zouu' }
385 !       undef           %hash
386 !       undef           +{"" => "empty key"}
387 !       undef           {}
388
389 # ARRAY ref against:
390 #  - another array ref
391         []                      []
392 =!      []                      [1]
393         [["foo"], ["bar"]]      [qr/o/, qr/a/]
394 !       [["foo"], ["bar"]]      [qr/ARRAY/, qr/ARRAY/]
395         ["foo", "bar"]          [qr/o/, qr/a/]
396 !       [qr/o/, qr/a/]          ["foo", "bar"]
397         ["foo", "bar"]          [["foo"], ["bar"]]
398 !       ["foo", "bar"]          [qr/o/, "foo"]
399         ["foo", undef, "bar"]   [qr/o/, undef, "bar"]
400 !       ["foo", undef, "bar"]   [qr/o/, "",    "bar"]
401 !       ["foo", "", "bar"]      [qr/o/, undef, "bar"]
402         $deep1                  $deep1
403         @$deep1                 @$deep1
404 !       $deep1                  $deep2
405
406 =       \@nums                  \@tied_nums
407 =       @nums                   \@tied_nums
408 =       \@nums                  @tied_nums
409 =       @nums                   @tied_nums
410
411 #  - an object
412 !       $obj            @fooormore
413         $obj            [sub{ref shift}]
414
415 #  - a regex
416 =       qr/x/           [qw(foo bar baz quux)]
417 =!      qr/y/           [qw(foo bar baz quux)]
418 =       /x/             [qw(foo bar baz quux)]
419 =!      /y/             [qw(foo bar baz quux)]
420 =       /FOO/i          @fooormore
421 =!      /bar/           @fooormore
422
423 # - a number
424         2               [qw(1.00 2.00)]
425         2               [qw(foo 2)]
426         2.0_0e+0        [qw(foo 2)]
427 !       2               [qw(1foo bar2)]
428
429 # - a string
430 !       "2"             [qw(1foo 2bar)]
431         "2bar"          [qw(1foo 2bar)]
432
433 # - undef
434         undef           [1, 2, undef, 4]
435 !       undef           [1, 2, [undef], 4]
436 !       undef           @fooormore
437         undef           @sparse
438         undef           [undef]
439 !       0               [undef]
440 !       ""              [undef]
441 !       undef           [0]
442 !       undef           [""]
443
444 # - nested arrays and ~~ distributivity
445         11              [[11]]
446 !       11              [[12]]
447         "foo"           [{foo => "bar"}]
448 !       "bar"           [{foo => "bar"}]
449
450 # Number against number
451         2               2
452         20              2_0
453 !       2               3
454         0               FALSE
455         3-2             TRUE
456 !       undef           0
457 !       (my $u)         0
458
459 # Number against string
460 =       2               "2"
461 =       2               "2.0"
462 !       2               "2bananas"
463 !=      2_3             "2_3"           NOWARNINGS
464         FALSE           "0"
465 !       undef           "0"
466 !       undef           ""
467
468 # Regex against string
469         "x"             qr/x/
470 !       "x"             qr/y/
471
472 # Regex against number
473         12345           qr/3/
474 !       12345           qr/7/
475
476 # array/hash against string
477         @fooormore      "".\@fooormore
478 !       @keyandmore     "".\@fooormore
479         %fooormore      "".\%fooormore
480 !       %keyandmore     "".\%fooormore
481
482 # Test the implicit referencing
483         7               @nums
484         @nums           \@nums
485 !       @nums           \\@nums
486         @nums           [1..10]
487 !       @nums           [0..9]
488
489         "foo"           %hash
490         /bar/           %hash
491         [qw(bar)]       %hash
492 !       [qw(a b c)]     %hash
493         %hash           %hash
494         %hash           +{%hash}
495         %hash           \%hash
496         %hash           %tied_hash
497         %tied_hash      %tied_hash
498         %hash           { foo => 5, bar => 10 }
499 !       %hash           { foo => 5, bar => 10, quux => 15 }
500
501         @nums           {  1, '',  2, '' }
502         @nums           {  1, '', 12, '' }
503 !       @nums           { 11, '', 12, '' }
504
505 # array slices
506         @nums[0..-1]    []
507         @nums[0..0]     [1]
508 !       @nums[0..1]     [0..2]
509         @nums[0..4]     [1..5]
510
511 !       undef           @nums[0..-1]
512         1               @nums[0..0]
513         2               @nums[0..1]
514 !       @nums[0..1]     2
515
516         @nums[0..1]     @nums[0..1]
517
518 # hash slices
519         @keyandmore{qw(not)}            [undef]
520         @keyandmore{qw(key)}            [0]
521
522         undef                           @keyandmore{qw(not)}
523         0                               @keyandmore{qw(key and more)}
524 !       2                               @keyandmore{qw(key and)}
525
526         @fooormore{qw(foo)}             @keyandmore{qw(key)}
527         @fooormore{qw(foo or more)}     @keyandmore{qw(key and more)}
528
529 # UNDEF
530 !       3               undef
531 !       1               undef
532 !       []              undef
533 !       {}              undef
534 !       \%::main        undef
535 !       [1,2]           undef
536 !       %hash           undef
537 !       @nums           undef
538 !       "foo"           undef
539 !       ""              undef
540 !       !1              undef
541 !       \&foo           undef
542 !       sub { }         undef