Ignore the OS X GNUmakefile*s, and t/test_state.
[p5sagit/p5-mst-13.2.git] / lib / Fatal.pm
1 package Fatal;
2
3 use 5.008;  # 5.8.x needed for autodie
4 use Carp;
5 use strict;
6 use warnings;
7
8 use constant LEXICAL_TAG => q{:lexical};
9 use constant VOID_TAG    => q{:void};
10
11 use constant ERROR_NOARGS    => 'Cannot use lexical %s with no arguments';
12 use constant ERROR_VOID_LEX  => VOID_TAG.' cannot be used with lexical scope';
13 use constant ERROR_LEX_FIRST => LEXICAL_TAG.' must be used as first argument';
14 use constant ERROR_NO_LEX    => "no %s can only start with ".LEXICAL_TAG;
15 use constant ERROR_BADNAME   => "Bad subroutine name for %s: %s";
16 use constant ERROR_NOTSUB    => "%s is not a Perl subroutine";
17 use constant ERROR_NOT_BUILT => "%s is neither a builtin, nor a Perl subroutine";
18 use constant ERROR_CANT_OVERRIDE => "Cannot make the non-overridable builtin %s fatal";
19
20 use constant ERROR_NO_IPC_SYS_SIMPLE => "IPC::System::Simple required for Fatalised/autodying system()";
21
22 use constant ERROR_IPC_SYS_SIMPLE_OLD => "IPC::System::Simple version %f required for Fatalised/autodying system().  We only have version %f";
23
24 use constant ERROR_AUTODIE_CONFLICT => q{"no autodie '%s'" is not allowed while "use Fatal '%s'" is in effect};
25
26 use constant ERROR_FATAL_CONFLICT => q{"use Fatal '%s'" is not allowed while "no autodie '%s'" is in effect};
27
28 # Older versions of IPC::System::Simple don't support all the
29 # features we need.
30
31 use constant MIN_IPC_SYS_SIMPLE_VER => 0.12;
32
33 # All the Fatal/autodie modules share the same version number.
34 our $VERSION = '1.998';
35
36 our $Debug ||= 0;
37
38 # EWOULDBLOCK values for systems that don't supply their own.
39 # Even though this is defined with our, that's to help our
40 # test code.  Please don't rely upon this variable existing in
41 # the future.
42
43 our %_EWOULDBLOCK = (
44     MSWin32 => 33,
45 );
46
47 # We have some tags that can be passed in for use with import.
48 # These are all assumed to be CORE::
49
50 my %TAGS = (
51     ':io'      => [qw(:dbm :file :filesys :ipc :socket
52                        read seek sysread syswrite sysseek )],
53     ':dbm'     => [qw(dbmopen dbmclose)],
54     ':file'    => [qw(open close flock sysopen fcntl fileno binmode
55                      ioctl truncate)],
56     ':filesys' => [qw(opendir closedir chdir link unlink rename mkdir
57                       symlink rmdir readlink umask)],
58     ':ipc'     => [qw(:msg :semaphore :shm pipe)],
59     ':msg'     => [qw(msgctl msgget msgrcv msgsnd)],
60     ':threads' => [qw(fork)],
61     ':semaphore'=>[qw(semctl semget semop)],
62     ':shm'     => [qw(shmctl shmget shmread)],
63     ':system'  => [qw(system exec)],
64
65     # Can we use qw(getpeername getsockname)? What do they do on failure?
66     # XXX - Can socket return false?
67     ':socket'  => [qw(accept bind connect getsockopt listen recv send
68                    setsockopt shutdown socketpair)],
69
70     # Our defaults don't include system(), because it depends upon
71     # an optional module, and it breaks the exotic form.
72     #
73     # This *may* change in the future.  I'd love IPC::System::Simple
74     # to be a dependency rather than a recommendation, and hence for
75     # system() to be autodying by default.
76
77     ':default' => [qw(:io :threads)],
78
79     # Version specific tags.  These allow someone to specify
80     # use autodie qw(:1.994) and know exactly what they'll get.
81
82     ':1.994' => [qw(:default)],
83     ':1.995' => [qw(:default)],
84     ':1.996' => [qw(:default)],
85     ':1.997' => [qw(:default)],
86     ':1.998' => [qw(:default)],
87
88 );
89
90 $TAGS{':all'}  = [ keys %TAGS ];
91
92 # This hash contains subroutines for which we should
93 # subroutine() // die() rather than subroutine() || die()
94
95 my %Use_defined_or;
96
97 # CORE::open returns undef on failure.  It can legitimately return
98 # 0 on success, eg: open(my $fh, '-|') || exec(...);
99
100 @Use_defined_or{qw(
101     CORE::fork
102     CORE::recv
103     CORE::send
104     CORE::open
105     CORE::fileno
106     CORE::read
107     CORE::readlink
108     CORE::sysread
109     CORE::syswrite
110     CORE::sysseek
111     CORE::umask
112 )} = ();
113
114 # Cached_fatalised_sub caches the various versions of our
115 # fatalised subs as they're produced.  This means we don't
116 # have to build our own replacement of CORE::open and friends
117 # for every single package that wants to use them.
118
119 my %Cached_fatalised_sub = ();
120
121 # Every time we're called with package scope, we record the subroutine
122 # (including package or CORE::) in %Package_Fatal.  This allows us
123 # to detect illegal combinations of autodie and Fatal, and makes sure
124 # we don't accidently make a Fatal function autodying (which isn't
125 # very useful).
126
127 my %Package_Fatal = ();
128
129 # The first time we're called with a user-sub, we cache it here.
130 # In the case of a "no autodie ..." we put back the cached copy.
131
132 my %Original_user_sub = ();
133
134 # We use our package in a few hash-keys.  Having it in a scalar is
135 # convenient.  The "guard $PACKAGE" string is used as a key when
136 # setting up lexical guards.
137
138 my $PACKAGE       = __PACKAGE__;
139 my $PACKAGE_GUARD = "guard $PACKAGE";
140 my $NO_PACKAGE    = "no $PACKAGE";      # Used to detect 'no autodie'
141
142 # Here's where all the magic happens when someone write 'use Fatal'
143 # or 'use autodie'.
144
145 sub import {
146     my $class   = shift(@_);
147     my $void    = 0;
148     my $lexical = 0;
149
150     my ($pkg, $filename) = caller();
151
152     @_ or return;   # 'use Fatal' is a no-op.
153
154     # If we see the :lexical flag, then _all_ arguments are
155     # changed lexically
156
157     if ($_[0] eq LEXICAL_TAG) {
158         $lexical = 1;
159         shift @_;
160
161         # If we see no arguments and :lexical, we assume they
162         # wanted ':default'.
163
164         if (@_ == 0) {
165             push(@_, ':default');
166         }
167
168         # Don't allow :lexical with :void, it's needlessly confusing.
169         if ( grep { $_ eq VOID_TAG } @_ ) {
170             croak(ERROR_VOID_LEX);
171         }
172     }
173
174     if ( grep { $_ eq LEXICAL_TAG } @_ ) {
175         # If we see the lexical tag as the non-first argument, complain.
176         croak(ERROR_LEX_FIRST);
177     }
178
179     my @fatalise_these =  @_;
180
181     # Thiese subs will get unloaded at the end of lexical scope.
182     my %unload_later;
183
184     # This hash helps us track if we've alredy done work.
185     my %done_this;
186
187     # NB: we're using while/shift rather than foreach, since
188     # we'll be modifying the array as we walk through it.
189
190     while (my $func = shift @fatalise_these) {
191
192         if ($func eq VOID_TAG) {
193
194             # When we see :void, set the void flag.
195             $void = 1;
196
197         } elsif (exists $TAGS{$func}) {
198
199             # When it's a tag, expand it.
200             push(@fatalise_these, @{ $TAGS{$func} });
201
202         } else {
203
204             # Otherwise, fatalise it.
205
206             # If we've already made something fatal this call,
207             # then don't do it twice.
208
209             next if $done_this{$func};
210
211             # We're going to make a subroutine fatalistic.
212             # However if we're being invoked with 'use Fatal qw(x)'
213             # and we've already been called with 'no autodie qw(x)'
214             # in the same scope, we consider this to be an error.
215             # Mixing Fatal and autodie effects was considered to be
216             # needlessly confusing on p5p.
217
218             my $sub = $func;
219             $sub = "${pkg}::$sub" unless $sub =~ /::/;
220
221             # If we're being called as Fatal, and we've previously
222             # had a 'no X' in scope for the subroutine, then complain
223             # bitterly.
224
225             if (! $lexical and $^H{$NO_PACKAGE}{$sub}) {
226                  croak(sprintf(ERROR_FATAL_CONFLICT, $func, $func));
227             }
228
229             # We're not being used in a confusing way, so make
230             # the sub fatal.  Note that _make_fatal returns the
231             # old (original) version of the sub, or undef for
232             # built-ins.
233
234             my $sub_ref = $class->_make_fatal(
235                 $func, $pkg, $void, $lexical, $filename
236             );
237
238             $done_this{$func}++;
239
240             $Original_user_sub{$sub} ||= $sub_ref;
241
242             # If we're making lexical changes, we need to arrange
243             # for them to be cleaned at the end of our scope, so
244             # record them here.
245
246             $unload_later{$func} = $sub_ref if $lexical;
247         }
248     }
249
250     if ($lexical) {
251
252         # Dark magic to have autodie work under 5.8
253         # Copied from namespace::clean, that copied it from
254         # autobox, that found it on an ancient scroll written
255         # in blood.
256
257         # This magic bit causes %^H to be lexically scoped.
258
259         $^H |= 0x020000;
260
261         # Our package guard gets invoked when we leave our lexical
262         # scope.
263
264         push(@ { $^H{$PACKAGE_GUARD} }, autodie::Scope::Guard->new(sub {
265             $class->_install_subs($pkg, \%unload_later);
266         }));
267
268     }
269
270     return;
271
272 }
273
274 # The code here is originally lifted from namespace::clean,
275 # by Robert "phaylon" Sedlacek.
276 #
277 # It's been redesigned after feedback from ikegami on perlmonks.
278 # See http://perlmonks.org/?node_id=693338 .  Ikegami rocks.
279 #
280 # Given a package, and hash of (subname => subref) pairs,
281 # we install the given subroutines into the package.  If
282 # a subref is undef, the subroutine is removed.  Otherwise
283 # it replaces any existing subs which were already there.
284
285 sub _install_subs {
286     my ($class, $pkg, $subs_to_reinstate) = @_;
287
288     my $pkg_sym = "${pkg}::";
289
290     while(my ($sub_name, $sub_ref) = each %$subs_to_reinstate) {
291
292         my $full_path = $pkg_sym.$sub_name;
293
294         # Copy symbols across to temp area.
295
296         no strict 'refs';   ## no critic
297
298         local *__tmp = *{ $full_path };
299
300         # Nuke the old glob.
301         { no strict; delete $pkg_sym->{$sub_name}; }    ## no critic
302
303         # Copy innocent bystanders back.
304
305         foreach my $slot (qw( SCALAR ARRAY HASH IO FORMAT ) ) {
306             next unless defined *__tmp{ $slot };
307             *{ $full_path } = *__tmp{ $slot };
308         }
309
310         # Put back the old sub (if there was one).
311
312         if ($sub_ref) {
313
314             no strict;  ## no critic
315             *{ $pkg_sym . $sub_name } = $sub_ref;
316         }
317     }
318
319     return;
320 }
321
322 sub unimport {
323     my $class = shift;
324
325     # Calling "no Fatal" must start with ":lexical"
326     if ($_[0] ne LEXICAL_TAG) {
327         croak(sprintf(ERROR_NO_LEX,$class));
328     }
329
330     shift @_;   # Remove :lexical
331
332     my $pkg = (caller)[0];
333
334     # If we've been called with arguments, then the developer
335     # has explicitly stated 'no autodie qw(blah)',
336     # in which case, we disable Fatalistic behaviour for 'blah'.
337
338     my @unimport_these = @_ ? @_ : ':all';
339
340     while (my $symbol = shift @unimport_these) {
341
342         if ($symbol =~ /^:/) {
343
344             # Looks like a tag!  Expand it!
345             push(@unimport_these, @{ $TAGS{$symbol} });
346
347             next;
348         }
349
350         my $sub = $symbol;
351         $sub = "${pkg}::$sub" unless $sub =~ /::/;
352
353         # If 'blah' was already enabled with Fatal (which has package
354         # scope) then, this is considered an error.
355
356         if (exists $Package_Fatal{$sub}) {
357             croak(sprintf(ERROR_AUTODIE_CONFLICT,$symbol,$symbol));
358         }
359
360         # Record 'no autodie qw($sub)' as being in effect.
361         # This is to catch conflicting semantics elsewhere
362         # (eg, mixing Fatal with no autodie)
363
364         $^H{$NO_PACKAGE}{$sub} = 1;
365
366         if (my $original_sub = $Original_user_sub{$sub}) {
367             # Hey, we've got an original one of these, put it back.
368             $class->_install_subs($pkg, { $symbol => $original_sub });
369             next;
370         }
371
372         # We don't have an original copy of the sub, on the assumption
373         # it's core (or doesn't exist), we'll just nuke it.
374
375         $class->_install_subs($pkg,{ $symbol => undef });
376
377     }
378
379     return;
380
381 }
382
383 # TODO - This is rather terribly inefficient right now.
384
385 # NB: Perl::Critic's dump-autodie-tag-contents depends upon this
386 # continuing to work.
387
388 {
389     my %tag_cache;
390
391     sub _expand_tag {
392         my ($class, $tag) = @_;
393
394         if (my $cached = $tag_cache{$tag}) {
395             return $cached;
396         }
397
398         if (not exists $TAGS{$tag}) {
399             croak "Invalid exception class $tag";
400         }
401
402         my @to_process = @{$TAGS{$tag}};
403
404         my @taglist = ();
405
406         while (my $item = shift @to_process) {
407             if ($item =~ /^:/) {
408                 push(@to_process, @{$TAGS{$item}} );
409             } else {
410                 push(@taglist, "CORE::$item");
411             }
412         }
413
414         $tag_cache{$tag} = \@taglist;
415
416         return \@taglist;
417
418     }
419
420 }
421
422 # This code is from the original Fatal.  It scares me.
423
424 sub fill_protos {
425     my $proto = shift;
426     my ($n, $isref, @out, @out1, $seen_semi) = -1;
427     while ($proto =~ /\S/) {
428         $n++;
429         push(@out1,[$n,@out]) if $seen_semi;
430         push(@out, $1 . "{\$_[$n]}"), next if $proto =~ s/^\s*\\([\@%\$\&])//;
431         push(@out, "\$_[$n]"),        next if $proto =~ s/^\s*([_*\$&])//;
432         push(@out, "\@_[$n..\$#_]"),  last if $proto =~ s/^\s*(;\s*)?\@//;
433         $seen_semi = 1, $n--,         next if $proto =~ s/^\s*;//; # XXXX ????
434         die "Internal error: Unknown prototype letters: \"$proto\"";
435     }
436     push(@out1,[$n+1,@out]);
437     return @out1;
438 }
439
440 # This generates the code that will become our fatalised subroutine.
441
442 sub write_invocation {
443     my ($class, $core, $call, $name, $void, $lexical, $sub, @argvs) = @_;
444
445     if (@argvs == 1) {        # No optional arguments
446
447         my @argv = @{$argvs[0]};
448         shift @argv;
449
450         return $class->one_invocation($core,$call,$name,$void,$sub,! $lexical,@argv);
451
452     } else {
453         my $else = "\t";
454         my (@out, @argv, $n);
455         while (@argvs) {
456             @argv = @{shift @argvs};
457             $n = shift @argv;
458
459             push @out, "${else}if (\@_ == $n) {\n";
460             $else = "\t} els";
461
462         push @out, $class->one_invocation($core,$call,$name,$void,$sub,! $lexical,@argv);
463         }
464         push @out, q[
465             }
466             die "Internal error: $name(\@_): Do not expect to get ", scalar \@_, " arguments";
467     ];
468
469         return join '', @out;
470     }
471 }
472
473 sub one_invocation {
474     my ($class, $core, $call, $name, $void, $sub, $back_compat, @argv) = @_;
475
476     # If someone is calling us directly (a child class perhaps?) then
477     # they could try to mix void without enabling backwards
478     # compatibility.  We just don't support this at all, so we gripe
479     # about it rather than doing something unwise.
480
481     if ($void and not $back_compat) {
482         Carp::confess("Internal error: :void mode not supported with $class");
483     }
484
485     # @argv only contains the results of the in-built prototype
486     # function, and is therefore safe to interpolate in the
487     # code generators below.
488
489     # TODO - The following clobbers context, but that's what the
490     #        old Fatal did.  Do we care?
491
492     if ($back_compat) {
493
494         # TODO - Use Fatal qw(system) is not yet supported.  It should be!
495
496         if ($call eq 'CORE::system') {
497             return q{
498                 croak("UNIMPLEMENTED: use Fatal qw(system) not yet supported.");
499             };
500         }
501
502         local $" = ', ';
503
504         if ($void) {
505             return qq/return (defined wantarray)?$call(@argv):
506                    $call(@argv) || croak "Can't $name(\@_)/ .
507                    ($core ? ': $!' : ', \$! is \"$!\"') . '"'
508         } else {
509             return qq{return $call(@argv) || croak "Can't $name(\@_)} .
510                    ($core ? ': $!' : ', \$! is \"$!\"') . '"';
511         }
512     }
513
514     # The name of our original function is:
515     #   $call if the function is CORE
516     #   $sub if our function is non-CORE
517
518     # The reason for this is that $call is what we're actualling
519     # calling.  For our core functions, this is always
520     # CORE::something.  However for user-defined subs, we're about to
521     # replace whatever it is that we're calling; as such, we actually
522     # calling a subroutine ref.
523
524     # Unfortunately, none of this tells us the *ultimate* name.
525     # For example, if I export 'copy' from File::Copy, I'd like my
526     # ultimate name to be File::Copy::copy.
527     #
528     # TODO - Is there any way to find the ultimate name of a sub, as
529     # described above?
530
531     my $true_sub_name = $core ? $call : $sub;
532
533     if ($call eq 'CORE::system') {
534
535         # Leverage IPC::System::Simple if we're making an autodying
536         # system.
537
538         local $" = ", ";
539
540         # We need to stash $@ into $E, rather than using
541         # local $@ for the whole sub.  If we don't then
542         # any exceptions from internal errors in autodie/Fatal
543         # will mysteriously disappear before propogating
544         # upwards.
545
546         return qq{
547             my \$retval;
548             my \$E;
549
550
551             {
552                 local \$@;
553
554                 eval {
555                     \$retval = IPC::System::Simple::system(@argv);
556                 };
557
558                 \$E = \$@;
559             }
560
561             if (\$E) {
562
563                 # XXX - TODO - This can't be overridden in child
564                 # classes!
565
566                 die autodie::exception::system->new(
567                     function => q{CORE::system}, args => [ @argv ],
568                     message => "\$E", errno => \$!,
569                 );
570             }
571
572             return \$retval;
573         };
574
575     }
576
577     # Should we be testing to see if our result is defined, or
578     # just true?
579     my $use_defined_or = exists ( $Use_defined_or{$call} );
580
581     local $" = ', ';
582
583     # If we're going to throw an exception, here's the code to use.
584     my $die = qq{
585         die $class->throw(
586             function => q{$true_sub_name}, args => [ @argv ],
587             pragma => q{$class}, errno => \$!,
588         )
589     };
590
591     if ($call eq 'CORE::flock') {
592
593         # flock needs special treatment.  When it fails with
594         # LOCK_UN and EWOULDBLOCK, then it's not really fatal, it just
595         # means we couldn't get the lock right now.
596
597         require POSIX;      # For POSIX::EWOULDBLOCK
598
599         local $@;   # Don't blat anyone else's $@.
600
601         # Ensure that our vendor supports EWOULDBLOCK.  If they
602         # don't (eg, Windows), then we use known values for its
603         # equivalent on other systems.
604
605         my $EWOULDBLOCK = eval { POSIX::EWOULDBLOCK(); }
606                           || $_EWOULDBLOCK{$^O}
607                           || _autocroak("Internal error - can't overload flock - EWOULDBLOCK not defined on this system.");
608
609         require Fcntl;      # For Fcntl::LOCK_NB
610
611         return qq{
612
613             # Try to flock.  If successful, return it immediately.
614
615             my \$retval = $call(@argv);
616             return \$retval if \$retval;
617
618             # If we failed, but we're using LOCK_NB and
619             # returned EWOULDBLOCK, it's not a real error.
620
621             if (\$_[1] & Fcntl::LOCK_NB() and \$! == $EWOULDBLOCK ) {
622                 return \$retval;
623             }
624
625             # Otherwise, we failed.  Die noisily.
626
627             $die;
628
629         };
630     }
631
632     # AFAIK everything that can be given an unopned filehandle
633     # will fail if it tries to use it, so we don't really need
634     # the 'unopened' warning class here.  Especially since they
635     # then report the wrong line number.
636
637     return qq{
638         no warnings qw(unopened);
639
640         if (wantarray) {
641             my \@results = $call(@argv);
642             # If we got back nothing, or we got back a single
643             # undef, we die.
644             if (! \@results or (\@results == 1 and ! defined \$results[0])) {
645                 $die;
646             };
647             return \@results;
648         }
649
650         # Otherwise, we're in scalar context.
651         # We're never in a void context, since we have to look
652         # at the result.
653
654         my \$result = $call(@argv);
655
656     } . ( $use_defined_or ? qq{
657
658         $die if not defined \$result;
659
660         return \$result;
661
662     } : qq{
663
664         return \$result || $die;
665
666     } ) ;
667
668 }
669
670 # This returns the old copy of the sub, so we can
671 # put it back at end of scope.
672
673 # TODO : Check to make sure prototypes are restored correctly.
674
675 # TODO: Taking a huge list of arguments is awful.  Rewriting to
676 #       take a hash would be lovely.
677
678 sub _make_fatal {
679     my($class, $sub, $pkg, $void, $lexical, $filename) = @_;
680     my($name, $code, $sref, $real_proto, $proto, $core, $call);
681     my $ini = $sub;
682
683     $sub = "${pkg}::$sub" unless $sub =~ /::/;
684
685     # Figure if we're using lexical or package semantics and
686     # twiddle the appropriate bits.
687
688     if (not $lexical) {
689         $Package_Fatal{$sub} = 1;
690     }
691
692     # TODO - We *should* be able to do skipping, since we know when
693     # we've lexicalised / unlexicalised a subroutine.
694
695     $name = $sub;
696     $name =~ s/.*::// or $name =~ s/^&//;
697
698     warn  "# _make_fatal: sub=$sub pkg=$pkg name=$name void=$void\n" if $Debug;
699     croak(sprintf(ERROR_BADNAME, $class, $name)) unless $name =~ /^\w+$/;
700
701     if (defined(&$sub)) {   # user subroutine
702
703         # This could be something that we've fatalised that
704         # was in core.
705
706         local $@; # Don't clobber anyone else's $@
707
708         if ( $Package_Fatal{$sub} and eval { prototype "CORE::$name" } ) {
709
710             # Something we previously made Fatal that was core.
711             # This is safe to replace with an autodying to core
712             # version.
713
714             $core  = 1;
715             $call  = "CORE::$name";
716             $proto = prototype $call;
717
718             # We return our $sref from this subroutine later
719             # on, indicating this subroutine should be placed
720             # back when we're finished.
721
722             $sref = \&$sub;
723
724         } else {
725
726             # A regular user sub, or a user sub wrapping a
727             # core sub.
728
729             $sref = \&$sub;
730             $proto = prototype $sref;
731             $call = '&$sref';
732
733         }
734
735     } elsif ($sub eq $ini && $sub !~ /^CORE::GLOBAL::/) {
736         # Stray user subroutine
737         croak(sprintf(ERROR_NOTSUB,$sub));
738
739     } elsif ($name eq 'system') {
740
741         # If we're fatalising system, then we need to load
742         # helper code.
743
744         eval {
745             require IPC::System::Simple; # Only load it if we need it.
746             require autodie::exception::system;
747         };
748
749         if ($@) { croak ERROR_NO_IPC_SYS_SIMPLE; }
750
751             # Make sure we're using a recent version of ISS that actually
752             # support fatalised system.
753             if ($IPC::System::Simple::VERSION < MIN_IPC_SYS_SIMPLE_VER) {
754                 croak sprintf(
755                 ERROR_IPC_SYS_SIMPLE_OLD, MIN_IPC_SYS_SIMPLE_VER,
756                 $IPC::System::Simple::VERSION
757                 );
758             }
759
760         $call = 'CORE::system';
761         $name = 'system';
762
763     } elsif ($name eq 'exec') {
764         # Exec doesn't have a prototype.  We don't care.  This
765         # breaks the exotic form with lexical scope, and gives
766         # the regular form a "do or die" beaviour as expected.
767
768         $call = 'CORE::exec';
769         $name = 'exec';
770         $core = 1;
771
772     } else {            # CORE subroutine
773         $proto = eval { prototype "CORE::$name" };
774         croak(sprintf(ERROR_NOT_BUILT,$name)) if $@;
775         croak(sprintf(ERROR_CANT_OVERRIDE,$name)) if not defined $proto;
776         $core = 1;
777         $call = "CORE::$name";
778     }
779
780     if (defined $proto) {
781         $real_proto = " ($proto)";
782     } else {
783         $real_proto = '';
784         $proto = '@';
785     }
786
787     my $true_name = $core ? $call : $sub;
788
789     # TODO: This caching works, but I don't like using $void and
790     # $lexical as keys.  In particular, I suspect our code may end up
791     # wrapping already wrapped code when autodie and Fatal are used
792     # together.
793
794     # NB: We must use '$sub' (the name plus package) and not
795     # just '$name' (the short name) here.  Failing to do so
796     # results code that's in the wrong package, and hence has
797     # access to the wrong package filehandles.
798
799     if (my $subref = $Cached_fatalised_sub{$class}{$sub}{$void}{$lexical}) {
800         $class->_install_subs($pkg, { $name => $subref });
801         return $sref;
802     }
803
804     $code = qq[
805         sub$real_proto {
806             local(\$", \$!) = (', ', 0);    # TODO - Why do we do this?
807     ];
808
809     # Don't have perl whine if exec fails, since we'll be handling
810     # the exception now.
811     $code .= "no warnings qw(exec);\n" if $call eq "CORE::exec";
812
813     my @protos = fill_protos($proto);
814     $code .= $class->write_invocation($core, $call, $name, $void, $lexical, $sub, @protos);
815     $code .= "}\n";
816     warn $code if $Debug;
817
818     # I thought that changing package was a monumental waste of
819     # time for CORE subs, since they'll always be the same.  However
820     # that's not the case, since they may refer to package-based
821     # filehandles (eg, with open).
822     #
823     # There is potential to more aggressively cache core subs
824     # that we know will never want to interact with package variables
825     # and filehandles.
826
827     {
828         local $@;
829         no strict 'refs'; ## no critic # to avoid: Can't use string (...) as a symbol ref ...
830         $code = eval("package $pkg; use Carp; $code");  ## no critic
831         if (not $code) {
832
833             # For some reason, using a die, croak, or confess in here
834             # results in the error being completely surpressed. As such,
835             # we need to do our own reporting.
836             #
837             # TODO: Fix the above.
838
839             _autocroak("Internal error in autodie/Fatal processing $true_name: $@");
840
841         }
842     }
843
844     # Now we need to wrap our fatalised sub inside an itty bitty
845     # closure, which can detect if we've leaked into another file.
846     # Luckily, we only need to do this for lexical (autodie)
847     # subs.  Fatal subs can leak all they want, it's considered
848     # a "feature" (or at least backwards compatible).
849
850     # TODO: Cache our leak guards!
851
852     # TODO: This is pretty hairy code.  A lot more tests would
853     # be really nice for this.
854
855     my $leak_guard;
856
857     if ($lexical) {
858
859         $leak_guard = qq<
860             package $pkg;
861
862             sub$real_proto {
863
864                 # If we're called from the correct file, then use the
865                 # autodying code.
866                 goto &\$code if ((caller)[1] eq \$filename);
867
868                 # Oh bother, we've leaked into another file.  Call the
869                 # original code.  Note that \$sref may actually be a
870                 # reference to a Fatalised version of a core built-in.
871                 # That's okay, because Fatal *always* leaks between files.
872
873                 goto &\$sref if \$sref;
874         >;
875
876
877         # If we're here, it must have been a core subroutine called.
878         # Warning: The following code may disturb some viewers.
879
880         # TODO: It should be possible to combine this with
881         # write_invocation().
882
883         foreach my $proto (@protos) {
884             local $" = ", ";    # So @args is formatted correctly.
885             my ($count, @args) = @$proto;
886             $leak_guard .= qq<
887                 if (\@_ == $count) {
888                     return $call(@args);
889                 }
890             >;
891         }
892
893         $leak_guard .= qq< croak "Internal error in Fatal/autodie.  Leak-guard failure"; } >;
894
895         # warn "$leak_guard\n";
896
897         local $@;
898
899         $leak_guard = eval $leak_guard;  ## no critic
900
901         die "Internal error in $class: Leak-guard installation failure: $@" if $@;
902     }
903
904     $class->_install_subs($pkg, { $name => $leak_guard || $code });
905
906     $Cached_fatalised_sub{$class}{$sub}{$void}{$lexical} = $leak_guard || $code;
907
908     return $sref;
909
910 }
911
912 # This subroutine exists primarily so that child classes can override
913 # it to point to their own exception class.  Doing this is significantly
914 # less complex than overriding throw()
915
916 sub exception_class { return "autodie::exception" };
917
918 {
919     my %exception_class_for;
920     my %class_loaded;
921
922     sub throw {
923         my ($class, @args) = @_;
924
925         # Find our exception class if we need it.
926         my $exception_class =
927              $exception_class_for{$class} ||= $class->exception_class;
928
929         if (not $class_loaded{$exception_class}) {
930             if ($exception_class =~ /[^\w:']/) {
931                 confess "Bad exception class '$exception_class'.\nThe '$class->exception_class' method wants to use $exception_class\nfor exceptions, but it contains characters which are not word-characters or colons.";
932             }
933
934             # Alas, Perl does turn barewords into modules unless they're
935             # actually barewords.  As such, we're left doing a string eval
936             # to make sure we load our file correctly.
937
938             my $E;
939
940             {
941                 local $@;   # We can't clobber $@, it's wrong!
942                 eval "require $exception_class"; ## no critic
943                 $E = $@;    # Save $E despite ending our local.
944             }
945
946             # We need quotes around $@ to make sure it's stringified
947             # while still in scope.  Without them, we run the risk of
948             # $@ having been cleared by us exiting the local() block.
949
950             confess "Failed to load '$exception_class'.\nThis may be a typo in the '$class->exception_class' method,\nor the '$exception_class' module may not exist.\n\n $E" if $E;
951
952             $class_loaded{$exception_class}++;
953
954         }
955
956         return $exception_class->new(@args);
957     }
958 }
959
960 # For some reason, dying while replacing our subs doesn't
961 # kill our calling program.  It simply stops the loading of
962 # autodie and keeps going with everything else.  The _autocroak
963 # sub allows us to die with a vegence.  It should *only* ever be
964 # used for serious internal errors, since the results of it can't
965 # be captured.
966
967 sub _autocroak {
968     warn Carp::longmess(@_);
969     exit(255);  # Ugh!
970 }
971
972 package autodie::Scope::Guard;
973
974 # This code schedules the cleanup of subroutines at the end of
975 # scope.  It's directly inspired by chocolateboy's excellent
976 # Scope::Guard module.
977
978 sub new {
979     my ($class, $handler) = @_;
980
981     return bless $handler, $class;
982 }
983
984 sub DESTROY {
985     my ($self) = @_;
986
987     $self->();
988 }
989
990 1;
991
992 __END__
993
994 =head1 NAME
995
996 Fatal - Replace functions with equivalents which succeed or die
997
998 =head1 SYNOPSIS
999
1000     use Fatal qw(open close);
1001
1002     open(my $fh, "<", $filename);  # No need to check errors!
1003
1004     use File::Copy qw(move);
1005     use Fatal qw(move);
1006
1007     move($file1, $file2); # No need to check errors!
1008
1009     sub juggle { . . . }
1010     Fatal->import('juggle');
1011
1012 =head1 BEST PRACTICE
1013
1014 B<Fatal has been obsoleted by the new L<autodie> pragma.> Please use
1015 L<autodie> in preference to C<Fatal>.  L<autodie> supports lexical scoping,
1016 throws real exception objects, and provides much nicer error messages.
1017
1018 The use of C<:void> with Fatal is discouraged.
1019
1020 =head1 DESCRIPTION
1021
1022 C<Fatal> provides a way to conveniently replace
1023 functions which normally return a false value when they fail with
1024 equivalents which raise exceptions if they are not successful.  This
1025 lets you use these functions without having to test their return
1026 values explicitly on each call.  Exceptions can be caught using
1027 C<eval{}>.  See L<perlfunc> and L<perlvar> for details.
1028
1029 The do-or-die equivalents are set up simply by calling Fatal's
1030 C<import> routine, passing it the names of the functions to be
1031 replaced.  You may wrap both user-defined functions and overridable
1032 CORE operators (except C<exec>, C<system>, C<print>, or any other
1033 built-in that cannot be expressed via prototypes) in this way.
1034
1035 If the symbol C<:void> appears in the import list, then functions
1036 named later in that import list raise an exception only when
1037 these are called in void context--that is, when their return
1038 values are ignored.  For example
1039
1040     use Fatal qw/:void open close/;
1041
1042     # properly checked, so no exception raised on error
1043     if (not open(my $fh, '<' '/bogotic') {
1044         warn "Can't open /bogotic: $!";
1045     }
1046
1047     # not checked, so error raises an exception
1048     close FH;
1049
1050 The use of C<:void> is discouraged, as it can result in exceptions
1051 not being thrown if you I<accidentally> call a method without
1052 void context.  Use L<autodie> instead if you need to be able to
1053 disable autodying/Fatal behaviour for a small block of code.
1054
1055 =head1 DIAGNOSTICS
1056
1057 =over 4
1058
1059 =item Bad subroutine name for Fatal: %s
1060
1061 You've called C<Fatal> with an argument that doesn't look like
1062 a subroutine name, nor a switch that this version of Fatal
1063 understands.
1064
1065 =item %s is not a Perl subroutine
1066
1067 You've asked C<Fatal> to try and replace a subroutine which does not
1068 exist, or has not yet been defined.
1069
1070 =item %s is neither a builtin, nor a Perl subroutine
1071
1072 You've asked C<Fatal> to replace a subroutine, but it's not a Perl
1073 built-in, and C<Fatal> couldn't find it as a regular subroutine.
1074 It either doesn't exist or has not yet been defined.
1075
1076 =item Cannot make the non-overridable %s fatal
1077
1078 You've tried to use C<Fatal> on a Perl built-in that can't be
1079 overridden, such as C<print> or C<system>, which means that
1080 C<Fatal> can't help you, although some other modules might.
1081 See the L</"SEE ALSO"> section of this documentation.
1082
1083 =item Internal error: %s
1084
1085 You've found a bug in C<Fatal>.  Please report it using
1086 the C<perlbug> command.
1087
1088 =back
1089
1090 =head1 BUGS
1091
1092 C<Fatal> clobbers the context in which a function is called and always
1093 makes it a scalar context, except when the C<:void> tag is used.
1094 This problem does not exist in L<autodie>.
1095
1096 "Used only once" warnings can be generated when C<autodie> or C<Fatal>
1097 is used with package filehandles (eg, C<FILE>).  It's strongly recommended
1098 you use scalar filehandles instead.
1099
1100 =head1 AUTHOR
1101
1102 Original module by Lionel Cons (CERN).
1103
1104 Prototype updates by Ilya Zakharevich <ilya@math.ohio-state.edu>.
1105
1106 L<autodie> support, bugfixes, extended diagnostics, C<system>
1107 support, and major overhauling by Paul Fenwick <pjf@perltraining.com.au>
1108
1109 =head1 LICENSE
1110
1111 This module is free software, you may distribute it under the
1112 same terms as Perl itself.
1113
1114 =head1 SEE ALSO
1115
1116 L<autodie> for a nicer way to use lexical Fatal.
1117
1118 L<IPC::System::Simple> for a similar idea for calls to C<system()>
1119 and backticks.
1120
1121 =cut