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