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