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