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