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