4 # ABSTRACT: safely and cleanly create closures via string eval
7 @Eval::Closure::EXPORT = @Eval::Closure::EXPORT_OK = 'eval_closure';
11 use Scalar::Util qw(reftype);
14 use constant HAS_LEXICAL_SUBS => $] >= 5.018;
20 my $code = eval_closure(
21 source => 'sub { $foo++ }',
30 my $code2 = eval_closure(
31 source => 'sub { $code->() }',
32 ); # dies, $code isn't in scope
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's easy
41 to miss compilation errors, since eval catches them and sticks them in $@
44 This module attempts to solve these problems. It provides an C<eval_closure>
45 function, which evals a string in a clean environment, other than a fixed list
46 of specified variables. Compilation errors are rethrown automatically.
50 =func eval_closure(%args)
52 This function provides the main functionality of this module. It is exported by
53 default. It takes a hash of parameters, with these keys being valid:
59 The string to be evaled. It should end by returning a code reference. It can
60 access any variable declared in the C<environment> parameter (and only those
61 variables). It can be either a string, or an arrayref of lines (which will be
62 joined with newlines to produce the string).
66 The environment to provide to the eval. This should be a hashref, mapping
67 variable names (including sigils) to references of the appropriate type. For
68 instance, a valid value for environment would be C<< { '@foo' => [] } >> (which
69 would allow the generated function to use an array named C<@foo>). Generally,
70 this is used to allow the generated function to access externally defined
71 variables (so you would pass in a reference to a variable that already exists).
73 In perl 5.18 and greater, the environment hash can contain variables with a
74 sigil of C<&>. This will create a lexical sub in the evaluated code (see
75 L<feature/The 'lexical_subs' feature>). Using a C<&> sigil on perl versions
76 before lexical subs were available will throw an error.
80 This lets you provide a bit more information in backtraces. Normally, when a
81 function that was generated through string eval is called, that stack frame
82 will show up as "(eval n)", where 'n' is a sequential identifier for every
83 string eval that has happened so far in the program. Passing a C<description>
84 parameter lets you override that to something more useful (for instance,
85 L<Moose> overrides the description for accessors to something like "accessor
86 foo at MyClass.pm, line 123").
90 This lets you override the particular line number that appears in backtraces,
91 much like the C<description> option. The default is 1.
95 Normally, this function appends the source code that failed to compile, and
96 prepends some explanatory text. Setting this option to true suppresses that
97 behavior so you get only the compilation error that Perl actually reported.
106 $args{source} = _canonicalize_source($args{source});
107 _validate_env($args{environment} ||= {});
109 $args{source} = _line_directive(@args{qw(line description)})
111 if defined $args{description} && !($^P & 0x10);
113 my ($code, $e) = _clean_eval_closure(@args{qw(source environment)});
116 if ($args{terse_error}) {
120 croak("Failed to compile source: $e\n\nsource:\n$args{source}")
127 sub _canonicalize_source {
130 if (defined($source)) {
132 if (reftype($source) eq 'ARRAY'
133 || overload::Method($source, '@{}')) {
134 return join "\n", @$source;
136 elsif (overload::Method($source, '""')) {
140 croak("The 'source' parameter to eval_closure must be a "
141 . "string or array reference");
149 croak("The 'source' parameter to eval_closure is required");
156 croak("The 'environment' parameter must be a hashref")
157 unless reftype($env) eq 'HASH';
159 for my $var (keys %$env) {
160 if (HAS_LEXICAL_SUBS) {
161 croak("Environment key '$var' should start with \@, \%, \$, or \&")
162 unless $var =~ /^([\@\%\$\&])/;
165 croak("Environment key '$var' should start with \@, \%, or \$")
166 unless $var =~ /^([\@\%\$])/;
168 croak("Environment values must be references, not $env->{$var}")
169 unless ref($env->{$var});
173 sub _line_directive {
174 my ($line, $description) = @_;
176 $line = 1 unless defined($line);
178 return qq{#line $line "$description"\n};
181 sub _clean_eval_closure {
182 my ($source, $captures) = @_;
184 my @capture_keys = sort keys %$captures;
186 if ($ENV{EVAL_CLOSURE_PRINT_SOURCE}) {
187 _dump_source(_make_compiler_source($source, @capture_keys));
190 my ($compiler, $e) = _make_compiler($source, @capture_keys);
192 if (defined $compiler) {
193 $code = $compiler->(@$captures{@capture_keys});
196 if (defined($code) && (!ref($code) || ref($code) ne 'CODE')) {
197 $e = "The 'source' parameter must return a subroutine reference, "
206 my $source = _make_compiler_source(@_);
208 return @{ _clean_eval($source) };
214 my $compiler = eval $_[0];
219 $Eval::Closure::SANDBOX_ID = 0;
221 sub _make_compiler_source {
222 my ($source, @capture_keys) = @_;
223 $Eval::Closure::SANDBOX_ID++;
226 "package Eval::Closure::Sandbox_$Eval::Closure::SANDBOX_ID;",
228 (map { _make_lexical_assignment($_, $i++) } @capture_keys),
234 sub _make_lexical_assignment {
235 my ($key, $index) = @_;
236 my $sigil = substr($key, 0, 1);
237 my $name = substr($key, 1);
238 if (HAS_LEXICAL_SUBS && $sigil eq '&') {
239 my $tmpname = '$__' . $name . '__' . $index;
240 return 'use feature "lexical_subs"; '
241 . 'no warnings "experimental::lexical_subs"; '
242 . 'my ' . $tmpname . ' = $_[' . $index . ']; '
243 . 'my sub ' . $name . ' { goto ' . $tmpname . ' }';
246 return 'my ' . $key . ' = ' . $sigil . '{$_[' . $index . ']};';
254 if (try { require Perl::Tidy }) {
255 Perl::Tidy::perltidy(
257 destination => \$output,
272 Please report any bugs to GitHub Issues at L<https://github.com/doy/eval-closure/issues>.
278 =item * L<Class::MOP::Method::Accessor>
280 This module is a factoring out of code that used to live here
286 You can find this documentation for this module with the perldoc command.
288 perldoc Eval::Closure
290 You can also look for information at:
296 L<https://metacpan.org/release/Reply>
300 L<https://github.com/doy/reply>
302 =item * RT: CPAN's request tracker
304 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Reply>
308 L<http://cpanratings.perl.org/d/Reply>
314 Based on code from L<Class::MOP::Method::Accessor>, by Stevan Little and the