Fix wording on global unquote
[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';
9use base qw(Exporter);
10
625d6219 11our @EXPORT = qw(quote_sub unquote_sub quoted_from_sub);
a165a07f 12
13our %QUOTE_OUTSTANDING;
14
15our %QUOTED;
16
8c6626cf 17sub capture_unroll {
18 my ($from, $captures, $indent) = @_;
19 join(
20 '',
21 map {
22 /^([\@\%\$])/
17a8e3f0 23 or die "capture key should start with \@, \% or \$: $_";
8c6626cf 24 (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
25 } keys %$captures
26 );
27}
28
e57f338d 29sub inlinify {
30 my ($code, $args, $extra, $local) = @_;
31 my $do = 'do { '.($extra||'');
32 if (my ($code_args, $body) = $code =~ / +my \(([^)]+)\) = \@_;(.*)$/s) {
33 if ($code_args eq $args) {
34 $do.$body.' }'
35 } else {
f537c364 36 $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
e57f338d 37 }
38 } else {
39 $do.($local ? 'local ' : '').'@_ = ('.$args.'); '.$code.' }';
40 }
41}
42
a165a07f 43sub _unquote_all_outstanding {
44 return unless %QUOTE_OUTSTANDING;
45 my ($assembled_code, @assembled_captures, @localize_these) = '';
6d377074 46 # we sort the keys in order to make debugging more predictable
47 foreach my $outstanding (sort keys %QUOTE_OUTSTANDING) {
a165a07f 48 my ($name, $code, $captures) = @{$QUOTE_OUTSTANDING{$outstanding}};
49
50 push @localize_these, $name if $name;
51
52 my $make_sub = "{\n";
53
54 if (keys %$captures) {
55 my $ass_cap_count = @assembled_captures;
8c6626cf 56 $make_sub .= capture_unroll("\$_[1][${ass_cap_count}]", $captures, 2);
a165a07f 57 push @assembled_captures, $captures;
58 }
59
60 my $o_quoted = perlstring $outstanding;
61 $make_sub .= (
62 $name
934ea2c1 63 # disable the 'variable $x will not stay shared' warning since
64 # we're not letting it escape from this scope anyway so there's
65 # nothing trying to share it
a165a07f 66 ? " no warnings 'closure';\n sub ${name} {\n"
934ea2c1 67 : " \$Sub::Quote::QUOTED{${o_quoted}}[3] = sub {\n"
a165a07f 68 );
69 $make_sub .= $code;
70 $make_sub .= " }".($name ? '' : ';')."\n";
71 if ($name) {
72 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
73 }
74 $make_sub .= "}\n";
75 $assembled_code .= $make_sub;
76 }
a16d301e 77 my $debug_code = $assembled_code;
a165a07f 78 if (@localize_these) {
a16d301e 79 $debug_code =
e8b2bab6 80 "# localizing: ".join(', ', @localize_these)."\n"
81 .$assembled_code;
a165a07f 82 $assembled_code = join("\n",
83 (map { "local *${_};" } @localize_these),
a16d301e 84 'eval '.perlstring($assembled_code).'; die $@ if $@;'
a165a07f 85 );
e8b2bab6 86 } else {
87 $ENV{SUB_QUOTE_DEBUG} && warn $assembled_code;
a165a07f 88 }
a16d301e 89 $assembled_code .= "\n1;";
90 unless (_clean_eval $assembled_code, \@assembled_captures) {
91 die "Eval went very, very wrong:\n\n${debug_code}\n\n$@";
a165a07f 92 }
a16d301e 93 $ENV{SUB_QUOTE_DEBUG} && warn $debug_code;
a165a07f 94 %QUOTE_OUTSTANDING = ();
95}
96
97sub quote_sub {
98 # HOLY DWIMMERY, BATMAN!
6f68f022 99 # $name => $code => \%captures => \%options
a165a07f 100 # $name => $code => \%captures
101 # $name => $code
6f68f022 102 # $code => \%captures => \%options
a165a07f 103 # $code
6f68f022 104 my $options =
105 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
106 ? pop
107 : {};
a165a07f 108 my $captures = pop if ref($_[-1]) eq 'HASH';
625d6219 109 undef($captures) if $captures && !keys %$captures;
a165a07f 110 my $code = pop;
111 my $name = $_[0];
112 my $outstanding;
6f68f022 113 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
a165a07f 114 unquote_sub($outstanding);
115 };
116 $outstanding = "$deferred";
117 $QUOTE_OUTSTANDING{$outstanding} = $QUOTED{$outstanding} = [
118 $name, $code, $captures
119 ];
120 return $deferred;
121}
122
123sub quoted_from_sub {
124 my ($sub) = @_;
6d377074 125 $QUOTED{$sub||''};
a165a07f 126}
127
128sub unquote_sub {
129 my ($sub) = @_;
130 _unquote_all_outstanding;
131 $QUOTED{$sub}[3];
132}
133
1341;
8595641b 135
0b6e5fff 136=head1 NAME
137
138Sub::Quote - efficient generation of subroutines via string eval
8595641b 139
140=head1 SYNOPSIS
141
142 package Silly;
143
144 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
145
146 quote_sub 'Silly::kitty', q{ print "meow" };
147
148 quote_sub 'Silly::doggy', q{ print "woof" };
149
150 my $sound; $$sound = 0;
151
152 quote_sub 'Silly::dagron',
153 q{ print ++$$sound % 2 ? 'burninate' : 'roar' },
154 { '$sound' => \$sound };
155
156And elsewhere:
157
158 Silly->kitty; # meow
159 Silly->doggy; # woof
160 Silly->dagron; # burninate
161 Silly->dagron; # roar
162 Silly->dagron; # burninate
163
164=head1 DESCRIPTION
165
166This package provides performant ways to generate subroutines from strings.
167
168=head1 SUBROUTINES
169
170=head2 quote_sub
171
172 my $coderef = quote_sub 'Foo:bar', q{ print $x++ . "\n" }, { '$x' => \0 };
173
174Arguments: ?$name, $code, ?\%captures, ?\%options
175
176C<$name> is the subroutine where the coderef will be installed.
177
178C<$code> is a string that will be turned into code.
179
180C<\%captures> is a hashref of variables that will be made available to the
181code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
182
183=head3 options
184
185=over 2
186
187=item * no_install
188
189B<Boolean>. Set this option to not install the generated coderef into the
005c00f2 190passed subroutine name on undefer.
8595641b 191
192=back
193
194=head2 unquote_sub
195
005c00f2 196 my $coderef = unquote_sub $sub;
8595641b 197
0d39f9d3 198Forcibly replace subroutine with actual code. Note that for performance
199reasons all quoted subs declared so far will be globally unquoted/parsed in
200a single eval. This means that if you have a syntax error in one of your
201quoted subs you may find out when some other sub is unquoted.
8595641b 202
005c00f2 203If $sub is not a quoted sub, this is a no-op.
204
8595641b 205=head2 quoted_from_sub
206
005c00f2 207 my $data = quoted_from_sub $sub;
208
209 my ($name, $code, $captures, $compiled_sub) = @$data;
210
211Returns original arguments to quote_sub, plus the compiled version if this
212sub has already been unquoted.
8595641b 213
005c00f2 214Note that $sub can be either the original quoted version or the compiled
215version for convenience.
8595641b 216
217=head2 inlinify
218
219 my $prelude = capture_unroll {
220 '$x' => 1,
221 '$y' => 2,
222 };
223
224 my $inlined_code = inlinify q{
225 my ($x, $y) = @_;
226
227 print $x + $y . "\n";
228 }, '$x, $y', $prelude;
229
230Takes a string of code, a string of arguments, a string of code which acts as a
231"prelude", and a B<Boolean> representing whether or not to localize the
232arguments.
233
234=head2 capture_unroll
235
236 my $prelude = capture_unroll {
237 '$x' => 1,
238 '$y' => 2,
239 };
240
241Generates a snippet of code which is suitable to be used as a prelude for
242L</inlinify>. The keys are the names of the variables and the values are (duh)
243the values. Note that references work as values.