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 0 unless defined $r;
184 return $r eq 'list' unless ref $r;
185 return $r->{list} and 1 == scalar keys %$r;
190 return unless defined $r;
191 return { 0 => 1 } unless keys %$r;
192 my $total = count $r;
193 return { map { $_ => $r->{$_} / $total } keys %$r };
198 return unless defined $r;
199 return (ref $r) ? { map { $_ => $r->{$_} * $c } keys %$r } : { $r => $c };
205 my $la = delete $a->{list};
206 my $lb = delete $b->{list};
207 if (defined $la || defined $lb) {
210 $res{list} = $la + $lb - $la * $lb;
212 while (my ($ka, $va) = each %$a) {
214 while (my ($kb, $vb) = each %$b) {
215 my $key = $ka + int $kb;
216 $res{$key} += $va * $vb;
220 }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
224 my ($p, $n, $c) = @_;
225 return unless defined $p;
226 return { 0 => $c } unless $n;
228 my $z = delete $p->{0};
229 return { 'list' => $c } unless $z;
230 return { 0 => $c } if $z == 1;
231 return { 0 => $c * $z, list => $c * (1 - $z) };
233 my $r = combine map { { %$p } } 1 .. $n;
234 $r->{$_} *= $c for keys %$r;
240 $a->{$_} += $b->{$_} for keys %$b;
242 } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
247 $ops{$_} = 1 for scalops;
248 $ops{$_} = 0 for qw/stub nextstate pushmark iter unstack/;
249 $ops{$_} = 1 for qw/padsv/;
250 $ops{$_} = 'list' for qw/padav/;
251 $ops{$_} = 'list' for qw/padhv rv2hv/;
252 $ops{$_} = 'list' for qw/padany/;
253 $ops{$_} = 'list' for qw/match entereval readline/;
255 $ops{each} = { 0 => 0.5, 2 => 0.5 };
256 $ops{stat} = { 0 => 0.5, 13 => 0.5 };
258 $ops{caller} = sub { my @a = caller 0; scalar @a }->();
259 $ops{localtime} = do { my @a = localtime; scalar @a };
260 $ops{gmtime} = do { my @a = gmtime; scalar @a };
262 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
263 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for map "ggr$_", qw/nam gid ent/;
264 $ops{$_} = 'list' for qw/ghbyname ghbyaddr ghostent/;
265 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gnbyname gnbyaddr gnetent/;
266 $ops{$_} = { 0 => 0.5, 3 => 0.5 } for qw/gpbyname gpbynumber gprotoent/;
267 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gsbyname gsbyport gservent/;
270 my ($self, $cv) = @_;
272 return undef, 'list' if class($cv) ne 'CV';
276 return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
278 # Anything can happen with recursion
279 for (@{$self->{cv}}) {
280 return undef, 'list' if $tag == tag($_->ROOT);
283 unshift @{$self->{cv}}, $cv;
284 my $r = add $self->inspect($op->first);
285 shift @{$self->{cv}};
287 $r = { $r => 1 } unless ref $r;
288 $self->{cache}->{$tag} = { %$r };
293 my ($self, $op) = @_;
296 diag "@ $n" if $DEBUG;
297 return add($self->inspect_kids($op)), undef if $n eq 'return';
299 my $meth = $self->can('pp_' . $n);
300 return $self->$meth($op) if $meth;
302 if (exists $ops{$n}) {
304 $l = { %$l } if ref $l;
308 if (class($op) eq 'LOGOP' and not null $op->first) {
311 diag "? logop\n" if $DEBUG;
314 my ($r1, $l1) = $self->inspect($op);
315 return $r1, $l1 if $r1 and zero $l1;
319 my ($r2, $l2) = $self->inspect($op);
324 # If the logop has no else branch, it can also return the *scalar* result of
328 ($r3, $l3) = $self->inspect($op);
331 my $r = add $r1, scale $c / 2, add $r2, $r3;
332 my $l = scale $c / 2, add $l2, $l3;
336 return $self->inspect_kids($op);
340 my ($self, $op) = @_;
342 return undef, 0 unless $op->flags & OPf_KIDS;
345 return undef, 0 if null $op;
346 if (name($op) eq 'pushmark') {
348 return undef, 0 if null $op;
353 for (; not null $op; $op = $op->sibling) {
355 if ($n eq 'nextstate') {
359 if ($n eq 'lineseq') {
364 diag "> $n ($c)" if $DEBUG;
365 my ($rc, $lc) = $self->inspect($op);
366 $r = add $r, scale $c, $rc if defined $rc;
367 if ($rc and not defined $lc) {
371 push @l, scale $c, $lc;
372 $c *= count $lc if defined $lc;
380 # Stolen from B::Deparse
382 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
385 my ($self, $op) = @_;
386 if (class($op) eq 'PADOP') {
387 return $self->padval($op->padix)
388 } else { # class($op) eq "SVOP"
394 my ($self, $op) = @_;
396 # the constant could be in the pad (under useithreads)
397 $sv = $self->padval($op->targ) unless $$sv;
402 my ($self, $op) = @_;
404 $op = $op->first while $op->flags & OPf_KIDS;
405 return undef, 0 if null $op;
406 if (name($op) eq 'pushmark') {
408 return undef, 0 if null $op;
413 for (; not null $op->sibling; $op = $op->sibling) {
415 next if $n eq 'nextstate';
416 diag "* $n" if $DEBUG;
417 my ($rc, $lc) = $self->inspect($op);
418 $r = add $r, scale $c, $rc if defined $rc;
421 return $r, $c ? { 0 => $c } : undef
426 if (name($op) eq 'rv2cv') {
430 my $next = $op->sibling;
431 while (not null $next) {
433 $next = $next->sibling;
436 } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
437 return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
438 local $self->{sub} = 1;
439 my ($rc, $lc) = $self->inspect($op);
440 return $r, scale $c, $lc;
443 return $r, { 'list' => $c };
448 my ($self, $op) = @_;
450 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
454 my ($self, $op) = @_;
456 return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
460 my ($self, $op) = @_;
463 while ($op->flags & OPf_KIDS) {
464 my $nop = $op->first;
466 if ($nn eq 'pushmark') {
467 $nop = $nop->sibling;
470 if ($n eq 'rv2cv' and $nn eq 'gv') {
471 return $self->enter($self->gv_or_padgv($nop)->CV);
477 return undef, 'list';
481 my ($self, $op) = @_;
483 return undef, 0 unless $op->isa('B::SVOP');
485 my $sv = $self->const_sv($op);
490 } elsif ($c eq 'HV') {
497 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
500 *pp_hslice = *pp_aslice{CODE};
502 sub pp_lslice { $_[0]->inspect($_[1]->first) }
505 my ($self, $op) = @_;
508 my ($r, $l) = $self->inspect($op);
509 if (name($op) ne 'const') {
510 my $c = 1 - count $r;
511 $l = $c ? { list => $c } : 0;
517 my ($self, $op) = @_;
521 # Can't assign to return
522 my $l = ($self->inspect($op->sibling))[1];
523 return undef, $l if not exists $l->{list};
529 my ($self, $op) = @_;
531 diag "* leaveloop" if $DEBUG;
535 if (name($op) eq 'enteriter') {
536 ($r1, $l1) = $self->inspect($op);
537 return $r1, $l1 if $r1 and zero $l1;
541 my $r = (name($op->first) eq 'and') ? ($self->inspect($op->first->first->sibling))[0]
542 : ($self->inspect($op))[0];
543 my $c = 1 - count $r;
544 diag "& leaveloop" if $DEBUG;
545 return $r, $c ? { 0 => $c } : undef;
549 my ($self, $op) = @_;
552 return $self->inspect($op) if name($op) ne 'range';
555 my $begin = $op->first;
556 if (name($begin) eq 'const') {
557 my $end = $begin->sibling;
558 if (name($end) eq 'const') {
559 $begin = $self->const_sv($begin);
560 $end = $self->const_sv($end);
562 no warnings 'numeric';
563 $begin = int ${$begin->object_2svref};
564 $end = int ${$end->object_2svref};
566 return undef, $end - $begin + 1;
568 ($r, $l) = $self->inspect($end);
571 ($r, $l) = $self->inspect($begin);
574 my $c = 1 - count $r;
575 return $r, ($l && $c) ? { 'list' => $c } : undef
579 my ($self, $op) = @_;
582 return $self->inspect($op) if name($op) ne 'grepstart';
583 $op = $op->first->sibling;
585 my ($r2, $l2) = $self->inspect($op->sibling);
586 return $r2, $l2 if $r2 and zero $l2;
587 diag Dumper [ $r2, $l2 ] if $DEBUG;
588 my $c = count $l2; # First one to happen
590 my ($r1, $l1) = $self->inspect($op);
591 diag Dumper [ $r1, $l1 ] if $DEBUG;
592 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
593 return { 'list' => 1 }, undef if list $l2;
595 $l2 = { $l2 => 1 } unless ref $l2;
596 my $r = add $r2, scale $c,
598 add map { power $r1, $_, $l2->{$_} } keys %$l2;
600 return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
604 my ($self, $op) = @_;
607 return $self->inspect($op) if name($op) ne 'mapstart';
608 $op = $op->first->sibling;
610 my ($r2, $l2) = $self->inspect($op->sibling);
611 return $r2, $l2 if $r2 and zero $l2;
612 my $c = count $l2; # First one to happen
614 my ($r1, $l1) = $self->inspect($op);
615 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
616 diag Dumper [ [ $r1, $l1 ], [ $r2, $l2 ] ] if $DEBUG;
618 $l2 = { $l2 => 1 } unless ref $l2;
619 my $r = add $r2, scale $c,
621 add map { power $r1, $_, $l2->{$_} } keys %$l2;
623 my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
629 An object-oriented module shouldn't export any function, and so does this one.
633 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
635 C<wantarray> isn't specialized when encountered in the optree.
641 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).
645 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
647 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
651 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.
655 You can find documentation for this module with the perldoc command.
659 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
661 =head1 ACKNOWLEDGEMENTS
663 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
665 =head1 COPYRIGHT & LICENSE
667 Copyright 2008 Vincent Pit, all rights reserved.
669 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
673 1; # End of Sub::Nary