9 use List::Util qw/reduce/;
11 use B qw/class ppname svref_2object OPf_KIDS/;
13 use Test::More; use Data::Dumper;
17 Sub::Nary - Try to count how many elements a subroutine can return in list context.
36 my $sn = Sub::Nary->new();
37 my $r = $sn->nary(\&hlagh);
41 This module uses the L<B> framework to walk into subroutines and try to guess how many scalars are likely to be returned in list context. It's not always possible to give a definitive answer to this question at compile time, so the results are given in terms of "probability of return" (to be understood in a sense described below).
47 The usual constructor. Currently takes no argument.
49 =head2 C<nary $coderef>
51 Takes a code reference to a named or anonymous subroutine, and returns a hash reference whose keys are the possible numbers of returning scalars, and the corresponding values the "probability" to get them. The special key C<'list'> is used to denote a possibly infinite number of returned arguments. The return value hence would look at
53 { 1 => 0.2, 2 => 0.4, 4 => 0.3, list => 0.1 }
55 that is, we should get C<1> scalar C<1> time over C<5> and so on. The sum of all values is C<1>. The returned result, and all the results obtained from intermediate subs, are cached into the object.
59 Flushes the L<Sub::Nary> object cache. Returns the object itself.
61 =head1 PROBABILITY OF RETURN
63 The probability is computed as such :
67 =item * When branching, each branch is considered equally possible.
69 For example, the subroutine
79 is seen returning one or two arguments each with probability C<1/2>.
91 it is considered to return C<3> scalars with probability C<1/2>, C<2> with probability C<1/2 * 1/2 = 1/4> and C<1> (when the two tests fail, the last computed value is returned, which here is C<< $x > 0.9 >> evaluated in the scalar context of the test) with remaining probability C<1/4>.
93 =item * The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
101 returns C<3> or C<4> arguments with probability C<1/2> ; and
104 return simple(), simple()
107 never returns C<1> argument but returns C<2> with probability C<1/2 * 1/2 = 1/4>, C<3> with probability C<1/2 * 1/2 + 1/2 * 1/2 = 1/2> and C<4> with probability C<1/4> too.
109 =item * If a core function may return different numbers of scalars, each kind is considered equally possible.
111 For example, C<stat> returns C<13> elements on success and C<0> on error. The according probability will then be C<< { 0 => 0.5, 13 => 0.5 } >>.
113 =item * The C<list> state is absorbing in regard of all the other ones.
115 This is just a pedantic way to say that "list + fixed length = list".
119 return 1, simple(), @_
122 is considered as always returning an unbounded list.
124 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
135 return oneorlist(), oneorlist()
138 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
146 XSLoader::load(__PACKAGE__, $VERSION);
150 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
151 unless ref $_[0] and $_[0]->isa(__PACKAGE__);
156 $class = ref($class) || $class || __PACKAGE__;
157 bless { cache => { } }, $class;
163 $self->{cache} = { };
172 return ($self->enter(svref_2object($sub)))[1];
176 local $SIG{__DIE__} = \&Carp::confess;
178 $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
183 return 1 unless defined $r;
184 return $r eq '0' unless ref $r;
185 return $r->{0} and 1 == scalar keys %$r;
190 return 0 unless defined $r;
191 return $r eq 'list' unless ref $r;
192 return $r->{list} and 1 == scalar keys %$r;
197 return unless defined $r;
198 return { 0 => 1 } unless keys %$r;
199 my $total = count $r;
200 return { map { $_ => $r->{$_} / $total } keys %$r };
205 return unless defined $r;
206 return (ref $r) ? { map { $_ => $r->{$_} * $c } keys %$r } : { $r => $c };
212 my $la = delete $a->{list};
213 my $lb = delete $b->{list};
214 if (defined $la || defined $lb) {
217 $res{list} = $la + $lb - $la * $lb;
219 while (my ($ka, $va) = each %$a) {
221 while (my ($kb, $vb) = each %$b) {
222 my $key = $ka + int $kb;
223 $res{$key} += $va * $vb;
227 }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
231 my ($p, $n, $c) = @_;
232 return unless defined $p;
233 return { 0 => $c } unless $n;
235 my $z = delete $p->{0};
236 return { 'list' => $c } unless $z;
237 return { 0 => $c } if $z == 1;
238 return { 0 => $c * $z, list => $c * (1 - $z) };
240 my $r = combine map { { %$p } } 1 .. $n;
241 $r->{$_} *= $c for keys %$r;
247 $a->{$_} += $b->{$_} for keys %$b;
249 } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
254 $ops{$_} = 1 for scalops;
255 $ops{$_} = 0 for qw/stub nextstate pushmark iter unstack/;
256 $ops{$_} = 1 for qw/padsv/;
257 $ops{$_} = 'list' for qw/padav/;
258 $ops{$_} = 'list' for qw/padhv rv2hv/;
259 $ops{$_} = 'list' for qw/padany/;
260 $ops{$_} = 'list' for qw/match entereval readline/;
262 $ops{each} = { 0 => 0.5, 2 => 0.5 };
263 $ops{stat} = { 0 => 0.5, 13 => 0.5 };
265 $ops{caller} = sub { my @a = caller 0; scalar @a }->();
266 $ops{localtime} = do { my @a = localtime; scalar @a };
267 $ops{gmtime} = do { my @a = gmtime; scalar @a };
269 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
270 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for map "ggr$_", qw/nam gid ent/;
271 $ops{$_} = 'list' for qw/ghbyname ghbyaddr ghostent/;
272 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gnbyname gnbyaddr gnetent/;
273 $ops{$_} = { 0 => 0.5, 3 => 0.5 } for qw/gpbyname gpbynumber gprotoent/;
274 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gsbyname gsbyport gservent/;
277 my ($self, $cv) = @_;
279 return undef, 'list' if class($cv) ne 'CV';
283 return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
285 # Anything can happen with recursion
286 for (@{$self->{cv}}) {
287 return undef, 'list' if $tag == tag($_->ROOT);
290 unshift @{$self->{cv}}, $cv;
291 my $r = add $self->inspect($op->first);
292 shift @{$self->{cv}};
294 $r = { $r => 1 } unless ref $r;
295 $self->{cache}->{$tag} = { %$r };
300 my ($self, $op) = @_;
303 diag "@ $n" if $DEBUG;
304 return add($self->inspect_kids($op)), undef if $n eq 'return';
306 my $meth = $self->can('pp_' . $n);
307 return $self->$meth($op) if $meth;
309 if (exists $ops{$n}) {
311 $l = { %$l } if ref $l;
315 if (class($op) eq 'LOGOP' and not null $op->first) {
318 diag "? logop\n" if $DEBUG;
321 my ($r1, $l1) = $self->inspect($op);
322 return $r1, $l1 if $r1 and zero $l1;
326 my ($r2, $l2) = $self->inspect($op);
331 # If the logop has no else branch, it can also return the *scalar* result of
335 ($r3, $l3) = $self->inspect($op);
338 my $r = add $r1, scale $c / 2, add $r2, $r3;
339 my $l = scale $c / 2, add $l2, $l3;
343 return $self->inspect_kids($op);
347 my ($self, $op) = @_;
349 return undef, 0 unless $op->flags & OPf_KIDS;
352 return undef, 0 if null $op;
353 if (name($op) eq 'pushmark') {
355 return undef, 0 if null $op;
360 for (; not null $op; $op = $op->sibling) {
362 if ($n eq 'nextstate') {
366 if ($n eq 'lineseq') {
371 diag "> $n ($c)" if $DEBUG;
372 my ($rc, $lc) = $self->inspect($op);
373 $r = add $r, scale $c, $rc if defined $rc;
374 if ($rc and not defined $lc) {
378 push @l, scale $c, $lc;
379 $c *= count $lc if defined $lc;
387 # Stolen from B::Deparse
389 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
392 my ($self, $op) = @_;
393 if (class($op) eq 'PADOP') {
394 return $self->padval($op->padix)
395 } else { # class($op) eq "SVOP"
401 my ($self, $op) = @_;
403 # the constant could be in the pad (under useithreads)
404 $sv = $self->padval($op->targ) unless $$sv;
409 my ($self, $op) = @_;
411 $op = $op->first while $op->flags & OPf_KIDS;
412 return undef, 0 if null $op;
413 if (name($op) eq 'pushmark') {
415 return undef, 0 if null $op;
420 for (; not null $op->sibling; $op = $op->sibling) {
422 next if $n eq 'nextstate';
423 diag "* $n" if $DEBUG;
424 my ($rc, $lc) = $self->inspect($op);
425 $r = add $r, scale $c, $rc if defined $rc;
428 return $r, $c ? { 0 => $c } : undef
433 if (name($op) eq 'rv2cv') {
437 my $next = $op->sibling;
438 while (not null $next) {
440 $next = $next->sibling;
443 } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
444 return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
445 local $self->{sub} = 1;
446 my ($rc, $lc) = $self->inspect($op);
447 return $r, scale $c, $lc;
450 return $r, { 'list' => $c };
455 my ($self, $op) = @_;
457 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
461 my ($self, $op) = @_;
463 return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
467 my ($self, $op) = @_;
470 while ($op->flags & OPf_KIDS) {
471 my $nop = $op->first;
473 if ($nn eq 'pushmark') {
474 $nop = $nop->sibling;
477 if ($n eq 'rv2cv' and $nn eq 'gv') {
478 return $self->enter($self->gv_or_padgv($nop)->CV);
484 return undef, 'list';
488 my ($self, $op) = @_;
490 return undef, 0 unless $op->isa('B::SVOP');
492 my $sv = $self->const_sv($op);
497 } elsif ($c eq 'HV') {
504 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
507 *pp_hslice = *pp_aslice{CODE};
509 sub pp_lslice { $_[0]->inspect($_[1]->first) }
512 my ($self, $op) = @_;
515 my ($r, $l) = $self->inspect($op);
516 if (name($op) ne 'const') {
517 my $c = 1 - count $r;
518 $l = $c ? { list => $c } : 0;
524 my ($self, $op) = @_;
528 # Can't assign to return
529 my $l = ($self->inspect($op->sibling))[1];
530 return undef, $l if not exists $l->{list};
536 my ($self, $op) = @_;
538 diag "* leaveloop" if $DEBUG;
542 if (name($op) eq 'enteriter') {
543 ($r1, $l1) = $self->inspect($op);
544 return $r1, $l1 if $r1 and zero $l1;
548 my $r = (name($op->first) eq 'and') ? ($self->inspect($op->first->first->sibling))[0]
549 : ($self->inspect($op))[0];
550 my $c = 1 - count $r;
551 diag "& leaveloop" if $DEBUG;
552 return $r, $c ? { 0 => $c } : undef;
556 my ($self, $op) = @_;
559 return $self->inspect($op) if name($op) ne 'range';
562 my $begin = $op->first;
563 if (name($begin) eq 'const') {
564 my $end = $begin->sibling;
565 if (name($end) eq 'const') {
566 $begin = $self->const_sv($begin);
567 $end = $self->const_sv($end);
569 no warnings 'numeric';
570 $begin = int ${$begin->object_2svref};
571 $end = int ${$end->object_2svref};
573 return undef, $end - $begin + 1;
575 ($r, $l) = $self->inspect($end);
578 ($r, $l) = $self->inspect($begin);
581 my $c = 1 - count $r;
582 return $r, ($l && $c) ? { 'list' => $c } : undef
586 my ($self, $op) = @_;
589 return $self->inspect($op) if name($op) ne 'grepstart';
590 $op = $op->first->sibling;
592 my ($r2, $l2) = $self->inspect($op->sibling);
593 return $r2, $l2 if $r2 and zero $l2;
594 diag Dumper [ $r2, $l2 ] if $DEBUG;
595 my $c = count $l2; # First one to happen
597 my ($r1, $l1) = $self->inspect($op);
598 diag Dumper [ $r1, $l1 ] if $DEBUG;
599 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
600 return { 'list' => 1 }, undef if list $l2;
602 $l2 = { $l2 => 1 } unless ref $l2;
603 my $r = add $r2, scale $c,
605 add map { power $r1, $_, $l2->{$_} } keys %$l2;
607 return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
611 my ($self, $op) = @_;
614 return $self->inspect($op) if name($op) ne 'mapstart';
615 $op = $op->first->sibling;
617 my ($r2, $l2) = $self->inspect($op->sibling);
618 return $r2, $l2 if $r2 and zero $l2;
619 my $c = count $l2; # First one to happen
621 my ($r1, $l1) = $self->inspect($op);
622 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
623 diag Dumper [ [ $r1, $l1 ], [ $r2, $l2 ] ] if $DEBUG;
625 $l2 = { $l2 => 1 } unless ref $l2;
626 my $r = add $r2, scale $c,
628 add map { power $r1, $_, $l2->{$_} } keys %$l2;
630 my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
636 An object-oriented module shouldn't export any function, and so does this one.
640 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
642 C<wantarray> isn't specialized when encountered in the optree.
648 L<Carp> (standard since perl 5), L<B> (since perl 5.005), L<XSLoader> (since perl 5.006) and L<List::Util> (since perl 5.007003).
652 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
654 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
658 Please report any bugs or feature requests to C<bug-b-nary at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sub-Nary>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
662 You can find documentation for this module with the perldoc command.
666 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
668 =head1 ACKNOWLEDGEMENTS
670 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
672 =head1 COPYRIGHT & LICENSE
674 Copyright 2008 Vincent Pit, all rights reserved.
676 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
680 1; # End of Sub::Nary