blib/lib/Sub/Uplevel.pm

filter: Statementstmt 98.6% 73 / 74 Branchbran 94.1% 32 / 34 Conditioncond 100% 5 / 5 MC/DCmcdc 100% 3 / 3 Subroutinesub 100% 12 / 12 Podpod 100% 1 / 1 totaltotal 97.6% 126 / 129 CC 21 SCAR 16.4
CC
21
Cov
97%
_uplevel_caller
10.0
_normal_caller
5.0
import
4.0
CRAP 5.1
↑ Summary
1 package Sub::Uplevel;
2 8 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 # ABSTRACT: apparently run a function in a higher stack frame
5  
6 8 our $VERSION = '0.2800';
7  
8 # Frame check global constant
9 8 our $CHECK_FRAMES;
10 8 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 $CHECK_FRAMES = !! $CHECK_FRAMES;
12 }
13 8 ▶use constant CHECK_FRAMES => $CHECK_FRAMES;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 # We must override *CORE::GLOBAL::caller if it hasn't already been
16 # overridden or else Perl won't see our local override later.
17  
18 8 ▶if ( not defined *CORE::GLOBAL::caller{CODE} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined *CORE::GLOBAL::caller{"CODE"}) 7 1 8
19 7 *CORE::GLOBAL::caller = \&_normal_caller;
20 }
21  
22 # modules to force reload if ":aggressive" is specified
23 8 my @reload_list = qw/Exporter Exporter::Heavy/;
24  
25 10 ▶sub import {
Subroutine import: called CC=4 SCAR=13.9
26 8 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
27 10 my ($class, @args) = @_;
28 10 for my $tag ( @args, 'uplevel' ) {
29 11 ▶ if ( $tag eq 'uplevel' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($tag eq 'uplevel') { } 10 1 11
elsif ($tag eq ':aggressive') { } 1 0 1
30 10 my $caller = caller(0);
31 10 *{"$caller\::uplevel"} = \&uplevel;
32 }
33 elsif( $tag eq ':aggressive' ) {
34 1 _force_reload( @reload_list );
35 }
36 else {
37 0 die qq{"$tag" is not exported by the $class module\n}
38 }
39 }
40 10 return;
41 }
42  
43 1 ▶sub _force_reload {
Subroutine _force_reload: called CC=3 SCAR=11.0
44 8 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
45 1 local $^W = 0;
46 1 for my $m ( @_ ) {
47 2 $m =~ s{::}{/}g;
48 2 $m .= ".pm";
49 2 ▶ require $m if delete $INC{$m};
Branch: 1 branch
BranchTrueFalseTotal
if delete $INC{$m} 2 0 2
50 }
51 }
52  
53 #pod =head1 SYNOPSIS
54 #pod
55 #pod use Sub::Uplevel;
56 #pod
57 #pod sub foo {
58 #pod print join " - ", caller;
59 #pod }
60 #pod
61 #pod sub bar {
62 #pod uplevel 1, \&foo;
63 #pod }
64 #pod
65 #pod #line 11
66 #pod bar(); # main - foo.plx - 11
67 #pod
68 #pod =head1 DESCRIPTION
69 #pod
70 #pod Like Tcl's uplevel() function, but not quite so dangerous. The idea
71 #pod is just to fool caller(). All the really naughty bits of Tcl's
72 #pod uplevel() are avoided.
73 #pod
74 #pod B<THIS IS NOT THE SORT OF THING YOU WANT TO DO EVERYDAY>
75 #pod
76 #pod =over 4
77 #pod
78 #pod =item B<uplevel>
79 #pod
80 #pod uplevel $num_frames, \&func, @args;
81 #pod
82 #pod Makes the given function think it's being executed $num_frames higher
83 #pod than the current stack level. So when they use caller($frames) it
84 #pod will actually give caller($frames + $num_frames) for them.
85 #pod
86 #pod C<uplevel(1, \&some_func, @_)> is effectively C<goto &some_func> but
87 #pod you don't immediately exit the current subroutine. So while you can't
88 #pod do this:
89 #pod
90 #pod sub wrapper {
91 #pod print "Before\n";
92 #pod goto &some_func;
93 #pod print "After\n";
94 #pod }
95 #pod
96 #pod you can do this:
97 #pod
98 #pod sub wrapper {
99 #pod print "Before\n";
100 #pod my @out = uplevel 1, &some_func;
101 #pod print "After\n";
102 #pod return @out;
103 #pod }
104 #pod
105 #pod C<uplevel> has the ability to issue a warning if C<$num_frames> is more than
106 #pod the current call stack depth, although this warning is disabled and compiled
107 #pod out by default as the check is relatively expensive.
108 #pod
109 #pod To enable the check for debugging or testing, you should set the global
110 #pod C<$Sub::Uplevel::CHECK_FRAMES> to true before loading Sub::Uplevel for the
111 #pod first time as follows:
112 #pod
113 #pod #!/usr/bin/perl
114 #pod
115 #pod BEGIN {
116 #pod $Sub::Uplevel::CHECK_FRAMES = 1;
117 #pod }
118 #pod use Sub::Uplevel;
119 #pod
120 #pod Setting or changing the global after the module has been loaded will have
121 #pod no effect.
122 #pod
123 #pod =cut
124  
125 # @Up_Frames -- uplevel stack
126 # $Caller_Proxy -- whatever caller() override was in effect before uplevel
127 8 our (@Up_Frames, $Caller_Proxy);
128  
129 2 ▶sub _apparent_stack_height {
Subroutine _apparent_stack_height: called CC=2 SCAR=6.9
130 2 my $height = 1; # start above this function
131 2 while ( 1 ) {
132 6 ▶ last if ! defined scalar $Caller_Proxy->($height);
Branch: 1 branch
BranchTrueFalseTotal
unless defined scalar &$Sub::Uplevel::Caller_Proxy($height) 2 4 6
133 4 $height++;
134 }
135 2 return $height - 1; # subtract 1 for this function
136 }
137  
138 122 ▶sub uplevel {
Subroutine uplevel: called CC=2 SCAR=6.9
Pod documented
139 # Backwards compatible version of "no warnings 'redefine'"
140 122 my $old_W = $^W;
141 122 $^W = 0;
142  
143 # Update the caller proxy if the uplevel override isn't in effect
144 local $Caller_Proxy = *CORE::GLOBAL::caller{CODE}
145 122 ▶ if *CORE::GLOBAL::caller{CODE} != \&_uplevel_caller;
Branch: 1 branch
BranchTrueFalseTotal
if *CORE::GLOBAL::caller{"CODE"} != \&Sub::Uplevel::_uplevel_caller 30 92 122
146 122 local *CORE::GLOBAL::caller = \&_uplevel_caller;
147  
148 # Restore old warnings state
149 122 $^W = $old_W;
150  
151 122 if ( CHECK_FRAMES and $_[0] >= _apparent_stack_height() ) {
152 require Carp;
153 Carp::carp("uplevel $_[0] is more than the caller stack");
154 }
155  
156 121 local @Up_Frames = (shift, @Up_Frames );
157  
158 121 my $function = shift;
159 122 return $function->(@_);
160 }
161  
162 722 ▶sub _normal_caller (;$) { ## no critic Prototypes
Subroutine _normal_caller: called CC=5 SCAR=16.1
163 724 my ($height) = @_;
164 724 $height++;
165 722 my @caller = CORE::caller($height);
166 722 ▶ if ( CORE::caller() eq 'DB' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (caller() eq "DB") 12 712 724
167 # Oops, redo picking up @DB::args
168 package DB;
169 11 @caller = CORE::caller($height);
170 }
171  
172 722 ▶ return if ! @caller; # empty
Branch: 1 branch
BranchTrueFalseTotal
unless @caller 123 599 722
173 599 ▶ return $caller[0] if ! wantarray; # scalar context
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 17 582 599
174 582 ▶ return @_ ? @caller : @caller[0..2]; # extra info or regular
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 581 1 582
175 }
176  
177 692 ▶sub _uplevel_caller (;$) { ## no critic Prototypes
Subroutine _uplevel_caller: called CC=10 SCAR=23.0
178 692 ▶ my $height = $_[0] || 0;
Condition100%2/2
$_[0] || 0
l!l
576116
MC/DC100%1/1
$_[0] || 0
$_[0]
Truth table100%2/2
A
A= $_[0]
Aresult
11
00
179  
180 # shortcut if no uplevels have been called
181 # always add +1 to CORE::caller (proxy caller function)
182 # to skip this function's caller
183 692 ▶ return $Caller_Proxy->( $height + 1 ) if ! @Up_Frames;
Branch: 1 branch
BranchTrueFalseTotal
unless @Sub::Uplevel::Up_Frames 8 684 692
184  
185 #pod =begin _private
186 #pod
187 #pod So it has to work like this:
188 #pod
189 #pod Call stack Actual uplevel 1
190 #pod CORE::GLOBAL::caller
191 #pod Carp::short_error_loc 0
192 #pod Carp::shortmess_heavy 1 0
193 #pod Carp::croak 2 1
194 #pod try_croak 3 2
195 #pod uplevel 4
196 #pod function_that_called_uplevel 5
197 #pod caller_we_want_to_see 6 3
198 #pod its_caller 7 4
199 #pod
200 #pod So when caller(X) winds up below uplevel(), it only has to use
201 #pod CORE::caller(X+1) (to skip CORE::GLOBAL::caller). But when caller(X)
202 #pod winds up no or above uplevel(), it's CORE::caller(X+1+uplevel+1).
203 #pod
204 #pod Which means I'm probably going to have to do something nasty like walk
205 #pod up the call stack on each caller() to see if I'm going to wind up
206 #pod before or after Sub::Uplevel::uplevel().
207 #pod
208 #pod =end _private
209 #pod
210 #pod =begin _dagolden
211 #pod
212 #pod I found the description above a bit confusing. Instead, this is the logic
213 #pod that I found clearer when CORE::GLOBAL::caller is invoked and we have to
214 #pod walk up the call stack:
215 #pod
216 #pod * if searching up to the requested height in the real call stack doesn't find
217 #pod a call to uplevel, then we can return the result at that height in the
218 #pod call stack
219 #pod
220 #pod * if we find a call to uplevel, we need to keep searching upwards beyond the
221 #pod requested height at least by the amount of upleveling requested for that
222 #pod call to uplevel (from the Up_Frames stack set during the uplevel call)
223 #pod
224 #pod * additionally, we need to hide the uplevel subroutine call, too, so we search
225 #pod upwards one more level for each call to uplevel
226 #pod
227 #pod * when we've reached the top of the search, we want to return that frame
228 #pod in the call stack, i.e. the requested height plus any uplevel adjustments
229 #pod found during the search
230 #pod
231 #pod =end _dagolden
232 #pod
233 #pod =cut
234  
235 684 my $saw_uplevel = 0;
236 684 my $adjust = 0;
237  
238 # walk up the call stack to fight the right package level to return;
239 # look one higher than requested for each call to uplevel found
240 # and adjust by the amount found in the Up_Frames stack for that call.
241 # We *must* use CORE::caller here since we need the real stack not what
242 # some other override says the stack looks like, just in case that other
243 # override breaks things in some horrible way
244 684 my $test_caller;
245 684 ▶ for ( my $up = 0; $up <= $height + $adjust; $up++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($up <= $height + $adjust) 5958 684 6642
246 5958 $test_caller = scalar CORE::caller($up + 1);
247 5958 ▶ if( $test_caller && $test_caller eq __PACKAGE__ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($test_caller and $test_caller eq __PACKAGE__) 1220 4738 5958
Condition100%3/3
$test_caller and $test_caller eq __PACKAGE__
!ll&&!rl&&r
11446241220
MC/DC100%2/2
$test_caller and $test_caller eq __PACKAGE__
$test_caller $test_caller eq __PACKAGE__
Truth table100%3/3
A and B
A= $test_callerB= $test_caller eq __PACKAGE__
ABresult
0X0
100
111
248 # add one for each uplevel call seen
249 # and look into the uplevel stack for the offset
250 1220 $adjust += 1 + $Up_Frames[$saw_uplevel];
251 1220 $saw_uplevel++;
252 }
253 }
254  
255 # For returning values, we pass through the call to the proxy caller
256 # function, just at a higher stack level
257 684 my @caller = $Caller_Proxy->($height + $adjust + 1);
258 684 ▶ if ( CORE::caller() eq 'DB' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (caller() eq "DB") 10 674 684
259 # Oops, redo picking up @DB::args
260 package DB;
261 10 @caller = $Sub::Uplevel::Caller_Proxy->($height + $adjust + 1);
262 }
263  
264 684 ▶ return if ! @caller; # empty
Branch: 1 branch
BranchTrueFalseTotal
unless @caller 114 570 684
265 570 ▶ return $caller[0] if ! wantarray; # scalar context
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 545 25 570
266 25 ▶ return @_ ? @caller : @caller[0..2]; # extra info or regular
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 23 2 25
267 }
268  
269 #pod =back
270 #pod
271 #pod =head1 EXAMPLE
272 #pod
273 #pod The main reason I wrote this module is so I could write wrappers
274 #pod around functions and they wouldn't be aware they've been wrapped.
275 #pod
276 #pod use Sub::Uplevel;
277 #pod
278 #pod my $original_foo = \&foo;
279 #pod
280 #pod *foo = sub {
281 #pod my @output = uplevel 1, $original_foo;
282 #pod print "foo() returned: @output";
283 #pod return @output;
284 #pod };
285 #pod
286 #pod If this code frightens you B<you should not use this module.>
287 #pod
288 #pod
289 #pod =head1 BUGS and CAVEATS
290 #pod
291 #pod Well, the bad news is uplevel() is about 5 times slower than a normal
292 #pod function call. XS implementation anyone? It also slows down every invocation
293 #pod of caller(), regardless of whether uplevel() is in effect.
294 #pod
295 #pod Sub::Uplevel overrides CORE::GLOBAL::caller temporarily for the scope of
296 #pod each uplevel call. It does its best to work with any previously existing
297 #pod CORE::GLOBAL::caller (both when Sub::Uplevel is first loaded and within
298 #pod each uplevel call) such as from Contextual::Return or Hook::LexWrap.
299 #pod
300 #pod However, if you are routinely using multiple modules that override
301 #pod CORE::GLOBAL::caller, you are probably asking for trouble.
302 #pod
303 #pod You B<should> load Sub::Uplevel as early as possible within your program. As
304 #pod with all CORE::GLOBAL overloading, the overload will not affect modules that
305 #pod have already been compiled prior to the overload. One module that often is
306 #pod unavoidably loaded prior to Sub::Uplevel is Exporter. To forcibly recompile
307 #pod Exporter (and Exporter::Heavy) after loading Sub::Uplevel, use it with the
308 #pod ":aggressive" tag:
309 #pod
310 #pod use Sub::Uplevel qw/:aggressive/;
311 #pod
312 #pod The private function C<Sub::Uplevel::_force_reload()> may be passed a list of
313 #pod additional modules to reload if ":aggressive" is not aggressive enough.
314 #pod Reloading modules may break things, so only use this as a last resort.
315 #pod
316 #pod As of version 0.20, Sub::Uplevel requires Perl 5.6 or greater.
317 #pod
318 #pod =head1 HISTORY
319 #pod
320 #pod Those who do not learn from HISTORY are doomed to repeat it.
321 #pod
322 #pod The lesson here is simple: Don't sit next to a Tcl programmer at the
323 #pod dinner table.
324 #pod
325 #pod =head1 THANKS
326 #pod
327 #pod Thanks to Brent Welch, Damian Conway and Robin Houston.
328 #pod
329 #pod See http://www.perl.com/perl/misc/Artistic.html
330 #pod
331 #pod =head1 SEE ALSO
332 #pod
333 #pod PadWalker (for the similar idea with lexicals), Hook::LexWrap,
334 #pod Tcl's uplevel() at http://www.scriptics.com/man/tcl8.4/TclCmd/uplevel.htm
335 #pod
336 #pod =cut
337  
338 8 1;
339  
340 __END__
↑ Summary