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