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 my $sn = Sub::Nary->new;
44 The usual constructor. Currently takes no argument.
48 my $res = $sn->nary($coderef);
50 Takes a 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 :
68 When branching, each branch is considered equally possible.
70 For example, the subroutine
80 is seen returning one or two arguments each with probability C<1/2>.
92 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>.
96 The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
101 return 1, simple(), 2
104 returns C<3> or C<4> arguments with probability C<1/2> ; and
107 return simple(), simple()
110 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.
114 If a core function may return different numbers of scalars, each kind is considered equally possible.
116 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 } >>.
120 The C<list> state is absorbing in regard of all the other ones.
122 This is just a pedantic way to say that "list + fixed length = list".
126 return 1, simple(), @_
129 is considered as always returning an unbounded list.
131 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
142 return oneorlist(), oneorlist()
145 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
153 XSLoader::load(__PACKAGE__, $VERSION);
157 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
158 unless ref $_[0] and $_[0]->isa(__PACKAGE__);
163 $class = ref($class) || $class || __PACKAGE__;
164 bless { cache => { } }, $class;
170 $self->{cache} = { };
179 return ($self->enter(svref_2object($sub)))[1];
183 local $SIG{__DIE__} = \&Carp::confess;
185 $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
189 my ($p, $n, $c) = @_;
190 return unless defined $p;
191 return { 0 => $c } unless $n;
193 my $z = delete $p->{0};
194 return { 'list' => $c } unless $z;
195 return { 0 => $c } if $z == 1;
196 return { 0 => $c * $z, list => $c * (1 - $z) };
198 my $r = combine map { { %$p } } 1 .. $n;
199 $r->{$_} *= $c for keys %$r;
205 $ops{$_} = 1 for scalops;
206 $ops{$_} = 0 for qw/stub nextstate pushmark iter unstack/;
207 $ops{$_} = 1 for qw/padsv/;
208 $ops{$_} = 'list' for qw/padav/;
209 $ops{$_} = 'list' for qw/padhv rv2hv/;
210 $ops{$_} = 'list' for qw/padany/;
211 $ops{$_} = 'list' for qw/match entereval readline/;
213 $ops{each} = { 0 => 0.5, 2 => 0.5 };
214 $ops{stat} = { 0 => 0.5, 13 => 0.5 };
216 $ops{caller} = sub { my @a = caller 0; scalar @a }->();
217 $ops{localtime} = do { my @a = localtime; scalar @a };
218 $ops{gmtime} = do { my @a = gmtime; scalar @a };
220 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
221 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for map "ggr$_", qw/nam gid ent/;
222 $ops{$_} = 'list' for qw/ghbyname ghbyaddr ghostent/;
223 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gnbyname gnbyaddr gnetent/;
224 $ops{$_} = { 0 => 0.5, 3 => 0.5 } for qw/gpbyname gpbynumber gprotoent/;
225 $ops{$_} = { 0 => 0.5, 4 => 0.5 } for qw/gsbyname gsbyport gservent/;
228 my ($self, $cv) = @_;
230 return undef, 'list' if class($cv) ne 'CV';
234 return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
236 # Anything can happen with recursion
237 for (@{$self->{cv}}) {
238 return undef, 'list' if $tag == tag($_->ROOT);
241 unshift @{$self->{cv}}, $cv;
242 my $r = add $self->inspect($op->first);
243 shift @{$self->{cv}};
245 $self->{cache}->{$tag} = { %$r };
250 my ($self, $op) = @_;
253 return add($self->inspect_kids($op)), undef if $n eq 'return';
255 my $meth = $self->can('pp_' . $n);
256 return $self->$meth($op) if $meth;
258 if (exists $ops{$n}) {
260 $l = { %$l } if ref $l;
264 if (class($op) eq 'LOGOP' and not null $op->first) {
268 my ($r1, $l1) = $self->inspect($op);
269 return $r1, $l1 if defined $r1 and zero $l1;
273 my ($r2, $l2) = $self->inspect($op);
278 # If the logop has no else branch, it can also return the *scalar* result of
282 ($r3, $l3) = $self->inspect($op);
285 my $r = add $r1, scale $c / 2, add $r2, $r3;
286 my $l = scale $c / 2, add $l2, $l3;
290 return $self->inspect_kids($op);
294 my ($self, $op) = @_;
296 return undef, 0 unless $op->flags & OPf_KIDS;
299 return undef, 0 if null $op;
300 if (name($op) eq 'pushmark') {
302 return undef, 0 if null $op;
307 for (; not null $op; $op = $op->sibling) {
309 if ($n eq 'nextstate') {
313 if ($n eq 'lineseq') {
318 my ($rc, $lc) = $self->inspect($op);
320 $r = add $r, scale $c, $rc if defined $rc;
321 if (not defined $lc) {
325 push @l, scale $c, $lc;
328 my $l = scale +(1 - count $r), normalize combine @l;
333 # Stolen from B::Deparse
335 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
338 my ($self, $op) = @_;
339 if (class($op) eq 'PADOP') {
340 return $self->padval($op->padix)
341 } else { # class($op) eq "SVOP"
347 my ($self, $op) = @_;
349 # the constant could be in the pad (under useithreads)
350 $sv = $self->padval($op->targ) unless $$sv;
355 my ($self, $op) = @_;
357 $op = $op->first while $op->flags & OPf_KIDS;
358 # First must be a pushmark
360 # Next must be non null - at worse it's the rv2cv
364 for (; not null $op->sibling; $op = $op->sibling) {
365 my ($rc, $lc) = $self->inspect($op);
366 return $rc, $lc if defined $rc and not defined $lc;
367 $r = add $r, scale $c, $rc;
371 if (name($op) eq 'rv2cv') {
375 my $next = $op->sibling;
376 while (not null $next) {
378 $next = $next->sibling;
381 } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
382 return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
383 local $self->{sub} = 1;
384 my ($rc, $lc) = $self->inspect($op);
385 return $r, scale $c, $lc;
388 return $r, { 'list' => $c };
393 my ($self, $op) = @_;
395 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
399 my ($self, $op) = @_;
401 return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
405 my ($self, $op) = @_;
408 while ($op->flags & OPf_KIDS) {
409 my $nop = $op->first;
411 if ($nn eq 'pushmark') {
412 $nop = $nop->sibling;
415 if ($n eq 'rv2cv' and $nn eq 'gv') {
416 return $self->enter($self->gv_or_padgv($nop)->CV);
422 return undef, 'list';
426 my ($self, $op) = @_;
428 return undef, 0 unless $op->isa('B::SVOP');
430 my $sv = $self->const_sv($op);
435 } elsif ($c eq 'HV') {
442 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
445 *pp_hslice = *pp_aslice{CODE};
447 sub pp_lslice { $_[0]->inspect($_[1]->first) }
450 my ($self, $op) = @_;
453 if (name($op) eq 'gv') {
454 return undef, { list => 1 };
461 my ($self, $op) = @_;
463 my $r = ($self->inspect($op->first))[0];
465 my $c = 1 - count $r;
466 return $r, $c ? { 1 => $c } : undef
470 my ($self, $op) = @_;
474 # Can't assign to return
475 my $l = ($self->inspect($op->sibling))[1];
476 return undef, $l if not exists $l->{list};
482 my ($self, $op) = @_;
487 if (name($op) eq 'enteriter') { # for loop ?
489 ($r1, $l1) = $self->inspect($op);
490 return $r1, $l1 if defined $r1 and zero $l1;
495 if (name($op->first) eq 'and') {
496 ($r2, $l2) = $self->inspect($op->first->first);
497 return $r2, $l2 if defined $r2 and zero $l2;
499 return { list => 1 }, undef if !$for and defined $r2;
500 my ($r3, $l3) = $self->inspect($op->first->first->sibling);
501 return { list => 1 }, undef if defined $r3 and defined $l3;
502 $r2 = add $r2, scale $c, $r3;
504 ($r2, $l2) = $self->inspect($op);
505 return { list => 1 }, undef if defined $r2 and defined $l2;
508 my $r = (defined $r1) ? add $r1, scale +(1 - count $r1), $r2
510 my $c = 1 - count $r;
511 return $r, $c ? { 0 => $c } : undef;
515 my ($self, $op) = @_;
518 return $self->inspect($op) if name($op) ne 'range';
521 my $begin = $op->first;
522 if (name($begin) eq 'const') {
523 my $end = $begin->sibling;
524 if (name($end) eq 'const') {
525 $begin = $self->const_sv($begin);
526 $end = $self->const_sv($end);
528 no warnings 'numeric';
529 $begin = int ${$begin->object_2svref};
530 $end = int ${$end->object_2svref};
532 return undef, $end - $begin + 1;
534 ($r, $l) = $self->inspect($end);
537 ($r, $l) = $self->inspect($begin);
540 my $c = 1 - count $r;
541 return $r, $c ? { 'list' => $c } : undef
545 my ($self, $op) = @_;
548 return $self->inspect($op) if name($op) ne 'grepstart';
549 $op = $op->first->sibling;
551 my ($r2, $l2) = $self->inspect($op->sibling);
552 return $r2, $l2 if defined $r2 and zero $l2;
553 my $c2 = count $l2; # First one to happen
555 my ($r1, $l1) = $self->inspect($op);
556 return (add $r2, scale $c2, $r1), undef if defined $r1 and zero $l1
560 $l2 = { $l2 => 1 } unless ref $l2;
563 add map { scale $l2->{$_}, cumulate $r1, $_, $c1 } keys %$l2;
564 my $c = 1 - count $r;
565 return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
569 my ($self, $op) = @_;
572 return $self->inspect($op) if name($op) ne 'mapstart';
573 $op = $op->first->sibling;
575 my ($r2, $l2) = $self->inspect($op->sibling);
576 return $r2, $l2 if defined $r2 and zero $l2;
577 my $c2 = count $l2; # First one to happen
579 my ($r1, $l1) = $self->inspect($op);
580 return (add $r2, scale $c2, $r1), undef if defined $r1 and zero $l1
584 $l2 = { $l2 => 1 } unless ref $l2;
587 add map { scale $l2->{$_}, cumulate $r1, $_, $c1 } keys %$l2;
588 my $c = 1 - count $r;
589 my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
595 An object-oriented module shouldn't export any function, and so does this one.
599 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
601 C<wantarray> isn't specialized when encountered in the optree.
607 L<Carp> (standard since perl 5), L<B> (since perl 5.005) and L<XSLoader> (since perl 5.006).
611 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
613 You can contact me by mail or on C<irc.perl.org> (vincent).
617 Please report any bugs or feature requests to C<bug-sub-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.
621 You can find documentation for this module with the perldoc command.
625 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
627 =head1 ACKNOWLEDGEMENTS
629 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
631 =head1 COPYRIGHT & LICENSE
633 Copyright 2008 Vincent Pit, all rights reserved.
635 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
639 1; # End of Sub::Nary