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