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.
18 sub foo { $i = shift if @_; $i }
25 # closure: lexical outside sub
26 my $foo = sub {$i = shift if @_; $i };
27 my $bar = sub {$i = shift if @_; $i };
31 # did the lexical change?
32 is(foo, 3, 'lexical changed');
33 is($i, 3, 'lexical changed');
34 # did the second closure notice?
35 is(&$bar(), 3, 'second closure noticed');
37 # closure: lexical inside sub
40 sub { $i = shift if @_; $i }
55 sub {$i = shift if @_; $i };
58 sub {$i = shift if @_; $i };
70 is(&$foo(11)-1, &$bar());
75 $foo[$_] = sub {$i = shift if @_; $i };
98 $foo[$_] = sub {$i = shift if @_; $i };
120 # test if closures get created in optimized for loops
123 for my $n ('A'..'E') {
124 $foo{$n} = sub { $n eq $_[0] };
134 $foo[$n] = sub { $n == $_[0] };
145 # no intervening reference to $n here
150 ok($foo[0]->()->(0));
151 ok($foo[1]->()->(1));
152 ok($foo[2]->()->(2));
153 ok($foo[3]->()->(3));
154 ok($foo[4]->()->(4));
166 # Additional tests by Tom Phoenix <rootbeer@teleport.com>.
172 my($debugging, %expected, $inner_type, $where_declared, $within);
173 my($nc_attempt, $call_outer, $call_inner, $undef_outer);
174 my($code, $inner_sub_test, $expected, $line, $errors, $output);
175 my(@inners, $sub_test, $pid);
176 $debugging = 1 if defined($ARGV[0]) and $ARGV[0] eq '-debug';
178 # The expected values for these tests
180 'global_scalar' => 1001,
181 'global_array' => 2101,
182 'global_hash' => 3004,
186 'sub_scalar' => 7001,
192 # Our innermost sub is either named or anonymous
193 for $inner_type (qw!named anon!) {
194 # And it may be declared at filescope, within a named
195 # sub, or within an anon sub
196 for $where_declared (qw!filescope in_named in_anon!) {
197 # And that, in turn, may be within a foreach loop,
198 # a naked block, or another named sub
199 for $within (qw!foreach naked other_sub!) {
201 my $test = curr_test();
202 # Here are a number of variables which show what's
203 # going on, in a way.
204 $nc_attempt = 0+ # Named closure attempted
205 ( ($inner_type eq 'named') ||
206 ($within eq 'other_sub') ) ;
207 $call_inner = 0+ # Need to call &inner
208 ( ($inner_type eq 'anon') &&
209 ($within eq 'other_sub') ) ;
210 $call_outer = 0+ # Need to call &outer or &$outer
211 ( ($inner_type eq 'anon') &&
212 ($within ne 'other_sub') ) ;
213 $undef_outer = 0+ # $outer is created but unused
214 ( ($where_declared eq 'in_anon') &&
215 (not $call_outer) ) ;
217 $code = "# This is a test script built by t/op/closure.t\n\n";
219 print <<"DEBUG_INFO" if $debugging;
220 # inner_type: $inner_type
221 # where_declared: $where_declared
223 # nc_attempt: $nc_attempt
224 # call_inner: $call_inner
225 # call_outer: $call_outer
226 # undef_outer: $undef_outer
229 $code .= <<"END_MARK_ONE";
231 BEGIN { \$SIG{__WARN__} = sub {
235 $code .= <<"END_MARK_TWO" if $nc_attempt;
236 return if index(\$msg, 'will not stay shared') != -1;
237 return if index(\$msg, 'is not available') != -1;
240 $code .= <<"END_MARK_THREE"; # Backwhack a lot!
241 print "not ok: got unexpected warning \$msg\\n";
247 # some of the variables which the closure will access
248 \$global_scalar = 1000;
249 \@global_array = (2000, 2100, 2200, 2300);
250 %global_hash = 3000..3009;
252 my \$fs_scalar = 4000;
253 my \@fs_array = (5000, 5100, 5200, 5300);
254 my %fs_hash = 6000..6009;
258 if ($where_declared eq 'filescope') {
260 } elsif ($where_declared eq 'in_named') {
263 my $sub_scalar = 7000;
264 my @sub_array = (8000, 8100, 8200, 8300);
265 my %sub_hash = 9000..9009;
268 } elsif ($where_declared eq 'in_anon') {
271 my $sub_scalar = 7000;
272 my @sub_array = (8000, 8100, 8200, 8300);
273 my %sub_hash = 9000..9009;
277 die "What was $where_declared?"
280 if ($within eq 'foreach') {
282 my \$foreach = 12000;
283 my \@list = (10000, 10010);
284 foreach \$foreach (\@list) {
286 } elsif ($within eq 'naked') {
287 $code .= " { # naked block\n" # }
288 } elsif ($within eq 'other_sub') {
289 $code .= " sub inner_sub {\n" # }
291 die "What was $within?"
295 @inners = ( qw!global_scalar global_array global_hash! ,
296 qw!fs_scalar fs_array fs_hash! );
297 push @inners, 'foreach' if $within eq 'foreach';
298 if ($where_declared ne 'filescope') {
299 push @inners, qw!sub_scalar sub_array sub_hash!;
301 for $inner_sub_test (@inners) {
303 if ($inner_type eq 'named') {
304 $code .= " sub named_$sub_test "
305 } elsif ($inner_type eq 'anon') {
306 $code .= " \$anon_$sub_test = sub "
308 die "What was $inner_type?"
311 # Now to write the body of the test sub
312 if ($inner_sub_test eq 'global_scalar') {
313 $code .= '{ ++$global_scalar }'
314 } elsif ($inner_sub_test eq 'fs_scalar') {
315 $code .= '{ ++$fs_scalar }'
316 } elsif ($inner_sub_test eq 'sub_scalar') {
317 $code .= '{ ++$sub_scalar }'
318 } elsif ($inner_sub_test eq 'global_array') {
319 $code .= '{ ++$global_array[1] }'
320 } elsif ($inner_sub_test eq 'fs_array') {
321 $code .= '{ ++$fs_array[1] }'
322 } elsif ($inner_sub_test eq 'sub_array') {
323 $code .= '{ ++$sub_array[1] }'
324 } elsif ($inner_sub_test eq 'global_hash') {
325 $code .= '{ ++$global_hash{3002} }'
326 } elsif ($inner_sub_test eq 'fs_hash') {
327 $code .= '{ ++$fs_hash{6002} }'
328 } elsif ($inner_sub_test eq 'sub_hash') {
329 $code .= '{ ++$sub_hash{9002} }'
330 } elsif ($inner_sub_test eq 'foreach') {
331 $code .= '{ ++$foreach }'
333 die "What was $inner_sub_test?"
337 if ($inner_type eq 'anon') {
341 $sub_test++; # sub name sequence number
343 } # End of foreach $inner_sub_test
345 # Close up $within block # {
348 # Close up $where_declared block
349 if ($where_declared eq 'in_named') { # {
351 } elsif ($where_declared eq 'in_anon') { # {
355 # We may need to do something with the sub we just made...
356 $code .= "undef \$outer;\n" if $undef_outer;
357 $code .= "&inner_sub;\n" if $call_inner;
359 if ($where_declared eq 'in_named') {
360 $code .= "&outer;\n\n";
361 } elsif ($where_declared eq 'in_anon') {
362 $code .= "&\$outer;\n\n"
366 # Now, we can actually prep to run the tests.
367 for $inner_sub_test (@inners) {
368 $expected = $expected{$inner_sub_test} or
369 die "expected $inner_sub_test missing";
371 # Named closures won't access the expected vars
373 substr($inner_sub_test, 0, 4) eq "sub_" ) {
377 # If you make a sub within a foreach loop,
378 # what happens if it tries to access the
379 # foreach index variable? If it's a named
380 # sub, it gets the var from "outside" the loop,
381 # but if it's anon, it gets the value to which
382 # the index variable is aliased.
384 # Of course, if the value was set only
385 # within another sub which was never called,
386 # the value has not been set yet.
388 if ($inner_sub_test eq 'foreach') {
389 if ($inner_type eq 'named') {
390 if ($call_outer || ($where_declared eq 'filescope')) {
399 my $desc = "$inner_type $where_declared $within $inner_sub_test";
400 if ($inner_type eq 'anon') {
401 $code .= "is(&\$anon_$test, $expected, '$desc');\n"
403 $code .= "is(&named_$test, $expected, '$desc');\n"
408 if ($Config{d_fork} and $^O ne 'VMS' and $^O ne 'MSWin32' and $^O ne 'NetWare') {
409 # Fork off a new perl to run the tests.
410 # (This is so we can catch spurious warnings.)
411 $| = 1; print ""; $| = 0; # flush output before forking
412 pipe READ, WRITE or die "Can't make pipe: $!";
413 pipe READ2, WRITE2 or die "Can't make second pipe: $!";
414 die "Can't fork: $!" unless defined($pid = open PERL, "|-");
416 # Child process here. We're going to send errors back
417 # through the extra pipe.
420 open STDOUT, ">&WRITE" or die "Can't redirect STDOUT: $!";
421 open STDERR, ">&WRITE2" or die "Can't redirect STDERR: $!";
422 exec which_perl(), '-w', '-'
423 or die "Can't exec perl: $!";
425 # Parent process here.
431 $output = join '', <READ>;
432 $errors = join '', <READ2>; }
437 # No fork(). Do it the hard way.
438 my $cmdfile = tempfile();
439 my $errfile = tempfile();
440 open CMD, ">$cmdfile"; print CMD $code; close CMD;
441 my $cmd = which_perl();
442 $cmd .= " -w $cmdfile 2>$errfile";
443 if ($^O eq 'VMS' or $^O eq 'MSWin32' or $^O eq 'NetWare') {
444 # Use pipe instead of system so we don't inherit STD* from
445 # this process, and then foul our pipe back to parent by
446 # redirecting output in the child.
447 open PERL,"$cmd |" or die "Can't open pipe: $!\n";
448 { local $/; $output = join '', <PERL> }
451 my $outfile = tempfile();
452 system "$cmd >$outfile";
453 { local $/; open IN, $outfile; $output = <IN>; close IN }
456 printf "not ok: exited with error code %04X\n", $?;
459 { local $/; open IN, $errfile; $errors = <IN>; close IN }
463 print STDERR $errors;
464 # This has the side effect of alerting *our* test.pl to the state of
465 # what has just been passed to STDOUT, so that if anything there has
466 # failed, our test.pl will print a diagnostic and exit uncleanly.
467 unlike($output, qr/not ok/, 'All good');
468 is($errors, '', 'STDERR is silent');
469 if ($debugging && ($errors || $? || ($output =~ /not ok/))) {
471 for $line (split '\n', $code) {
472 printf "%3d: %s\n", ++$lnum, $line;
475 is($?, 0, 'exited cleanly') or diag(sprintf "Error code $? = 0x%X", $?);
476 print '#', "-" x 30, "\n" if $debugging;
478 } # End of foreach $within
479 } # End of foreach $where_declared
480 } # End of foreach $inner_type
484 # The following dumps core with perl <= 5.8.0 (bugid 9535) ...
485 BEGIN { $vanishing_pad = sub { eval $_[0] } }
487 is($vanishing_pad->('$some_var'), 123, 'RT #9535');
489 # ... and here's another coredump variant - this time we explicitly
490 # delete the sub rather than using a BEGIN ...
492 sub deleteme { $a = sub { eval '$newvar' } }
494 *deleteme = sub {}; # delete the sub
495 $newvar = 123; # realloc the SV of the freed CV
496 is($a->(), 123, 'RT #9535');
498 # ... and a further coredump variant - the fixup of the anon sub's
499 # CvOUTSIDE pointer when the middle eval is freed, wasn't good enough to
500 # survive the outer eval also being freed.
508 @a = ('\1\1\1\1\1\1\1') x 100; # realloc recently-freed CVs
509 is($a->(), 123, 'RT #9535');
511 # this coredumped on <= 5.8.0 because evaling the closure caused
512 # an SvFAKE to be added to the outer anon's pad, which was then grown.
516 $x = eval 'sub { $outer }';
523 # [perl #17605] found that an empty block called in scalar context
524 # can lead to stack corruption
528 is($x, 'fbar', 'RT #17605');
532 # SvFAKE lexicals should be visible thoughout a function.
533 # On <= 5.8.0, the third test failed, eg bugid #18286
538 is(sub {eval'$x'}->(), 1, 'RT #18286');
539 { $x; is(sub {eval'$x'}->(), 1, 'RT #18286'); }
540 is(sub {eval'$x'}->(), 1, 'RT #18286');
548 sub tmp { sub { eval '$x' } }
552 "undefining a sub shouldn't alter visibility of outer lexicals");
555 # handy class: $x = Watch->new(\$foo,'bar')
556 # causes 'bar' to be appended to $foo when $x is destroyed
557 sub Watch::new { bless [ $_[1], $_[2] ], $_[0] }
558 sub Watch::DESTROY { ${$_[0][0]} .= $_[0][1] }
561 # nested anon subs (and associated lexicals) not freed early enough
564 my $x = Watch->new($_[0], '2');
574 is($watch, '12', 'RT #1028');
578 # obj not freed early enough
581 my $obj = Watch->new($_[0], '2');
582 sub { sub { $obj } };
587 is($watch, 12, 'RT #10085');
590 # bugid 16302 - named subs didn't capture lexicals on behalf of inner subs
596 is($x, 1, 'RT #16302');
602 # The presence of an eval should turn cloneless anon subs into clonable
603 # subs - otherwise the CvOUTSIDE of that sub may be wrong
608 $a{$x} = sub { $x=$x; sub { eval '$x' } };
610 is($a{7}->()->() + $a{11}->()->(), 18);
614 # bugid #23265 - this used to coredump during destruction of PL_maincv
617 fresh_perl_is(<< '__EOF__', "yxx\n", {stderr => 1}, 'RT #23265');
619 sub {$_[0]->(@_)} -> (
622 ? $_[0]->($_[0], $_[1] - 1) . sub {"x"}->()
633 # bugid #24914 = used to coredump restoring PL_comppad in the
634 # savestack, due to the early freeing of the anon closure
636 fresh_perl_is('sub d {die} my $f; $f = sub {my $x=1; $f = 0; d}; eval{$f->()}; print qq(ok\n)',
637 "ok\n", {stderr => 1}, 'RT #24914');
641 # After newsub is redefined outside the BEGIN, its CvOUTSIDE should point
642 # to main rather than BEGIN, and BEGIN should be freed.
646 sub X::DESTROY { $flag = 1 }
649 BEGIN {$x = \&newsub }
671 "don't copy a stale lexical; create a fresh undef one instead");
674 # test PL_cv_has_eval. Any anon sub that could conceivably contain an
675 # eval, should be marked as cloneable
680 push @s, sub { eval '1' } for 1,2;
681 isnt($s[0], $s[1], "cloneable with eval");
683 push @s, sub { use re 'eval'; my $x; s/$x/1/; } for 1,2;
684 isnt($s[0], $s[1], "cloneable with use re eval");
686 push @s, sub { s/1/1/ee; } for 1,2;
687 isnt($s[0], $s[1], "cloneable with //ee");
693 push @trace::trace, "destroyed";
697 my $a = bless \my $dummy, trace::;
713 my $inner = $outer2->();
714 is "@trace::trace", "destroyed",
715 'closures only close over named variables, not entire subs';
718 # [perl #113812] Closure prototypes with no CvOUTSIDE (crash caused by the
720 do "./op/closure_test.pl" or die $@||$!;
721 is $closure_test::s2->()(), '10 cubes',
722 'cloning closure proto with no CvOUTSIDE';
724 # Also brought up in #113812: Even when being cloned, a closure prototype
725 # might have its CvOUTSIDE pointing to the wrong thing.
727 package main::113812;
736 undef &$s1; # frees $s2's prototype, causing the $s3 proto to have its
737 # CvOUTSIDE point to $s1
738 ::is $s2->()(), 3, 'cloning closure proto whose CvOUTSIDE has changed';
741 # This should never emit two different values:
743 # print sub { $x }->(), "\n";
744 # This test case started to do just that in commit 33894c1aa3e
751 is sub { $x }->(), $x, 'closing over stale var in 2nd sub call';
755 # And this case in commit adf8f095c588 (5.14):
760 is sub { $x }->(), $x,
761 'closing over stale var before 1st sub call';
766 # [perl #114018] Similar to the above, but with string eval
772 is eval '$x', $x, 'eval closing over stale var in active sub';
779 # Test that closure creation localises PL_comppad_name properly. Usually
780 # at compile time a BEGIN block will localise PL_comppad_name for use, so
781 # pp_anoncode can mess with it without any visible effects.
782 # But inside a source filter, it affects the directly enclosing compila-
785 skip_if_miniperl("no XS on miniperl (for source filters)");
786 fresh_perl_is <<' [perl #114888]', "ok\n", {stderr=>1},
790 use Filter::Util::Call;
791 sub import { filter_add( sub {
792 my $status = filter_read();
798 my $x = "ok\n"; # stores $x in the wrong padnamelist
799 print $x; # cannot find it - strict violation
801 'closures in source filters do not interfere with pad names';
806 sub test_ref_to_unavailable {
809 is $f, 7, 'taking a ref to unavailable var should not copy it';
812 test_ref_to_unavailable();