9 use List::Util qw/reduce sum/;
11 use B qw/class ppname svref_2object OPf_KIDS/;
15 Sub::Nary - Try to count how many elements a subroutine can return in list context.
32 my $sn = Sub::Nary->new();
33 my $r = $sn->nary(\&hlagh);
37 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).
43 The usual constructor. Currently takes no argument.
45 =head2 C<nary $coderef>
47 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
49 { 1 => 0.2, 2 => 0.4, 4 => 0.3, list => 0.1 }
51 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.
55 Flushes the L<Sub::Nary> object cache. Returns the object itself.
57 =head1 PROBABILITY OF RETURN
59 The probability is computed as such :
63 =item * All the returning points in the same subroutine (i.e. all the explicit C<return> and the last computed value) are considered equally possible.
65 For example, the subroutine
75 is seen returning one or two arguments each with probability C<1/2>.
87 it is considered to return 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), C<2> or C<3> arguments each with probability C<1/3>.
89 =item * The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
97 returns C<3> or C<4> arguments with probability C<1/2> ; and
100 return simple(), simple()
103 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.
105 =item * If a core function may return different numbers of scalars, each kind is considered equally possible.
107 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 } >>.
109 =item * The C<list> state is absorbing in regard of all the other ones.
111 This is just a pedantic way to say that "list + fixed length = list".
115 return 1, simple(), @_
118 is considered as always returning an unbounded list.
120 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
131 return oneorlist(), oneorlist()
134 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
142 XSLoader::load(__PACKAGE__, $VERSION);
146 croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
147 unless ref $_[0] and $_[0]->isa(__PACKAGE__);
152 $class = ref($class) || $class || __PACKAGE__;
153 bless { cache => { } }, $class;
159 $self->{cache} = { };
168 return $self->enter(svref_2object($sub));
173 $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
179 my $la = delete $a->{list};
180 my $lb = delete $b->{list};
181 if (defined $la || defined $lb) {
184 $res{list} = $la + $lb - $la * $lb;
186 while (my ($ka, $va) = each %$a) {
188 while (my ($kb, $vb) = each %$b) {
189 my $key = $ka + int $kb;
190 $res{$key} += $va * $vb;
194 }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
199 $a->{$_} += $b->{$_} for keys %$b;
201 } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
206 $ops{$_} = 1 for scalops;
207 $ops{$_} = 0 for qw/stub nextstate/;
208 $ops{$_} = 1 for qw/padsv/;
209 $ops{$_} = 'list' for qw/padav/;
210 $ops{$_} = 'list' for qw/padhv rv2hv/;
211 $ops{$_} = 'list' for qw/padany 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 'list' if class($cv) ne 'CV';
234 return { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
236 # Anything can happen with recursion
237 for (@{$self->{cv}}) {
238 return 'list' if $tag == tag($_->ROOT);
241 unshift @{$self->{cv}}, $cv;
242 (my $r, undef) = $self->expect_any($op->first);
243 shift @{$self->{cv}};
245 $r = { $r => 1} unless ref $r;
246 my $total = sum values %$r;
247 $r = { map { $_ => $r->{$_} / $total } keys %$r };
248 $self->{cache}->{$tag} = { %$r };
253 my ($self, $op) = @_;
255 return ($self->expect_list($op))[0] => 1 if name($op) eq 'return';
257 if ($op->flags & OPf_KIDS) {
258 for ($op = $op->first; not null $op; $op = $op->sibling) {
259 my ($p, $r) = $self->expect_return($op);
260 return $p => 1 if $r;
268 my ($self, $op) = @_;
271 my $meth = $self->can('pp_' . $n);
272 return $self->$meth($op) if $meth;
273 if (exists $ops{$n}) {
275 $r = { %$r } if ref $r eq 'HASH';
279 if ($op->flags & OPf_KIDS) {
282 for ($op = $op->first; not null $op; $op = $op->sibling) {
284 next if $n eq 'pushmark';
285 if ($n eq 'nextstate'
286 and not null(($op = $op->sibling)->sibling)) {
287 ($p, $r) = $self->expect_return($op);
288 return $p => 1 if $r;
290 ($p, $r) = $self->expect_any($op);
291 return $p => 1 if $r;
295 return (combine @res) => 0;
302 my ($self, $op) = @_;
304 return ($self->expect_list($op))[0] => 1 if name($op) eq 'return';
306 if (class($op) eq 'LOGOP' and not null $op->first) {
311 ($p, $r) = $self->expect_return($op);
312 return $p => 1 if $r;
315 push @res, ($self->expect_any($op))[0];
317 # If the logop has no else branch, it can also return the *scalar* result of
323 push @res, ($self->expect_any($op))[0];
326 return (add @res) => 0;
329 return $self->expect_list($op);
332 # Stolen from B::Deparse
334 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
337 my ($self, $op) = @_;
338 if (class($op) eq 'PADOP') {
339 return $self->padval($op->padix)
340 } else { # class($op) eq "SVOP"
346 my ($self, $op) = @_;
348 # the constant could be in the pad (under useithreads)
349 $sv = $self->padval($op->targ) unless $$sv;
354 my ($self, $op, $exp) = @_;
357 while ($next->flags & OPf_KIDS) {
358 $next = $next->first;
360 while (not null $next) {
362 my ($p, $r) = $self->expect_return($op, $exp);
363 return $p => 1 if $r;
364 $next = $op->sibling;
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' unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
379 local $self->{sub} = 1;
380 return $self->expect_any($op, $exp);
388 my ($self, $op) = @_;
390 return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : 1
394 my ($self, $op) = @_;
396 return $self->{sub} ? $self->enter($self->const_sv($op)) : 1
400 my ($self, $op) = @_;
403 while ($op->flags & OPf_KIDS) {
404 my $nop = $op->first;
406 if ($nn eq 'pushmark') {
407 $nop = $nop->sibling;
410 if ($n eq 'rv2cv' and $nn eq 'gv') {
411 return $self->enter($self->gv_or_padgv($nop)->CV);
421 my ($self, $op) = @_;
423 my $sv = $self->const_sv($op);
426 return $sv->FILL + 1;
427 } elsif ($c eq 'HV') {
428 return 2 * $sv->FILL;
434 sub pp_aslice { $_[0]->expect_any($_[1]->first->sibling) }
437 *pp_hslice = *pp_aslice{CODE};
439 sub pp_lslice { $_[0]->expect_any($_[1]->first) }
442 my ($self, $op) = @_;
445 return (name($op) eq 'const') ? $self->expect_any($op) : 'list';
449 my ($self, $op) = @_;
453 # Can't assign to return
454 my ($p, $r) = $self->expect_list($op->sibling);
455 return $p => 0 if not exists $p->{list};
457 $self->expect_any($op);
460 sub pp_leaveloop { $_[0]->expect_return($_[1]->first->sibling) }
463 my ($self, $op) = @_;
466 return 'list' if name($op) ne 'range';
468 my $begin = $op->first;
469 if (name($begin) eq 'const') {
470 my $end = $begin->sibling;
471 if (name($end) eq 'const') {
472 $begin = $self->const_sv($begin);
473 $end = $self->const_sv($end);
474 no warnings 'numeric';
475 return int(${$end->object_2svref}) - int(${$begin->object_2svref}) + 1;
477 my ($p, $r) = $self->expect_return($end);
478 return $p => 1 if $r;
481 my ($p, $r) = $self->expect_return($begin);
482 return $p => 1 if $r;
490 An object-oriented module shouldn't export any function, and so does this one.
494 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
496 C<wantarray> isn't specialized when encountered in the optree.
502 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).
506 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
508 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
512 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.
516 You can find documentation for this module with the perldoc command.
520 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
522 =head1 ACKNOWLEDGEMENTS
524 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
526 =head1 COPYRIGHT & LICENSE
528 Copyright 2008 Vincent Pit, all rights reserved.
530 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
534 1; # End of Sub::Nary