4 # Original written by Ulrich Pfeifer on 2 Jan 1997.
5 # Greatly extended by Tom Phoenix <rootbeer@teleport.com> on 28 Jan 1997.
7 # Run with -debug for debugging output.
15 require './test.pl'; # for runperl()
22 print $ok ? "ok $test\n" : "not ok $test\n";
23 printf "# Failed at line %d\n", (caller)[2] unless $ok;
28 sub foo { $i = shift if @_; $i }
35 # closure: lexical outside sub
36 my $foo = sub {$i = shift if @_; $i };
37 my $bar = sub {$i = shift if @_; $i };
41 # did the lexical change?
42 test { foo == 3 and $i == 3};
43 # did the second closure notice?
46 # closure: lexical inside sub
49 sub { $i = shift if @_; $i }
64 sub {$i = shift if @_; $i };
67 sub {$i = shift if @_; $i };
79 test {&$foo(11)-1 == &$bar()};
84 $foo[$_] = sub {$i = shift if @_; $i };
100 &{$foo[0]}() == 4 and
101 &{$foo[1]}() == 3 and
102 &{$foo[2]}() == 2 and
103 &{$foo[3]}() == 1 and
109 for (qw(0 1 2 3 4)) {
111 $foo[$_] = sub {$i = shift if @_; $i };
118 &{$foo[0]}() == 0 and
119 &{$foo[1]}() == 1 and
120 &{$foo[2]}() == 2 and
121 &{$foo[3]}() == 3 and
130 &{$foo[0]}() == 4 and
131 &{$foo[1]}() == 3 and
132 &{$foo[2]}() == 2 and
133 &{$foo[3]}() == 1 and
137 # test if closures get created in optimized for loops
140 for my $n ('A'..'E') {
141 $foo{$n} = sub { $n eq $_[0] };
153 $foo[$n] = sub { $n == $_[0] };
166 # no intervening reference to $n here
189 # Additional tests by Tom Phoenix <rootbeer@teleport.com>.
195 my($debugging, %expected, $inner_type, $where_declared, $within);
196 my($nc_attempt, $call_outer, $call_inner, $undef_outer);
197 my($code, $inner_sub_test, $expected, $line, $errors, $output);
198 my(@inners, $sub_test, $pid);
199 $debugging = 1 if defined($ARGV[0]) and $ARGV[0] eq '-debug';
201 # The expected values for these tests
203 'global_scalar' => 1001,
204 'global_array' => 2101,
205 'global_hash' => 3004,
209 'sub_scalar' => 7001,
215 # Our innermost sub is either named or anonymous
216 for $inner_type (qw!named anon!) {
217 # And it may be declared at filescope, within a named
218 # sub, or within an anon sub
219 for $where_declared (qw!filescope in_named in_anon!) {
220 # And that, in turn, may be within a foreach loop,
221 # a naked block, or another named sub
222 for $within (qw!foreach naked other_sub!) {
224 # Here are a number of variables which show what's
225 # going on, in a way.
226 $nc_attempt = 0+ # Named closure attempted
227 ( ($inner_type eq 'named') ||
228 ($within eq 'other_sub') ) ;
229 $call_inner = 0+ # Need to call &inner
230 ( ($inner_type eq 'anon') &&
231 ($within eq 'other_sub') ) ;
232 $call_outer = 0+ # Need to call &outer or &$outer
233 ( ($inner_type eq 'anon') &&
234 ($within ne 'other_sub') ) ;
235 $undef_outer = 0+ # $outer is created but unused
236 ( ($where_declared eq 'in_anon') &&
237 (not $call_outer) ) ;
239 $code = "# This is a test script built by t/op/closure.t\n\n";
241 print <<"DEBUG_INFO" if $debugging;
242 # inner_type: $inner_type
243 # where_declared: $where_declared
245 # nc_attempt: $nc_attempt
246 # call_inner: $call_inner
247 # call_outer: $call_outer
248 # undef_outer: $undef_outer
251 $code .= <<"END_MARK_ONE";
253 BEGIN { \$SIG{__WARN__} = sub {
257 $code .= <<"END_MARK_TWO" if $nc_attempt;
258 return if index(\$msg, 'will not stay shared') != -1;
259 return if index(\$msg, 'is not available') != -1;
262 $code .= <<"END_MARK_THREE"; # Backwhack a lot!
263 print "not ok: got unexpected warning \$msg\\n";
270 print \$ok ? "ok \$test\n" : "not ok \$test\n";
271 printf "# Failed at line %d\n", (caller)[2] unless \$ok;
276 # some of the variables which the closure will access
277 \$global_scalar = 1000;
278 \@global_array = (2000, 2100, 2200, 2300);
279 %global_hash = 3000..3009;
281 my \$fs_scalar = 4000;
282 my \@fs_array = (5000, 5100, 5200, 5300);
283 my %fs_hash = 6000..6009;
287 if ($where_declared eq 'filescope') {
289 } elsif ($where_declared eq 'in_named') {
292 my $sub_scalar = 7000;
293 my @sub_array = (8000, 8100, 8200, 8300);
294 my %sub_hash = 9000..9009;
297 } elsif ($where_declared eq 'in_anon') {
300 my $sub_scalar = 7000;
301 my @sub_array = (8000, 8100, 8200, 8300);
302 my %sub_hash = 9000..9009;
306 die "What was $where_declared?"
309 if ($within eq 'foreach') {
311 my \$foreach = 12000;
312 my \@list = (10000, 10010);
313 foreach \$foreach (\@list) {
315 } elsif ($within eq 'naked') {
316 $code .= " { # naked block\n" # }
317 } elsif ($within eq 'other_sub') {
318 $code .= " sub inner_sub {\n" # }
320 die "What was $within?"
324 @inners = ( qw!global_scalar global_array global_hash! ,
325 qw!fs_scalar fs_array fs_hash! );
326 push @inners, 'foreach' if $within eq 'foreach';
327 if ($where_declared ne 'filescope') {
328 push @inners, qw!sub_scalar sub_array sub_hash!;
330 for $inner_sub_test (@inners) {
332 if ($inner_type eq 'named') {
333 $code .= " sub named_$sub_test "
334 } elsif ($inner_type eq 'anon') {
335 $code .= " \$anon_$sub_test = sub "
337 die "What was $inner_type?"
340 # Now to write the body of the test sub
341 if ($inner_sub_test eq 'global_scalar') {
342 $code .= '{ ++$global_scalar }'
343 } elsif ($inner_sub_test eq 'fs_scalar') {
344 $code .= '{ ++$fs_scalar }'
345 } elsif ($inner_sub_test eq 'sub_scalar') {
346 $code .= '{ ++$sub_scalar }'
347 } elsif ($inner_sub_test eq 'global_array') {
348 $code .= '{ ++$global_array[1] }'
349 } elsif ($inner_sub_test eq 'fs_array') {
350 $code .= '{ ++$fs_array[1] }'
351 } elsif ($inner_sub_test eq 'sub_array') {
352 $code .= '{ ++$sub_array[1] }'
353 } elsif ($inner_sub_test eq 'global_hash') {
354 $code .= '{ ++$global_hash{3002} }'
355 } elsif ($inner_sub_test eq 'fs_hash') {
356 $code .= '{ ++$fs_hash{6002} }'
357 } elsif ($inner_sub_test eq 'sub_hash') {
358 $code .= '{ ++$sub_hash{9002} }'
359 } elsif ($inner_sub_test eq 'foreach') {
360 $code .= '{ ++$foreach }'
362 die "What was $inner_sub_test?"
366 if ($inner_type eq 'anon') {
370 $sub_test++; # sub name sequence number
372 } # End of foreach $inner_sub_test
374 # Close up $within block # {
377 # Close up $where_declared block
378 if ($where_declared eq 'in_named') { # {
380 } elsif ($where_declared eq 'in_anon') { # {
384 # We may need to do something with the sub we just made...
385 $code .= "undef \$outer;\n" if $undef_outer;
386 $code .= "&inner_sub;\n" if $call_inner;
388 if ($where_declared eq 'in_named') {
389 $code .= "&outer;\n\n";
390 } elsif ($where_declared eq 'in_anon') {
391 $code .= "&\$outer;\n\n"
395 # Now, we can actually prep to run the tests.
396 for $inner_sub_test (@inners) {
397 $expected = $expected{$inner_sub_test} or
398 die "expected $inner_sub_test missing";
400 # Named closures won't access the expected vars
402 substr($inner_sub_test, 0, 4) eq "sub_" ) {
406 # If you make a sub within a foreach loop,
407 # what happens if it tries to access the
408 # foreach index variable? If it's a named
409 # sub, it gets the var from "outside" the loop,
410 # but if it's anon, it gets the value to which
411 # the index variable is aliased.
413 # Of course, if the value was set only
414 # within another sub which was never called,
415 # the value has not been set yet.
417 if ($inner_sub_test eq 'foreach') {
418 if ($inner_type eq 'named') {
419 if ($call_outer || ($where_declared eq 'filescope')) {
428 if ($inner_type eq 'anon') {
429 $code .= "test { &\$anon_$test == $expected };\n"
431 $code .= "test { &named_$test == $expected };\n"
436 if ($Config{d_fork} and $^O ne 'VMS' and $^O ne 'MSWin32' and $^O ne 'NetWare') {
437 # Fork off a new perl to run the tests.
438 # (This is so we can catch spurious warnings.)
439 $| = 1; print ""; $| = 0; # flush output before forking
440 pipe READ, WRITE or die "Can't make pipe: $!";
441 pipe READ2, WRITE2 or die "Can't make second pipe: $!";
442 die "Can't fork: $!" unless defined($pid = open PERL, "|-");
444 # Child process here. We're going to send errors back
445 # through the extra pipe.
448 open STDOUT, ">&WRITE" or die "Can't redirect STDOUT: $!";
449 open STDERR, ">&WRITE2" or die "Can't redirect STDERR: $!";
450 exec which_perl(), '-w', '-'
451 or die "Can't exec perl: $!";
453 # Parent process here.
459 $output = join '', <READ>;
460 $errors = join '', <READ2>; }
465 # No fork(). Do it the hard way.
466 my $cmdfile = tempfile();
467 my $errfile = tempfile();
468 open CMD, ">$cmdfile"; print CMD $code; close CMD;
469 my $cmd = which_perl();
470 $cmd .= " -w $cmdfile 2>$errfile";
471 if ($^O eq 'VMS' or $^O eq 'MSWin32' or $^O eq 'NetWare') {
472 # Use pipe instead of system so we don't inherit STD* from
473 # this process, and then foul our pipe back to parent by
474 # redirecting output in the child.
475 open PERL,"$cmd |" or die "Can't open pipe: $!\n";
476 { local $/; $output = join '', <PERL> }
479 my $outfile = tempfile();
480 system "$cmd >$outfile";
481 { local $/; open IN, $outfile; $output = <IN>; close IN }
484 printf "not ok: exited with error code %04X\n", $?;
487 { local $/; open IN, $errfile; $errors = <IN>; close IN }
490 print STDERR $errors;
491 if ($debugging && ($errors || $? || ($output =~ /not ok/))) {
493 for $line (split '\n', $code) {
494 printf "%3d: %s\n", ++$lnum, $line;
497 printf "not ok: exited with error code %04X\n", $? if $?;
498 print '#', "-" x 30, "\n" if $debugging;
500 } # End of foreach $within
501 } # End of foreach $where_declared
502 } # End of foreach $inner_type
506 # The following dumps core with perl <= 5.8.0 (bugid 9535) ...
507 BEGIN { $vanishing_pad = sub { eval $_[0] } }
509 test { $vanishing_pad->( '$some_var' ) == 123 };
511 # ... and here's another coredump variant - this time we explicitly
512 # delete the sub rather than using a BEGIN ...
514 sub deleteme { $a = sub { eval '$newvar' } }
516 *deleteme = sub {}; # delete the sub
517 $newvar = 123; # realloc the SV of the freed CV
518 test { $a->() == 123 };
520 # ... and a further coredump variant - the fixup of the anon sub's
521 # CvOUTSIDE pointer when the middle eval is freed, wasn't good enough to
522 # survive the outer eval also being freed.
530 @a = ('\1\1\1\1\1\1\1') x 100; # realloc recently-freed CVs
531 test { $a->() == 123 };
533 # this coredumped on <= 5.8.0 because evaling the closure caused
534 # an SvFAKE to be added to the outer anon's pad, which was then grown.
538 $x = eval 'sub { $outer }';
545 # [perl #17605] found that an empty block called in scalar context
546 # can lead to stack corruption
550 test { $x eq 'fbar' }
554 # SvFAKE lexicals should be visible thoughout a function.
555 # On <= 5.8.0, the third test failed, eg bugid #18286
560 test { sub {eval'$x'}->() == 1 };
561 { $x; test { sub {eval'$x'}->() == 1 } }
562 test { sub {eval'$x'}->() == 1 };
567 # undefining a sub shouldn't alter visibility of outer lexicals
572 sub tmp { sub { eval '$x' } }
575 test { $a->() == 2 };
578 # handy class: $x = Watch->new(\$foo,'bar')
579 # causes 'bar' to be appended to $foo when $x is destroyed
580 sub Watch::new { bless [ $_[1], $_[2] ], $_[0] }
581 sub Watch::DESTROY { ${$_[0][0]} .= $_[0][1] }
585 # nested anon subs (and associated lexicals) not freed early enough
588 my $x = Watch->new($_[0], '2');
598 test { $watch eq '12' }
602 # obj not freed early enough
605 my $obj = Watch->new($_[0], '2');
606 sub { sub { $obj } };
611 test { $watch eq '12' }
614 # bugid 16302 - named subs didn't capture lexicals on behalf of inner subs
620 test { defined $x and $x == 1 }
626 # The presence of an eval should turn cloneless anon subs into clonable
627 # subs - otherwise the CvOUTSIDE of that sub may be wrong
632 $a{$x} = sub { $x=$x; sub { eval '$x' } };
634 test { $a{7}->()->() + $a{11}->()->() == 18 };
638 # bugid #23265 - this used to coredump during destruction of PL_maincv
641 my $progfile = "b23265.pl";
642 open(T, ">$progfile") or die "$0: $!\n";
643 print T << '__EOF__';
645 sub {$_[0]->(@_)} -> (
648 ? $_[0]->($_[0], $_[1] - 1) . sub {"x"}->()
657 my $got = runperl(progfile => $progfile);
658 test { chomp $got; $got eq "yxx" };
659 END { 1 while unlink $progfile }
663 # bugid #24914 = used to coredump restoring PL_comppad in the
664 # savestack, due to the early freeing of the anon closure
666 my $got = runperl(stderr => 1, prog =>
667 'sub d {die} my $f; $f = sub {my $x=1; $f = 0; d}; eval{$f->()}; print qq(ok\n)'
669 test { $got eq "ok\n" };
672 # After newsub is redefined outside the BEGIN, it's CvOUTSIDE should point
673 # to main rather than BEGIN, and BEGIN should be freed.
677 sub X::DESTROY { $flag = 1 }
680 BEGIN {$x = \&newsub }
687 # don't copy a stale lexical; crate a fresh undef one instead