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