Add persistent hints
[p5sagit/Eval-WithLexicals.git] / lib / Eval / WithLexicals.pm
1 package Eval::WithLexicals;
2
3 use Moo;
4 use Moo::Role ();
5 use Sub::Quote;
6
7 our $VERSION = '1.001000'; # 1.1.0
8 $VERSION = eval $VERSION;
9
10 has lexicals => (is => 'rw', default => quote_sub q{ {} });
11
12 {
13   my %valid_contexts = map +($_ => 1), qw(list scalar void);
14
15   has context => (
16     is => 'rw', default => quote_sub(q{ 'list' }),
17     isa => sub {
18       my ($val) = @_;
19       die "Invalid context type $val - should be list, scalar or void"
20         unless $valid_contexts{$val};
21     },
22   );
23 }
24
25 has in_package => (
26   is => 'rw', default => quote_sub q{ 'Eval::WithLexicals::Scratchpad' }
27 );
28
29 has prelude => (
30   is => 'rw', default => quote_sub q{ 'use strictures 1;' }
31 );
32
33 sub with_plugins {
34   my($class, @names) = @_;
35
36   Moo::Role->create_class_with_roles($class,
37     map "Eval::WithLexicals::With$_", @names);
38 }
39
40 sub setup_code {
41   my($self) = @_;
42   $self->prelude;
43 }
44
45 sub capture_code {
46   ( qq{ BEGIN { Eval::WithLexicals::Util::capture_list() } } )
47 }
48
49 sub eval {
50   my ($self, $to_eval) = @_;
51   local *Eval::WithLexicals::Cage::current_line;
52   local *Eval::WithLexicals::Cage::pad_capture;
53   local *Eval::WithLexicals::Cage::grab_captures;
54
55   my $package = $self->in_package;
56   my $setup_code = join '', $self->setup_code,
57     # $_[2] being what is passed to _eval_do below
58     Sub::Quote::capture_unroll('$_[2]', $self->lexicals, 2);
59
60   my $capture_code = join '', $self->capture_code;
61
62   local our $current_code = qq!
63 ${setup_code}
64 sub Eval::WithLexicals::Cage::current_line {
65 package ${package};
66 #line 1 "(eval)"
67 ${to_eval}
68 ;sub Eval::WithLexicals::Cage::pad_capture { }
69 ${capture_code}
70 sub Eval::WithLexicals::Cage::grab_captures {
71   no warnings 'closure'; no strict 'vars';
72   package Eval::WithLexicals::VarScope;!;
73   # rest is appended by Eval::WithLexicals::Util::capture_list, called
74   # during parsing by the BEGIN block from capture_code.
75
76   $self->_eval_do(\$current_code, $self->lexicals, $to_eval);
77   $self->_run(\&Eval::WithLexicals::Cage::current_line);
78 }
79
80 sub _run {
81   my($self, $code) = @_;
82
83   my @ret;
84   my $ctx = $self->context;
85   if ($ctx eq 'list') {
86     @ret = $code->();
87   } elsif ($ctx eq 'scalar') {
88     $ret[0] = $code->();
89   } else {
90     $code->();
91   }
92   $self->lexicals({
93     %{$self->lexicals},
94     %{$self->_grab_captures},
95   });
96   @ret;
97 }
98
99 sub _grab_captures {
100   my ($self) = @_;
101   my $cap = Eval::WithLexicals::Cage::grab_captures();
102   foreach my $key (keys %$cap) {
103     my ($sigil, $name) = $key =~ /^(.)(.+)$/;
104     my $var_scope_name = $sigil.'Eval::WithLexicals::VarScope::'.$name;
105     if ($cap->{$key} eq eval "\\${var_scope_name}") {
106       delete $cap->{$key};
107     }
108   }
109   $cap;
110 }
111
112 sub _eval_do {
113   my ($self, $text_ref, $lexical, $original) = @_;
114   local @INC = (sub {
115     if ($_[1] eq '/eval_do') {
116       open my $fh, '<', $text_ref;
117       $fh;
118     } else {
119       ();
120     }
121   }, @INC);
122   do '/eval_do' or die $@;
123 }
124
125 {
126   package Eval::WithLexicals::Util;
127
128   use B qw(svref_2object);
129
130   sub capture_list {
131     my $pad_capture = \&Eval::WithLexicals::Cage::pad_capture;
132     my @names = grep $_ ne '&', map $_->PV, grep $_->isa('B::PV'),
133       svref_2object($pad_capture)->OUTSIDE->PADLIST->ARRAYelt(0)->ARRAY;
134     $Eval::WithLexicals::current_code .=
135       '+{ '.join(', ', map "'$_' => \\$_", @names).' };'
136       ."\n}\n}\n1;\n";
137   }
138 }
139
140 =head1 NAME
141
142 Eval::WithLexicals - pure perl eval with persistent lexical variables
143
144 =head1 SYNOPSIS
145
146   # file: bin/tinyrepl
147
148   #!/usr/bin/env perl
149
150   use strictures 1;
151   use Eval::WithLexicals;
152   use Term::ReadLine;
153   use Data::Dumper;
154   use Getopt::Long;
155
156   GetOptions(
157     "plugin=s" => \my @plugins
158   );
159
160   $SIG{INT} = sub { warn "SIGINT\n" };
161
162   { package Data::Dumper; no strict 'vars';
163     $Terse = $Indent = $Useqq = $Deparse = $Sortkeys = 1;
164     $Quotekeys = 0;
165   }
166
167   my $eval = @plugins
168    ? Eval::WithLexicals->with_plugins(@plugins)->new
169    : Eval::WithLexicals->new;
170
171   my $read = Term::ReadLine->new('Perl REPL');
172   while (1) {
173     my $line = $read->readline('re.pl$ ');
174     exit unless defined $line;
175     my @ret; eval {
176       local $SIG{INT} = sub { die "Caught SIGINT" };
177       @ret = $eval->eval($line); 1;
178     } or @ret = ("Error!", $@);
179     print Dumper @ret;
180   }
181
182   # shell session:
183
184   $ perl -Ilib bin/tinyrepl 
185   re.pl$ my $x = 0;
186   0
187   re.pl$ ++$x;
188   1
189   re.pl$ $x + 3;
190   4
191   re.pl$ ^D
192   $
193
194 =head1 METHODS
195
196 =head2 new
197
198   my $eval = Eval::WithLexicals->new(
199     lexicals => { '$x' => \1 },      # default {}
200     in_package => 'PackageToEvalIn', # default Eval::WithLexicals::Scratchpad
201     context => 'scalar',             # default 'list'
202     prelude => 'use warnings',       # default 'use strictures 1'
203   );
204
205 =head2 eval
206
207   my @return_value = $eval->eval($code_to_eval);
208
209 =head2 lexicals
210
211   my $current_lexicals = $eval->lexicals;
212
213   $eval->lexicals(\%new_lexicals);
214
215 =head2 in_package
216
217   my $current_package = $eval->in_package;
218
219   $eval->in_package($new_package);
220
221 =head2 context
222
223   my $current_context = $eval->context;
224
225   $eval->context($new_context); # 'list', 'scalar' or 'void'
226
227 =head2 prelude
228
229 Code to run before evaling code. Loads L<strictures> by default.
230
231   my $current_prelude = $eval->prelude;
232
233   $eval->prelude(q{use warnings}); # only warnings, not strict.
234
235 =head2 with_plugins
236
237   my $eval = Eval::WithLexicals->with_plugins("HintPersistence")->new;
238
239 Construct a class with the given plugins. Plugins are roles located under
240 a package name like C<Eval::WithLexicals::With*>.
241
242 Current plugins are:
243
244 =over 4
245
246 =item * HintPersistence
247
248 When enabled this will persist pragams and other compile hints between evals
249 (for example the L<strict> and L<warnings> flags in effect). See
250 L<Eval::WithLexicals::WithHintPersistence> for further details.
251
252 =back
253
254 =head1 AUTHOR
255
256 Matt S. Trout <mst@shadowcat.co.uk>
257
258 =head1 CONTRIBUTORS
259
260 David Leadbeater <dgl@dgl.cx>
261
262 =head1 COPYRIGHT
263
264 Copyright (c) 2010 the Eval::WithLexicals L</AUTHOR> and L</CONTRIBUTORS>
265 as listed above.
266
267 =head1 LICENSE
268
269 This library is free software and may be distributed under the same terms
270 as perl itself.
271
272 =cut
273
274 1;