This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Get t/uni/cache.t working under minitest
[perl5.git] / t / op / sort.t
1 #!./perl
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = qw(. ../lib);
6     require 'test.pl';
7 }
8 use warnings;
9 plan( tests => 182 );
10
11 # these shouldn't hang
12 {
13     no warnings;
14     sort { for ($_ = 0;; $_++) {} } @a;
15     sort { while(1) {}            } @a;
16     sort { while(1) { last; }     } @a;
17     sort { while(0) { last; }     } @a;
18
19     # Change 26011: Re: A surprising segfault
20     map scalar(sort(+())), ('')x68;
21 }
22
23 sub Backwards { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
24 sub Backwards_stacked($$) { my($a,$b) = @_; $a lt $b ? 1 : $a gt $b ? -1 : 0 }
25 sub Backwards_other { $a lt $b ? 1 : $a gt $b ? -1 : 0 }
26
27 my $upperfirst = 'A' lt 'a';
28
29 # Beware: in future this may become hairier because of possible
30 # collation complications: qw(A a B b) can be sorted at least as
31 # any of the following
32 #
33 #       A a B b
34 #       A B a b
35 #       a b A B
36 #       a A b B
37 #
38 # All the above orders make sense.
39 #
40 # That said, EBCDIC sorts all small letters first, as opposed
41 # to ASCII which sorts all big letters first.
42
43 @harry = ('dog','cat','x','Cain','Abel');
44 @george = ('gone','chased','yz','punished','Axed');
45
46 $x = join('', sort @harry);
47 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
48
49 cmp_ok($x,'eq',$expected,'upper first 1');
50
51 $x = join('', sort( Backwards @harry));
52 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
53
54 cmp_ok($x,'eq',$expected,'upper first 2');
55
56 $x = join('', sort( Backwards_stacked @harry));
57 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
58
59 cmp_ok($x,'eq',$expected,'upper first 3');
60
61 $x = join('', sort @george, 'to', @harry);
62 $expected = $upperfirst ?
63     'AbelAxedCaincatchaseddoggonepunishedtoxyz' :
64     'catchaseddoggonepunishedtoxyzAbelAxedCain' ;
65
66 cmp_ok($x,'eq',$expected,'upper first 4');
67 $" = ' ';
68 @a = ();
69 @b = reverse @a;
70 cmp_ok("@b",'eq',"",'reverse 1');
71
72 @a = (1);
73 @b = reverse @a;
74 cmp_ok("@b",'eq',"1",'reverse 2');
75
76 @a = (1,2);
77 @b = reverse @a;
78 cmp_ok("@b",'eq',"2 1",'reverse 3');
79
80 @a = (1,2,3);
81 @b = reverse @a;
82 cmp_ok("@b",'eq',"3 2 1",'reverse 4');
83
84 @a = (1,2,3,4);
85 @b = reverse @a;
86 cmp_ok("@b",'eq',"4 3 2 1",'reverse 5');
87
88 @a = (10,2,3,4);
89 @b = sort {$a <=> $b;} @a;
90 cmp_ok("@b",'eq',"2 3 4 10",'sort numeric');
91
92 $sub = 'Backwards';
93 $x = join('', sort $sub @harry);
94 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
95
96 cmp_ok($x,'eq',$expected,'sorter sub name in var 1');
97
98 $sub = 'Backwards_stacked';
99 $x = join('', sort $sub @harry);
100 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
101
102 cmp_ok($x,'eq',$expected,'sorter sub name in var 2');
103
104 # literals, combinations
105
106 @b = sort (4,1,3,2);
107 cmp_ok("@b",'eq','1 2 3 4','just sort');
108
109
110 @b = sort grep { $_ } (4,1,3,2);
111 cmp_ok("@b",'eq','1 2 3 4','grep then sort');
112
113
114 @b = sort map { $_ } (4,1,3,2);
115 cmp_ok("@b",'eq','1 2 3 4','map then sort');
116
117
118 @b = sort reverse (4,1,3,2);
119 cmp_ok("@b",'eq','1 2 3 4','reverse then sort');
120
121
122 @b = sort CORE::reverse (4,1,3,2);
123 cmp_ok("@b",'eq','1 2 3 4','CORE::reverse then sort');
124
125
126
127 sub twoface { no warnings 'redefine'; *twoface = sub { $a <=> $b }; &twoface }
128 eval { @b = sort twoface 4,1,3,2 };
129 cmp_ok("@b",'eq','1 2 3 4','redefine sort sub inside the sort sub');
130
131
132 eval { no warnings 'redefine'; *twoface = sub { &Backwards } };
133 ok(!$@,"redefining sort subs outside the sort \$@=[$@]");
134
135 eval { @b = sort twoface 4,1,3,2 };
136 cmp_ok("@b",'eq','4 3 2 1','twoface redefinition');
137
138 {
139   no warnings 'redefine';
140   *twoface = sub { *twoface = *Backwards_other; $a <=> $b };
141 }
142
143 eval { @b = sort twoface 4,1,9,5 };
144 ok(($@ eq "" && "@b" eq "1 4 5 9"),'redefinition should not take effect during the sort');
145
146 {
147   no warnings 'redefine';
148   *twoface = sub {
149                  eval 'sub twoface { $a <=> $b }';
150                  die($@ eq "" ? "good\n" : "bad\n");
151                  $a <=> $b;
152                };
153 }
154 eval { @b = sort twoface 4,1 };
155 cmp_ok(substr($@,0,4), 'eq', 'good', 'twoface eval');
156
157 eval <<'CODE';
158     my @result = sort main'Backwards 'one', 'two';
159 CODE
160 cmp_ok($@,'eq','',q(old skool package));
161
162 eval <<'CODE';
163     # "sort 'one', 'two'" should not try to parse "'one" as a sort sub
164     my @result = sort 'one', 'two';
165 CODE
166 cmp_ok($@,'eq','',q(one is not a sub));
167
168 {
169   my $sortsub = \&Backwards;
170   my $sortglob = *Backwards;
171   my $sortglobr = \*Backwards;
172   my $sortname = 'Backwards';
173   @b = sort $sortsub 4,1,3,2;
174   cmp_ok("@b",'eq','4 3 2 1','sortname 1');
175   @b = sort $sortglob 4,1,3,2;
176   cmp_ok("@b",'eq','4 3 2 1','sortname 2');
177   @b = sort $sortname 4,1,3,2;
178   cmp_ok("@b",'eq','4 3 2 1','sortname 3');
179   @b = sort $sortglobr 4,1,3,2;
180   cmp_ok("@b",'eq','4 3 2 1','sortname 4');
181 }
182
183 {
184   my $sortsub = \&Backwards_stacked;
185   my $sortglob = *Backwards_stacked;
186   my $sortglobr = \*Backwards_stacked;
187   my $sortname = 'Backwards_stacked';
188   @b = sort $sortsub 4,1,3,2;
189   cmp_ok("@b",'eq','4 3 2 1','sortname 5');
190   @b = sort $sortglob 4,1,3,2;
191   cmp_ok("@b",'eq','4 3 2 1','sortname 6');
192   @b = sort $sortname 4,1,3,2;
193   cmp_ok("@b",'eq','4 3 2 1','sortname 7');
194   @b = sort $sortglobr 4,1,3,2;
195   cmp_ok("@b",'eq','4 3 2 1','sortname 8');
196 }
197
198 {
199   local $sortsub = \&Backwards;
200   local $sortglob = *Backwards;
201   local $sortglobr = \*Backwards;
202   local $sortname = 'Backwards';
203   @b = sort $sortsub 4,1,3,2;
204   cmp_ok("@b",'eq','4 3 2 1','sortname local 1');
205   @b = sort $sortglob 4,1,3,2;
206   cmp_ok("@b",'eq','4 3 2 1','sortname local 2');
207   @b = sort $sortname 4,1,3,2;
208   cmp_ok("@b",'eq','4 3 2 1','sortname local 3');
209   @b = sort $sortglobr 4,1,3,2;
210   cmp_ok("@b",'eq','4 3 2 1','sortname local 4');
211 }
212
213 {
214   local $sortsub = \&Backwards_stacked;
215   local $sortglob = *Backwards_stacked;
216   local $sortglobr = \*Backwards_stacked;
217   local $sortname = 'Backwards_stacked';
218   @b = sort $sortsub 4,1,3,2;
219   cmp_ok("@b",'eq','4 3 2 1','sortname local 5');
220   @b = sort $sortglob 4,1,3,2;
221   cmp_ok("@b",'eq','4 3 2 1','sortname local 6');
222   @b = sort $sortname 4,1,3,2;
223   cmp_ok("@b",'eq','4 3 2 1','sortname local 7');
224   @b = sort $sortglobr 4,1,3,2;
225   cmp_ok("@b",'eq','4 3 2 1','sortname local 8');
226 }
227
228 ## exercise sort builtins... ($a <=> $b already tested)
229 @a = ( 5, 19, 1996, 255, 90 );
230 @b = sort {
231     my $dummy;          # force blockness
232     return $b <=> $a
233 } @a;
234 cmp_ok("@b",'eq','1996 255 90 19 5','force blockness');
235
236 $x = join('', sort { $a cmp $b } @harry);
237 $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
238 cmp_ok($x,'eq',$expected,'a cmp b');
239
240 $x = join('', sort { $b cmp $a } @harry);
241 $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
242 cmp_ok($x,'eq',$expected,'b cmp a');
243
244 {
245     use integer;
246     @b = sort { $a <=> $b } @a;
247     cmp_ok("@b",'eq','5 19 90 255 1996','integer a <=> b');
248
249     @b = sort { $b <=> $a } @a;
250     cmp_ok("@b",'eq','1996 255 90 19 5','integer b <=> a');
251
252     $x = join('', sort { $a cmp $b } @harry);
253     $expected = $upperfirst ? 'AbelCaincatdogx' : 'catdogxAbelCain';
254     cmp_ok($x,'eq',$expected,'integer a cmp b');
255
256     $x = join('', sort { $b cmp $a } @harry);
257     $expected = $upperfirst ? 'xdogcatCainAbel' : 'CainAbelxdogcat';
258     cmp_ok($x,'eq',$expected,'integer b cmp a');
259
260 }
261
262
263
264 $x = join('', sort { $a <=> $b } 3, 1, 2);
265 cmp_ok($x,'eq','123',q(optimized-away comparison block doesn't take any other arguments away with it));
266
267 # test sorting in non-main package
268 {
269     package Foo;
270     @a = ( 5, 19, 1996, 255, 90 );
271     @b = sort { $b <=> $a } @a;
272     ::cmp_ok("@b",'eq','1996 255 90 19 5','not in main:: 1');
273
274     @b = sort ::Backwards_stacked @a;
275     ::cmp_ok("@b",'eq','90 5 255 1996 19','not in main:: 2');
276
277     # check if context for sort arguments is handled right
278     sub test_if_list {
279         my $gimme = wantarray;
280         ::is($gimme,1,'wantarray 1');
281     }
282     my $m = sub { $a <=> $b };
283
284     sub cxt_one { sort $m test_if_list() }
285     cxt_one();
286     sub cxt_two { sort { $a <=> $b } test_if_list() }
287     cxt_two();
288     sub cxt_three { sort &test_if_list() }
289     cxt_three();
290     sub cxt_three_anna_half { sort 0, test_if_list() }
291     cxt_three_anna_half();
292
293     sub test_if_scalar {
294         my $gimme = wantarray;
295         ::is(!($gimme or !defined($gimme)),1,'wantarray 2');
296     }
297
298     $m = \&test_if_scalar;
299     sub cxt_four { sort $m 1,2 }
300     @x = cxt_four();
301     sub cxt_five { sort { test_if_scalar($a,$b); } 1,2 }
302     @x = cxt_five();
303     sub cxt_six { sort test_if_scalar 1,2 }
304     @x = cxt_six();
305 }
306
307
308 # test against a reentrancy bug
309 {
310     package Bar;
311     sub compare { $a cmp $b }
312     sub reenter { my @force = sort compare qw/a b/ }
313 }
314 {
315     my($def, $init) = (0, 0);
316     @b = sort {
317         $def = 1 if defined $Bar::a;
318         Bar::reenter() unless $init++;
319         $a <=> $b
320     } qw/4 3 1 2/;
321     cmp_ok("@b",'eq','1 2 3 4','reenter 1');
322
323     ok(!$def,'reenter 2');
324 }
325
326
327 {
328     sub routine { "one", "two" };
329     @a = sort(routine(1));
330     cmp_ok("@a",'eq',"one two",'bug id 19991001.003');
331 }
332
333
334 # check for in-place optimisation of @a = sort @a
335 {
336     my ($r1,$r2,@a);
337     our @g;
338     @g = (3,2,1); $r1 = \$g[2]; @g = sort @g; $r2 = \$g[0];
339     is "$r1-@g", "$r2-1 2 3", "inplace sort of global";
340
341     @a = qw(b a c); $r1 = \$a[1]; @a = sort @a; $r2 = \$a[0];
342     is "$r1-@a", "$r2-a b c", "inplace sort of lexical";
343
344     @g = (2,3,1); $r1 = \$g[1]; @g = sort { $b <=> $a } @g; $r2 = \$g[0];
345     is "$r1-@g", "$r2-3 2 1", "inplace reversed sort of global";
346
347     @g = (2,3,1);
348     $r1 = \$g[1]; @g = sort { $a<$b?1:$a>$b?-1:0 } @g; $r2 = \$g[0];
349     is "$r1-@g", "$r2-3 2 1", "inplace custom sort of global";
350
351     sub mysort { $b cmp $a };
352     @a = qw(b c a); $r1 = \$a[1]; @a = sort mysort @a; $r2 = \$a[0];
353     is "$r1-@a", "$r2-c b a", "inplace sort with function of lexical";
354
355     use Tie::Array;
356     my @t;
357     tie @t, 'Tie::StdArray';
358
359     @t = qw(b c a); @t = sort @t;
360     is "@t", "a b c", "inplace sort of tied array";
361
362     @t = qw(b c a); @t = sort mysort @t;
363     is "@t", "c b a", "inplace sort of tied array with function";
364
365     #  [perl #29790] don't optimise @a = ('a', sort @a) !
366
367     @g = (3,2,1); @g = ('0', sort @g);
368     is "@g", "0 1 2 3", "un-inplace sort of global";
369     @g = (3,2,1); @g = (sort(@g),'4');
370     is "@g", "1 2 3 4", "un-inplace sort of global 2";
371
372     @a = qw(b a c); @a = ('x', sort @a);
373     is "@a", "x a b c", "un-inplace sort of lexical";
374     @a = qw(b a c); @a = ((sort @a), 'x');
375     is "@a", "a b c x", "un-inplace sort of lexical 2";
376
377     @g = (2,3,1); @g = ('0', sort { $b <=> $a } @g);
378     is "@g", "0 3 2 1", "un-inplace reversed sort of global";
379     @g = (2,3,1); @g = ((sort { $b <=> $a } @g),'4');
380     is "@g", "3 2 1 4", "un-inplace reversed sort of global 2";
381
382     @g = (2,3,1); @g = ('0', sort { $a<$b?1:$a>$b?-1:0 } @g);
383     is "@g", "0 3 2 1", "un-inplace custom sort of global";
384     @g = (2,3,1); @g = ((sort { $a<$b?1:$a>$b?-1:0 } @g),'4');
385     is "@g", "3 2 1 4", "un-inplace custom sort of global 2";
386
387     @a = qw(b c a); @a = ('x', sort mysort @a);
388     is "@a", "x c b a", "un-inplace sort with function of lexical";
389     @a = qw(b c a); @a = ((sort mysort @a),'x');
390     is "@a", "c b a x", "un-inplace sort with function of lexical 2";
391
392     # RT#54758. Git 62b40d2474e7487e6909e1872b6bccdf812c6818
393     no warnings 'void';
394     my @m; push @m, 0 for 1 .. 1024; $#m; @m = sort @m;
395     ::pass("in-place sorting segfault");
396 }
397
398 # Test optimisations of reversed sorts. As we now guarantee stability by
399 # default, # optimisations which do not provide this are bogus.
400
401 {
402     package Oscalar;
403     use overload (qw("" stringify 0+ numify fallback 1));
404
405     sub new {
406         bless [$_[1], $_[2]], $_[0];
407     }
408
409     sub stringify { $_[0]->[0] }
410
411     sub numify { $_[0]->[1] }
412 }
413
414 sub generate {
415     my $count = 0;
416     map {new Oscalar $_, $count++} qw(A A A B B B C C C);
417 }
418
419 my @input = &generate;
420 my @output = sort @input;
421 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", "Simple stable sort";
422
423 @input = &generate;
424 @input = sort @input;
425 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
426     "Simple stable in place sort";
427
428 # This won't be very interesting
429 @input = &generate;
430 @output = sort {$a <=> $b} @input;
431 is "@output", "A A A B B B C C C", 'stable $a <=> $b sort';
432
433 @input = &generate;
434 @output = sort {$a cmp $b} @input;
435 is join(" ", map {0+$_} @output), "0 1 2 3 4 5 6 7 8", 'stable $a cmp $b sort';
436
437 @input = &generate;
438 @input = sort {$a cmp $b} @input;
439 is join(" ", map {0+$_} @input), "0 1 2 3 4 5 6 7 8",
440     'stable $a cmp $b in place sort';
441
442 @input = &generate;
443 @output = sort {$b cmp $a} @input;
444 is join(" ", map {0+$_} @output), "6 7 8 3 4 5 0 1 2", 'stable $b cmp $a sort';
445
446 @input = &generate;
447 @input = sort {$b cmp $a} @input;
448 is join(" ", map {0+$_} @input), "6 7 8 3 4 5 0 1 2",
449     'stable $b cmp $a in place sort';
450
451 @input = &generate;
452 @output = reverse sort @input;
453 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0", "Reversed stable sort";
454
455 @input = &generate;
456 @input = reverse sort @input;
457 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
458     "Reversed stable in place sort";
459
460 @input = &generate;
461 my $output = reverse sort @input;
462 is $output, "CCCBBBAAA", "Reversed stable sort in scalar context";
463
464
465 @input = &generate;
466 @output = reverse sort {$a cmp $b} @input;
467 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
468     'reversed stable $a cmp $b sort';
469
470 @input = &generate;
471 @input = reverse sort {$a cmp $b} @input;
472 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
473     'revesed stable $a cmp $b in place sort';
474
475 @input = &generate;
476 $output = reverse sort {$a cmp $b} @input;
477 is $output, "CCCBBBAAA", 'Reversed stable $a cmp $b sort in scalar context';
478
479 @input = &generate;
480 @output = reverse sort {$b cmp $a} @input;
481 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
482     'reversed stable $b cmp $a sort';
483
484 @input = &generate;
485 @input = reverse sort {$b cmp $a} @input;
486 is join(" ", map {0+$_} @input), "2 1 0 5 4 3 8 7 6",
487     'revesed stable $b cmp $a in place sort';
488
489 @input = &generate;
490 $output = reverse sort {$b cmp $a} @input;
491 is $output, "AAABBBCCC", 'Reversed stable $b cmp $a sort in scalar context';
492
493 sub stuff {
494     # Something complex enough to defeat any constant folding optimiser
495     $$ - $$;
496 }
497
498 @input = &generate;
499 @output = reverse sort {stuff || $a cmp $b} @input;
500 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
501     'reversed stable complex sort';
502
503 @input = &generate;
504 @input = reverse sort {stuff || $a cmp $b} @input;
505 is join(" ", map {0+$_} @input), "8 7 6 5 4 3 2 1 0",
506     'revesed stable complex in place sort';
507
508 @input = &generate;
509 $output = reverse sort {stuff || $a cmp $b } @input;
510 is $output, "CCCBBBAAA", 'Reversed stable complex sort in scalar context';
511
512 sub sortr {
513     reverse sort @_;
514 }
515
516 @output = sortr &generate;
517 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
518     'reversed stable sort return list context';
519 $output = sortr &generate;
520 is $output, "CCCBBBAAA",
521     'reversed stable sort return scalar context';
522
523 sub sortcmpr {
524     reverse sort {$a cmp $b} @_;
525 }
526
527 @output = sortcmpr &generate;
528 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
529     'reversed stable $a cmp $b sort return list context';
530 $output = sortcmpr &generate;
531 is $output, "CCCBBBAAA",
532     'reversed stable $a cmp $b sort return scalar context';
533
534 sub sortcmprba {
535     reverse sort {$b cmp $a} @_;
536 }
537
538 @output = sortcmprba &generate;
539 is join(" ", map {0+$_} @output), "2 1 0 5 4 3 8 7 6",
540     'reversed stable $b cmp $a sort return list context';
541 $output = sortcmprba &generate;
542 is $output, "AAABBBCCC",
543 'reversed stable $b cmp $a sort return scalar context';
544
545 sub sortcmprq {
546     reverse sort {stuff || $a cmp $b} @_;
547 }
548
549 @output = sortcmpr &generate;
550 is join(" ", map {0+$_} @output), "8 7 6 5 4 3 2 1 0",
551     'reversed stable complex sort return list context';
552 $output = sortcmpr &generate;
553 is $output, "CCCBBBAAA",
554     'reversed stable complex sort return scalar context';
555
556 # And now with numbers
557
558 sub generate1 {
559     my $count = 'A';
560     map {new Oscalar $count++, $_} 0, 0, 0, 1, 1, 1, 2, 2, 2;
561 }
562
563 # This won't be very interesting
564 @input = &generate1;
565 @output = sort {$a cmp $b} @input;
566 is "@output", "A B C D E F G H I", 'stable $a cmp $b sort';
567
568 @input = &generate1;
569 @output = sort {$a <=> $b} @input;
570 is "@output", "A B C D E F G H I", 'stable $a <=> $b sort';
571
572 @input = &generate1;
573 @input = sort {$a <=> $b} @input;
574 is "@input", "A B C D E F G H I", 'stable $a <=> $b in place sort';
575
576 @input = &generate1;
577 @output = sort {$b <=> $a} @input;
578 is "@output", "G H I D E F A B C", 'stable $b <=> $a sort';
579
580 @input = &generate1;
581 @input = sort {$b <=> $a} @input;
582 is "@input", "G H I D E F A B C", 'stable $b <=> $a in place sort';
583
584 # test that optimized {$b cmp $a} and {$b <=> $a} remain stable
585 # (new in 5.9) without overloading
586 { no warnings;
587 @b = sort { $b <=> $a } @input = qw/5first 6first 5second 6second/;
588 is "@b" , "6first 6second 5first 5second", "optimized {$b <=> $a} without overloading" ;
589 @input = sort {$b <=> $a} @input;
590 is "@input" , "6first 6second 5first 5second","inline optimized {$b <=> $a} without overloading" ;
591 };
592
593 # These two are actually doing string cmp on 0 1 and 2
594 @input = &generate1;
595 @output = reverse sort @input;
596 is "@output", "I H G F E D C B A", "Reversed stable sort";
597
598 @input = &generate1;
599 @input = reverse sort @input;
600 is "@input", "I H G F E D C B A", "Reversed stable in place sort";
601
602 @input = &generate1;
603 $output = reverse sort @input;
604 is $output, "IHGFEDCBA", "Reversed stable sort in scalar context";
605
606 @input = &generate1;
607 @output = reverse sort {$a <=> $b} @input;
608 is "@output", "I H G F E D C B A", 'reversed stable $a <=> $b sort';
609
610 @input = &generate1;
611 @input = reverse sort {$a <=> $b} @input;
612 is "@input", "I H G F E D C B A", 'revesed stable $a <=> $b in place sort';
613
614 @input = &generate1;
615 $output = reverse sort {$a <=> $b} @input;
616 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort in scalar context';
617
618 @input = &generate1;
619 @output = reverse sort {$b <=> $a} @input;
620 is "@output", "C B A F E D I H G", 'reversed stable $b <=> $a sort';
621
622 @input = &generate1;
623 @input = reverse sort {$b <=> $a} @input;
624 is "@input", "C B A F E D I H G", 'revesed stable $b <=> $a in place sort';
625
626 @input = &generate1;
627 $output = reverse sort {$b <=> $a} @input;
628 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort in scalar context';
629
630 @input = &generate1;
631 @output = reverse sort {stuff || $a <=> $b} @input;
632 is "@output", "I H G F E D C B A", 'reversed stable complex sort';
633
634 @input = &generate1;
635 @input = reverse sort {stuff || $a <=> $b} @input;
636 is "@input", "I H G F E D C B A", 'revesed stable complex in place sort';
637
638 @input = &generate1;
639 $output = reverse sort {stuff || $a <=> $b} @input;
640 is $output, "IHGFEDCBA", 'reversed stable complex sort in scalar context';
641
642 sub sortnumr {
643     reverse sort {$a <=> $b} @_;
644 }
645
646 @output = sortnumr &generate1;
647 is "@output", "I H G F E D C B A",
648     'reversed stable $a <=> $b sort return list context';
649 $output = sortnumr &generate1;
650 is $output, "IHGFEDCBA", 'reversed stable $a <=> $b sort return scalar context';
651
652 sub sortnumrba {
653     reverse sort {$b <=> $a} @_;
654 }
655
656 @output = sortnumrba &generate1;
657 is "@output", "C B A F E D I H G",
658     'reversed stable $b <=> $a sort return list context';
659 $output = sortnumrba &generate1;
660 is $output, "CBAFEDIHG", 'reversed stable $b <=> $a sort return scalar context';
661
662 sub sortnumrq {
663     reverse sort {stuff || $a <=> $b} @_;
664 }
665
666 @output = sortnumrq &generate1;
667 is "@output", "I H G F E D C B A",
668     'reversed stable complex sort return list context';
669 $output = sortnumrq &generate1;
670 is $output, "IHGFEDCBA", 'reversed stable complex sort return scalar context';
671
672 @output = reverse (sort(qw(C A B)), 0);
673 is "@output", "0 C B A", 'reversed sort with trailing argument';
674
675 @output = reverse (0, sort(qw(C A B)));
676 is "@output", "C B A 0", 'reversed sort with leading argument';
677
678 eval { @output = sort {goto sub {}} 1,2; };
679 $fail_msg = q(Can't goto subroutine outside a subroutine);
680 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr outside subr');
681
682
683
684 sub goto_sub {goto sub{}}
685 eval { @output = sort goto_sub 1,2; };
686 $fail_msg = q(Can't goto subroutine from a sort sub);
687 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto subr from a sort sub');
688
689
690
691 eval { @output = sort {goto label} 1,2; };
692 $fail_msg = q(Can't "goto" out of a pseudo block);
693 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 1');
694
695
696
697 sub goto_label {goto label}
698 label: eval { @output = sort goto_label 1,2; };
699 $fail_msg = q(Can't "goto" out of a pseudo block);
700 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'goto out of a pseudo block 2');
701
702
703
704 sub self_immolate {undef &self_immolate; $a<=>$b}
705 eval { @output = sort self_immolate 1,2,3 };
706 $fail_msg = q(Can't undef active subroutine);
707 cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'undef active subr');
708
709
710 for(1,2) # We run this twice, to make sure sort does not lower the ref
711 {        # count. See bug 71076.
712     my $failed = 0;
713
714     sub rec {
715         my $n = shift;
716         if (!defined($n)) {  # No arg means we're being called by sort()
717             return 1;
718         }
719         if ($n<5) { rec($n+1); }
720         else { () = sort rec 1,2; }
721
722         $failed = 1 if !defined $n;
723     }
724
725     rec(1);
726     ok(!$failed, "sort from active sub");
727 }
728
729 # $a and $b are set in the package the sort() is called from,
730 # *not* the package the sort sub is in. This is longstanding
731 # de facto behaviour that shouldn't be broken.
732 my $answer = "good";
733 () = sort OtherPack::foo 1,2,3,4;
734
735 {
736     package OtherPack;
737     no warnings 'once';
738     sub foo {
739         $answer = "something was unexpectedly defined or undefined" if
740         defined($a) || defined($b) || !defined($main::a) || !defined($main::b);
741         $main::a <=> $main::b;
742     }
743 }
744
745 cmp_ok($answer,'eq','good','sort subr called from other package');
746
747
748 # Bug 36430 - sort called in package2 while a
749 # sort in package1 is active should set $package2::a/b.
750 {
751     my $answer = "good";
752     my @list = sort { A::min(@$a) <=> A::min(@$b) }
753       [3, 1, 5], [2, 4], [0];
754
755     cmp_ok($answer,'eq','good','bug 36430');
756
757     package A;
758     sub min {
759         my @list = sort {
760             $answer = '$a and/or $b are not defined ' if !defined($a) || !defined($b);
761             $a <=> $b;
762         } @_;
763         $list[0];
764     }
765 }
766
767
768 # Bug 7567 - an array shouldn't be modifiable while it's being
769 # sorted in-place.
770 {
771     eval { @a=(1..8); @a = sort { @a = (0) } @a; };
772
773     $fail_msg = q(Modification of a read-only value attempted);
774     cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'bug 7567');
775     eval { @a=1..3 };
776     is $@, "", 'abrupt scope exit turns off readonliness';
777 }
778
779 {
780     local $TODO = "sort should make sure elements are not freed in the sort block";
781     eval { @nomodify_x=(1..8);
782            our @copy = sort { undef @nomodify_x; 1 } (@nomodify_x, 3); };
783     is($@, "");
784 }
785
786
787 # Sorting shouldn't increase the refcount of a sub
788 {
789     sub sportello {(1+$a) <=> (1+$b)}
790     my $refcnt = &Internals::SvREFCNT(\&sportello);
791     @output = sort sportello 3,7,9;
792
793     {
794         package Doc;
795         ::is($refcnt, &Internals::SvREFCNT(\&::sportello), "sort sub refcnt");
796         $fail_msg = q(Modification of a read-only value attempted);
797         # Sorting a read-only array in-place shouldn't be allowed
798         my @readonly = (1..10);
799         Internals::SvREADONLY(@readonly, 1);
800         eval { @readonly = sort @readonly; };
801         ::cmp_ok(substr($@,0,length($fail_msg)),'eq',$fail_msg,'in-place sort of read-only array');
802     }
803 }
804
805
806 # Using return() should be okay even in a deeper context
807 @b = sort {while (1) {return ($a <=> $b)} } 1..10;
808 is("@b", "1 2 3 4 5 6 7 8 9 10", "return within loop");
809
810 # Using return() should be okay even if there are other items
811 # on the stack at the time.
812 @b = sort {$_ = ($a<=>$b) + do{return $b<=> $a}} 1..10;
813 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
814
815 # As above, but with a sort sub rather than a sort block.
816 sub ret_with_stacked { $_ = ($a<=>$b) + do {return $b <=> $a} }
817 @b = sort ret_with_stacked 1..10;
818 is("@b", "10 9 8 7 6 5 4 3 2 1", "return with SVs on stack");
819
820 # Comparison code should be able to give result in non-integer representation.
821 sub cmp_as_string($$) { $_[0] < $_[1] ? "-1" : $_[0] == $_[1] ? "0" : "+1" }
822 @b = sort { cmp_as_string($a, $b) } (1,5,4,7,3,2,3);
823 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
824 @b = sort cmp_as_string (1,5,4,7,3,2,3);
825 is("@b", "1 2 3 3 4 5 7", "comparison result as string");
826
827 # RT #34604: sort didn't honour overloading if the overloaded elements
828 # were retrieved via tie
829
830 {
831     package RT34604;
832
833     sub TIEHASH { bless {
834                         p => bless({ val => 2 }),
835                         q => bless({ val => 1 }),
836                     }
837                 }
838     sub FETCH { $_[0]{$_[1] } }
839
840     my $cc = 0;
841     sub compare { $cc++; $_[0]{val} cmp $_[1]{val} }
842     my $cs = 0;
843     sub str { $cs++; $_[0]{val} }
844
845     use overload 'cmp' => \&compare, '""' => \&str;
846
847     package main;
848
849     tie my %h, 'RT34604';
850     my @sorted = sort @h{qw(p q)};
851     is($cc, 1, 'overload compare called once');
852     is("@sorted","1 2", 'overload sort result');
853     is($cs, 2, 'overload string called twice');
854 }
855
856 fresh_perl_is('sub w ($$) {my ($l, my $r) = @_; my $v = \@_; undef @_; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
857              '0 1 2 3',
858              {stderr => 1, switches => ['-w']},
859              'RT #72334');
860
861 fresh_perl_is('sub w ($$) {my ($l, my $r) = @_; my $v = \@_; undef @_; @_ = 0..2; $l <=> $r}; print join q{ }, sort w 3, 1, 2, 0',
862              '0 1 2 3',
863              {stderr => 1, switches => ['-w']},
864              'RT #72334');
865
866 {
867     my $count = 0;
868     {
869         package Counter;
870
871         sub new {
872             ++$count;
873             bless [];
874         }
875
876         sub DESTROY {
877             --$count;
878         }
879     }
880
881     sub sorter ($$) {
882         my ($l, $r) = @_;
883         my $q = \@_;
884         $l <=> $r;
885     }
886
887     is($count, 0, 'None before we start');
888     my @a = map { Counter->new() } 0..1;
889     is($count, 2, '2 here');
890
891     my @b = sort sorter @a;
892
893     is(scalar @b, 2);
894     cmp_ok($b[0], '<', $b[1], 'sorted!');
895
896     is($count, 2, 'still the same 2 here');
897
898     @a = (); @b = ();
899
900     is($count, 0, 'all gone');
901 }
902
903 # [perl #77930] The context stack may be reallocated during a sort, as a
904 #               result of deeply-nested (or not-so-deeply-nested) calls
905 #               from a custom sort subroutine.
906 fresh_perl_is
907  '
908    $sub = sub {
909     local $count = $count+1;
910     ()->$sub if $count < 1000;
911     $a cmp $b
912    };
913    () = sort $sub qw<a b c d e f g>;
914    print "ok"
915  ',
916  'ok',
917   {},
918  '[perl #77930] cx_stack reallocation during sort'
919 ;
920
921 # [perl #76026]
922 # Match vars should not leak from one sort sub call to the next
923 {
924   my $output = '';
925   sub soarter {
926     $output .= $1;
927     "Leakage" =~ /(.*)/;
928     1
929   }
930   sub soarterdd($$) {
931     $output .= $1;
932     "Leakage" =~ /(.*)/;
933     1
934   }
935
936   "Win" =~ /(.*)/;
937   my @b = sort soarter 0..2;
938
939   like $output, qr/^(?:Win)+\z/,
940    "Match vars do not leak from one plain sort sub to the next";
941
942   $output = '';
943
944   "Win" =~ /(.*)/;
945   @b = sort soarterdd 0..2;
946
947   like $output, qr/^(?:Win)+\z/,
948    'Match vars do not leak from one $$ sort sub to the next';
949 }
950
951 # [perl #30661] autoloading
952 AUTOLOAD { $b <=> $a }
953 sub stubbedsub;
954 is join("", sort stubbedsub split//, '04381091'), '98431100',
955     'stubborn AUTOLOAD';
956 is join("", sort hopefullynonexistent split//, '04381091'), '98431100',
957     'AUTOLOAD without stub';
958 my $stubref = \&givemeastub;
959 is join("", sort $stubref split//, '04381091'), '98431100',
960     'AUTOLOAD with stubref';
961
962 # [perl #90030] sort without arguments
963 eval '@x = (sort); 1';
964 is $@, '', '(sort) does not die';
965 is @x, 0, '(sort) returns empty list';
966 eval '@x = sort; 1';
967 is $@, '', 'sort; does not die';
968 is @x, 0, 'sort; returns empty list';
969 eval '{@x = sort} 1';
970 is $@, '', '{sort} does not die';
971 is @x, 0, '{sort} returns empty list';
972
973 # this happened while the padrange op was being added. Sort blocks
974 # are executed in void context, and the padrange op was skipping pushing
975 # the item in void cx. The net result was that the return value was
976 # whatever was on the stack last.
977
978 {
979     my @a = sort {
980         my $r = $a <=> $b;
981         if ($r) {
982             undef; # this got returned by mistake
983             return $r
984         }
985         return 0;
986     } 5,1,3,6,0;
987     is "@a", "0 1 3 5 6", "padrange and void context";
988 }
989
990 # Fatal warnings an sort sub returning a non-number
991 # We need two evals, because the panic used to happen on scope exit.
992 eval { eval { use warnings FATAL => 'all'; () = sort { undef } 1,2 } };
993 is $@, "",
994   'no panic/crash with fatal warnings when sort sub returns undef';
995 eval { eval { use warnings FATAL => 'all'; () = sort { "no thin" } 1,2 } };
996 is $@, "",
997   'no panic/crash with fatal warnings when sort sub returns string';
998 sub notdef($$) { undef }
999 eval { eval { use warnings FATAL => 'all'; () = sort notdef 1,2 } };
1000 is $@, "",
1001   'no panic/crash with fatal warnings when sort sub($$) returns undef';
1002 sub yarn($$) { "no thinking aloud" }
1003 eval { eval { use warnings FATAL => 'all'; () = sort yarn 1,2 } };
1004 is $@, "",
1005   'no panic/crash with fatal warnings when sort sub($$) returns string';
1006
1007 $#a = -1;
1008 () = [sort { $a = 10; $b = 10; 0 } $#a, $#a];
1009 is $#a, 10, 'sort block modifying $a and $b';
1010
1011 () = sort {
1012     is \$a, \$a, '[perl #78194] op return values passed to sort'; 0
1013 } "${\''}", "${\''}";
1014
1015 package deletions {
1016     @_=sort { delete $deletions::{a}; delete $deletions::{b}; 3 } 1..3;
1017 }
1018 pass "no crash when sort block deletes *a and *b";