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