]> git.vpit.fr Git - perl/modules/Sub-Nary.git/blob - lib/Sub/Nary.pm
We stole from B::Deparse, not Sub::Deparse
[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.01
20
21 =cut
22
23 our $VERSION;
24 BEGIN {
25  $VERSION  = '0.01';
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 $coderf>
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 * The C<'list'> state is absorbant in regard of all the other ones.
106
107 This is just a pedantic way to say that "list + fixed length = list".
108 That's why
109
110     sub listy {
111      return 1, simple(), @_
112     }
113
114 is considered as always returning an unbounded list.
115 The convolution law also does not behave the same when C<list> elements are involved : in the following example,
116
117     sub oneorlist {
118      if (rand < 0.1) {
119       return 1
120      } else {
121       return @_
122      }
123     }
124
125     sub composed {
126      return oneorlist(), oneorlist()
127     }
128
129 C<composed> returns C<2> scalars with probability C<1/2 * 1/2 = 1/4> and a C<list> with probability C<3/4>.
130
131 =back
132
133 =cut
134
135 BEGIN {
136  require XSLoader;
137  XSLoader::load(__PACKAGE__, $VERSION);
138 }
139
140 sub _check_self {
141  croak 'First argument isn\'t a valid ' . __PACKAGE__ . ' object'
142   unless ref $_[0] and $_[0]->isa(__PACKAGE__);
143 }
144
145 sub new {
146  my $class = shift;
147  $class = ref($class) || $class || __PACKAGE__;
148  bless { cache => { } }, $class;
149 }
150
151 sub flush {
152  my $self = shift;
153  _check_self($self);
154  $self->{cache} = { };
155  $self;
156 }
157
158 sub nary {
159  my $self = shift;
160  my $sub  = shift;
161
162  $self->{cv} = [ ];
163  return $self->enter(svref_2object($sub));
164 }
165
166 sub name ($) {
167  my $n = $_[0]->name;
168  $n eq 'null' ? substr(ppname($_[0]->targ), 3) : $n
169 }
170
171 sub combine {
172  reduce {{
173   my %res;
174   my $la = delete $a->{list};
175   my $lb = delete $b->{list};
176   if (defined $la || defined $lb) {
177    $la ||= 0;
178    $lb ||= 0;
179    $res{list} = $la + $lb - $la * $lb;
180   }
181   while (my ($ka, $va) = each %$a) {
182    $ka = int $ka;
183    while (my ($kb, $vb) = each %$b) {
184     my $key = $ka + int $kb;
185     $res{$key} += $va * $vb;
186    }
187   }
188   \%res
189  }} map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
190 }
191
192 sub add {
193  reduce {
194   $a->{$_} += $b->{$_} for keys %$b;
195   $a
196  } map { (ref) ? $_ : { $_ => 1 } } grep defined, @_;
197 }
198
199 my %ops;
200 $ops{$_} = 1      for scalops;
201 $ops{$_} = 0      for qw/stub nextstate/;
202 $ops{$_} = 1      for qw/padsv/;
203 $ops{$_} = 'list' for qw/padav/;
204 $ops{$_} = 'list' for qw/padhv rv2hv/;
205 $ops{$_} = 'list' for qw/padany flip match/;
206
207 sub enter {
208  my ($self, $cv) = @_;
209
210  my $op  = $cv->ROOT;
211  my $tag = tag($op);
212
213  return { %{$self->{cache}->{$tag}} } if exists $self->{cache}->{$tag};
214
215  # Anything can happen with recursion
216  for (@{$self->{cv}}) {
217   return 'list' if $tag == tag($_->ROOT);
218  }
219
220  unshift @{$self->{cv}}, $cv;
221  (my $r, undef) = $self->expect_any($op->first);
222  shift @{$self->{cv}};
223
224  $r = { $r => 1} unless ref $r;
225  my $total = sum values %$r;
226  $r = { map { $_ => $r->{$_} / $total } keys %$r };
227  $self->{cache}->{$tag} = { %$r };
228  return $r;
229 }
230
231 sub expect_return {
232  my ($self, $op) = @_;
233
234  return ($self->expect_list($op))[0] => 1 if name($op) eq 'return';
235
236  if ($op->flags & OPf_KIDS) {
237   for ($op = $op->first; not null $op; $op = $op->sibling) {
238    my ($p, $r) = $self->expect_return($op);
239    return $p => 1 if $r;
240   }
241  }
242
243  return;
244 }
245
246 sub expect_list {
247  my ($self, $op) = @_;
248
249  my $n = name($op);
250  my $meth = $self->can('pp_' . $n);
251  return $self->$meth($op) if $meth;
252  return $ops{$n} => 0 if exists $ops{$n};
253
254  if ($op->flags & OPf_KIDS) {
255   my @res = (0);
256   my ($p, $r);
257   for ($op = $op->first; not null $op; $op = $op->sibling) {
258    my $n = name($op);
259    next if $n eq 'pushmark';
260    if ($n eq 'nextstate'
261        and not null(($op = $op->sibling)->sibling)) {
262     ($p, $r) = $self->expect_return($op);
263     return $p => 1 if $r;
264    } else {
265     ($p, $r) = $self->expect_any($op);
266     return $p => 1 if $r;
267     push @res, $p;
268    }
269   }
270   return (combine @res) => 0;
271  }
272
273  return;
274 }
275
276 sub expect_any {
277  my ($self, $op) = @_;
278
279  return ($self->expect_list($op))[0] => 1 if name($op) eq 'return';
280
281  if (class($op) eq 'LOGOP') {
282   my @res;
283   my ($p, $r);
284
285   my $op   = $op->first;
286   ($p, $r) = $self->expect_return($op);
287   return $p => 1 if $r;
288
289   $op = $op->sibling;
290   push @res, ($self->expect_any($op))[0];
291
292   # If the logop has no else branch, it can also return the *scalar* result of
293   # the conditional
294   $op = $op->sibling;
295   if (null $op) {
296    push @res, 1;
297   } else {
298    push @res, ($self->expect_any($op))[0];
299   }
300
301   return (add @res) => 0;
302  }
303
304  return $self->expect_list($op);
305 }
306
307 # Stolen from B::Deparse
308
309 sub padval { $_[0]->{cv}->[0]->PADLIST->ARRAYelt(1)->ARRAYelt($_[1]) }
310
311 sub gv_or_padgv {
312  my ($self, $op) = @_;
313  if (class($op) eq 'PADOP') {
314   return $self->padval($op->padix)
315  } else { # class($op) eq "SVOP"
316   return $op->gv;
317  }
318 }
319
320 sub const_sv {
321  my ($self, $op) = @_;
322  my $sv = $op->sv;
323  # the constant could be in the pad (under useithreads)
324  $sv = $self->padval($op->targ) unless $$sv;
325  return $sv;
326 }
327
328 sub pp_entersub {
329  my ($self, $op, $exp) = @_;
330
331  my $next = $op;
332  while ($next->flags & OPf_KIDS) {
333   $next = $next->first;
334  }
335  while (not null $next) {
336   $op = $next;
337   my ($p, $r) = $self->expect_return($op, $exp);
338   return $p => 1 if $r;
339   $next = $op->sibling;
340  }
341
342  if (name($op) eq 'rv2cv') {
343   my $n;
344   do {
345    $op = $op->first;
346    my $next = $op->sibling;
347    while (not null $next) {
348     $op   = $next;
349     $next = $next->sibling;
350    }
351    $n  = name($op)
352   } while ($op->flags & OPf_KIDS and { map { $_ => 1 } qw/null leave/ }->{$n});
353   return 'list' unless { map { $_ => 1 } qw/gv refgen/ }->{$n};
354   local $self->{sub} = 1;
355   return $self->expect_any($op, $exp);
356  } else {
357   # Method call ?
358   return 'list';
359  }
360 }
361
362 sub pp_gv {
363  my ($self, $op) = @_;
364
365  return $self->{sub} ? $self->enter($self->gv_or_padgv($op)->CV) : 1
366 }
367
368 sub pp_anoncode {
369  my ($self, $op) = @_;
370
371  return $self->{sub} ? $self->enter($self->const_sv($op)) : 1
372 }
373
374 sub pp_goto {
375  my ($self, $op) = @_;
376
377  my $n = name($op);
378  while ($op->flags & OPf_KIDS) {
379   my $nop = $op->first;
380   my $nn  = name($nop);
381   if ($nn eq 'pushmark') {
382    $nop = $nop->sibling;
383    $nn  = name($nop);
384   }
385   if ($n eq 'rv2cv' and $nn eq 'gv') {
386    return $self->enter($self->gv_or_padgv($nop)->CV);
387   }
388   $op = $nop;
389   $n  = $nn;
390  }
391
392  return 'list';
393 }
394
395 sub pp_const {
396  my ($self, $op) = @_;
397
398  if (class($op) eq 'SVOP' and (my $sv = $self->const_sv($op))) {
399   my $c = class($sv);
400   if ($c eq 'AV') {
401    return $sv->FILL + 1;
402   } elsif ($c eq 'HV') {
403    return 2 * $sv->FILL;
404   }
405  }
406
407  return 1;
408 }
409
410 sub pp_aslice { $_[0]->expect_any($_[1]->first->sibling) }
411
412 sub pp_hslice;
413 *pp_hslice = *pp_aslice{CODE};
414
415 sub pp_lslice { $_[0]->expect_any($_[1]->first) }
416
417 sub pp_rv2av {
418  my ($self, $op) = @_;
419  $op = $op->first;
420
421  return (name($op) eq 'const') ? $self->expect_any($op) : 'list';
422 }
423
424 sub pp_aassign { $_[0]->expect_any($_[1]->first) }
425
426 sub pp_leaveloop { $_[0]->expect_return($_[1]->first->sibling) }
427
428 =head1 EXPORT
429
430 An object-oriented module shouldn't export any function, and so does this one.
431
432 =head1 CAVEATS
433
434 The algorithm may be pessimistic (things seen as C<list> while they are of fixed length) but not optimistic (the opposite, duh).
435
436 C<wantarray> isn't specialized when encountered in the optree.
437
438 =head1 DEPENDENCIES
439
440 L<perl> 5.8.1.
441
442 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).
443
444 =head1 AUTHOR
445
446 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
447
448 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
449
450 =head1 BUGS
451
452 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.
453
454 =head1 SUPPORT
455
456 You can find documentation for this module with the perldoc command.
457
458     perldoc Sub::Nary
459
460 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Nary>.
461
462 =head1 ACKNOWLEDGEMENTS
463
464 Thanks to Sebastien Aperghis-Tramoni for helping to name this module.
465
466 =head1 COPYRIGHT & LICENSE
467
468 Copyright 2008 Vincent Pit, all rights reserved.
469
470 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
471
472 =cut
473
474 1; # End of Sub::Nary