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