]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - README
This is 0.16
[perl/modules/Scope-Upper.git] / README
1 NAME
2     Scope::Upper - Act on upper scopes.
3
4 VERSION
5     Version 0.16
6
7 SYNOPSIS
8     "reap", "localize", "localize_elem", "localize_delete" and "WORDS" :
9
10         package Scope;
11
12         use Scope::Upper qw<reap localize localize_elem localize_delete :words>;
13
14         sub new {
15          my ($class, $name) = @_;
16
17          localize '$tag' => bless({ name => $name }, $class) => UP;
18
19          reap { print Scope->tag->name, ": end\n" } UP;
20         }
21
22         # Get the tag stored in the caller namespace
23         sub tag {
24          my $l   = 0;
25          my $pkg = __PACKAGE__;
26          $pkg    = caller $l++ while $pkg eq __PACKAGE__;
27
28          no strict 'refs';
29          ${$pkg . '::tag'};
30         }
31
32         sub name { shift->{name} }
33
34         # Locally capture warnings and reprint them with the name prefixed
35         sub catch {
36          localize_elem '%SIG', '__WARN__' => sub {
37           print Scope->tag->name, ': ', @_;
38          } => UP;
39         }
40
41         # Locally clear @INC
42         sub private {
43          for (reverse 0 .. $#INC) {
44           # First UP is the for loop, second is the sub boundary
45           localize_delete '@INC', $_ => UP UP;
46          }
47         }
48
49         ...
50
51         package UserLand;
52
53         {
54          Scope->new("top");      # initializes $UserLand::tag
55
56          {
57           Scope->catch;
58           my $one = 1 + undef;   # prints "top: Use of uninitialized value..."
59
60           {
61            Scope->private;
62            eval { require Cwd };
63            print $@;             # prints "Can't locate Cwd.pm in @INC (@INC contains:) at..."
64           }
65
66           require Cwd;           # loads Cwd.pm
67          }
68
69         }                        # prints "top: done"
70
71     "unwind" and "want_at" :
72
73         package Try;
74
75         use Scope::Upper qw<unwind want_at :words>;
76
77         sub try (&) {
78          my @result = shift->();
79          my $cx = SUB UP; # Point to the sub above this one
80          unwind +(want_at($cx) ? @result : scalar @result) => $cx;
81         }
82
83         ...
84
85         sub zap {
86          try {
87           my @things = qw<a b c>;
88           return @things; # returns to try() and then outside zap()
89           # not reached
90          };
91          # not reached
92         }
93
94         my @stuff = zap(); # @stuff contains qw<a b c>
95         my $stuff = zap(); # $stuff contains 3
96
97     "uplevel" :
98
99         package Uplevel;
100
101         use Scope::Upper qw<uplevel CALLER>;
102
103         sub target {
104          faker(@_);
105         }
106
107         sub faker {
108          uplevel {
109           my $sub = (caller 0)[3];
110           print "$_[0] from $sub()";
111          } @_ => CALLER(1);
112         }
113
114         target('hello'); # "hello from Uplevel::target()"
115
116 DESCRIPTION
117     This module lets you defer actions *at run-time* that will take place
118     when the control flow returns into an upper scope. Currently, you can:
119
120     *   hook an upper scope end with "reap" ;
121
122     *   localize variables, array/hash values or deletions of elements in
123         higher contexts with respectively "localize", "localize_elem" and
124         "localize_delete" ;
125
126     *   return values immediately to an upper level with "unwind", and know
127         which context was in use then with "want_at" ;
128
129     *   execute a subroutine in the context of an upper subroutine stack
130         frame with "uplevel".
131
132 FUNCTIONS
133     In all those functions, $context refers to the target scope.
134
135     You have to use one or a combination of "WORDS" to build the $context
136     passed to these functions. This is needed in order to ensure that the
137     module still works when your program is ran in the debugger. The only
138     thing you can assume is that it is an *absolute* indicator of the frame,
139     which means that you can safely store it at some point and use it when
140     needed, and it will still denote the original scope.
141
142   "reap $callback, $context"
143     Adds a destructor that calls $callback (in void context) when the upper
144     scope represented by $context ends.
145
146   "localize $what, $value, $context"
147     Introduces a "local" delayed to the time of first return into the upper
148     scope denoted by $context. $what can be :
149
150     *   A glob, in which case $value can either be a glob or a reference.
151         "localize" follows then the same syntax as "local *x = $value". For
152         example, if $value is a scalar reference, then the "SCALAR" slot of
153         the glob will be set to $$value - just like "local *x = \1" sets $x
154         to 1.
155
156     *   A string beginning with a sigil, representing the symbol to localize
157         and to assign to. If the sigil is '$', "localize" follows the same
158         syntax as "local $x = $value", i.e. $value isn't dereferenced. For
159         example,
160
161             localize '$x', \'foo' => HERE;
162
163         will set $x to a reference to the string 'foo'. Other sigils ('@',
164         '%', '&' and '*') require $value to be a reference of the
165         corresponding type.
166
167         When the symbol is given by a string, it is resolved when the actual
168         localization takes place and not when "localize" is called. Thus, if
169         the symbol name is not qualified, it will refer to the variable in
170         the package where the localization actually takes place and not in
171         the one where the "localize" call was compiled. For example,
172
173             {
174              package Scope;
175              sub new { localize '$tag', $_[0] => UP }
176             }
177
178             {
179              package Tool;
180              {
181               Scope->new;
182               ...
183              }
184             }
185
186         will localize $Tool::tag and not $Scope::tag. If you want the other
187         behaviour, you just have to specify $what as a glob or a qualified
188         name.
189
190         Note that if $what is a string denoting a variable that wasn't
191         declared beforehand, the relevant slot will be vivified as needed
192         and won't be deleted from the glob when the localization ends. This
193         situation never arises with "local" because it only compiles when
194         the localized variable is already declared. Although I believe it
195         shouldn't be a problem as glob slots definedness is pretty much an
196         implementation detail, this behaviour may change in the future if
197         proved harmful.
198
199   "localize_elem $what, $key, $value, $context"
200     Introduces a "local $what[$key] = $value" or "local $what{$key} =
201     $value" delayed to the time of first return into the upper scope denoted
202     by $context. Unlike "localize", $what must be a string and the type of
203     localization is inferred from its sigil. The two only valid types are
204     array and hash ; for anything besides those, "localize_elem" will throw
205     an exception. $key is either an array index or a hash key, depending of
206     which kind of variable you localize.
207
208     If $what is a string pointing to an undeclared variable, the variable
209     will be vivified as soon as the localization occurs and emptied when it
210     ends, although it will still exist in its glob.
211
212   "localize_delete $what, $key, $context"
213     Introduces the deletion of a variable or an array/hash element delayed
214     to the time of first return into the upper scope denoted by $context.
215     $what can be:
216
217     *   A glob, in which case $key is ignored and the call is equivalent to
218         "local *x".
219
220     *   A string beginning with '@' or '%', for which the call is equivalent
221         to respectiveley "local $a[$key]; delete $a[$key]" and "local
222         $h{$key}; delete $h{$key}".
223
224     *   A string beginning with '&', which more or less does "undef &func"
225         in the upper scope. It's actually more powerful, as &func won't even
226         "exists" anymore. $key is ignored.
227
228   "unwind @values, $context"
229     Returns @values *from* the context pointed by $context, i.e. from the
230     subroutine, eval or format at or just above $context, and immediately
231     restart the program flow at this point - thus effectively returning to
232     an upper scope.
233
234     The upper context isn't coerced onto @values, which is hence always
235     evaluated in list context. This means that
236
237         my $num = sub {
238          my @a = ('a' .. 'z');
239          unwind @a => HERE;
240          # not reached
241         }->();
242
243     will set $num to 'z'. You can use "want_at" to handle these cases.
244
245   "want_at $context"
246     Like "wantarray", but for the subroutine/eval/format at or just above
247     $context.
248
249     The previous example can then be "corrected" :
250
251         my $num = sub {
252          my @a = ('a' .. 'z');
253          unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
254          # not reached
255         }->();
256
257     will rightfully set $num to 26.
258
259   "uplevel $code, @args, $context"
260     Executes the code reference $code with arguments @args as if it were
261     located at the subroutine stack frame pointed by $context, effectively
262     fooling "caller" and "die" into believing that the call actually
263     happened higher in the stack. The code is executed in the context of the
264     "uplevel" call, and what it returns is returned as-is by "uplevel".
265
266         sub target {
267          faker(@_);
268         }
269
270         sub faker {
271          uplevel {
272           map { 1 / $_ } @_;
273          } @_ => CALLER(1);
274         }
275
276         my @inverses = target(1, 2, 4); # @inverses contains (0, 0.5, 0.25)
277         my $count    = target(1, 2, 4); # $target is 3
278
279     Sub::Uplevel also implements a pure-Perl version of "uplevel". Both are
280     identical, with the following caveats :
281
282     *   The Sub::Uplevel implementation of "uplevel" may execute a code
283         reference in the context of any upper stack frame. The Scope::Upper
284         version only allows to uplevel to a subroutine stack frame, and will
285         croak if you try to target an "eval" or a format.
286
287     *   Exceptions thrown from the code called by this version of "uplevel"
288         will not be caught by "eval" blocks between the target frame and the
289         uplevel call, while they will for Sub::Uplevel's version. This means
290         that :
291
292             eval {
293              sub {
294               local $@;
295               eval {
296                sub {
297                 uplevel { die 'wut' } CALLER(2); # for Scope::Upper
298                 # uplevel(3, sub { die 'wut' })  # for Sub::Uplevel
299                }->();
300               };
301               print "inner block: $@";
302               $@ and exit;
303              }->();
304             };
305             print "outer block: $@";
306
307         will print "inner block: wut..." with Sub::Uplevel and "outer block:
308         wut..." with Scope::Upper.
309
310     *   Sub::Uplevel globally overrides "CORE::GLOBAL::caller", while
311         Scope::Upper does not.
312
313     A simple wrapper lets you mimic the interface of "uplevel" in
314     Sub::Uplevel :
315
316         use Scope::Upper;
317
318         sub uplevel {
319          my $frame = shift;
320          my $code  = shift;
321          my $cxt   = Scope::Upper::CALLER($frame);
322          &Scope::Upper::uplevel($code => @_ => $cxt);
323         }
324
325     Albeit the three exceptions listed above, it passes all the tests of
326     Sub::Uplevel.
327
328 CONSTANTS
329   "SU_THREADSAFE"
330     True iff the module could have been built when thread-safety features.
331
332 WORDS
333   Constants
334    "TOP"
335     Returns the context that currently represents the highest scope.
336
337    "HERE"
338     The context of the current scope.
339
340   Getting a context from a context
341     For any of those functions, $from is expected to be a context. When
342     omitted, it defaults to the the current context.
343
344    "UP $from"
345     The context of the scope just above $from.
346
347    "SUB $from"
348     The context of the closest subroutine above $from. Note that $from is
349     returned if it is already a subroutine context ; hence "SUB SUB == SUB".
350
351    "EVAL $from"
352     The context of the closest eval above $from. Note that $from is returned
353     if it is already an eval context ; hence "EVAL EVAL == EVAL".
354
355   Getting a context from a level
356     Here, $level should denote a number of scopes above the current one.
357     When omitted, it defaults to 0 and those functions return the same
358     context as "HERE".
359
360    "SCOPE $level"
361     The $level-th upper context, regardless of its type.
362
363    "CALLER $level"
364     The context of the $level-th upper subroutine/eval/format. It kind of
365     corresponds to the context represented by "caller $level", but while
366     e.g. "caller 0" refers to the caller context, "CALLER 0" will refer to
367     the top scope in the current context.
368
369   Examples
370     Where "reap" fires depending on the $cxt :
371
372         sub {
373          eval {
374           sub {
375            {
376             reap \&cleanup => $cxt;
377             ...
378            }     # $cxt = SCOPE(0), or HERE
379            ...
380           }->(); # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
381           ...
382          };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
383          ...
384         }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
385         ...
386
387     Where "localize", "localize_elem" and "localize_delete" act depending on
388     the $cxt :
389
390         sub {
391          eval {
392           sub {
393            {
394             localize '$x' => 1 => $cxt;
395             # $cxt = SCOPE(0), or HERE
396             ...
397            }
398            # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
399            ...
400           }->();
401           # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
402           ...
403          };
404          # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
405          ...
406         }->();
407         # $cxt = SCOPE(4), UP SUB UP SUB, or UP SUB EVAL, or UP CALLER(2), or TOP
408         ...
409
410     Where "unwind", "want_at" and "uplevel" point to depending on the $cxt:
411
412         sub {
413          eval {
414           sub {
415            {
416             unwind @things => $cxt;     # or uplevel { ... } $cxt;
417             ...
418            }
419            ...
420           }->(); # $cxt = SCOPE(0 .. 1), or HERE, or UP, or SUB, or CALLER(0)
421           ...
422          };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1) (*)
423          ...
424         }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
425         ...
426
427         # (*) Note that uplevel() will croak if you pass that scope frame,
428         #     because it can't target eval scopes.
429
430 EXPORT
431     The functions "reap", "localize", "localize_elem", "localize_delete",
432     "unwind", "want_at" and "uplevel" are only exported on request, either
433     individually or by the tags ':funcs' and ':all'.
434
435     The constant "SU_THREADSAFE" is also only exported on request,
436     individually or by the tags ':consts' and ':all'.
437
438     Same goes for the words "TOP", "HERE", "UP", "SUB", "EVAL", "SCOPE" and
439     "CALLER" that are only exported on request, individually or by the tags
440     ':words' and ':all'.
441
442 CAVEATS
443     Be careful that local variables are restored in the reverse order in
444     which they were localized. Consider those examples:
445
446         local $x = 0;
447         {
448          reap sub { print $x } => HERE;
449          local $x = 1;
450          ...
451         }
452         # prints '0'
453         ...
454         {
455          local $x = 1;
456          reap sub { $x = 2 } => HERE;
457          ...
458         }
459         # $x is 0
460
461     The first case is "solved" by moving the "local" before the "reap", and
462     the second by using "localize" instead of "reap".
463
464     The effects of "reap", "localize" and "localize_elem" can't cross
465     "BEGIN" blocks, hence calling those functions in "import" is deemed to
466     be useless. This is an hopeless case because "BEGIN" blocks are executed
467     once while localizing constructs should do their job at each run.
468     However, it's possible to hook the end of the current scope compilation
469     with B::Hooks::EndOfScope.
470
471     Some rare oddities may still happen when running inside the debugger. It
472     may help to use a perl higher than 5.8.9 or 5.10.0, as they contain some
473     context-related fixes.
474
475 DEPENDENCIES
476     XSLoader (standard since perl 5.006).
477
478 SEE ALSO
479     "local" in perlfunc, "Temporary Values via local()" in perlsub.
480
481     Alias, Hook::Scope, Scope::Guard, Guard.
482
483     Continuation::Escape is a thin wrapper around Scope::Upper that gives
484     you a continuation passing style interface to "unwind". It's easier to
485     use, but it requires you to have control over the scope where you want
486     to return.
487
488     Scope::Escape.
489
490     Sub::Uplevel provides a pure-Perl implementation of "uplevel".
491
492 AUTHOR
493     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
494
495     You can contact me by mail or on "irc.perl.org" (vincent).
496
497 BUGS
498     Please report any bugs or feature requests to "bug-scope-upper at
499     rt.cpan.org", or through the web interface at
500     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper>. I will be
501     notified, and then you'll automatically be notified of progress on your
502     bug as I make changes.
503
504 SUPPORT
505     You can find documentation for this module with the perldoc command.
506
507         perldoc Scope::Upper
508
509     Tests code coverage report is available at
510     <http://www.profvince.com/perl/cover/Scope-Upper>.
511
512 ACKNOWLEDGEMENTS
513     Inspired by Ricardo Signes.
514
515     Thanks to Shawn M. Moore for motivation.
516
517 COPYRIGHT & LICENSE
518     Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
519
520     This program is free software; you can redistribute it and/or modify it
521     under the same terms as Perl itself.
522