10 use B qw/class ppname svref_2object OPf_KIDS/;
12 use Test::More; use Data::Dumper;
16 Sub::Nary - Try to count how many elements a subroutine can return in list context.
35 my $sn = Sub::Nary->new();
36 my $r = $sn->nary(\&hlagh);
40 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).
46 The usual constructor. Currently takes no argument.
48 =head2 C<nary $coderef>
50 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
52 { 1 => 0.2, 2 => 0.4, 4 => 0.3, list => 0.1 }
54 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.
58 Flushes the L<Sub::Nary> object cache. Returns the object itself.
60 =head1 PROBABILITY OF RETURN
62 The probability is computed as such :
66 =item * When branching, each branch is considered equally possible.
68 For example, the subroutine
78 is seen returning one or two arguments each with probability C<1/2>.
90 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>.
92 =item * The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
100 returns C<3> or C<4> arguments with probability C<1/2> ; and
103 return simple(), simple()
106 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.
108 =item * If a core function may return different numbers of scalars, each kind is considered equally possible.
110 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 } >>.
112 =item * The C<list> state is absorbing in regard of all the other ones.
114 This is just a pedantic way to say that "list + fixed length = list".
118 return 1, simple(), @_
121 is considered as always returning an unbounded list.
123 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
134 return oneorlist(), oneorlist()
137 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
145 XSLoader::load(__PACKAGE__, $VERSION);
149 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
150 unless ref $_[0] and $_[0]->isa(__PACKAGE__);
155 $class = ref($class) || $class || __PACKAGE__;
156 bless { cache => { } }, $class;
162 $self->{cache} = { };
171 return ($self->enter(svref_2object($sub)))[1];
175 local $SIG{__DIE__} = \&Carp::confess;
177 $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
181 my ($p, $n, $c) = @_;
182 return unless defined $p;
183 return { 0 => $c } unless $n;
185 my $z = delete $p->{0};
186 return { 'list' => $c } unless $z;
187 return { 0 => $c } if $z == 1;
188 return { 0 => $c * $z, list => $c * (1 - $z) };
190 my $r = combine map { { %$p } } 1 .. $n;
191 $r->{$_} *= $c for keys %$r;
197 $ops{$_} = 1 for scalops;
198 $ops{$_} = 0 for qw/stub nextstate pushmark iter unstack/;
199 $ops{$_} = 1 for qw/padsv/;
200 $ops{$_} = 'list' for qw/padav/;
201 $ops{$_} = 'list' for qw/padhv rv2hv/;
202 $ops{$_} = 'list' for qw/padany/;
203 $ops{$_} = 'list' for qw/match entereval readline/;
205 $ops{each} = { 0 => 0.5, 2 => 0.5 };
206 $ops{stat} = { 0 => 0.5, 13 => 0.5 };
208 $ops{caller} = sub { my @a = caller 0; scalar @a }->();
209 $ops{localtime} = do { my @a = localtime; scalar @a };
210 $ops{gmtime} = do { my @a = gmtime; scalar @a };
212 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
213 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for map "ggr$_", qw/nam gid ent/;
214 $ops{$_} = 'list' for qw/ghbyname ghbyaddr ghostent/;
215 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gnbyname gnbyaddr gnetent/;
216 $ops{$_} = { 0 => 0.5, 3 => 0.5 } for qw/gpbyname gpbynumber gprotoent/;
217 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gsbyname gsbyport gservent/;
220 my ($self, $cv) = @_;
222 return undef, 'list' if class($cv) ne 'CV';
226 return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
228 # Anything can happen with recursion
229 for (@{$self->{cv}}) {
230 return undef, 'list' if $tag == tag($_->ROOT);
233 unshift @{$self->{cv}}, $cv;
234 my $r = add $self->inspect($op->first);
235 shift @{$self->{cv}};
237 $r = { $r => 1 } unless ref $r;
238 $self->{cache}->{$tag} = { %$r };
243 my ($self, $op) = @_;
246 diag "@ $n" if $DEBUG;
247 return add($self->inspect_kids($op)), undef if $n eq 'return';
249 my $meth = $self->can('pp_' . $n);
250 return $self->$meth($op) if $meth;
252 if (exists $ops{$n}) {
254 $l = { %$l } if ref $l;
258 if (class($op) eq 'LOGOP' and not null $op->first) {
261 diag "? logop\n" if $DEBUG;
264 my ($r1, $l1) = $self->inspect($op);
265 return $r1, $l1 if $r1 and zero $l1;
269 my ($r2, $l2) = $self->inspect($op);
274 # If the logop has no else branch, it can also return the *scalar* result of
278 ($r3, $l3) = $self->inspect($op);
281 my $r = add $r1, scale $c / 2, add $r2, $r3;
282 my $l = scale $c / 2, add $l2, $l3;
286 return $self->inspect_kids($op);
290 my ($self, $op) = @_;
292 return undef, 0 unless $op->flags & OPf_KIDS;
295 return undef, 0 if null $op;
296 if (name($op) eq 'pushmark') {
298 return undef, 0 if null $op;
303 for (; not null $op; $op = $op->sibling) {
305 if ($n eq 'nextstate') {
309 if ($n eq 'lineseq') {
314 diag "> $n ($c)" if $DEBUG;
315 my ($rc, $lc) = $self->inspect($op);
316 $r = add $r, scale $c, $rc if defined $rc;
317 if ($rc and not defined $lc) {
321 push @l, scale $c, $lc;
322 $c *= count $lc if defined $lc;
330 # Stolen from B::Deparse
332 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
335 my ($self, $op) = @_;
336 if (class($op) eq 'PADOP') {
337 return $self->padval($op->padix)
338 } else { # class($op) eq "SVOP"
344 my ($self, $op) = @_;
346 # the constant could be in the pad (under useithreads)
347 $sv = $self->padval($op->targ) unless $$sv;
352 my ($self, $op) = @_;
354 $op = $op->first while $op->flags & OPf_KIDS;
355 return undef, 0 if null $op;
356 if (name($op) eq 'pushmark') {
358 return undef, 0 if null $op;
363 for (; not null $op->sibling; $op = $op->sibling) {
365 next if $n eq 'nextstate';
366 diag "* $n" if $DEBUG;
367 my ($rc, $lc) = $self->inspect($op);
368 $r = add $r, scale $c, $rc if defined $rc;
371 return $r, $c ? { 0 => $c } : undef
376 if (name($op) eq 'rv2cv') {
380 my $next = $op->sibling;
381 while (not null $next) {
383 $next = $next->sibling;
386 } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
387 return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
388 local $self->{sub} = 1;
389 my ($rc, $lc) = $self->inspect($op);
390 return $r, scale $c, $lc;
393 return $r, { 'list' => $c };
398 my ($self, $op) = @_;
400 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
404 my ($self, $op) = @_;
406 return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
410 my ($self, $op) = @_;
413 while ($op->flags & OPf_KIDS) {
414 my $nop = $op->first;
416 if ($nn eq 'pushmark') {
417 $nop = $nop->sibling;
420 if ($n eq 'rv2cv' and $nn eq 'gv') {
421 return $self->enter($self->gv_or_padgv($nop)->CV);
427 return undef, 'list';
431 my ($self, $op) = @_;
433 return undef, 0 unless $op->isa('B::SVOP');
435 my $sv = $self->const_sv($op);
440 } elsif ($c eq 'HV') {
447 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
450 *pp_hslice = *pp_aslice{CODE};
452 sub pp_lslice { $_[0]->inspect($_[1]->first) }
455 my ($self, $op) = @_;
458 my ($r, $l) = $self->inspect($op);
459 if (name($op) ne 'const') {
460 my $c = 1 - count $r;
461 $l = $c ? { list => $c } : 0;
467 my ($self, $op) = @_;
471 # Can't assign to return
472 my $l = ($self->inspect($op->sibling))[1];
473 return undef, $l if not exists $l->{list};
479 my ($self, $op) = @_;
481 diag "* leaveloop" if $DEBUG;
485 if (name($op) eq 'enteriter') {
486 ($r1, $l1) = $self->inspect($op);
487 return $r1, $l1 if $r1 and zero $l1;
491 my $r = (name($op->first) eq 'and') ? ($self->inspect($op->first->first->sibling))[0]
492 : ($self->inspect($op))[0];
493 my $c = 1 - count $r;
494 diag "& leaveloop" if $DEBUG;
495 return $r, $c ? { 0 => $c } : undef;
499 my ($self, $op) = @_;
502 return $self->inspect($op) if name($op) ne 'range';
505 my $begin = $op->first;
506 if (name($begin) eq 'const') {
507 my $end = $begin->sibling;
508 if (name($end) eq 'const') {
509 $begin = $self->const_sv($begin);
510 $end = $self->const_sv($end);
512 no warnings 'numeric';
513 $begin = int ${$begin->object_2svref};
514 $end = int ${$end->object_2svref};
516 return undef, $end - $begin + 1;
518 ($r, $l) = $self->inspect($end);
521 ($r, $l) = $self->inspect($begin);
524 my $c = 1 - count $r;
525 return $r, ($l && $c) ? { 'list' => $c } : undef
529 my ($self, $op) = @_;
532 return $self->inspect($op) if name($op) ne 'grepstart';
533 $op = $op->first->sibling;
535 my ($r2, $l2) = $self->inspect($op->sibling);
536 return $r2, $l2 if $r2 and zero $l2;
537 diag Dumper [ $r2, $l2 ] if $DEBUG;
538 my $c = count $l2; # First one to happen
540 my ($r1, $l1) = $self->inspect($op);
541 diag Dumper [ $r1, $l1 ] if $DEBUG;
542 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
543 return { 'list' => 1 }, undef if list $l2;
545 $l2 = { $l2 => 1 } unless ref $l2;
546 my $r = add $r2, scale $c,
548 add map { power $r1, $_, $l2->{$_} } keys %$l2;
550 return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
554 my ($self, $op) = @_;
557 return $self->inspect($op) if name($op) ne 'mapstart';
558 $op = $op->first->sibling;
560 my ($r2, $l2) = $self->inspect($op->sibling);
561 return $r2, $l2 if $r2 and zero $l2;
562 my $c = count $l2; # First one to happen
564 my ($r1, $l1) = $self->inspect($op);
565 return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
566 diag Dumper [ [ $r1, $l1 ], [ $r2, $l2 ] ] if $DEBUG;
568 $l2 = { $l2 => 1 } unless ref $l2;
569 my $r = add $r2, scale $c,
571 add map { power $r1, $_, $l2->{$_} } keys %$l2;
573 my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
579 An object-oriented module shouldn't export any function, and so does this one.
583 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
585 C<wantarray> isn't specialized when encountered in the optree.
591 L<Carp> (standard since perl 5), L<B> (since perl 5.005) and L<XSLoader> (since perl 5.006).
595 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
597 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
601 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.
605 You can find documentation for this module with the perldoc command.
609 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
611 =head1 ACKNOWLEDGEMENTS
613 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
615 =head1 COPYRIGHT & LICENSE
617 Copyright 2008 Vincent Pit, all rights reserved.
619 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
623 1; # End of Sub::Nary