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