c174bbd4d164f08cf246f2f3075b68f4330adf00
[p5sagit/Devel-REPL.git] / lib / Devel / REPL.pm
1 package Devel::REPL;
2
3 use Term::ReadLine;
4 use Moose;
5 use namespace::autoclean;
6 use 5.008001; # backwards compat, doesn't warn like 5.8.1
7
8 our $VERSION = '1.003017';
9
10 with 'MooseX::Object::Pluggable';
11
12 use Devel::REPL::Error;
13
14 has 'term' => (
15   is => 'rw',
16   default => sub { Term::ReadLine->new('Perl REPL') }
17 );
18
19 has 'prompt' => (
20   is => 'rw',
21   default => sub { '$ ' }
22 );
23
24 has 'out_fh' => (
25   is => 'rw',
26   lazy => 1,
27   default => sub { shift->term->OUT || \*STDOUT; }
28 );
29
30 has 'exit_repl' => (
31   is => 'rw',
32   default => sub { 0 }
33 );
34
35 sub run {
36   my ($self) = @_;
37   while ($self->run_once_safely) {
38     # keep looping unless we want to exit REPL
39     last if $self->exit_repl;
40   }
41 }
42
43 sub run_once_safely {
44   my ($self, @args) = @_;
45
46   my $ret = eval { $self->run_once(@args) };
47
48   if ($@) {
49     my $error = $@;
50     eval { $self->print("Error! - $error\n"); };
51     return 1;
52   } else {
53     return $ret;
54   }
55 }
56
57 sub run_once {
58   my ($self) = @_;
59
60   my $line = $self->read;
61   return unless defined($line);     # undefined value == EOF
62
63   my @ret = $self->formatted_eval($line);
64
65   $self->print(@ret) unless $self->exit_repl;
66
67   return 1;
68 }
69
70 sub formatted_eval {
71   my ( $self, @args ) = @_;
72
73   my @ret = $self->eval(@args);
74
75   return $self->format(@ret);
76 }
77
78 sub format {
79   my ( $self, @stuff ) = @_;
80
81   if ( $self->is_error($stuff[0]) ) {
82     return $self->format_error(@stuff);
83   } else {
84     return $self->format_result(@stuff);
85   }
86 }
87
88 sub format_result {
89   my ( $self, @stuff ) = @_;
90
91   return @stuff;
92 }
93
94 sub format_error {
95   my ( $self, $error ) = @_;
96   return $error->stringify;
97 }
98
99 sub is_error {
100   my ( $self, $thingy ) = @_;
101   blessed($thingy) and $thingy->isa("Devel::REPL::Error");
102 }
103
104 sub read {
105   my ($self) = @_;
106   return $self->term->readline($self->prompt);
107 }
108
109 sub eval {
110   my ($self, $line) = @_;
111   my $compiled = $self->compile($line);
112   return $compiled unless defined($compiled) and not $self->is_error($compiled);
113   return $self->execute($compiled);
114 }
115
116 sub compile {
117   my ( $_REPL, @args ) = @_;
118   my $compiled = eval $_REPL->wrap_as_sub(@args);
119   return $_REPL->error_return("Compile error", $@) if $@;
120   return $compiled;
121 }
122
123 sub wrap_as_sub {
124   my ($self, $line, %args) = @_;
125   return qq!sub {\n!. ( $args{no_mangling} ? $line : $self->mangle_line($line) ).qq!\n}\n!;
126 }
127
128 sub mangle_line {
129   my ($self, $line) = @_;
130   return $line;
131 }
132
133 sub execute {
134   my ($self, $to_exec, @args) = @_;
135   my @ret = eval { $to_exec->(@args) };
136   return $self->error_return("Runtime error", $@) if $@;
137   return @ret;
138 }
139
140 sub error_return {
141   my ($self, $type, $error) = @_;
142   return Devel::REPL::Error->new( type => $type, message => $error );
143 }
144
145 sub print {
146   my ($self, @ret) = @_;
147   my $fh = $self->out_fh;
148   no warnings 'uninitialized';
149   print $fh "@ret";
150   print $fh "\n" if $self->term->ReadLine =~ /Gnu/;
151 }
152
153 =head1 NAME
154
155 Devel::REPL - a modern perl interactive shell
156
157 =head1 SYNOPSIS
158
159   my $repl = Devel::REPL->new;
160   $repl->load_plugin($_) for qw(History LexEnv);
161   $repl->run
162
163 Alternatively, use the 're.pl' script installed with the distribution
164
165   system$ re.pl
166
167 =head1 DESCRIPTION
168
169 This is an interactive shell for Perl, commonly known as a REPL - Read,
170 Evaluate, Print, Loop. The shell provides for rapid development or testing
171 of code without the need to create a temporary source code file.
172
173 Through a plugin system, many features are available on demand. You can also
174 tailor the environment through the use of profiles and run control files, for
175 example to pre-load certain Perl modules when working on a particular project.
176
177 =head1 USAGE
178
179 To start a shell, follow one of the examples in the L</"SYNOPSIS"> above.
180
181 Once running, the shell accepts and will attempt to execute any code given. If
182 the code executes successfully you'll be shown the result, otherwise an error
183 message will be returned. Here are a few examples:
184
185  $_ print "Hello, world!\n"
186  Hello, world!
187  1
188  $_ nosuchfunction
189  Compile error: Bareword "nosuchfunction" not allowed while "strict subs" in use at (eval 130) line 5.
190
191  $_
192
193 In the first example above you see the output of the command (C<Hello,
194 world!>), if any, and then the return value of the statement (C<1>). Following
195 that example, an error is returned when the execution of some code fails.
196
197 Note that the lack of semicolon on the end is not a mistake - the code is
198 run inside a Block structure (to protect the REPL in case the code blows up),
199 which means a single statement doesn't require the semicolon. You can add one
200 if you like, though.
201
202 If you followed the first example in the L</"SYNOPSIS"> above, you'll have the
203 History and LexEnv plugins loaded (and there are many more available).
204 Although the shell might support "up-arrow" history, the History plugin adds
205 "bang" history to that so you can re-execute chosen commands (with e.g.
206 C<!53>). The LexEnv plugin ensures that lexical variables declared with the
207 C<my> keyword will automatically persist between statements executed in the
208 REPL shell.
209
210 When you C<use> any Perl module, the C<import()> will work as expected - the
211 exported functions from that module are available for immediate use:
212
213  $_ carp "I'm dieeeing!\n"
214  String found where operator expected at (eval 129) line 5, near "carp "I'm dieeeing!\n""
215          (Do you need to predeclare carp?)
216  Compile error: syntax error at (eval 129) line 5, near "carp "I'm dieeeing!\n""
217  BEGIN not safe after errors--compilation aborted at (eval 129) line 5.
218
219  $_ use Carp
220
221  $_ carp "I'm dieeeing!\n"
222  I'm dieeeing!
223   at /usr/share/perl5/Lexical/Persistence.pm line 327
224  1
225  $_
226
227 To quit from the shell, hit C<Ctrl+D> or C<Ctrl+C>.
228
229   MSWin32 NOTE: control keys won't work if TERM=dumb
230   because readline functionality will be disabled.
231
232
233 =head2 Run Control Files
234
235 For particular projects you might well end up running the same commands each
236 time the REPL shell starts up - loading Perl modules, setting configuration,
237 and so on. A run control file lets you have this done automatically, and you
238 can have multiple files for different projects.
239
240 By default the C<re.pl> program looks for C<< $HOME/.re.pl/repl.rc >>, and
241 runs whatever code is in there as if you had entered it at the REPL shell
242 yourself.
243
244 To set a new run control file that's also in that directory, pass it as a
245 filename like so:
246
247  system$ re.pl --rcfile myproject.pc
248
249 If the filename happens to contain a forwardslash, then it's used absolutely,
250 or realive to the current working directory:
251
252  system$ re.pl --rcfile /path/to/my/project/repl.rc
253
254 Within the run control file you might want to load plugins. This is covered in
255 L</"The REPL shell object"> section, below.
256
257 =head2 Profiles
258
259 To allow for the sharing of run control files, you can fashion them into a
260 Perl module for distribution (perhaps via the CPAN). For more information on
261 this feature, please see the L<Devel::REPL::Profile> manual page.
262
263 A default profile ships with C<Devel::REPL>; it loads the following plugins:
264
265 =over 4
266
267 =item *
268
269 L<Devel::REPL::Plugin::History>
270
271 =item *
272
273 L<Devel::REPL::Plugin::LexEnv>
274
275 =item *
276
277 L<Devel::REPL::Plugin::DDS>
278
279 =item *
280
281 L<Devel::REPL::Plugin::Packages>
282
283 =item *
284
285 L<Devel::REPL::Plugin::Commands>
286
287 =item *
288
289 L<Devel::REPL::Plugin::MultiLine::PPI>
290
291 =item *
292
293 L<Devel::REPL::Plugin::Colors>
294
295 =item *
296
297 L<Devel::REPL::Plugin::Completion>
298
299 =item *
300
301 L<Devel::REPL::Plugin::CompletionDriver::INC>
302
303 =item *
304
305 L<Devel::REPL::Plugin::CompletionDriver::LexEnv>
306
307 =item *
308
309 L<Devel::REPL::Plugin::CompletionDriver::Keywords>
310
311 =item *
312
313 L<Devel::REPL::Plugin::CompletionDriver::Methods>
314
315 =item *
316
317 L<Devel::REPL::Plugin::ReadlineHistory>
318
319 =back
320
321 =head2 Plugins
322
323 Plugins are a way to add funcionality to the REPL shell, and take advantage of
324 C<Devel::REPL> being based on the L<Moose> object system for Perl 5. This
325 means it's simple to 'hook into' many steps of the R-E-P-L process. Plugins
326 can change the way commands are interpreted, or the way their results are
327 output, or even add commands to the shell environment.
328
329 A number of plugins ship with C<Devel::REPL>, and more are available on the
330 CPAN. Some of the shipped plugins are loaded in the default profile, mentioned
331 above.  These plugins can be loaded in your C<< $HOME/.re.pl/repl.rc >> like:
332
333   load_plugin qw( CompletionDriver::Global DumpHistory );
334
335 Writing your own plugins is not difficult, and is discussed in the
336 L<Devel::REPL::Plugin> manual page, along with links to the manual pages of
337 all the plugins shipped with C<Devel::REPL>.
338
339 =head2 The REPL shell object
340
341 From time to time you'll want to interact with or manipulate the
342 C<Devel::REPL> shell object itself; that is, the instance of the shell you're
343 currently running.
344
345 The object is always available through the C<$_REPL> variable. One common
346 requirement is to load an additional plugin, after your profile and run
347 control files have already been executed:
348
349  $_ $_REPL->load_plugin('Timing');
350  1
351  $_ print "Hello again, world!\n"
352  Hello again, world!
353  Took 0.00148296356201172 seconds.
354  1
355  $_
356
357 =head1 REQUIREMENTS
358
359 In addition to the contents of the standard Perl distribution, you will need
360 the following:
361
362 =over 4
363
364 =item *
365
366 L<Moose> >= 0.74
367
368 =item *
369
370 L<MooseX::Object::Pluggable> >= 0.0009
371
372 =item *
373
374 L<MooseX::Getopt> >= 0.18
375
376 =item *
377
378 L<namespace::autoclean>
379
380 =item *
381
382 L<File::HomeDir>
383
384 =item *
385
386 L<Task::Weaken>
387
388 =item *
389
390 L<B::Concise>
391
392 =item *
393
394 L<Term::ANSIColor>
395
396 =item *
397
398 L<Devel::Peek>
399
400 =back
401
402 Optionally, some plugins if installed will require the following modules:
403
404 =over 4
405
406 =item *
407
408 L<PPI>
409
410 =item *
411
412 L<Data::Dump::Streamer>
413
414 =item *
415
416 L<Data::Dumper::Concise>
417
418 =item *
419
420 L<File::Next>
421
422 =item *
423
424 L<Sys::SigAction>
425
426 =item *
427
428 L<B::Keywords>
429
430 =item *
431
432 L<Lexical::Persistence>
433
434 =item *
435
436 L<App::Nopaste>
437
438 =item *
439
440 L<Module::Refresh>
441
442 =back
443
444 =head1 AUTHOR
445
446 Matt S Trout - mst (at) shadowcatsystems.co.uk (L<http://www.shadowcatsystems.co.uk/>)
447
448 =head1 CONTRIBUTORS
449
450 =over 4
451
452 =item Stevan Little - stevan (at) iinteractive.com
453
454 =item Alexis Sukrieh - sukria+perl (at) sukria.net
455
456 =item epitaph
457
458 =item mgrimes - mgrimes (at) cpan dot org
459
460 =item Shawn M Moore - sartak (at) gmail.com
461
462 =item Oliver Gorwits - oliver on irc.perl.org
463
464 =item Andrew Moore - C<< <amoore@cpan.org> >>
465
466 =item Norbert Buchmuller C<< <norbi@nix.hu> >>
467
468 =item Dave Houston C<< <dhouston@cpan.org> >>
469
470 =item Chris Marshall
471
472 =back
473
474 =head1 LICENSE
475
476 This library is free software under the same terms as perl itself
477
478 =cut
479
480 1;