]> git.vpit.fr Git - perl/modules/Sub-Nary.git/blob - lib/Sub/Nary.pm
Complete rewrite. Make the inspect process return both the ret state and the last...
[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 sum/;
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 count ($) {
196  my $r = $_[0];
197  return 0 unless defined $r;
198  return 1 unless ref $r;
199  sum values %$r;
200 }
201
202 sub normalize ($) {
203  my $r = $_[0];
204  return unless defined $r;
205  return { 0 => 1 } unless keys %$r;
206  my $total = count $r;
207  return { map { $_ => $r->{$_} / $total } keys %$r };
208 }
209
210 sub scale {
211  my ($c, $r) = @_;
212  return unless defined $r;
213  return (ref $r) ? { map { $_ => $r->{$_} * $c } keys %$r } : { $r => $c };
214 }
215
216 sub combine {
217  reduce {{
218   my %res;
219   my $la = delete $a->{list};
220   my $lb = delete $b->{list};
221   if (defined $la || defined $lb) {
222    $la ||= 0;
223    $lb ||= 0;
224    $res{list} = $la + $lb - $la * $lb;
225   }
226   while (my ($ka, $va) = each %$a) {
227    $ka = int $ka;
228    while (my ($kb, $vb) = each %$b) {
229     my $key = $ka + int $kb;
230     $res{$key} += $va * $vb;
231    }
232   }
233   \%res
234  }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
235 }
236
237 sub power {
238  my ($p, $n, $c) = @_;
239  return unless defined $p;
240  return { 0 => $c } unless $n;
241  if ($n eq 'list') {
242   my $z = delete $p->{0};
243   return { 'list' => $c } unless $z;
244   return { 0      => $c } if $z == 1;
245   return { 0 => $c * $z, list => $c * (1 - $z) };
246  }
247  my $r = combine map { { %$p } } 1 .. $n;
248  $r->{$_} *= $c for keys %$r;
249  return $r;
250 }
251
252 sub add {
253  reduce {
254   $a->{$_} += $b->{$_} for keys %$b;
255   $a
256  } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
257 }
258
259 my %ops;
260
261 $ops{$_} = 1      for scalops;
262 $ops{$_} = 0      for qw/stub nextstate pushmark iter unstack/;
263 $ops{$_} = 1      for qw/padsv/;
264 $ops{$_} = 'list' for qw/padav/;
265 $ops{$_} = 'list' for qw/padhv rv2hv/;
266 $ops{$_} = 'list' for qw/padany/;
267 $ops{$_} = 'list' for qw/match entereval readline/;
268
269 $ops{each}      = { 0 => 0.5, 2 => 0.5 };
270 $ops{stat}      = { 0 => 0.5, 13 => 0.5 };
271
272 $ops{caller}    = sub { my @a = caller 0; scalar @a }->();
273 $ops{localtime} = do { my @a = localtime; scalar @a };
274 $ops{gmtime}    = do { my @a = gmtime; scalar @a };
275
276 $ops{$_} = { 0 => 0.5, 10 => 0.5 } for map "gpw$_", qw/nam uid ent/;
277 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for map "ggr$_", qw/nam gid ent/;
278 $ops{$_} = 'list'                  for qw/ghbyname ghbyaddr ghostent/;
279 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for qw/gnbyname gnbyaddr gnetent/;
280 $ops{$_} = { 0 => 0.5, 3 => 0.5 }  for qw/gpbyname gpbynumber gprotoent/;
281 $ops{$_} = { 0 => 0.5, 4 => 0.5 }  for qw/gsbyname gsbyport gservent/;
282
283 sub enter {
284  my ($self, $cv) = @_;
285
286  return undef, 'list' if class($cv) ne 'CV';
287  my $op  = $cv->ROOT;
288  my $tag = tag($op);
289
290  return undef, { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
291
292  # Anything can happen with recursion
293  for (@{$self->{cv}}) {
294   return undef, 'list' if $tag == tag($_->ROOT);
295  }
296
297  unshift @{$self->{cv}}, $cv;
298  my $r = add $self->inspect($op->first);
299  shift @{$self->{cv}};
300
301  $r = { $r => 1 } unless ref $r;
302  $self->{cache}->{$tag} = { %$r };
303  return undef, $r;
304 }
305
306 sub inspect {
307  my ($self, $op) = @_;
308
309  my $n = name($op);
310  diag "@ $n" if $DEBUG;
311  return add($self->inspect_kids($op)), undef if $n eq 'return';
312
313  my $meth = $self->can('pp_' . $n);
314  return $self->$meth($op) if $meth;
315
316  if (exists $ops{$n}) {
317   my $l = $ops{$n};
318   $l = { %$l } if ref $l;
319   return undef, $l;
320  }
321
322  if (class($op) eq 'LOGOP' and not null $op->first) {
323   my @res;
324
325   diag "? logop\n" if $DEBUG;
326
327   my $op = $op->first;
328   my ($r1, $l1) = $self->inspect($op);
329   return $r1, $l1 if $r1 and zero $l1;
330   my $c = count $l1;
331
332   $op = $op->sibling;
333   my ($r2, $l2) = $self->inspect($op);
334
335   $op = $op->sibling;
336   my ($r3, $l3);
337   if (null $op) {
338    # If the logop has no else branch, it can also return the *scalar* result of
339    # the conditional
340    $l3 = { 1 => $c };
341   } else {
342    ($r3, $l3) = $self->inspect($op);
343   }
344
345   my $r = add $r1, scale $c / 2, add $r2, $r3;
346   my $l = scale $c / 2, add $l2, $l3;
347   return $r, $l
348  }
349
350  return $self->inspect_kids($op);
351 }
352
353 sub inspect_kids {
354  my ($self, $op) = @_;
355
356  return undef, 0 unless $op->flags & OPf_KIDS;
357
358  $op = $op->first;
359  return undef, 0 if null $op;
360  if (name($op) eq 'pushmark') {
361   $op = $op->sibling;
362   return undef, 0 if null $op;
363  }
364
365  my ($r, @l);
366  my $c = 1;
367  for (; not null $op; $op = $op->sibling) {
368   my $n = name($op);
369   if ($n eq 'nextstate') {
370    @l  = ();
371    next;
372   }
373   if ($n eq 'lineseq') {
374    @l  = ();
375    $op = $op->first;
376    redo;
377   }
378   diag "> $n ($c)" if $DEBUG;
379   my ($rc, $lc) = $self->inspect($op);
380   $r = add $r, scale $c, $rc if defined $rc;
381   if ($rc and not defined $lc) {
382    @l = ();
383    last;
384   }
385   push @l, scale $c, $lc;
386   $c *= count $lc if defined $lc;
387  }
388
389  my $l = combine @l;
390
391  return $r, $l;
392 }
393
394 # Stolen from B::Deparse
395
396 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
397
398 sub gv_or_padgv {
399  my ($self, $op) = @_;
400  if (class($op) eq 'PADOP') {
401   return $self->padval($op->padix)
402  } else { # class($op) eq "SVOP"
403   return $op->gv;
404  }
405 }
406
407 sub const_sv {
408  my ($self, $op) = @_;
409  my $sv = $op->sv;
410  # the constant could be in the pad (under useithreads)
411  $sv = $self->padval($op->targ) unless $$sv;
412  return $sv;
413 }
414
415 sub pp_entersub {
416  my ($self, $op) = @_;
417
418  $op = $op->first while $op->flags & OPf_KIDS;
419  return undef, 0 if null $op;
420  if (name($op) eq 'pushmark') {
421   $op = $op->sibling;
422   return undef, 0 if null $op;
423  }
424
425  my $r;
426  my $c = 1;
427  for (; not null $op->sibling; $op = $op->sibling) {
428   my $n = name($op);
429   next if $n eq 'nextstate';
430   diag "* $n" if $DEBUG;
431   my ($rc, $lc) = $self->inspect($op);
432   $r = add $r, scale $c, $rc if defined $rc;
433   if (zero $lc) {
434    $c = 1 - count $r;
435    return $r, $c ? { 0 => $c } : undef
436   }
437   $c *= count $lc;
438  }
439
440  if (name($op) eq 'rv2cv') {
441   my $n;
442   do {
443    $op = $op->first;
444    my $next = $op->sibling;
445    while (not null $next) {
446     $op   = $next;
447     $next = $next->sibling;
448    }
449    $n  = name($op)
450   } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
451   return 'list', undef unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
452   local $self->{sub} = 1;
453   my ($rc, $lc) = $self->inspect($op);
454   return $r, scale $c, $lc;
455  } else {
456   # Method call ?
457   return $r, { 'list' => $c };
458  }
459 }
460
461 sub pp_gv {
462  my ($self, $op) = @_;
463
464  return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : (undef, 1)
465 }
466
467 sub pp_anoncode {
468  my ($self, $op) = @_;
469
470  return $self->{sub} ? $self->enter($self->const_sv($op)) : (undef, 1)
471 }
472
473 sub pp_goto {
474  my ($self, $op) = @_;
475
476  my $n = name($op);
477  while ($op->flags & OPf_KIDS) {
478   my $nop = $op->first;
479   my $nn  = name($nop);
480   if ($nn eq 'pushmark') {
481    $nop = $nop->sibling;
482    $nn  = name($nop);
483   }
484   if ($n eq 'rv2cv' and $nn eq 'gv') {
485    return $self->enter($self->gv_or_padgv($nop)->CV);
486   }
487   $op = $nop;
488   $n  = $nn;
489  }
490
491  return undef, 'list';
492 }
493
494 sub pp_const {
495  my ($self, $op) = @_;
496
497  return undef, 0 unless $op->isa('B::SVOP');
498
499  my $sv = $self->const_sv($op);
500  my $n  = 1;
501  my $c  = class($sv);
502  if ($c eq 'AV') {
503   $n = $sv->FILL + 1
504  } elsif ($c eq 'HV') {
505   $n = 2 * $sv->FILL
506  }
507
508  return undef, $n
509 }
510
511 sub pp_aslice { $_[0]->inspect($_[1]->first->sibling) }
512
513 sub pp_hslice;
514 *pp_hslice = *pp_aslice{CODE};
515
516 sub pp_lslice { $_[0]->inspect($_[1]->first) }
517
518 sub pp_rv2av {
519  my ($self, $op) = @_;
520  $op = $op->first;
521
522  my ($r, $l) = $self->inspect($op);
523  if (name($op) ne 'const') {
524   my $c = 1 - count $r;
525   $l = $c ? { list => $c } : 0;
526  }
527  return $r, $l; 
528 }
529
530 sub pp_aassign {
531  my ($self, $op) = @_;
532
533  $op = $op->first;
534
535  # Can't assign to return
536  my $l = ($self->inspect($op->sibling))[1];
537  return undef, $l if not exists $l->{list};
538
539  $self->inspect($op);
540 }
541
542 sub pp_leaveloop {
543  my ($self, $op) = @_;
544
545  diag "* leaveloop" if $DEBUG;
546
547  $op = $op->first;
548  my ($r1, $l1);
549  if (name($op) eq 'enteriter') {
550   ($r1, $l1) = $self->inspect($op);
551   return $r1, $l1 if $r1 and zero $l1;
552  }
553
554  $op = $op->sibling;
555  my $r = (name($op->first) eq 'and') ? ($self->inspect($op->first->first->sibling))[0]
556                                      : ($self->inspect($op))[0];
557  my $c = 1 - count $r;
558  diag "& leaveloop" if $DEBUG;
559  return $r, $c ? { 0 => $c } : undef;
560 }
561
562 sub pp_flip {
563  my ($self, $op) = @_;
564
565  $op = $op->first;
566  return $self->inspect($op) if name($op) ne 'range';
567
568  my ($r, $l);
569  my $begin = $op->first;
570  if (name($begin) eq 'const') {
571   my $end = $begin->sibling;
572   if (name($end) eq 'const') {
573    $begin = $self->const_sv($begin);
574    $end   = $self->const_sv($end);
575    {
576     no warnings 'numeric';
577     $begin = int ${$begin->object_2svref};
578     $end   = int ${$end->object_2svref};
579    }
580    return undef, $end - $begin + 1;
581   } else {
582    ($r, $l) = $self->inspect($end);
583   }
584  } else {
585   ($r, $l) = $self->inspect($begin);
586  }
587
588  my $c = 1 - count $r;
589  return $r, ($l && $c) ? { 'list' => $c } : undef
590 }
591
592 sub pp_grepwhile {
593  my ($self, $op) = @_;
594
595  $op = $op->first;
596  return $self->inspect($op) if name($op) ne 'grepstart';
597  $op = $op->first->sibling;
598
599  my ($r2, $l2) = $self->inspect($op->sibling);
600  return $r2, $l2 if $r2 and zero $l2;
601  diag Dumper [ $r2, $l2 ] if $DEBUG;
602  my $c = count $l2; # First one to happen
603
604  my ($r1, $l1) = $self->inspect($op);
605  diag Dumper [ $r1, $l1 ] if $DEBUG;
606  return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
607  return { 'list' => 1 }, undef if list $l2;
608
609  $l2 = { $l2 => 1 } unless ref $l2;
610  my $r = add $r2, scale $c,
611                    normalize
612                     add map { power $r1, $_, $l2->{$_} } keys %$l2;
613  $c = 1 - count $r;
614  return $r, $c ? { ((zero $l2) ? 0 : 'list') => $c } : undef;
615 }
616
617 sub pp_mapwhile {
618  my ($self, $op) = @_;
619
620  $op = $op->first;
621  return $self->inspect($op) if name($op) ne 'mapstart';
622  $op = $op->first->sibling;
623
624  my ($r2, $l2) = $self->inspect($op->sibling);
625  return $r2, $l2 if $r2 and zero $l2;
626  my $c = count $l2; # First one to happen
627
628  my ($r1, $l1) = $self->inspect($op);
629  return (add $r2, scale $c, $r1), undef if $r1 and zero $l1 and not zero $l2;
630  diag Dumper [ [ $r1, $l1 ], [ $r2, $l2 ] ] if $DEBUG;
631
632  $l2 = { $l2 => 1 } unless ref $l2;
633  my $r = add $r2, scale $c,
634                    normalize
635                     add map { power $r1, $_, $l2->{$_} } keys %$l2;
636  $c = 1 - count $r;
637  my $l = scale $c, normalize add map { power $l1, $_, $l2->{$_} } keys %$l2;
638  return $r, $l;
639 }
640
641 =head1 EXPORT
642
643 An object-oriented module shouldn't export any function, and so does this one.
644
645 =head1 CAVEATS
646
647 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
648
649 C<wantarray> isn't specialized when encountered in the optree.
650
651 =head1 DEPENDENCIES
652
653 L<perl> 5.8.1.
654
655 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).
656
657 =head1 AUTHOR
658
659 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
660
661 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
662
663 =head1 BUGS
664
665 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.
666
667 =head1 SUPPORT
668
669 You can find documentation for this module with the perldoc command.
670
671     perldoc Sub::Nary
672
673 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
674
675 =head1 ACKNOWLEDGEMENTS
676
677 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
678
679 =head1 COPYRIGHT & LICENSE
680
681 Copyright 2008 Vincent Pit, all rights reserved.
682
683 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
684
685 =cut
686
687 1; # End of Sub::Nary