5 sub _clean_eval { eval $_[0] }
9 use Scalar::Util qw(weaken);
10 use base qw(Exporter);
12 our @EXPORT = qw(quote_sub unquote_sub quoted_from_sub);
14 our %QUOTE_OUTSTANDING;
21 my ($from, $captures, $indent) = @_;
26 or die "capture key should start with \@, \% or \$: $_";
27 (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
33 my ($code, $args, $extra, $local) = @_;
34 my $do = 'do { '.($extra||'');
35 if (my ($code_args, $body) = $code =~ / +my \(([^)]+)\) = \@_;(.*)$/s) {
36 if ($code_args eq $args) {
39 $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
42 $do.($local ? 'local ' : '').'@_ = ('.$args.'); '.$code.' }';
46 sub _unquote_all_outstanding {
47 return unless %QUOTE_OUTSTANDING;
48 my ($assembled_code, @assembled_captures, @localize_these) = '';
49 # we sort the keys in order to make debugging more predictable
50 foreach my $outstanding (sort keys %QUOTE_OUTSTANDING) {
51 my ($name, $code, $captures) = @{$QUOTE_OUTSTANDING{$outstanding}};
53 push @localize_these, $name if $name;
57 if (keys %$captures) {
58 my $ass_cap_count = @assembled_captures;
59 $make_sub .= capture_unroll("\$_[1][${ass_cap_count}]", $captures, 2);
60 push @assembled_captures, $captures;
63 my $o_quoted = perlstring $outstanding;
66 # disable the 'variable $x will not stay shared' warning since
67 # we're not letting it escape from this scope anyway so there's
68 # nothing trying to share it
69 ? " no warnings 'closure';\n sub ${name} {\n"
70 : " \$Sub::Quote::QUOTED{${o_quoted}}[3] = sub {\n"
73 $make_sub .= " }".($name ? '' : ';')."\n";
75 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
78 $assembled_code .= $make_sub;
80 my $debug_code = $assembled_code;
81 if (@localize_these) {
83 "# localizing: ".join(', ', @localize_these)."\n"
85 $assembled_code = join("\n",
86 (map { "local *${_};" } @localize_these),
87 'eval '.perlstring($assembled_code).'; die $@ if $@;'
90 $ENV{SUB_QUOTE_DEBUG} && warn $assembled_code;
92 $assembled_code .= "\n1;";
95 unless (_clean_eval $assembled_code, \@assembled_captures) {
96 die "Eval went very, very wrong:\n\n${debug_code}\n\n$@";
99 $ENV{SUB_QUOTE_DEBUG} && warn $debug_code;
100 %QUOTE_OUTSTANDING = ();
104 # HOLY DWIMMERY, BATMAN!
105 # $name => $code => \%captures => \%options
106 # $name => $code => \%captures
108 # $code => \%captures => \%options
111 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
114 my $captures = pop if ref($_[-1]) eq 'HASH';
115 undef($captures) if $captures && !keys %$captures;
119 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
120 unquote_sub($outstanding);
122 $outstanding = "$deferred";
123 $QUOTE_OUTSTANDING{$outstanding} = $QUOTED{$outstanding} = [
124 $name, $code, $captures
126 weaken($WEAK_REFS{$outstanding} = $deferred);
130 sub quoted_from_sub {
132 $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
137 _unquote_all_outstanding;
145 Sub::Quote - efficient generation of subroutines via string eval
151 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
153 quote_sub 'Silly::kitty', q{ print "meow" };
155 quote_sub 'Silly::doggy', q{ print "woof" };
159 quote_sub 'Silly::dagron',
160 q{ print ++$sound % 2 ? 'burninate' : 'roar' },
161 { '$sound' => \$sound };
167 Silly->dagron; # burninate
168 Silly->dagron; # roar
169 Silly->dagron; # burninate
173 This package provides performant ways to generate subroutines from strings.
179 my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
181 Arguments: ?$name, $code, ?\%captures, ?\%options
183 C<$name> is the subroutine where the coderef will be installed.
185 C<$code> is a string that will be turned into code.
187 C<\%captures> is a hashref of variables that will be made available to the
188 code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
196 B<Boolean>. Set this option to not install the generated coderef into the
197 passed subroutine name on undefer.
203 my $coderef = unquote_sub $sub;
205 Forcibly replace subroutine with actual code. Note that for performance
206 reasons all quoted subs declared so far will be globally unquoted/parsed in
207 a single eval. This means that if you have a syntax error in one of your
208 quoted subs you may find out when some other sub is unquoted.
210 If $sub is not a quoted sub, this is a no-op.
212 =head2 quoted_from_sub
214 my $data = quoted_from_sub $sub;
216 my ($name, $code, $captures, $compiled_sub) = @$data;
218 Returns original arguments to quote_sub, plus the compiled version if this
219 sub has already been unquoted.
221 Note that $sub can be either the original quoted version or the compiled
222 version for convenience.
226 my $prelude = capture_unroll {
231 my $inlined_code = inlinify q{
234 print $x + $y . "\n";
235 }, '$x, $y', $prelude;
237 Takes a string of code, a string of arguments, a string of code which acts as a
238 "prelude", and a B<Boolean> representing whether or not to localize the
241 =head2 capture_unroll
243 my $prelude = capture_unroll {
248 Generates a snippet of code which is suitable to be used as a prelude for
249 L</inlinify>. The keys are the names of the variables and the values are (duh)
250 the values. Note that references work as values.