Add a line option for controlling that bit as well
[gitmo/Eval-Closure.git] / lib / Eval / Closure.pm
CommitLineData
efb592ef 1package Eval::Closure;
b3bd5eb8 2use strict;
3use warnings;
efb592ef 4use Sub::Exporter -setup => {
5 exports => [qw(eval_closure)],
ce19c70b 6 groups => { default => [qw(eval_closure)] },
efb592ef 7};
ed9a00ae 8# ABSTRACT: safely and cleanly create closures via string eval
efb592ef 9
10use Carp;
11use overload ();
61717119 12use Memoize;
efb592ef 13use Scalar::Util qw(reftype);
14use Try::Tiny;
15
ed9a00ae 16=head1 SYNOPSIS
17
2e6086ab 18 use Eval::Closure;
19
20 my $code = eval_closure(
21 source => 'sub { $foo++ }',
22 environment => {
23 '$foo' => \1,
24 },
25 );
26
27 warn $code->(); # 1
28 warn $code->(); # 2
29
30 my $code2 = eval_closure(
31 source => 'sub { $code->() }',
32 ); # dies, $code isn't in scope
33
ed9a00ae 34=head1 DESCRIPTION
35
2e6086ab 36String eval is often used for dynamic code generation. For instance, C<Moose>
37uses it heavily, to generate inlined versions of accessors and constructors,
38which speeds code up at runtime by a significant amount. String eval is not
39without its issues however - it's difficult to control the scope it's used in
40(which determines which variables are in scope inside the eval), and it can be
41quite slow, especially if doing a large number of evals.
42
43This module attempts to solve both of those problems. It provides an
44C<eval_closure> function, which evals a string in a clean environment, other
45than a fixed list of specified variables. It also caches the result of the
c524c0f3 46eval, so that doing repeated evals of the same source, even with a different
47environment, will be much faster (but note that the description is part of the
48string to be evaled, so it must also be the same (or non-existent) if caching
49is to work properly).
2e6086ab 50
ed9a00ae 51=cut
52
53=func eval_closure(%args)
54
2e6086ab 55This function provides the main functionality of this module. It is exported by
56default. It takes a hash of parameters, with these keys being valid:
57
58=over 4
59
60=item source
61
62The string to be evaled. It should end by returning a code reference. It can
63access any variable declared in the C<environment> parameter (and only those
64variables). It can be either a string, or an arrayref of lines (which will be
65joined with newlines to produce the string).
66
67=item environment
68
69The environment to provide to the eval. This should be a hashref, mapping
70variable names (including sigils) to references of the appropriate type. For
71instance, a valid value for environment would be C<< { '@foo' => [] } >> (which
72would allow the generated function to use an array named C<@foo>). Generally,
73this is used to allow the generated function to access externally defined
74variables (so you would pass in a reference to a variable that already exists).
75
76=item description
77
78This lets you provide a bit more information in backtraces. Normally, when a
79function that was generated through string eval is called, that stack frame
80will show up as "(eval n)", where 'n' is a sequential identifier for every
81string eval that has happened so far in the program. Passing a C<description>
82parameter lets you override that to something more useful (for instance,
83L<Moose> overrides the description for accessors to something like "accessor
c4318911 84foo at MyClass.pm, line 123").
2e6086ab 85
75e6988b 86=item line
87
88This lets you override the particular line number that appears in backtraces,
89much like the description option. The default is "1".
90
5617e966 91=item terse_error
92
93Normally, this function appends the source code that failed to compile, and
94prepends some explanatory text. Setting this option to true suppresses that
95behavior so you get only the compilation error that Perl actually reported.
96
2e6086ab 97=back
98
ed9a00ae 99=cut
100
efb592ef 101sub eval_closure {
102 my (%args) = @_;
8e1b3d7b 103
efb592ef 104 $args{source} = _canonicalize_source($args{source});
8e1b3d7b 105 _validate_env($args{environment} ||= {});
efb592ef 106
75e6988b 107 $args{source} = _line_directive(@args{qw(line description)}) . $args{source}
68cb1ade 108 if defined $args{description};
3efcc087 109
409b8f41 110 my ($code, $e) = _clean_eval_closure(@args{qw(source environment)});
efb592ef 111
5617e966 112 if (!$code) {
113 if ($args{terse_error}) {
114 die "$e\n";
115 }
116 else {
117 croak("Failed to compile source: $e\n\nsource:\n$args{source}")
118 }
119 }
efb592ef 120
121 return $code;
122}
123
124sub _canonicalize_source {
125 my ($source) = @_;
126
127 if (defined($source)) {
128 if (ref($source)) {
129 if (reftype($source) eq 'ARRAY'
130 || overload::Method($source, '@{}')) {
131 return join "\n", @$source;
132 }
133 elsif (overload::Method($source, '""')) {
134 return "$source";
135 }
136 else {
137 croak("The 'source' parameter to eval_closure must be a "
138 . "string or array reference");
139 }
140 }
141 else {
142 return $source;
143 }
144 }
145 else {
146 croak("The 'source' parameter to eval_closure is required");
147 }
148}
149
8e1b3d7b 150sub _validate_env {
151 my ($env) = @_;
152
153 croak("The 'environment' parameter must be a hashref")
154 unless reftype($env) eq 'HASH';
155
156 for my $var (keys %$env) {
b3bd5eb8 157 croak("Environment key '$var' should start with \@, \%, or \$")
8e1b3d7b 158 unless $var =~ /^([\@\%\$])/;
159 croak("Environment values must be references, not $env->{$var}")
160 unless ref($env->{$var});
161 }
162}
163
3efcc087 164sub _line_directive {
75e6988b 165 my ($line, $description) = @_;
166
167 $line = 1 if !defined($line);
3efcc087 168
75e6988b 169 return qq{#line $line "$description"\n};
3efcc087 170}
171
efb592ef 172sub _clean_eval_closure {
f3c27658 173 my ($source, $captures) = @_;
efb592ef 174
a30f41f7 175 if ($ENV{EVAL_CLOSURE_PRINT_SOURCE}) {
f3c27658 176 _dump_source(_make_compiler_source(@_));
a30f41f7 177 }
efb592ef 178
53b0abc5 179 my @capture_keys = sort keys %$captures;
447800b5 180 my ($compiler, $e) = _make_compiler($source, @capture_keys);
f3c27658 181 my $code;
182 if (defined $compiler) {
447800b5 183 $code = $compiler->(@$captures{@capture_keys});
f3c27658 184 }
26eb0e7a 185
b86710e9 186 if (defined($code) && (!ref($code) || ref($code) ne 'CODE')) {
3eb05ecb 187 $e = "The 'source' parameter must return a subroutine reference, "
188 . "not $code";
26eb0e7a 189 undef $code;
26eb0e7a 190 }
191
18b5b42a 192 return ($code, $e);
efb592ef 193}
194
f3c27658 195sub _make_compiler {
196 local $@;
197 local $SIG{__DIE__};
198 my $compiler = eval _make_compiler_source(@_);
199 my $e = $@;
200 return ($compiler, $e);
201}
61717119 202memoize('_make_compiler');
f3c27658 203
204sub _make_compiler_source {
447800b5 205 my ($source, @capture_keys) = @_;
f3c27658 206 my $i = 0;
efb592ef 207 return join "\n", (
f3c27658 208 'sub {',
efb592ef 209 (map {
f3c27658 210 'my ' . $_ . ' = ' . substr($_, 0, 1) . '{$_[' . $i++ . ']};'
447800b5 211 } @capture_keys),
efb592ef 212 $source,
f3c27658 213 '}',
efb592ef 214 );
215}
216
217sub _dump_source {
409b8f41 218 my ($source) = @_;
efb592ef 219
220 my $output;
221 if (try { require Perl::Tidy }) {
222 Perl::Tidy::perltidy(
223 source => \$source,
224 destination => \$output,
225 );
226 }
227 else {
228 $output = $source;
229 }
230
409b8f41 231 warn "$output\n";
efb592ef 232}
233
ed9a00ae 234=head1 BUGS
235
236No known bugs.
237
238Please report any bugs through RT: email
239C<bug-eval-closure at rt.cpan.org>, or browse to
240L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Eval-Closure>.
241
242=head1 SEE ALSO
243
244=over 4
245
246=item * L<Class::MOP::Method::Accessor>
247
248This module is a factoring out of code that used to live here
249
250=back
251
252=head1 SUPPORT
253
254You can find this documentation for this module with the perldoc command.
255
256 perldoc Eval::Closure
257
258You can also look for information at:
259
260=over 4
261
262=item * AnnoCPAN: Annotated CPAN documentation
263
264L<http://annocpan.org/dist/Eval-Closure>
265
266=item * CPAN Ratings
267
268L<http://cpanratings.perl.org/d/Eval-Closure>
269
270=item * RT: CPAN's request tracker
271
272L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Eval-Closure>
273
274=item * Search CPAN
275
276L<http://search.cpan.org/dist/Eval-Closure>
277
278=back
279
280=head1 AUTHOR
281
282Jesse Luehrs <doy at tozt dot net>
283
284Based on code from L<Class::MOP::Method::Accessor>, by Stevan Little and the
285Moose Cabal.
286
287=cut
288
efb592ef 2891;