10 use B qw/class ppname svref_2object OPf_KIDS/;
14 Sub::Nary - Try to count how many elements a subroutine can return in list context.
31 my $sn = Sub::Nary->new();
32 my $r = $sn->nary(\&hlagh);
36 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).
42 The usual constructor. Currently takes no argument.
44 =head2 C<nary $coderef>
46 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
48 { 1 => 0.2, 2 => 0.4, 4 => 0.3, list => 0.1 }
50 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.
54 Flushes the L<Sub::Nary> object cache. Returns the object itself.
56 =head1 PROBABILITY OF RETURN
58 The probability is computed as such :
62 =item * When branching, each branch is considered equally possible.
64 For example, the subroutine
74 is seen returning one or two arguments each with probability C<1/2>.
86 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>.
88 =item * The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
96 returns C<3> or C<4> arguments with probability C<1/2> ; and
99 return simple(), simple()
102 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.
104 =item * If a core function may return different numbers of scalars, each kind is considered equally possible.
106 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 } >>.
108 =item * The C<list> state is absorbing in regard of all the other ones.
110 This is just a pedantic way to say that "list + fixed length = list".
114 return 1, simple(), @_
117 is considered as always returning an unbounded list.
119 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
130 return oneorlist(), oneorlist()
133 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
141 XSLoader::load(__PACKAGE__, $VERSION);
145 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
146 unless ref $_[0] and $_[0]->isa(__PACKAGE__);
151 $class = ref($class) || $class || __PACKAGE__;
152 bless { cache => { } }, $class;
158 $self->{cache} = { };
167 return ($self->enter(svref_2object($sub)))[1];
171 local $SIG{__DIE__} = \&Carp::confess;
173 $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
177 my ($p, $n, $c) = @_;
178 return unless defined $p;
179 return { 0 => $c } unless $n;
181 my $z = delete $p->{0};
182 return { 'list' => $c } unless $z;
183 return { 0 => $c } if $z == 1;
184 return { 0 => $c * $z, list => $c * (1 - $z) };
186 my $r = combine map { { %$p } } 1 .. $n;
187 $r->{$_} *= $c for keys %$r;
193 $ops{$_} = 1 for scalops;
194 $ops{$_} = 0 for qw/stub nextstate pushmark iter unstack/;
195 $ops{$_} = 1 for qw/padsv/;
196 $ops{$_} = 'list' for qw/padav/;
197 $ops{$_} = 'list' for qw/padhv rv2hv/;
198 $ops{$_} = 'list' for qw/padany/;
199 $ops{$_} = 'list' for qw/match entereval readline/;
201 $ops{each} = { 0 => 0.5, 2 => 0.5 };
202 $ops{stat} = { 0 => 0.5, 13 => 0.5 };
204 $ops{caller} = sub { my @a = caller 0; scalar @a }->();
205 $ops{localtime} = do { my @a = localtime; scalar @a };
206 $ops{gmtime} = do { my @a = gmtime; scalar @a };
208 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
209 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for map "ggr$_", qw/nam gid ent/;
210 $ops{$_} = 'list' for qw/ghbyname ghbyaddr ghostent/;
211 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gnbyname gnbyaddr gnetent/;
212 $ops{$_} = { 0 => 0.5, 3 => 0.5 } for qw/gpbyname gpbynumber gprotoent/;
213 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gsbyname gsbyport gservent/;
216 my ($self, $cv) = @_;
218 return undef, 'list' if class($cv) ne 'CV';
222 return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
224 # Anything can happen with recursion
225 for (@{$self->{cv}}) {
226 return undef, 'list' if $tag == tag($_->ROOT);
229 unshift @{$self->{cv}}, $cv;
230 my $r = add $self->inspect($op->first);
231 shift @{$self->{cv}};
233 $r = { $r => 1 } unless ref $r;
234 $self->{cache}->{$tag} = { %$r };
239 my ($self, $op) = @_;
242 return add($self->inspect_kids($op)), undef if $n eq 'return';
244 my $meth = $self->can('pp_' . $n);
245 return $self->$meth($op) if $meth;
247 if (exists $ops{$n}) {
249 $l = { %$l } if ref $l;
253 if (class($op) eq 'LOGOP' and not null $op->first) {
257 my ($r1, $l1) = $self->inspect($op);
258 return $r1, $l1 if defined $r1 and zero $l1;
262 my ($r2, $l2) = $self->inspect($op);
267 # If the logop has no else branch, it can also return the *scalar* result of
271 ($r3, $l3) = $self->inspect($op);
274 my $r = add $r1, scale $c / 2, add $r2, $r3;
275 my $l = scale $c / 2, add $l2, $l3;
279 return $self->inspect_kids($op);
283 my ($self, $op) = @_;
285 return undef, 0 unless $op->flags & OPf_KIDS;
288 return undef, 0 if null $op;
289 if (name($op) eq 'pushmark') {
291 return undef, 0 if null $op;
296 for (; not null $op; $op = $op->sibling) {
298 if ($n eq 'nextstate') {
302 if ($n eq 'lineseq') {
307 my ($rc, $lc) = $self->inspect($op);
309 $r = add $r, scale $c, $rc if defined $rc;
310 if (not defined $lc) {
314 push @l, scale $c, $lc;
317 my $l = scale +(1 - count $r), normalize combine @l;
322 # Stolen from B::Deparse
324 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
327 my ($self, $op) = @_;
328 if (class($op) eq 'PADOP') {
329 return $self->padval($op->padix)
330 } else { # class($op) eq "SVOP"
336 my ($self, $op) = @_;
338 # the constant could be in the pad (under useithreads)
339 $sv = $self->padval($op->targ) unless $$sv;
344 my ($self, $op) = @_;
346 $op = $op->first while $op->flags & OPf_KIDS;
347 return undef, 0 if null $op;
348 if (name($op) eq 'pushmark') {
350 return undef, 0 if null $op;
355 for (; not null $op->sibling; $op = $op->sibling) {
357 next if $n eq 'nextstate';
358 my ($rc, $lc) = $self->inspect($op);
359 $r = add $r, scale $c, $rc if defined $rc;
362 return $r, $c ? { 0 => $c } : undef
367 if (name($op) eq 'rv2cv') {
371 my $next = $op->sibling;
372 while (not null $next) {
374 $next = $next->sibling;
377 } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
378 return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
379 local $self->{sub} = 1;
380 my ($rc, $lc) = $self->inspect($op);
381 return $r, scale $c, $lc;
384 return $r, { 'list' => $c };
389 my ($self, $op) = @_;
391 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
395 my ($self, $op) = @_;
397 return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
401 my ($self, $op) = @_;
404 while ($op->flags & OPf_KIDS) {
405 my $nop = $op->first;
407 if ($nn eq 'pushmark') {
408 $nop = $nop->sibling;
411 if ($n eq 'rv2cv' and $nn eq 'gv') {
412 return $self->enter($self->gv_or_padgv($nop)->CV);
418 return undef, 'list';
422 my ($self, $op) = @_;
424 return undef, 0 unless $op->isa('B::SVOP');
426 my $sv = $self->const_sv($op);
431 } elsif ($c eq 'HV') {
438 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
441 *pp_hslice = *pp_aslice{CODE};
443 sub pp_lslice { $_[0]->inspect($_[1]->first) }
446 my ($self, $op) = @_;
449 if (name($op) eq 'gv') {
450 return undef, { list => 1 };
457 my ($self, $op) = @_;
461 # Can't assign to return
462 my $l = ($self->inspect($op->sibling))[1];
463 return undef, $l if not exists $l->{list};
469 my ($self, $op) = @_;
474 if (name($op) eq 'enteriter') { # for loop ?
476 ($r1, $l1) = $self->inspect($op);
477 return $r1, $l1 if defined $r1 and zero $l1;
482 if (name($op->first) eq 'and') {
483 ($r2, $l2) = $self->inspect($op->first->first);
484 return $r2, $l2 if defined $r2 and zero $l2;
486 return { list => 1 }, undef if !$for and defined $r2;
487 my ($r3, $l3) = $self->inspect($op->first->first->sibling);
488 return { list => 1 }, undef if defined $r3 and defined $l3;
489 $r2 = add $r2, scale $c, $r3;
491 ($r2, $l2) = $self->inspect($op);
492 return { list => 1 }, undef if defined $r2 and defined $l2;
495 my $r = (defined $r1) ? add $r1, scale +(1 - count $r1), $r2
497 my $c = 1 - count $r;
498 return $r, $c ? { 0 => $c } : undef;
502 my ($self, $op) = @_;
505 return $self->inspect($op) if name($op) ne 'range';
508 my $begin = $op->first;
509 if (name($begin) eq 'const') {
510 my $end = $begin->sibling;
511 if (name($end) eq 'const') {
512 $begin = $self->const_sv($begin);
513 $end = $self->const_sv($end);
515 no warnings 'numeric';
516 $begin = int ${$begin->object_2svref};
517 $end = int ${$end->object_2svref};
519 return undef, $end - $begin + 1;
521 ($r, $l) = $self->inspect($end);
524 ($r, $l) = $self->inspect($begin);
527 my $c = 1 - count $r;
528 return $r, $c ? { 'list' => $c } : undef
532 my ($self, $op) = @_;
535 return $self->inspect($op) if name($op) ne 'grepstart';
536 $op = $op->first->sibling;
538 my ($r2, $l2) = $self->inspect($op->sibling);
539 return $r2, $l2 if defined $r2 and zero $l2;
540 my $c2 = count $l2; # First one to happen
542 my ($r1, $l1) = $self->inspect($op);
543 return (add $r2, scale $c2, $r1), undef if defined $r1 and zero $l1
547 $l2 = { $l2 => 1 } unless ref $l2;
550 add map { scale $l2->{$_}, cumulate $r1, $_, $c1 } keys %$l2;
551 my $c = 1 - count $r;
552 return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
556 my ($self, $op) = @_;
559 return $self->inspect($op) if name($op) ne 'mapstart';
560 $op = $op->first->sibling;
562 my ($r2, $l2) = $self->inspect($op->sibling);
563 return $r2, $l2 if defined $r2 and zero $l2;
564 my $c2 = count $l2; # First one to happen
566 my ($r1, $l1) = $self->inspect($op);
567 return (add $r2, scale $c2, $r1), undef if defined $r1 and zero $l1
571 $l2 = { $l2 => 1 } unless ref $l2;
574 add map { scale $l2->{$_}, cumulate $r1, $_, $c1 } keys %$l2;
575 my $c = 1 - count $r;
576 my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
582 An object-oriented module shouldn't export any function, and so does this one.
586 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
588 C<wantarray> isn't specialized when encountered in the optree.
594 L<Carp> (standard since perl 5), L<B> (since perl 5.005) and L<XSLoader> (since perl 5.006).
598 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
600 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
604 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.
608 You can find documentation for this module with the perldoc command.
612 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
614 =head1 ACKNOWLEDGEMENTS
616 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
618 =head1 COPYRIGHT & LICENSE
620 Copyright 2008 Vincent Pit, all rights reserved.
622 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
626 1; # End of Sub::Nary