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