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