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