File Coverage

blib/lib/CPS.pm
Criterion Covered Total %
statement 126 128 98.4
branch 19 24 79.1
condition 2 2 100.0
subroutine 44 44 100.0
pod 10 17 58.8
total 201 215 93.4


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2008-2010 -- leonerd@leonerd.org.uk
5              
6             package CPS;
7              
8 16     16   268468 use strict;
  16         39  
  16         595  
9 16     16   81 use warnings;
  16         29  
  16         935  
10              
11             our $VERSION = '0.18';
12              
13 16     16   105 use Carp;
  16         42  
  16         2516  
14              
15             our @CPS_PRIMS = qw(
16             kloop
17             kwhile
18             kforeach
19             kdescendd kdescendb
20              
21             kpar
22             kpareach
23              
24             kseq
25             );
26              
27             our @EXPORT_OK = (
28             @CPS_PRIMS,
29             map( "g$_", @CPS_PRIMS ),
30              
31             qw(
32             liftk
33             dropk
34             ),
35             );
36              
37 16     16   84 use Exporter 'import';
  16         35  
  16         443  
38              
39 16     16   9408 use CPS::Governor::Simple;
  16         43  
  16         1576  
40              
41             # Don't hard-depend on Sub::Name since it's only a niceness for stack traces
42             BEGIN {
43 16 50   16   40 if( eval { require Sub::Name } ) {
  16         13554  
44 16         42514 *subname = \&Sub::Name::subname;
45             }
46             else {
47             # Ignore the name, return the CODEref
48 0         0 *subname = sub { return $_[1] };
  0         0  
49             }
50             }
51              
52             =head1 NAME
53              
54             C - manage flow of control in Continuation-Passing Style
55              
56             =head1 OVERVIEW
57              
58             The functions in this module implement or assist the writing of programs, or
59             parts of them, in Continuation Passing Style (CPS). Briefly, CPS is a style
60             of writing code where the normal call/return mechanism is replaced by explicit
61             "continuations", values passed in to functions which they should invoke, to
62             implement return behaviour. For more detail on CPS, see the SEE ALSO section.
63              
64             What this module implements is not in fact true CPS, as Perl does not natively
65             support the idea of a real continuation (such as is created by a co-routine).
66             Furthermore, for CPS to be efficient in languages that natively support it,
67             their runtimes typically implement a lot of optimisation of CPS code, which
68             the Perl interpreter would be unable to perform. Instead, CODE references are
69             passed around to stand in their place. While not particularly useful for most
70             regular cases, this becomes very useful whenever some form of asynchronous or
71             event-based programming is being used. Continuations passed in to the body
72             function of a control structure can be stored in the event handlers of the
73             asynchronous or event-driven framework, so that when they are invoked later,
74             the code continues, eventually arriving at its final answer at some point in
75             the future.
76              
77             In order for these examples to make sense, a fictional and simple
78             asynchronisation framework has been invented. The exact details of operation
79             should not be important, as it simply stands to illustrate the point. I hope
80             its general intention should be obvious. :)
81              
82             read_stdin_line( \&on_line ); # wait on a line from STDIN, then pass it
83             # to the handler function
84              
85             This module itself provides functions that manage the flow of control through
86             a continuation passing program. They do not directly facilitate the flow of
87             data through a program. That can be managed by lexical variables captured by
88             the closures passed around. See the EXAMPLES section.
89              
90             For CPS versions of data-flow functionals, such as C and C, see
91             also L.
92              
93             =head1 SYNOPSIS
94              
95             use CPS qw( kloop );
96              
97             kloop( sub {
98             my ( $knext, $klast ) = @_;
99              
100             print "Enter a number, or q to quit: ";
101              
102             read_stdin_line( sub {
103             my ( $first ) = @_;
104             chomp $first;
105              
106             return $klast->() if $first eq "q";
107              
108             print "Enter a second number: ";
109              
110             read_stdin_line( sub {
111             my ( $second ) = @_;
112              
113             print "The sum is " . ( $first + $second ) . "\n";
114              
115             $knext->();
116             } );
117             } );
118             },
119             sub { exit }
120             );
121              
122             =cut
123              
124             =head1 FUNCTIONS
125              
126             In all of the following functions, the C<\&body> function can provide results
127             by invoking its continuation / one of its continuations, either synchronously
128             or asynchronously at some point later (via some event handling or other
129             mechanism); the next invocation of C<\&body> will not take place until the
130             previous one exits if it is done synchronously.
131              
132             They all take the prefix C before the name of the regular perl keyword or
133             function they aim to replace. It is common in CPS code in other languages,
134             such as Scheme or Haskell, to store a continuation in a variable called C.
135             This convention is followed here.
136              
137             =cut
138              
139             =head2 kloop( \&body, $k )
140              
141             CPS version of perl's C loop. Repeatedly calls the C code
142             until it indicates the end of the loop, then invoke C<$k>.
143              
144             $body->( $knext, $klast )
145             $knext->()
146             $klast->()
147              
148             $k->()
149              
150             If C<$knext> is invoked, the body will be called again. If C<$klast> is
151             invoked, the continuation C<$k> is invoked.
152              
153             =head2 kwhile( \&body, $k )
154              
155             Compatibility synonym for C; it was renamed after version 0.10. New
156             code should use C instead.
157              
158             =cut
159              
160             sub _fix
161             {
162 112     112   213 my ( $func ) = @_;
163             sub {
164 89     89   173 unshift @_, _fix( $func );
165 89         306 goto &$func;
166 112         462 };
167             }
168              
169             sub gkloop
170             {
171 23     23 0 82 my ( $gov, $body, $k ) = @_;
172              
173             # We can't just call this as a method because we need to tailcall it
174             # Instead, keep a reference to the actual method so we can goto &$enter
175 23 50       223 my $enter = $gov->can('enter') or croak "Governor cannot ->enter";
176              
177             my $kfirst = _fix subname gkloop => sub {
178 89     89   118 my $knext = shift;
179              
180 89         109 my $sync = 1;
181 89         94 my $do_again;
182             $enter->( $gov, $body,
183             sub {
184 66 100       2955 if( $sync ) { $do_again=1 }
  60         210  
185 6         18 else { goto &$knext; }
186             },
187 23         1000 sub { @_ = (); goto &$k },
  23         56  
188 89         540 );
189 89         425 $sync = 0;
190              
191 89 100       394 if( $do_again ) {
192 60         149 $do_again = 0;
193 60         126 goto &$knext;
194             }
195 23         261 };
196              
197 23         101 goto &$kfirst;
198             }
199              
200             *gkwhile = \&gkloop;
201              
202             =head2 kforeach( \@items, \&body, $k )
203              
204             CPS version of perl's C loop. Calls the C code once for each
205             element in C<@items>, until either the items are exhausted or the C
206             invokes its C<$klast> continuation, then invoke C<$k>.
207              
208             $body->( $item, $knext, $klast )
209             $knext->()
210             $klast->()
211              
212             $k->()
213              
214             =cut
215              
216             sub gkforeach
217             {
218 10     10 0 1118 my ( $gov, $items, $body, $k ) = @_;
219              
220 10         16 my $idx = 0;
221              
222             gkloop( $gov,
223             sub {
224 35     35   58 my ( $knext, $klast ) = @_;
225 35 100       89 goto &$klast unless $idx < scalar @$items;
226 26         65 @_ =(
227             $items->[$idx++],
228             $knext,
229             $klast
230             );
231 26         69 goto &$body;
232             },
233 10         53 $k,
234             );
235             }
236              
237             =head2 kdescendd( $root, \&body, $k )
238              
239             CPS version of recursive descent on a tree-like structure, defined by a
240             function, C, which when given a node in the tree, yields a list of
241             child nodes.
242              
243             $body->( $node, $kmore )
244             $kmore->( @child_nodes )
245              
246             $k->()
247              
248             The first value to be passed into C is C<$root>.
249              
250             At each iteration, a node is given to the C function, and it is expected
251             to pass a list of child nodes into its C<$kmore> continuation. These will then
252             be iterated over, in the order given. The tree-like structure is visited
253             depth-first, descending fully into one subtree of a node before moving on to
254             the next.
255              
256             This function does not provide a way for the body to accumulate a resultant
257             data structure to pass into its own continuation. The body is executed simply
258             for its side-effects and its continuation is invoked with no arguments. A
259             variable of some sort should be shared between the body and the continuation
260             if this is required.
261              
262             =cut
263              
264             sub gkdescendd
265             {
266 1     1 0 3 my ( $gov, $root, $body, $k ) = @_;
267              
268 1         3 my @stack = ( $root );
269              
270             gkloop( $gov,
271             sub {
272 9     9   17 my ( $knext, $klast ) = @_;
273             @_ = (
274             shift @stack,
275             sub {
276 9         47 unshift @stack, @_;
277              
278 9 100       24 goto &$knext if @stack;
279 1         3 goto &$klast;
280             },
281 9         37 );
282 9         27 goto &$body;
283             },
284 1         7 $k,
285             );
286             }
287              
288             =head2 kdescendb( $root, \&body, $k )
289              
290             A breadth-first variation of C. This function visits each child
291             node of the parent, before iterating over all of these nodes's children,
292             recursively until the bottom of the tree.
293              
294             =cut
295              
296             sub gkdescendb
297             {
298 1     1 0 2 my ( $gov, $root, $body, $k ) = @_;
299              
300 1         2 my @queue = ( $root );
301              
302             gkloop( $gov,
303             sub {
304 9     9   12 my ( $knext, $klast ) = @_;
305             @_ = (
306             shift @queue,
307             sub {
308 9         41 push @queue, @_;
309              
310 9 100       24 goto &$knext if @queue;
311 1         3 goto &$klast;
312             },
313 9         29 );
314 9         22 goto &$body;
315             },
316 1         6 $k,
317             );
318             }
319              
320             =head2 kpar( @bodies, $k )
321              
322             This CPS function takes a list of function bodies and calls them all
323             immediately. Each is given its own continuation. Once every body has invoked
324             its continuation, the main continuation C<$k> is invoked.
325              
326             $body->( $kdone )
327             $kdone->()
328              
329             $k->()
330              
331             This allows running multiple operations in parallel, and waiting for them all
332             to complete before continuing. It provides in a CPS form functionality
333             similar to that provided in a more object-oriented fashion by modules such as
334             L or L.
335              
336             =cut
337              
338             sub gkpar
339             {
340 5     5 0 12 my ( $gov, @bodies ) = @_;
341 5         6 my $k = pop @bodies;
342              
343 5 50       42 $gov->can('enter') or croak "Governor cannot ->enter";
344              
345 5         8 my $sync = 1;
346 5         5 my @outstanding;
347             my $kdone = sub {
348 14 100   14   32 return if $sync;
349 9   100     34 $_ and return for @outstanding;
350 5         11 goto &$k;
351 5         15 };
352              
353             gkforeach( $gov, [ 0 .. $#bodies ],
354             sub {
355 9     9   10 my ( $idx, $knext ) = @_;
356 9         13 $outstanding[$idx]++;
357             $gov->enter( $bodies[$idx], sub {
358 9         1801 $outstanding[$idx]--;
359 9         12 @_ = ();
360 9         16 goto &$kdone;
361 9         47 } );
362 9         32 goto &$knext;
363             },
364             sub {
365 5     5   4 $sync = 0;
366 5         7 @_ = ();
367 5         6 goto &$kdone;
368             }
369 5         40 );
370             }
371              
372             =head2 kpareach( \@items, \&body, $k )
373              
374             This CPS function takes a list of items and a function body, and calls the
375             body immediately once for each item in the list. Each invocation is given its
376             own continuation. Once every body has invoked its continuation, the main
377             continuation C<$k> is invoked.
378              
379             $body->( $item, $kdone )
380             $kdone->()
381              
382             $k->()
383              
384             This is similar to C, except that the body is started concurrently
385             for all items in the list list, rather than each item waiting for the previous
386             to finish.
387              
388             =cut
389              
390             sub gkpareach
391             {
392 2     2 0 4 my ( $gov, $items, $body, $k ) = @_;
393              
394 4         7 gkpar( $gov,
395             (map {
396 2         4 my $item = $_;
397             sub {
398 4     4   9 unshift @_, $item;
399 4         7 goto &$body
400             }
401 4         17 } @$items),
402             $k
403             );
404             }
405              
406             =head2 kseq( @bodies, $k )
407              
408             This CPS function takes a list of function bodies and calls them each, one at
409             a time in sequence. Each is given a continuation to invoke, which will cause
410             the next body to be invoked. When the last body has invoked its continuation,
411             the main continuation C<$k> is invoked.
412              
413             $body->( $kdone )
414             $kdone->()
415              
416             $k->()
417              
418             A benefit of this is that it allows a long operation that uses many
419             continuation "pauses", to be written without code indenting further and
420             further to the right. Another is that it allows easy skipping of conditional
421             parts of a computation, which would otherwise be tricky to write in a CPS
422             form. See the EXAMPLES section.
423              
424             =cut
425              
426             sub gkseq
427             {
428 2     2 0 5 my ( $gov, @bodies ) = @_;
429 2         4 my $k = pop @bodies;
430              
431 2 50       21 my $enter = $gov->can('enter') or croak "Governor cannot ->enter";
432              
433 2         6 while( @bodies ) {
434 4         5 my $nextk = $k;
435 4         6 my $b = pop @bodies;
436             $k = sub {
437 4     4   1029 @_ = ( $gov, $b, $nextk );
438 4         20 goto &$enter;
439 4         19 };
440             }
441              
442 2         4 @_ = ();
443 2         6 goto &$k;
444             }
445              
446             =head1 GOVERNORS
447              
448             All of the above functions are implemented using a loop which repeatedly calls
449             the body function until some terminating condition. By controlling the way
450             this loop re-invokes itself, a program can control the behaviour of the
451             functions.
452              
453             For every one of the above functions, there also exists a variant which takes
454             a L object as its first argument. These functions use the
455             governor object to control their iteration.
456              
457             kloop( \&body, $k )
458             gkloop( $gov, \&body, $k )
459              
460             kforeach( \@items, \&body, $k )
461             gkforeach( $gov, \@items, \&body, $k )
462              
463             etc...
464              
465             In this way, other governor objects can be constructed which have different
466             running properties; such as interleaving iterations of their loop with other
467             IO activity in an event-driven framework, or giving rate-limitation control on
468             the speed of iteration of the loop.
469              
470             =cut
471              
472             # The above is a lie. The basic functions provided are actually the gk*
473             # versions; we wrap these to make the normal k* functions by passing a simple
474             # governor.
475             sub _governate
476             {
477 153     153   232 my $pkg = caller;
478 153         227 my ( $func, $name ) = @_;
479              
480 153         500 my $default_gov = CPS::Governor::Simple->new;
481              
482 16     16   118 no strict 'refs';
  16         33  
  16         6125  
483              
484 153 50       729 my $code = $pkg->can( $func ) or croak "$pkg cannot $func()";
485 153         1043 *{$pkg."::$name"} = subname $name => sub {
486 22     22 1 9359 unshift @_, $default_gov;
        22 1    
        22 1    
        5 1    
        5 1    
        22 1    
        5 1    
        22 1    
        5      
        22      
        22      
        22      
        5      
        22      
487 22         107 goto &$code;
488 153         982 };
489             }
490              
491             _governate "g$_" => $_ for @CPS_PRIMS;
492              
493             =head1 CPS UTILITIES
494              
495             These function names do not begin with C because they are not themselves
496             CPS primatives, but may be useful in CPS-oriented code.
497              
498             =cut
499              
500             =head2 $kfunc = liftk { BLOCK }
501              
502             =head2 $kfunc = liftk( \&func )
503              
504             Returns a new CODE reference to a CPS-wrapped version of the code block or
505             passed CODE reference. When C<$kfunc> is invoked, the function C<&func> is
506             called in list context, being passed all the arguments given to C<$kfunc>
507             apart from the last, expected to be its continuation. When C<&func> returns,
508             the result is passed into the continuation.
509              
510             $kfunc->( @func_args, $k )
511             $k->( @func_ret )
512              
513             The following are equivalent
514              
515             print func( 1, 2, 3 );
516              
517             my $kfunc = liftk( \&func );
518             $kfunc->( 1, 2, 3, sub { print @_ } );
519              
520             Note that the returned wrapper function only has one continuation slot in its
521             arguments. It therefore cannot be used as the body for C,
522             C or C, because these pass two continuations. There
523             does not exist a "natural" way to lift a normal call/return function into a
524             CPS function which requires more than one continuation, because there is no
525             way to distinguish the different named returns.
526              
527             =cut
528              
529             sub liftk(&)
530             {
531 3     3 1 1418 my ( $code ) = @_;
532              
533             return sub {
534 3     3   1106 my $k = pop;
535 3         13 @_ = $code->( @_ );
536 3         23 goto &$k;
537 3         21 };
538             }
539              
540             =head2 $func = dropk { BLOCK } $kfunc
541              
542             =head2 $func = dropk $waitfunc, $kfunc
543              
544             Returns a new CODE reference to a plain call/return version of the passed
545             CPS-style CODE reference. When the returned ("dropped") function is called,
546             it invokes the passed CPS function, then waits for it to invoke its
547             continuation. When it does, the list that was passed to the continuation is
548             returned by the dropped function. If called in scalar context, only the first
549             value in the list is returned.
550              
551             $kfunc->( @func_args, $k )
552             $k->( @func_ret )
553              
554             $waitfunc->()
555              
556             @func_ret = $func->( @func_args )
557              
558             Given the following trivial CPS function:
559              
560             $kadd = sub { $_[2]->( $_[0] + $_[1] ) };
561              
562             The following are equivalent
563              
564             $kadd->( 10, 20, sub { print "The total is $_[0]\n" } );
565              
566             $add = dropk { } $kadd;
567             print "The total is ".$add->( 10, 20 )."\n";
568              
569             In the general case the CPS function hasn't yet invoked its continuation by
570             the time it returns (such as would be the case when using any sort of
571             asynchronisation or event-driven framework). For C to actually work in
572             this situation, it requires a way to run the event framework, to cause it to
573             process events until the continuation has been invoked.
574              
575             This is provided by the block, or the first passed CODE reference. When the
576             returned function is invoked, it repeatedly calls the block or wait function,
577             until the CPS function has invoked its continuation.
578              
579             =cut
580              
581             sub dropk(&$)
582             {
583 2     2 1 580 my ( $waitfunc, $kfunc ) = @_;
584              
585             return sub {
586 3     3   1738 my @result;
587             my $done;
588              
589 3         21 $kfunc->( @_, sub { @result = @_; $done = 1 } );
  3         14  
  3         8  
590              
591 3         35 while( !$done ) {
592 2         7 $waitfunc->();
593             }
594              
595 3 100       12 return wantarray ? @result : $result[0];
596             }
597 2         13 }
598              
599             =head1 EXAMPLES
600              
601             =head2 Returning Data From Functions
602              
603             No facilities are provided directly to return data from CPS body functions in
604             C, C and C. Instead, normal lexical variable capture may
605             be used here.
606              
607             my $bat;
608             my $ball;
609              
610             kpar(
611             sub {
612             my ( $k ) = @_;
613             get_bat( on_bat => sub { $bat = shift; goto &$k } );
614             },
615             sub {
616             my ( $k ) = @_;
617             serve_ball( on_ball => sub { $ball = shift; goto &$k } );
618             },
619              
620             sub {
621             $bat->hit( $ball );
622             },
623             );
624              
625             The body function can set the value of a variable that it and its final
626             continuation both capture.
627              
628             =head2 Using C For Conditionals
629              
630             Consider the call/return style of code
631              
632             A();
633             if( $maybe ) {
634             B();
635             }
636             C();
637              
638             We cannot easily write this in CPS form without naming C twice
639              
640             kA( sub {
641             $maybe ?
642             kB( sub { kC() } ) :
643             kC();
644             } );
645              
646             While not so problematic here, it could get awkward if C were in fact a large
647             code block, or if more than a single conditional were employed in the logic; a
648             likely scenario. A further issue is that the logical structure becomes much
649             harder to read.
650              
651             Using C allows us to name the continuation so each arm of C can
652             invoke it indirectly.
653              
654             kseq(
655             \&kA,
656             sub { my $k = shift; $maybe ? kB( $k ) : goto &$k; },
657             \&kC
658             );
659              
660             =head1 SEE ALSO
661              
662             =over 4
663              
664             =item *
665              
666             L - functional utilities in Continuation-Passing Style
667              
668             =item *
669              
670             L on wikipedia
671              
672             =item *
673              
674             L - co-routines in Perl
675              
676             =back
677              
678             =head1 ACKNOWLEDGEMENTS
679              
680             Matt S. Trout (mst) - for the inspiration of C
681             and with apologies to for naming of the said. ;)
682              
683             =head1 AUTHOR
684              
685             Paul Evans
686              
687             =cut
688              
689             0x55AA;