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);
19 my ($from, $captures, $indent) = @_;
24 or die "capture key should start with \@, \% or \$: $_";
25 (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
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) {
37 $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
40 $do.($local ? 'local ' : '').'@_ = ('.$args.'); '.$code.' }';
45 # HOLY DWIMMERY, BATMAN!
46 # $name => $code => \%captures => \%options
47 # $name => $code => \%captures
49 # $code => \%captures => \%options
52 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
55 my $captures = pop if ref($_[-1]) eq 'HASH';
56 undef($captures) if $captures && !keys %$captures;
60 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
61 unquote_sub($outstanding);
63 $outstanding = "$deferred";
64 $QUOTED{$outstanding} = [ $name, $code, $captures ];
65 weaken($WEAK_REFS{$outstanding} = $deferred);
71 $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
76 unless ($QUOTED{$sub}[3]) {
77 my ($name, $code, $captures) = @{$QUOTED{$sub}};
81 if (keys %$captures) {
82 $make_sub .= capture_unroll("\$_[1]", $captures, 2);
85 my $o_quoted = perlstring $sub;
88 # disable the 'variable $x will not stay shared' warning since
89 # we're not letting it escape from this scope anyway so there's
90 # nothing trying to share it
91 ? " no warnings 'closure';\n sub ${name} {\n"
92 : " \$Sub::Quote::QUOTED{${o_quoted}}[3] = sub {\n"
95 $make_sub .= " }".($name ? '' : ';')."\n";
97 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
99 $make_sub .= "}\n1;\n";
100 $ENV{SUB_QUOTE_DEBUG} && warn $make_sub;
104 local *{$name} if $name;
105 unless (_clean_eval $make_sub, $captures) {
106 die "Eval went very, very wrong:\n\n${make_sub}\n\n$@";
117 Sub::Quote - efficient generation of subroutines via string eval
123 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
125 quote_sub 'Silly::kitty', q{ print "meow" };
127 quote_sub 'Silly::doggy', q{ print "woof" };
131 quote_sub 'Silly::dagron',
132 q{ print ++$sound % 2 ? 'burninate' : 'roar' },
133 { '$sound' => \$sound };
139 Silly->dagron; # burninate
140 Silly->dagron; # roar
141 Silly->dagron; # burninate
145 This package provides performant ways to generate subroutines from strings.
151 my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
153 Arguments: ?$name, $code, ?\%captures, ?\%options
155 C<$name> is the subroutine where the coderef will be installed.
157 C<$code> is a string that will be turned into code.
159 C<\%captures> is a hashref of variables that will be made available to the
160 code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
168 B<Boolean>. Set this option to not install the generated coderef into the
169 passed subroutine name on undefer.
175 my $coderef = unquote_sub $sub;
177 Forcibly replace subroutine with actual code. Note that for performance
178 reasons all quoted subs declared so far will be globally unquoted/parsed in
179 a single eval. This means that if you have a syntax error in one of your
180 quoted subs you may find out when some other sub is unquoted.
182 If $sub is not a quoted sub, this is a no-op.
184 =head2 quoted_from_sub
186 my $data = quoted_from_sub $sub;
188 my ($name, $code, $captures, $compiled_sub) = @$data;
190 Returns original arguments to quote_sub, plus the compiled version if this
191 sub has already been unquoted.
193 Note that $sub can be either the original quoted version or the compiled
194 version for convenience.
198 my $prelude = capture_unroll {
203 my $inlined_code = inlinify q{
206 print $x + $y . "\n";
207 }, '$x, $y', $prelude;
209 Takes a string of code, a string of arguments, a string of code which acts as a
210 "prelude", and a B<Boolean> representing whether or not to localize the
213 =head2 capture_unroll
215 my $prelude = capture_unroll {
220 Generates a snippet of code which is suitable to be used as a prelude for
221 L</inlinify>. The keys are the names of the variables and the values are (duh)
222 the values. Note that references work as values.
226 Much of this is just string-based code-generation, and as a result, a few caveats
231 Calling C<return> from a quote_sub'ed sub will not likely do what you intend.
232 Instead of returning from the code you defined in C<quote_sub>, it will return
233 from the overall function it is composited into.
237 quote_sub q{ return 1 if $condition; $morecode }
239 It might turn up in the intended context as follows:
245 return 1 if $condition;
252 Which will obviously return from foo, when all you meant to do was return from
253 the code context in quote_sub and proceed with running important code b.