remove the outstanding queue from Sub::Quote; benchamarks show it didn't actually...
[gitmo/Role-Tiny.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 {
40 $do.($local ? 'local ' : '').'@_ = ('.$args.'); '.$code.' }';
41 }
42}
43
a165a07f 44sub quote_sub {
45 # HOLY DWIMMERY, BATMAN!
6f68f022 46 # $name => $code => \%captures => \%options
a165a07f 47 # $name => $code => \%captures
48 # $name => $code
6f68f022 49 # $code => \%captures => \%options
a165a07f 50 # $code
6f68f022 51 my $options =
52 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
53 ? pop
54 : {};
a165a07f 55 my $captures = pop if ref($_[-1]) eq 'HASH';
625d6219 56 undef($captures) if $captures && !keys %$captures;
a165a07f 57 my $code = pop;
58 my $name = $_[0];
59 my $outstanding;
6f68f022 60 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
a165a07f 61 unquote_sub($outstanding);
62 };
63 $outstanding = "$deferred";
55d91f64 64 $QUOTED{$outstanding} = [ $name, $code, $captures ];
8a0ad775 65 weaken($WEAK_REFS{$outstanding} = $deferred);
a165a07f 66 return $deferred;
67}
68
69sub quoted_from_sub {
70 my ($sub) = @_;
8a0ad775 71 $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
a165a07f 72}
73
74sub unquote_sub {
75 my ($sub) = @_;
55d91f64 76 unless ($QUOTED{$sub}[3]) {
77 my ($name, $code, $captures) = @{$QUOTED{$sub}};
78
79 my $make_sub = "{\n";
80
81 if (keys %$captures) {
82 $make_sub .= capture_unroll("\$_[1]", $captures, 2);
83 }
84
85 my $o_quoted = perlstring $sub;
86 $make_sub .= (
87 $name
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"
93 );
94 $make_sub .= $code;
95 $make_sub .= " }".($name ? '' : ';')."\n";
96 if ($name) {
97 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
98 }
99 $make_sub .= "}\n1;\n";
100 $ENV{SUB_QUOTE_DEBUG} && warn $make_sub;
101 {
102 local $@;
103 no strict 'refs';
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$@";
107 }
108 }
109 }
a165a07f 110 $QUOTED{$sub}[3];
111}
112
1131;
8595641b 114
0b6e5fff 115=head1 NAME
116
117Sub::Quote - efficient generation of subroutines via string eval
8595641b 118
119=head1 SYNOPSIS
120
121 package Silly;
122
123 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
124
125 quote_sub 'Silly::kitty', q{ print "meow" };
126
127 quote_sub 'Silly::doggy', q{ print "woof" };
128
6b3002b2 129 my $sound = 0;
8595641b 130
131 quote_sub 'Silly::dagron',
6b3002b2 132 q{ print ++$sound % 2 ? 'burninate' : 'roar' },
8595641b 133 { '$sound' => \$sound };
134
135And elsewhere:
136
137 Silly->kitty; # meow
138 Silly->doggy; # woof
139 Silly->dagron; # burninate
140 Silly->dagron; # roar
141 Silly->dagron; # burninate
142
143=head1 DESCRIPTION
144
145This package provides performant ways to generate subroutines from strings.
146
147=head1 SUBROUTINES
148
149=head2 quote_sub
150
d925a566 151 my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
8595641b 152
153Arguments: ?$name, $code, ?\%captures, ?\%options
154
155C<$name> is the subroutine where the coderef will be installed.
156
157C<$code> is a string that will be turned into code.
158
159C<\%captures> is a hashref of variables that will be made available to the
160code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
161
162=head3 options
163
164=over 2
165
166=item * no_install
167
168B<Boolean>. Set this option to not install the generated coderef into the
005c00f2 169passed subroutine name on undefer.
8595641b 170
171=back
172
173=head2 unquote_sub
174
005c00f2 175 my $coderef = unquote_sub $sub;
8595641b 176
0d39f9d3 177Forcibly replace subroutine with actual code. Note that for performance
178reasons all quoted subs declared so far will be globally unquoted/parsed in
179a single eval. This means that if you have a syntax error in one of your
180quoted subs you may find out when some other sub is unquoted.
8595641b 181
005c00f2 182If $sub is not a quoted sub, this is a no-op.
183
8595641b 184=head2 quoted_from_sub
185
005c00f2 186 my $data = quoted_from_sub $sub;
187
188 my ($name, $code, $captures, $compiled_sub) = @$data;
189
190Returns original arguments to quote_sub, plus the compiled version if this
191sub has already been unquoted.
8595641b 192
005c00f2 193Note that $sub can be either the original quoted version or the compiled
194version for convenience.
8595641b 195
196=head2 inlinify
197
198 my $prelude = capture_unroll {
199 '$x' => 1,
200 '$y' => 2,
201 };
202
203 my $inlined_code = inlinify q{
204 my ($x, $y) = @_;
205
206 print $x + $y . "\n";
207 }, '$x, $y', $prelude;
208
209Takes 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
211arguments.
212
213=head2 capture_unroll
214
215 my $prelude = capture_unroll {
216 '$x' => 1,
217 '$y' => 2,
218 };
219
220Generates a snippet of code which is suitable to be used as a prelude for
221L</inlinify>. The keys are the names of the variables and the values are (duh)
222the values. Note that references work as values.