add version number to all public modules
[gitmo/Moo.git] / lib / Sub / Quote.pm
CommitLineData
a165a07f 1package Sub::Quote;
2
3use strictures 1;
4
5sub _clean_eval { eval $_[0] }
6
7use Sub::Defer;
8use B 'perlstring';
8a0ad775 9use Scalar::Util qw(weaken);
a165a07f 10use base qw(Exporter);
11
013a2be3 12our $VERSION = '1.003000';
13$VERSION = eval $VERSION;
14
625d6219 15our @EXPORT = qw(quote_sub unquote_sub quoted_from_sub);
a165a07f 16
a165a07f 17our %QUOTED;
18
8a0ad775 19our %WEAK_REFS;
20
8c6626cf 21sub capture_unroll {
22 my ($from, $captures, $indent) = @_;
23 join(
24 '',
25 map {
26 /^([\@\%\$])/
17a8e3f0 27 or die "capture key should start with \@, \% or \$: $_";
8c6626cf 28 (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
29 } keys %$captures
30 );
31}
32
e57f338d 33sub inlinify {
34 my ($code, $args, $extra, $local) = @_;
35 my $do = 'do { '.($extra||'');
36 if (my ($code_args, $body) = $code =~ / +my \(([^)]+)\) = \@_;(.*)$/s) {
37 if ($code_args eq $args) {
38 $do.$body.' }'
39 } else {
f537c364 40 $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
e57f338d 41 }
42 } else {
d89a7f56 43 my $assign = '';
44 if ($local || $args ne '@_') {
45 $assign = ($local ? 'local ' : '').'@_ = ('.$args.'); ';
46 }
47 $do.$assign.$code.' }';
e57f338d 48 }
49}
50
a165a07f 51sub quote_sub {
52 # HOLY DWIMMERY, BATMAN!
6f68f022 53 # $name => $code => \%captures => \%options
a165a07f 54 # $name => $code => \%captures
55 # $name => $code
6f68f022 56 # $code => \%captures => \%options
a165a07f 57 # $code
6f68f022 58 my $options =
59 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
60 ? pop
61 : {};
a165a07f 62 my $captures = pop if ref($_[-1]) eq 'HASH';
625d6219 63 undef($captures) if $captures && !keys %$captures;
a165a07f 64 my $code = pop;
65 my $name = $_[0];
66 my $outstanding;
6f68f022 67 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
a165a07f 68 unquote_sub($outstanding);
69 };
70 $outstanding = "$deferred";
55d91f64 71 $QUOTED{$outstanding} = [ $name, $code, $captures ];
8a0ad775 72 weaken($WEAK_REFS{$outstanding} = $deferred);
a165a07f 73 return $deferred;
74}
75
76sub quoted_from_sub {
77 my ($sub) = @_;
8a0ad775 78 $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
a165a07f 79}
80
81sub unquote_sub {
82 my ($sub) = @_;
55d91f64 83 unless ($QUOTED{$sub}[3]) {
84 my ($name, $code, $captures) = @{$QUOTED{$sub}};
85
86 my $make_sub = "{\n";
87
88 if (keys %$captures) {
89 $make_sub .= capture_unroll("\$_[1]", $captures, 2);
90 }
91
92 my $o_quoted = perlstring $sub;
93 $make_sub .= (
94 $name
95 # disable the 'variable $x will not stay shared' warning since
96 # we're not letting it escape from this scope anyway so there's
97 # nothing trying to share it
98 ? " no warnings 'closure';\n sub ${name} {\n"
99 : " \$Sub::Quote::QUOTED{${o_quoted}}[3] = sub {\n"
100 );
101 $make_sub .= $code;
102 $make_sub .= " }".($name ? '' : ';')."\n";
103 if ($name) {
104 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
105 }
106 $make_sub .= "}\n1;\n";
107 $ENV{SUB_QUOTE_DEBUG} && warn $make_sub;
108 {
109 local $@;
110 no strict 'refs';
111 local *{$name} if $name;
112 unless (_clean_eval $make_sub, $captures) {
113 die "Eval went very, very wrong:\n\n${make_sub}\n\n$@";
114 }
115 }
116 }
a165a07f 117 $QUOTED{$sub}[3];
118}
119
1201;
8595641b 121
0b6e5fff 122=head1 NAME
123
124Sub::Quote - efficient generation of subroutines via string eval
8595641b 125
126=head1 SYNOPSIS
127
128 package Silly;
129
130 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
131
132 quote_sub 'Silly::kitty', q{ print "meow" };
133
134 quote_sub 'Silly::doggy', q{ print "woof" };
135
6b3002b2 136 my $sound = 0;
8595641b 137
80c50620 138 quote_sub 'Silly::dagron',
6b3002b2 139 q{ print ++$sound % 2 ? 'burninate' : 'roar' },
8595641b 140 { '$sound' => \$sound };
141
142And elsewhere:
143
144 Silly->kitty; # meow
145 Silly->doggy; # woof
80c50620 146 Silly->dagron; # burninate
147 Silly->dagron; # roar
148 Silly->dagron; # burninate
8595641b 149
150=head1 DESCRIPTION
151
152This package provides performant ways to generate subroutines from strings.
153
154=head1 SUBROUTINES
155
156=head2 quote_sub
157
d925a566 158 my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
8595641b 159
160Arguments: ?$name, $code, ?\%captures, ?\%options
161
162C<$name> is the subroutine where the coderef will be installed.
163
164C<$code> is a string that will be turned into code.
165
166C<\%captures> is a hashref of variables that will be made available to the
80c50620 167code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
8595641b 168
169=head3 options
170
171=over 2
172
173=item * no_install
174
175B<Boolean>. Set this option to not install the generated coderef into the
005c00f2 176passed subroutine name on undefer.
8595641b 177
178=back
179
180=head2 unquote_sub
181
005c00f2 182 my $coderef = unquote_sub $sub;
8595641b 183
b53b6c19 184Forcibly replace subroutine with actual code.
8595641b 185
005c00f2 186If $sub is not a quoted sub, this is a no-op.
187
8595641b 188=head2 quoted_from_sub
189
005c00f2 190 my $data = quoted_from_sub $sub;
191
192 my ($name, $code, $captures, $compiled_sub) = @$data;
193
194Returns original arguments to quote_sub, plus the compiled version if this
195sub has already been unquoted.
8595641b 196
005c00f2 197Note that $sub can be either the original quoted version or the compiled
198version for convenience.
8595641b 199
200=head2 inlinify
201
8a4aa214 202 my $prelude = capture_unroll '$captures', {
8595641b 203 '$x' => 1,
204 '$y' => 2,
205 };
206
207 my $inlined_code = inlinify q{
208 my ($x, $y) = @_;
209
210 print $x + $y . "\n";
211 }, '$x, $y', $prelude;
212
213Takes a string of code, a string of arguments, a string of code which acts as a
214"prelude", and a B<Boolean> representing whether or not to localize the
215arguments.
216
217=head2 capture_unroll
218
8a4aa214 219 my $prelude = capture_unroll '$captures', {
8595641b 220 '$x' => 1,
221 '$y' => 2,
8a4aa214 222 }, 4;
223
224Arguments: $from, \%captures, $indent
8595641b 225
226Generates a snippet of code which is suitable to be used as a prelude for
8a4aa214 227L</inlinify>. C<$from> is a string will be used as a hashref in the resulting
228code. The keys of C<%captures> are the names of the variables and the values
229are ignored. C<$indent> is the number of spaces to indent the result by.
9c820461 230
231=head1 CAVEATS
232
233Much of this is just string-based code-generation, and as a result, a few caveats
234apply.
235
236=head2 return
237
238Calling C<return> from a quote_sub'ed sub will not likely do what you intend.
239Instead of returning from the code you defined in C<quote_sub>, it will return
240from the overall function it is composited into.
241
242So when you pass in:
243
244 quote_sub q{ return 1 if $condition; $morecode }
245
246It might turn up in the intended context as follows:
247
248 sub foo {
249
250 <important code a>
251 do {
252 return 1 if $condition;
253 $morecode
254 };
255 <important code b>
256
257 }
258
259Which will obviously return from foo, when all you meant to do was return from
260the code context in quote_sub and proceed with running important code b.
072d158f 261
da2ddf62 262=head2 strictures
263
264Sub::Quote compiles quoted subs in an environment where C<< use strictures >>
265is in effect. L<strictures> enables L<strict> and FATAL L<warnings>.
266
267The following dies I<< Use of uninitialized value in print... >>
268
269 no warnings;
270 quote_sub 'Silly::kitty', q{ print undef };
271
272If you need to disable parts of strictures, do it within the quoted sub:
273
274 quote_sub 'Silly::kitty', q{ no warnings; print undef };
275
072d158f 276=head1 SUPPORT
277
1108b2e2 278See L<Moo> for support and contact information.
072d158f 279
280=head1 AUTHORS
281
282See L<Moo> for authors.
283
284=head1 COPYRIGHT AND LICENSE
285
286See L<Moo> for the copyright and license.