blib/lib/B/Hooks/AtRuntime.pm

filter: Statementstmt 100% 65 / 65 Branchbran 91.6% 11 / 12 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 17 / 17 Podpod 40.0% 2 / 5 totaltotal 95.9% 95 / 99 CC 7 SCAR 5.3
CC
7
Cov
99%
__ANON__
3.0
find_hooks
3.0
BEGIN
2.0
CRAP 1.7
↑ Summary tlib/t/Util.pm »
1 package B::Hooks::AtRuntime;
2  
3 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 7 ▶use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Sub::Name "subname";
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 7 ▶use parent "Exporter::Tiny";
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 our @EXPORT = qw/at_runtime/;
12 7 our @EXPORT_OK = qw/at_runtime after_runtime lex_stuff/;
13  
14 7 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
15 7 our $VERSION = "8";
16 7 XSLoader::load __PACKAGE__, $VERSION;
17 }
18  
19 7 ▶use constant USE_FILTER =>
Subroutine BEGIN: called CC=2 SCAR=6.9
20 defined $ENV{PERL_B_HOOKS_ATRUNTIME}
21 7 ▶ ? $ENV{PERL_B_HOOKS_ATRUNTIME} eq "filter"
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'PERL_B_HOOKS_ATRUNTIME'} ? : 1 6 7
22 7 : not defined &lex_stuff;
23  
24 7 if (USE_FILTER) {
25 require Filter::Util::Call;
26  
27 # This isn't an exact replacement: it inserts the text at the start
28 # of the next line, rather than immediately after the current BEGIN.
29 #
30 # In theory I could use B::Hooks::Parser, which aims to emulate
31 # lex_stuff on older perls, but that uses a source filter to ensure
32 # PL_linebuf has some extra space in it (since it can't be
33 # reallocated without adjusting pointers we can't get to). This
34 # means BHP::setup needs to be called at least one source line
35 # before we want to insert any text (so the filter has a chance to
36 # run), which makes it precisely useless for our purposes :(.
37  
38 7 ▶ no warnings "redefine";
Subroutine BEGIN: called CC=1 SCAR=0.0
39 55 ▶ *lex_stuff = subname "lex_stuff", sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
40 55 my ($str) = @_;
41  
42 55 ▶ compiling_string_eval() and croak
Branch: 1 branch
BranchTrueFalseTotal
compiling_string_eval() and croak("Can't stuff into a string eval") 0 55 55
43 "Can't stuff into a string eval";
44  
45 55 ▶ if (defined(my $extra = remaining_text())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $extra = remaining_text())) 1 54 55
46 1 $extra =~ s/\n+\z//;
47 1 carp "Extra text '$extra' after call to lex_stuff";
48 }
49  
50 55 ▶ Filter::Util::Call::filter_add(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
51 55 $_ = $str;
52 55 Filter::Util::Call::filter_del();
53 55 return 1;
54 55 });
55 };
56 }
57  
58 # In order to avoid needing to stuff text into perl's lexer too often,
59 # the code stuffed looks like this
60 #
61 # B::Hooks::AtRuntime::run(@B::Hooks::Runtime::hooks);
62 # BEGIN { B::Hooks::Runtime::clear(1) }
63 #
64 # The way this works is as follows.
65 #
66 # - The @hooks global refers to a different array every time it is used.
67 # The sub replace_hooks is responsible for making sure that the global
68 # points to the correct array at the time the stuffed code is
69 # compiled.
70 #
71 # - The lexical array @Hooks below contains one entry for each time we
72 # have recursively entered compile time. So, for example, if the user
73 # writes
74 #
75 # BEGIN {
76 # BEGIN {
77 # at_runtime { ... };
78 # }
79 # }
80 #
81 # then the at_runtime sub is pushed onto @Hooks[2], because we are in
82 # our second recursive BEGIN. (@Hooks[0] is never used.)
83 #
84 # - The XS sub count_BEGINs is responsible for finding which level of
85 # @Hooks to push onto. It does this by looking for BEGIN blocks,
86 # because even use compiles out as a BEGIN block.
87 #
88 # - The call to clear() ensures that if we leave and re-enter compile
89 # time at this level we get a new array of hooks and a new code-stuff
90 # to call them. The number passed (interpolated into the compiled
91 # code) is the level of @Hooks to clear.
92  
93 7 my @Hooks;
94  
95 196 ▶sub replace_hooks {
Subroutine replace_hooks: called CC=2 SCAR=6.9
Pod undocumented
96 196 my ($new) = @_;
97  
98 # By deleting the stash entry we ensure the only ref to the glob is
99 # through the optree it was compiled into. This means that if that
100 # optree is ever freed, the glob will disappear along with anything
101 # closed over by the user's callbacks.
102 196 delete $B::Hooks::AtRuntime::{hooks};
103  
104 7 ▶ no strict "refs";
Subroutine BEGIN: called CC=1 SCAR=0.0
105 196 ▶ $new and *{"hooks"} = $new;
Branch: 1 branch
BranchTrueFalseTotal
$new and *{"hooks";} = $new 99 97 196
106 }
107  
108 98 ▶sub clear {
Subroutine clear: called CC=1 SCAR=0.0
Pod undocumented
109 98 my ($depth) = @_;
110 98 $Hooks[$depth] = undef;
111 98 replace_hooks $Hooks[$depth - 1];
112 }
113  
114 118 ▶sub find_hooks {
Subroutine find_hooks: called CC=3 SCAR=11.0
Pod undocumented
115 118 USE_FILTER and compiling_string_eval() and croak
116 "Can't use at_runtime from a string eval";
117  
118 116 ▶ my $depth = count_BEGINs()
Branch: 1 branch
BranchTrueFalseTotal
my $depth = count_BEGINs() or croak("You must call at_runtime at compile time") 61 57 118
119 or croak "You must call at_runtime at compile time";
120  
121 114 my $hk;
122 114 ▶ unless ($hk = $Hooks[$depth]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hk = $Hooks[$depth]) 106 9 115
123 # Close over an array of callbacks so we don't need to keep
124 # stuffing text into the buffer.
125 98 my @hooks;
126 98 $hk = $Hooks[$depth] = \@hooks;
127 98 replace_hooks $hk;
128  
129 # This must be all on one line, so we don't mess up perl's idea
130 # of the current line number.
131 98 lex_stuff(q{B::Hooks::AtRuntime::run(@B::Hooks::AtRuntime::hooks);} .
132 "BEGIN{B::Hooks::AtRuntime::clear($depth)}");
133 }
134  
135 114 return $hk;
136 }
137  
138 109 ▶sub at_runtime (&) {
Subroutine at_runtime: called CC=1 SCAR=0.0
Pod documented
139 109 my ($cv) = @_;
140 109 my $hk = find_hooks;
141 105 push @$hk, subname scalar(caller) . "::(at_runtime)", $cv;
142 }
143  
144 # The XS sub run() knows that a ref to a ref is an after_runtime sub.
145 9 ▶sub after_runtime (&) {
Subroutine after_runtime: called CC=1 SCAR=0.0
Pod documented
146 9 my ($cv) = @_;
147 9 my $hk = find_hooks;
148 9 push @$hk, \subname scalar(caller) . "::(after_runtime)", $cv;
149 }
150  
151 7 1;
152  
153 =head1 NAME
154  
155 B::Hooks::AtRuntime - Lower blocks from compile time to runtime
156  
157 =head1 SYNOPSIS
158  
159 # My::Module
160 sub import {
161 at_runtime { warn "TWO" };
162 }
163  
164 # elsewhere
165 warn "ONE";
166 use My::Module;
167 warn "THREE";
168  
169 =head1 DESCRIPTION
170  
171 This module allows code that runs at compile-time to do something at
172 runtime. A block passed to C<at_runtime> gets compiled into the code
173 that's currently compiling, and will be called when control reaches that
174 point at runtime. In the example in the SYNOPSIS, the warnings will
175 occur in order, and if that section of code runs more than once, so will
176 all three warnings.
177  
178 =head2 at_runtime
179  
180 at_runtime { ... };
181  
182 This sets up a block to be called at runtime. It must be called from
183 within a C<BEGIN> block or C<use>, otherwise there will be no compiling
184 code to insert into. The innermost enclosing C<BEGIN> block, which would
185 normally be invisible once the section of code it is in has been
186 compiled, will effectively leave behind a call to the given block. For
187 example, this
188  
189 BEGIN { warn "ONE" } warn "one";
190 BEGIN { warn "TWO"; at_runtime { warn "two" }; }
191  
192 will warn "ONE TWO one two", with the last warning 'lowered' out of the
193 C<BEGIN> block and back into the runtime control flow.
194  
195 This applies even if calls to other subs intervene between C<BEGIN> and
196 C<at_runtime>. The lowered block is always inserted at the innermost
197 point where perl is still compiling, so something like this
198  
199 # My::Module
200 sub also_at_runtime {
201 my ($msg) = @_;
202 at_runtime { warn $msg };
203 }
204  
205 sub import {
206 my ($class, $one, $two) = @_;
207 at_runtime { warn $one };
208 also_at_runtime $two;
209 }
210  
211 #
212 warn "one";
213 BEGIN { at_runtime { warn "two" } }
214 BEGIN { My::Module::also_at_runtime "three" }
215 use My::Module "four", "five";
216  
217 will still put the warnings in order.
218  
219 =head2 after_runtime
220  
221 after_runtime { ... };
222  
223 This arranges to call the block when runtime execution reaches the end
224 of the surrounding compiling scope. For example, this will warn in order:
225  
226 warn "one";
227 {
228 warn "two";
229 BEGIN {
230 after_runtime { warn "five" };
231 at_runtime { warn "three" };
232 }
233 warn "four";
234 }
235 warn "six";
236  
237 No exception handling is done, so if the block throws an exception it
238 will propogate normally into the surrounding code. (This is different
239 from the way perl calls C<DESTROY> methods, which have their exceptions
240 converted into warnings.)
241  
242 Note that the block will be called during stack unwind, so the package,
243 file and line information for C<caller 0> will be the point where the
244 surrounding scope was called. This is the same as a C<DESTROY> method.
245  
246 =head2 Object lifetimes
247  
248 C<at_runtime> and C<after_runtime> are careful to make sure the
249 anonymous sub passed to them doesn't live any longer than it has to.
250 That sub, and any lexicals it has closed over, will be destroyed when
251 the optree it has been compiled into is destroyed: for code outside any
252 sub, this is when the containing file or eval finishes executing; for
253 named subs, this is when the sub is un- or redefined; and for anonymous
254 subs, this is not until both the code containing the C<sub { }>
255 expression and all instances generated by that expression have been
256 destroyed.
257  
258 =head2 lex_stuff
259
260 lex_stuff $text;
261  
262 This is the function underlying C<at_runtime>. Under perl 5.12 and
263 later, this is just a Perl wrapper for the core function
264 L<lex_stuff_sv|perlapi/lex_stuff_sv>. Under earlier versions it is
265 implemented with a source filter, with some limitations, see L</CAVEATS>
266 below.
267  
268 This function pushes text into perl's line buffer, at the point perl is
269 currently compiling. You should probably not try to push too much at
270 once without giving perl a chance to compile it. If C<$text> contains
271 newlines, they will affect perl's idea of the current line number. You
272 probably shouldn't use this function at all.
273  
274 =head2 Exports
275  
276 B::Hooks::AtRuntime uses L<Exporter::Tiny>, so you can customise its
277 exports as described by that module's documentation. C<at_runtime> is
278 exported by default; C<after_runtime> and C<lex_stuff> can be exported
279 on request.
280  
281 =head1 CAVEATS
282  
283 =head2 Incompatible changes from version 1
284  
285 Version 1 used a different implementation for C<at_runtime>, which left
286 an extra scope between the provided block and the code it was compiled
287 into. Version 2 has removed this.
288  
289 =head2 Perls before 5.12
290  
291 Versions of perl before 5.12.0 don't have the C<lex_stuff_sv> function,
292 and don't export enough for it to be possible to emulate it entirely.
293 (L<B::Hooks::Parser> gets as close as it can, and just exactly doesn't
294 quite do what we need for C<at_runtime>.) This means our C<lex_stuff>
295 has to fall back to using a source filter to insert the text, which has
296 a couple of important limitations.
297  
298 =over 4
299  
300 =item * You cannot stuff text into a string C<eval>.
301  
302 String evals aren't affected by source filters, so the stuffed text
303 would end up getting inserted into the innermost compiling scope that
304 B<wasn't> a string eval. Since this would be rather confusing, and
305 different from what 5.12 does, C<lex_stuff> and C<at_runtime> will croak
306 if you try to use them to affect a string eval.
307  
308 =item * Stuffed text appears at the start of the next line.
309  
310 This, unfortunately, is rather annoying. With a filter, the earliest
311 point at which we can insert text is the start of the next line. This
312 means that if there is any text between the closing brace of the
313 C<BEGIN> block or the semicolon of the C<use> that caused the insertion,
314 and the end of the line, the insertion will certainly be in the wrong
315 place and probably cause a syntax error.
316  
317 C<lex_stuff> (and, therefore, C<at_runtime>) will issue a warning if
318 this is going to happen (specifically, if there are any non-space
319 non-comment characters between the point where we want to insert and the
320 point we're forced to settle for), but this may not be something you can
321 entirely control. If you are writing a module like the examples above
322 which calls C<at_runtime> from its C<import> method, what matters is
323 that B<users of your module> not put anything on a line after your
324 module's C<use> statement.
325  
326 =back
327  
328 If you want to use the filter implementation on perl 5.12 (for testing),
329 set C<PERL_B_HOOKS_ATRUNTIME=filter> in the environment. If the filter
330 implementation is in use, C<B::Hooks::AtRuntime::USE_FILTER> will be
331 true.
332  
333 =head1 SEE ALSO
334  
335 L<B::Hooks::Parser> will insert text 'here' in perls before 5.12, but
336 requires a setup step at least one source line in advance.
337  
338 L<Hook::AfterRuntime> uses it to implement something somewhat similar to
339 this module.
340  
341 L<Scope::OnExit> and L<B::Hooks::EndOfScope> provide hooks into
342 different points in the surrounding scope.
343  
344 L<Filter::Util::Call> is the generic interface to the source filtering
345 mechanism.
346  
347 =head1 AUTHOR
348  
349 Ben Morrow <ben@morrow.me.uk>
350  
351 =head1 BUGS
352  
353 Please report any bugs to <bug-B-Hooks-AtRuntime@rt.cpan.org>.
354  
355 =head1 ACKNOWLEDGEMENTS
356  
357 Zefram's work on the core lexer API made this module enormously easier.
358  
359 =head1 COPYRIGHT
360  
361 Copyright 2015 Ben Morrow.
362  
363 Released under the 2-clause BSD licence.
364  
365 =cut
↑ Summary tlib/t/Util.pm »