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