4a9478e619f35fb9eb2f227f83c75314203a0afd
[gitmo/Moo.git] / lib / Sub / Quote.pm
1 package Sub::Quote;
2
3 use strictures 1;
4
5 sub _clean_eval { eval $_[0] }
6
7 use Sub::Defer;
8 use B 'perlstring';
9 use Scalar::Util qw(weaken);
10 use base qw(Exporter);
11
12 our @EXPORT = qw(quote_sub unquote_sub quoted_from_sub);
13
14 our %QUOTED;
15
16 our %WEAK_REFS;
17
18 sub capture_unroll {
19   my ($from, $captures, $indent) = @_;
20   join(
21     '',
22     map {
23       /^([\@\%\$])/
24         or die "capture key should start with \@, \% or \$: $_";
25       (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
26     } keys %$captures
27   );
28 }
29
30 sub 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 {
37       $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
38     }
39   } else {
40     my $assign = '';
41     if ($local || $args ne '@_') {
42       $assign = ($local ? 'local ' : '').'@_ = ('.$args.'); ';
43     }
44     $do.$assign.$code.' }';
45   }
46 }
47
48 sub quote_sub {
49   # HOLY DWIMMERY, BATMAN!
50   # $name => $code => \%captures => \%options
51   # $name => $code => \%captures
52   # $name => $code
53   # $code => \%captures => \%options
54   # $code
55   my $options =
56     (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
57       ? pop
58       : {};
59   my $captures = pop if ref($_[-1]) eq 'HASH';
60   undef($captures) if $captures && !keys %$captures;
61   my $code = pop;
62   my $name = $_[0];
63   my $outstanding;
64   my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
65     unquote_sub($outstanding);
66   };
67   $outstanding = "$deferred";
68   $QUOTED{$outstanding} = [ $name, $code, $captures ];
69   weaken($WEAK_REFS{$outstanding} = $deferred);
70   return $deferred;
71 }
72
73 sub quoted_from_sub {
74   my ($sub) = @_;
75   $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
76 }
77
78 sub unquote_sub {
79   my ($sub) = @_;
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   }
114   $QUOTED{$sub}[3];
115 }
116
117 1;
118
119 =head1 NAME
120
121 Sub::Quote - efficient generation of subroutines via string eval
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
133  my $sound = 0;
134
135  quote_sub 'Silly::dagron',
136    q{ print ++$sound % 2 ? 'burninate' : 'roar' },
137    { '$sound' => \$sound };
138
139 And elsewhere:
140
141  Silly->kitty;  # meow
142  Silly->doggy;  # woof
143  Silly->dagron; # burninate
144  Silly->dagron; # roar
145  Silly->dagron; # burninate
146
147 =head1 DESCRIPTION
148
149 This package provides performant ways to generate subroutines from strings.
150
151 =head1 SUBROUTINES
152
153 =head2 quote_sub
154
155  my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
156
157 Arguments: ?$name, $code, ?\%captures, ?\%options
158
159 C<$name> is the subroutine where the coderef will be installed.
160
161 C<$code> is a string that will be turned into code.
162
163 C<\%captures> is a hashref of variables that will be made available to the
164 code.  See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
165
166 =head3 options
167
168 =over 2
169
170 =item * no_install
171
172 B<Boolean>.  Set this option to not install the generated coderef into the
173 passed subroutine name on undefer.
174
175 =back
176
177 =head2 unquote_sub
178
179  my $coderef = unquote_sub $sub;
180
181 Forcibly replace subroutine with actual code.
182
183 If $sub is not a quoted sub, this is a no-op.
184
185 =head2 quoted_from_sub
186
187  my $data = quoted_from_sub $sub;
188
189  my ($name, $code, $captures, $compiled_sub) = @$data;
190
191 Returns original arguments to quote_sub, plus the compiled version if this
192 sub has already been unquoted.
193
194 Note that $sub can be either the original quoted version or the compiled
195 version for convenience.
196
197 =head2 inlinify
198
199  my $prelude = capture_unroll '$captures', {
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
210 Takes 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
212 arguments.
213
214 =head2 capture_unroll
215
216  my $prelude = capture_unroll '$captures', {
217    '$x' => 1,
218    '$y' => 2,
219  }, 4;
220
221 Arguments: $from, \%captures, $indent
222
223 Generates a snippet of code which is suitable to be used as a prelude for
224 L</inlinify>.  C<$from> is a string will be used as a hashref in the resulting
225 code.  The keys of C<%captures> are the names of the variables and the values
226 are ignored.  C<$indent> is the number of spaces to indent the result by.
227
228 =head1 CAVEATS
229
230 Much of this is just string-based code-generation, and as a result, a few caveats
231 apply.
232
233 =head2 return
234
235 Calling C<return> from a quote_sub'ed sub will not likely do what you intend.
236 Instead of returning from the code you defined in C<quote_sub>, it will return
237 from the overall function it is composited into.
238
239 So when you pass in:
240
241    quote_sub q{  return 1 if $condition; $morecode }
242
243 It might turn up in the intended context as follows:
244
245   sub foo {
246
247     <important code a>
248     do {
249       return 1 if $condition;
250       $morecode
251     };
252     <important code b>
253
254   }
255
256 Which will obviously return from foo, when all you meant to do was return from
257 the code context in quote_sub and proceed with running important code b.
258
259 =head2 strictures
260
261 Sub::Quote compiles quoted subs in an environment where C<< use strictures >>
262 is in effect. L<strictures> enables L<strict> and FATAL L<warnings>.
263
264 The following dies I<< Use of uninitialized value in print... >>
265
266  no warnings;
267  quote_sub 'Silly::kitty', q{ print undef };
268
269 If you need to disable parts of strictures, do it within the quoted sub:
270
271  quote_sub 'Silly::kitty', q{ no warnings; print undef };
272
273 =head1 SUPPORT
274
275 See L<Moo> for support and contact informations.
276
277 =head1 AUTHORS
278
279 See L<Moo> for authors.
280
281 =head1 COPYRIGHT AND LICENSE
282
283 See L<Moo> for the copyright and license.