]> git.vpit.fr Git - perl/modules/Sub-Nary.git/blob - lib/Sub/Nary.pm
f538fc7c9eddbe327daa52c6f27630a76285b44d
[perl/modules/Sub-Nary.git] / lib / Sub / Nary.pm
1 package Sub::Nary;
2
3 use 5.008001;
4
5 use strict;
6 use warnings;
7
8 use Carp qw/croak/;
9 use List::Util qw/reduce/;
10
11 use B qw/class ppname svref_2object OPf_KIDS/;
12
13 use Test::More; use Data::Dumper;
14
15 =head1 NAME
16
17 Sub::Nary - Try to count how many elements a subroutine can return in list context.
18
19 =head1 VERSION
20
21 Version 0.02
22
23 =cut
24
25 our $VERSION;
26 BEGIN {
27  $VERSION  = '0.02';
28 }
29
30 our $DEBUG = 0;
31
32 =head1 SYNOPSIS
33
34     use Sub::Nary;
35
36     my $sn = Sub::Nary->new();
37     my $r  = $sn->nary(\&hlagh);
38
39 =head1 DESCRIPTION
40
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).
42
43 =head1 METHODS
44
45 =head2 C<new>
46
47 The usual constructor. Currently takes no argument.
48
49 =head2 C<nary $coderef>
50
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
52
53     { 1 => 0.2, 2 => 0.4, 4 => 0.3, list => 0.1 }
54
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.
56
57 =head2 C<flush>
58
59 Flushes the L<Sub::Nary> object cache. Returns the object itself.
60
61 =head1 PROBABILITY OF RETURN
62
63 The probability is computed as such :
64
65 =over 4
66
67 =item * When branching, each branch is considered equally possible.
68
69 For example, the subroutine
70
71     sub simple {
72      if (rand < 0.1) {
73       return 1;
74      } else {
75       return 2, 3;
76      }
77     }
78
79 is seen returning one or two arguments each with probability C<1/2>.
80 As for
81
82     sub hlagh {
83      my $x = rand;
84      if ($x < 0.1) {
85       return 1, 2, 3;
86      } elsif ($x > 0.9) {
87       return 4, 5;
88      }
89     }
90
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>.
92
93 =item * The total probability law for a given returning point is the convolution product of the probabilities of its list elements.
94
95 As such, 
96
97     sub notsosimple {
98      return 1, simple(), 2
99     }
100
101 returns C<3> or C<4> arguments with probability C<1/2> ; and
102
103     sub double {
104      return simple(), simple()
105     }
106
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.
108
109 =item * If a core function may return different numbers of scalars, each kind is considered equally possible.
110
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 } >>.
112
113 =item * The C<list> state is absorbing in regard of all the other ones.
114
115 This is just a pedantic way to say that "list + fixed length = list".
116 That's why
117
118     sub listy {
119      return 1, simple(), @_
120     }
121
122 is considered as always returning an unbounded list.
123
124 Also, the convolution law does not behave the same when C<list> elements are involved : in the following example,
125
126     sub oneorlist {
127      if (rand < 0.1) {
128       return 1
129      } else {
130       return @_
131      }
132     }
133
134     sub composed {
135      return oneorlist(), oneorlist()
136     }
137
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>.
139
140 =back
141
142 =cut
143
144 BEGIN {
145  require XSLoader;
146  XSLoader::load(__PACKAGE__, $VERSION);
147 }
148
149 sub _check_self {
150  croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
151   unless ref $_[0] and $_[0]->isa(__PACKAGE__);
152 }
153
154 sub new {
155  my $class = shift;
156  $class = ref($class) || $class || __PACKAGE__;
157  bless { cache => { } }, $class;
158 }
159
160 sub flush {
161  my $self = shift;
162  _check_self($self);
163  $self->{cache} = { };
164  $self;
165 }
166
167 sub nary {
168  my $self = shift;
169  my $sub  = shift;
170
171  $self->{cv} = [ ];
172  return ($self->enter(svref_2object($sub)))[1];
173 }
174
175 sub name ($) {
176  local $SIG{__DIE__} = \&Carp::confess;
177  my $n = $_[0]->name;
178  $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
179 }
180
181 sub zero ($) {
182  my $r = $_[0];
183  return 1 unless defined $r;
184  return $r eq '0' unless ref $r;
185  return $r->{0} and 1 == scalar keys %$r;
186 }
187
188 sub list ($) {
189  my $r = $_[0];
190  return 0 unless defined $r;
191  return $r eq 'list' unless ref $r;
192  return $r->{list} and 1 == scalar keys %$r;
193 }
194
195 sub normalize ($) {
196  my $r = $_[0];
197  return unless defined $r;
198  return { 0 => 1 } unless keys %$r;
199  my $total = count $r;
200  return { map { $_ => $r->{$_} / $total } keys %$r };
201 }
202
203 sub scale {
204  my ($c, $r) = @_;
205  return unless defined $r;
206  return (ref $r) ? { map { $_ => $r->{$_} * $c } keys %$r } : { $r => $c };
207 }
208
209 sub combine {
210  reduce {{
211   my %res;
212   my $la = delete $a->{list};
213   my $lb = delete $b->{list};
214   if (defined $la || defined $lb) {
215    $la ||= 0;
216    $lb ||= 0;
217    $res{list} = $la + $lb - $la * $lb;
218   }
219   while (my ($ka, $va) = each %$a) {
220    $ka = int $ka;
221    while (my ($kb, $vb) = each %$b) {
222     my $key = $ka + int $kb;
223     $res{$key} += $va * $vb;
224    }
225   }
226   \%res
227  }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
228 }
229
230 sub power {
231  my ($p, $n, $c) = @_;
232  return unless defined $p;
233  return { 0 => $c } unless $n;
234  if ($n eq 'list') {
235   my $z = delete $p->{0};
236   return { 'list' => $c } unless $z;
237   return { 0      => $c } if $z == 1;
238   return { 0 => $c * $z, list => $c * (1 - $z) };
239  }
240  my $r = combine map { { %$p } } 1 .. $n;
241  $r->{$_} *= $c for keys %$r;
242  return $r;
243 }
244
245 sub add {
246  reduce {
247   $a->{$_} += $b->{$_} for keys %$b;
248   $a
249  } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
250 }
251
252 my %ops;
253
254 $ops{$_} = 1      for scalops;
255 $ops{$_} = 0      for qw/stub nextstate pushmark iter unstack/;
256 $ops{$_} = 1      for qw/padsv/;
257 $ops{$_} = 'list' for qw/padav/;
258 $ops{$_} = 'list' for qw/padhv rv2hv/;
259 $ops{$_} = 'list' for qw/padany/;
260 $ops{$_} = 'list' for qw/match entereval readline/;
261
262 $ops{each}      = { 0 => 0.5, 2 => 0.5 };
263 $ops{stat}      = { 0 => 0.5, 13 => 0.5 };
264
265 $ops{caller}    = sub { my @a = caller 0; scalar @a }->();
266 $ops{localtime} = do { my @a = localtime; scalar @a };
267 $ops{gmtime}    = do { my @a = gmtime; scalar @a };
268
269 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
270 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for map "ggr$_", qw/nam gid ent/;
271 $ops{$_} = 'list'                  for qw/ghbyname ghbyaddr ghostent/;
272 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for qw/gnbyname gnbyaddr gnetent/;
273 $ops{$_} = { 0 => 0.5, 3 => 0.5 }  for qw/gpbyname gpbynumber gprotoent/;
274 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for qw/gsbyname gsbyport gservent/;
275
276 sub enter {
277  my ($self, $cv) = @_;
278
279  return undef, 'list' if class($cv) ne 'CV';
280  my $op  = $cv->ROOT;
281  my $tag = tag($op);
282
283  return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
284
285  # Anything can happen with recursion
286  for (@{$self->{cv}}) {
287   return undef, 'list' if $tag == tag($_->ROOT);
288  }
289
290  unshift @{$self->{cv}}, $cv;
291  my $r = add $self->inspect($op->first);
292  shift @{$self->{cv}};
293
294  $r = { $r => 1 } unless ref $r;
295  $self->{cache}->{$tag} = { %$r };
296  return undef, $r;
297 }
298
299 sub inspect {
300  my ($self, $op) = @_;
301
302  my $n = name($op);
303  diag "@ $n" if $DEBUG;
304  return add($self->inspect_kids($op)), undef if $n eq 'return';
305
306  my $meth = $self->can('pp_' . $n);
307  return $self->$meth($op) if $meth;
308
309  if (exists $ops{$n}) {
310   my $l = $ops{$n};
311   $l = { %$l } if ref $l;
312   return undef, $l;
313  }
314
315  if (class($op) eq 'LOGOP' and not null $op->first) {
316   my @res;
317
318   diag "? logop\n" if $DEBUG;
319
320   my $op = $op->first;
321   my ($r1, $l1) = $self->inspect($op);
322   return $r1, $l1 if $r1 and zero $l1;
323   my $c = count $l1;
324
325   $op = $op->sibling;
326   my ($r2, $l2) = $self->inspect($op);
327
328   $op = $op->sibling;
329   my ($r3, $l3);
330   if (null $op) {
331    # If the logop has no else branch, it can also return the *scalar* result of
332    # the conditional
333    $l3 = { 1 => $c };
334   } else {
335    ($r3, $l3) = $self->inspect($op);
336   }
337
338   my $r = add $r1, scale $c / 2, add $r2, $r3;
339   my $l = scale $c / 2, add $l2, $l3;
340   return $r, $l
341  }
342
343  return $self->inspect_kids($op);
344 }
345
346 sub inspect_kids {
347  my ($self, $op) = @_;
348
349  return undef, 0 unless $op->flags & OPf_KIDS;
350
351  $op = $op->first;
352  return undef, 0 if null $op;
353  if (name($op) eq 'pushmark') {
354   $op = $op->sibling;
355   return undef, 0 if null $op;
356  }
357
358  my ($r, @l);
359  my $c = 1;
360  for (; not null $op; $op = $op->sibling) {
361   my $n = name($op);
362   if ($n eq 'nextstate') {
363    @l  = ();
364    next;
365   }
366   if ($n eq 'lineseq') {
367    @l  = ();
368    $op = $op->first;
369    redo;
370   }
371   diag "> $n ($c)" if $DEBUG;
372   my ($rc, $lc) = $self->inspect($op);
373   $r = add $r, scale $c, $rc if defined $rc;
374   if ($rc and not defined $lc) {
375    @l = ();
376    last;
377   }
378   push @l, scale $c, $lc;
379   $c *= count $lc if defined $lc;
380  }
381
382  my $l = combine @l;
383
384  return $r, $l;
385 }
386
387 # Stolen from B::Deparse
388
389 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
390
391 sub gv_or_padgv {
392  my ($self, $op) = @_;
393  if (class($op) eq 'PADOP') {
394   return $self->padval($op->padix)
395  } else { # class($op) eq "SVOP"
396   return $op->gv;
397  }
398 }
399
400 sub const_sv {
401  my ($self, $op) = @_;
402  my $sv = $op->sv;
403  # the constant could be in the pad (under useithreads)
404  $sv = $self->padval($op->targ) unless $$sv;
405  return $sv;
406 }
407
408 sub pp_entersub {
409  my ($self, $op) = @_;
410
411  $op = $op->first while $op->flags & OPf_KIDS;
412  return undef, 0 if null $op;
413  if (name($op) eq 'pushmark') {
414   $op = $op->sibling;
415   return undef, 0 if null $op;
416  }
417
418  my $r;
419  my $c = 1;
420  for (; not null $op->sibling; $op = $op->sibling) {
421   my $n = name($op);
422   next if $n eq 'nextstate';
423   diag "* $n" if $DEBUG;
424   my ($rc, $lc) = $self->inspect($op);
425   $r = add $r, scale $c, $rc if defined $rc;
426   if (zero $lc) {
427    $c = 1 - count $r;
428    return $r, $c ? { 0 => $c } : undef
429   }
430   $c *= count $lc;
431  }
432
433  if (name($op) eq 'rv2cv') {
434   my $n;
435   do {
436    $op = $op->first;
437    my $next = $op->sibling;
438    while (not null $next) {
439     $op   = $next;
440     $next = $next->sibling;
441    }
442    $n  = name($op)
443   } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
444   return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
445   local $self->{sub} = 1;
446   my ($rc, $lc) = $self->inspect($op);
447   return $r, scale $c, $lc;
448  } else {
449   # Method call ?
450   return $r, { 'list' => $c };
451  }
452 }
453
454 sub pp_gv {
455  my ($self, $op) = @_;
456
457  return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
458 }
459
460 sub pp_anoncode {
461  my ($self, $op) = @_;
462
463  return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
464 }
465
466 sub pp_goto {
467  my ($self, $op) = @_;
468
469  my $n = name($op);
470  while ($op->flags & OPf_KIDS) {
471   my $nop = $op->first;
472   my $nn  = name($nop);
473   if ($nn eq 'pushmark') {
474    $nop = $nop->sibling;
475    $nn  = name($nop);
476   }
477   if ($n eq 'rv2cv' and $nn eq 'gv') {
478    return $self->enter($self->gv_or_padgv($nop)->CV);
479   }
480   $op = $nop;
481   $n  = $nn;
482  }
483
484  return undef, 'list';
485 }
486
487 sub pp_const {
488  my ($self, $op) = @_;
489
490  return undef, 0 unless $op->isa('B::SVOP');
491
492  my $sv = $self->const_sv($op);
493  my $n  = 1;
494  my $c  = class($sv);
495  if ($c eq 'AV') {
496   $n = $sv->FILL + 1
497  } elsif ($c eq 'HV') {
498   $n = 2 * $sv->FILL
499  }
500
501  return undef, $n
502 }
503
504 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
505
506 sub pp_hslice;
507 *pp_hslice = *pp_aslice{CODE};
508
509 sub pp_lslice { $_[0]->inspect($_[1]->first) }
510
511 sub pp_rv2av {
512  my ($self, $op) = @_;
513  $op = $op->first;
514
515  my ($r, $l) = $self->inspect($op);
516  if (name($op) ne 'const') {
517   my $c = 1 - count $r;
518   $l = $c ? { list => $c } : 0;
519  }
520  return $r, $l; 
521 }
522
523 sub pp_aassign {
524  my ($self, $op) = @_;
525
526  $op = $op->first;
527
528  # Can't assign to return
529  my $l = ($self->inspect($op->sibling))[1];
530  return undef, $l if not exists $l->{list};
531
532  $self->inspect($op);
533 }
534
535 sub pp_leaveloop {
536  my ($self, $op) = @_;
537
538  diag "* leaveloop" if $DEBUG;
539
540  $op = $op->first;
541  my ($r1, $l1);
542  if (name($op) eq 'enteriter') {
543   ($r1, $l1) = $self->inspect($op);
544   return $r1, $l1 if $r1 and zero $l1;
545  }
546
547  $op = $op->sibling;
548  my $r = (name($op->first) eq 'and') ? ($self->inspect($op->first->first->sibling))[0]
549                                      : ($self->inspect($op))[0];
550  my $c = 1 - count $r;
551  diag "& leaveloop" if $DEBUG;
552  return $r, $c ? { 0 => $c } : undef;
553 }
554
555 sub pp_flip {
556  my ($self, $op) = @_;
557
558  $op = $op->first;
559  return $self->inspect($op) if name($op) ne 'range';
560
561  my ($r, $l);
562  my $begin = $op->first;
563  if (name($begin) eq 'const') {
564   my $end = $begin->sibling;
565   if (name($end) eq 'const') {
566    $begin = $self->const_sv($begin);
567    $end   = $self->const_sv($end);
568    {
569     no warnings 'numeric';
570     $begin = int ${$begin->object_2svref};
571     $end   = int ${$end->object_2svref};
572    }
573    return undef, $end - $begin + 1;
574   } else {
575    ($r, $l) = $self->inspect($end);
576   }
577  } else {
578   ($r, $l) = $self->inspect($begin);
579  }
580
581  my $c = 1 - count $r;
582  return $r, ($l && $c) ? { 'list' => $c } : undef
583 }
584
585 sub pp_grepwhile {
586  my ($self, $op) = @_;
587
588  $op = $op->first;
589  return $self->inspect($op) if name($op) ne 'grepstart';
590  $op = $op->first->sibling;
591
592  my ($r2, $l2) = $self->inspect($op->sibling);
593  return $r2, $l2 if $r2 and zero $l2;
594  diag Dumper [ $r2, $l2 ] if $DEBUG;
595  my $c = count $l2; # First one to happen
596
597  my ($r1, $l1) = $self->inspect($op);
598  diag Dumper [ $r1, $l1 ] if $DEBUG;
599  return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
600  return { 'list' => 1 }, undef if list $l2;
601
602  $l2 = { $l2 => 1 } unless ref $l2;
603  my $r = add $r2, scale $c,
604                    normalize
605                     add map { power $r1, $_, $l2->{$_} } keys %$l2;
606  $c = 1 - count $r;
607  return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
608 }
609
610 sub pp_mapwhile {
611  my ($self, $op) = @_;
612
613  $op = $op->first;
614  return $self->inspect($op) if name($op) ne 'mapstart';
615  $op = $op->first->sibling;
616
617  my ($r2, $l2) = $self->inspect($op->sibling);
618  return $r2, $l2 if $r2 and zero $l2;
619  my $c = count $l2; # First one to happen
620
621  my ($r1, $l1) = $self->inspect($op);
622  return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
623  diag Dumper [ [ $r1, $l1 ], [ $r2, $l2 ] ] if $DEBUG;
624
625  $l2 = { $l2 => 1 } unless ref $l2;
626  my $r = add $r2, scale $c,
627                    normalize
628                     add map { power $r1, $_, $l2->{$_} } keys %$l2;
629  $c = 1 - count $r;
630  my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
631  return $r, $l;
632 }
633
634 =head1 EXPORT
635
636 An object-oriented module shouldn't export any function, and so does this one.
637
638 =head1 CAVEATS
639
640 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
641
642 C<wantarray> isn't specialized when encountered in the optree.
643
644 =head1 DEPENDENCIES
645
646 L<perl> 5.8.1.
647
648 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).
649
650 =head1 AUTHOR
651
652 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
653
654 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
655
656 =head1 BUGS
657
658 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.
659
660 =head1 SUPPORT
661
662 You can find documentation for this module with the perldoc command.
663
664     perldoc Sub::Nary
665
666 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
667
668 =head1 ACKNOWLEDGEMENTS
669
670 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
671
672 =head1 COPYRIGHT & LICENSE
673
674 Copyright 2008 Vincent Pit, all rights reserved.
675
676 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
677
678 =cut
679
680 1; # End of Sub::Nary