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