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