This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
add parallel support 4 Win32 dmake-COREDIR parallelism part 2
[perl5.git] / lib / diagnostics.pm
1 package diagnostics;
2
3 =head1 NAME
4
5 diagnostics, splain - produce verbose warning diagnostics
6
7 =head1 SYNOPSIS
8
9 Using the C<diagnostics> pragma:
10
11     use diagnostics;
12     use diagnostics -verbose;
13
14     enable  diagnostics;
15     disable diagnostics;
16
17 Using the C<splain> standalone filter program:
18
19     perl program 2>diag.out
20     splain [-v] [-p] diag.out
21
22 Using diagnostics to get stack traces from a misbehaving script:
23
24     perl -Mdiagnostics=-traceonly my_script.pl
25
26 =head1 DESCRIPTION
27
28 =head2 The C<diagnostics> Pragma
29
30 This module extends the terse diagnostics normally emitted by both the
31 perl compiler and the perl interpreter (from running perl with a -w 
32 switch or C<use warnings>), augmenting them with the more
33 explicative and endearing descriptions found in L<perldiag>.  Like the
34 other pragmata, it affects the compilation phase of your program rather
35 than merely the execution phase.
36
37 To use in your program as a pragma, merely invoke
38
39     use diagnostics;
40
41 at the start (or near the start) of your program.  (Note 
42 that this I<does> enable perl's B<-w> flag.)  Your whole
43 compilation will then be subject(ed :-) to the enhanced diagnostics.
44 These still go out B<STDERR>.
45
46 Due to the interaction between runtime and compiletime issues,
47 and because it's probably not a very good idea anyway,
48 you may not use C<no diagnostics> to turn them off at compiletime.
49 However, you may control their behaviour at runtime using the 
50 disable() and enable() methods to turn them off and on respectively.
51
52 The B<-verbose> flag first prints out the L<perldiag> introduction before
53 any other diagnostics.  The $diagnostics::PRETTY variable can generate nicer
54 escape sequences for pagers.
55
56 Warnings dispatched from perl itself (or more accurately, those that match
57 descriptions found in L<perldiag>) are only displayed once (no duplicate
58 descriptions).  User code generated warnings a la warn() are unaffected,
59 allowing duplicate user messages to be displayed.
60
61 This module also adds a stack trace to the error message when perl dies.
62 This is useful for pinpointing what
63 caused the death.  The B<-traceonly> (or
64 just B<-t>) flag turns off the explanations of warning messages leaving just
65 the stack traces.  So if your script is dieing, run it again with
66
67   perl -Mdiagnostics=-traceonly my_bad_script
68
69 to see the call stack at the time of death.  By supplying the B<-warntrace>
70 (or just B<-w>) flag, any warnings emitted will also come with a stack
71 trace.
72
73 =head2 The I<splain> Program
74
75 While apparently a whole nuther program, I<splain> is actually nothing
76 more than a link to the (executable) F<diagnostics.pm> module, as well as
77 a link to the F<diagnostics.pod> documentation.  The B<-v> flag is like
78 the C<use diagnostics -verbose> directive.
79 The B<-p> flag is like the
80 $diagnostics::PRETTY variable.  Since you're post-processing with 
81 I<splain>, there's no sense in being able to enable() or disable() processing.
82
83 Output from I<splain> is directed to B<STDOUT>, unlike the pragma.
84
85 =head1 EXAMPLES
86
87 The following file is certain to trigger a few errors at both
88 runtime and compiletime:
89
90     use diagnostics;
91     print NOWHERE "nothing\n";
92     print STDERR "\n\tThis message should be unadorned.\n";
93     warn "\tThis is a user warning";
94     print "\nDIAGNOSTIC TESTER: Please enter a <CR> here: ";
95     my $a, $b = scalar <STDIN>;
96     print "\n";
97     print $x/$y;
98
99 If you prefer to run your program first and look at its problem
100 afterwards, do this:
101
102     perl -w test.pl 2>test.out
103     ./splain < test.out
104
105 Note that this is not in general possible in shells of more dubious heritage, 
106 as the theoretical 
107
108     (perl -w test.pl >/dev/tty) >& test.out
109     ./splain < test.out
110
111 Because you just moved the existing B<stdout> to somewhere else.
112
113 If you don't want to modify your source code, but still have on-the-fly
114 warnings, do this:
115
116     exec 3>&1; perl -w test.pl 2>&1 1>&3 3>&- | splain 1>&2 3>&- 
117
118 Nifty, eh?
119
120 If you want to control warnings on the fly, do something like this.
121 Make sure you do the C<use> first, or you won't be able to get
122 at the enable() or disable() methods.
123
124     use diagnostics; # checks entire compilation phase 
125         print "\ntime for 1st bogus diags: SQUAWKINGS\n";
126         print BOGUS1 'nada';
127         print "done with 1st bogus\n";
128
129     disable diagnostics; # only turns off runtime warnings
130         print "\ntime for 2nd bogus: (squelched)\n";
131         print BOGUS2 'nada';
132         print "done with 2nd bogus\n";
133
134     enable diagnostics; # turns back on runtime warnings
135         print "\ntime for 3rd bogus: SQUAWKINGS\n";
136         print BOGUS3 'nada';
137         print "done with 3rd bogus\n";
138
139     disable diagnostics;
140         print "\ntime for 4th bogus: (squelched)\n";
141         print BOGUS4 'nada';
142         print "done with 4th bogus\n";
143
144 =head1 INTERNALS
145
146 Diagnostic messages derive from the F<perldiag.pod> file when available at
147 runtime.  Otherwise, they may be embedded in the file itself when the
148 splain package is built.   See the F<Makefile> for details.
149
150 If an extant $SIG{__WARN__} handler is discovered, it will continue
151 to be honored, but only after the diagnostics::splainthis() function 
152 (the module's $SIG{__WARN__} interceptor) has had its way with your
153 warnings.
154
155 There is a $diagnostics::DEBUG variable you may set if you're desperately
156 curious what sorts of things are being intercepted.
157
158     BEGIN { $diagnostics::DEBUG = 1 } 
159
160
161 =head1 BUGS
162
163 Not being able to say "no diagnostics" is annoying, but may not be
164 insurmountable.
165
166 The C<-pretty> directive is called too late to affect matters.
167 You have to do this instead, and I<before> you load the module.
168
169     BEGIN { $diagnostics::PRETTY = 1 } 
170
171 I could start up faster by delaying compilation until it should be
172 needed, but this gets a "panic: top_level" when using the pragma form
173 in Perl 5.001e.
174
175 While it's true that this documentation is somewhat subserious, if you use
176 a program named I<splain>, you should expect a bit of whimsy.
177
178 =head1 AUTHOR
179
180 Tom Christiansen <F<tchrist@mox.perl.com>>, 25 June 1995.
181
182 =cut
183
184 use strict;
185 use 5.009001;
186 use Carp;
187 $Carp::Internal{__PACKAGE__.""}++;
188
189 our $VERSION = '1.34';
190 our $DEBUG;
191 our $VERBOSE;
192 our $PRETTY;
193 our $TRACEONLY = 0;
194 our $WARNTRACE = 0;
195
196 use Config;
197 use Text::Tabs 'expand';
198 my $privlib = $Config{privlibexp};
199 if ($^O eq 'VMS') {
200     require VMS::Filespec;
201     $privlib = VMS::Filespec::unixify($privlib);
202 }
203 my @trypod = (
204            "$privlib/pod/perldiag.pod",
205            "$privlib/pods/perldiag.pod",
206           );
207 # handy for development testing of new warnings etc
208 unshift @trypod, "./pod/perldiag.pod" if -e "pod/perldiag.pod";
209 (my $PODFILE) = ((grep { -e } @trypod), $trypod[$#trypod])[0];
210
211 $DEBUG ||= 0;
212
213 local $| = 1;
214 local $_;
215 local $.;
216
217 my $standalone;
218 my(%HTML_2_Troff, %HTML_2_Latin_1, %HTML_2_ASCII_7);
219
220 CONFIG: {
221     our $opt_p = our $opt_d = our $opt_v = our $opt_f = '';
222
223     unless (caller) {
224         $standalone++;
225         require Getopt::Std;
226         Getopt::Std::getopts('pdvf:')
227             or die "Usage: $0 [-v] [-p] [-f splainpod]";
228         $PODFILE = $opt_f if $opt_f;
229         $DEBUG = 2 if $opt_d;
230         $VERBOSE = $opt_v;
231         $PRETTY = $opt_p;
232     }
233
234     if (open(POD_DIAG, $PODFILE)) {
235         warn "Happy happy podfile from real $PODFILE\n" if $DEBUG;
236         last CONFIG;
237     } 
238
239     if (caller) {
240         INCPATH: {
241             for my $file ( (map { "$_/".__PACKAGE__.".pm" } @INC), $0) {
242                 warn "Checking $file\n" if $DEBUG;
243                 if (open(POD_DIAG, $file)) {
244                     while (<POD_DIAG>) {
245                         next unless
246                             /^__END__\s*# wish diag dbase were more accessible/;
247                         print STDERR "podfile is $file\n" if $DEBUG;
248                         last INCPATH;
249                     }
250                 }
251             } 
252         }
253     } else { 
254         print STDERR "podfile is <DATA>\n" if $DEBUG;
255         *POD_DIAG = *main::DATA;
256     }
257 }
258 if (eof(POD_DIAG)) { 
259     die "couldn't find diagnostic data in $PODFILE @INC $0";
260 }
261
262
263 %HTML_2_Troff = (
264     'amp'       =>      '&',    #   ampersand
265     'lt'        =>      '<',    #   left chevron, less-than
266     'gt'        =>      '>',    #   right chevron, greater-than
267     'quot'      =>      '"',    #   double quote
268
269     "Aacute"    =>      "A\\*'",        #   capital A, acute accent
270     # etc
271
272 );
273
274 %HTML_2_Latin_1 = (
275     'amp'       =>      '&',    #   ampersand
276     'lt'        =>      '<',    #   left chevron, less-than
277     'gt'        =>      '>',    #   right chevron, greater-than
278     'quot'      =>      '"',    #   double quote
279
280     "Aacute"    =>      "\xC1"  #   capital A, acute accent
281
282     # etc
283 );
284
285 %HTML_2_ASCII_7 = (
286     'amp'       =>      '&',    #   ampersand
287     'lt'        =>      '<',    #   left chevron, less-than
288     'gt'        =>      '>',    #   right chevron, greater-than
289     'quot'      =>      '"',    #   double quote
290
291     "Aacute"    =>      "A"     #   capital A, acute accent
292     # etc
293 );
294
295 our %HTML_Escapes;
296 *HTML_Escapes = do {
297     if ($standalone) {
298         $PRETTY ? \%HTML_2_Latin_1 : \%HTML_2_ASCII_7; 
299     } else {
300         \%HTML_2_Latin_1; 
301     }
302 }; 
303
304 *THITHER = $standalone ? *STDOUT : *STDERR;
305
306 my %transfmt = (); 
307 my $transmo = <<EOFUNC;
308 sub transmo {
309     #local \$^W = 0;  # recursive warnings we do NOT need!
310 EOFUNC
311
312 my %msg;
313 {
314     print STDERR "FINISHING COMPILATION for $_\n" if $DEBUG;
315     local $/ = '';
316     local $_;
317     my $header;
318     my @headers;
319     my $for_item;
320     my $seen_body;
321     while (<POD_DIAG>) {
322
323         sub _split_pod_link {
324             $_[0] =~ m'(?:([^|]*)\|)?([^/]*)(?:/("?)(.*)\3)?'s;
325             ($1,$2,$4);
326         }
327
328         unescape();
329         if ($PRETTY) {
330             sub noop   { return $_[0] }  # spensive for a noop
331             sub bold   { my $str =$_[0];  $str =~ s/(.)/$1\b$1/g; return $str; } 
332             sub italic { my $str = $_[0]; $str =~ s/(.)/_\b$1/g;  return $str; } 
333             s/C<<< (.*?) >>>|C<< (.*?) >>|[BC]<(.*?)>/bold($+)/ges;
334             s/[IF]<(.*?)>/italic($1)/ges;
335             s/L<(.*?)>/
336                my($text,$page,$sect) = _split_pod_link($1);
337                defined $text
338                 ? $text
339                 : defined $sect
340                    ? italic($sect) . ' in ' . italic($page)
341                    : italic($page)
342              /ges;
343              s/S<(.*?)>/
344                $1
345              /ges;
346         } else {
347             s/C<<< (.*?) >>>|C<< (.*?) >>|[BC]<(.*?)>/$+/gs;
348             s/[IF]<(.*?)>/$1/gs;
349             s/L<(.*?)>/
350                my($text,$page,$sect) = _split_pod_link($1);
351                defined $text
352                 ? $text
353                 : defined $sect
354                    ? qq '"$sect" in $page'
355                    : $page
356              /ges;
357             s/S<(.*?)>/
358                $1
359              /ges;
360         } 
361         unless (/^=/) {
362             if (defined $header) { 
363                 if ( $header eq 'DESCRIPTION' && 
364                     (   /Optional warnings are enabled/ 
365                      || /Some of these messages are generic./
366                     ) )
367                 {
368                     next;
369                 }
370                 $_ = expand $_;
371                 s/^/    /gm;
372                 $msg{$header} .= $_;
373                 for my $h(@headers) { $msg{$h} .= $_ }
374                 ++$seen_body;
375                 undef $for_item;        
376             }
377             next;
378         } 
379
380         # If we have not come across the body of the description yet, then
381         # the previous header needs to share the same description.
382         if ($seen_body) {
383             @headers = ();
384         }
385         else {
386             push @headers, $header if defined $header;
387         }
388
389         unless ( s/=item (.*?)\s*\z//s) {
390
391             if ( s/=head1\sDESCRIPTION//) {
392                 $msg{$header = 'DESCRIPTION'} = '';
393                 undef $for_item;
394             }
395             elsif( s/^=for\s+diagnostics\s*\n(.*?)\s*\z// ) {
396                 $for_item = $1;
397             }
398             elsif( /^=back/ ) { # Stop processing body here
399                 undef $header;
400                 undef $for_item;
401                 $seen_body = 0;
402                 next;
403             }
404             next;
405         }
406
407         if( $for_item ) { $header = $for_item; undef $for_item } 
408         else {
409             $header = $1;
410
411             $header =~ s/\n/ /gs; # Allow multi-line headers
412         }
413
414         # strip formatting directives from =item line
415         $header =~ s/[A-Z]<(.*?)>/$1/g;
416
417         # Since we strip "(\.\s*)\n" when we search a warning, strip it here as well
418         $header =~ s/(\.\s*)?$//;
419
420         my @toks = split( /(%l?[dxX]|%[ucp]|%(?:\.\d+)?[fs])/, $header );
421         if (@toks > 1) {
422             my $conlen = 0;
423             for my $i (0..$#toks){
424                 if( $i % 2 ){
425                     if(      $toks[$i] eq '%c' ){
426                         $toks[$i] = '.';
427                     } elsif( $toks[$i] =~ /^%(?:d|u)$/ ){
428                         $toks[$i] = '\d+';
429                     } elsif( $toks[$i] =~ '^%(?:s|.*f)$' ){
430                         $toks[$i] = $i == $#toks ? '.*' : '.*?';
431                     } elsif( $toks[$i] =~ '%.(\d+)s' ){
432                         $toks[$i] = ".{$1}";
433                     } elsif( $toks[$i] =~ '^%l*([pxX])$' ){
434                         $toks[$i] = $1 eq 'X' ? '[\dA-F]+' : '[\da-f]+';
435                     }
436                 } elsif( length( $toks[$i] ) ){
437                     $toks[$i] = quotemeta $toks[$i];
438                     $conlen += length( $toks[$i] );
439                 }
440             }  
441             my $lhs = join( '', @toks );
442             $lhs =~ s/(\\\s)+/\\s+/g; # Replace lit space with multi-space match
443             $transfmt{$header}{pat} =
444               "    s\a^\\s*$lhs\\s*\a\Q$header\E\as\n\t&& return 1;\n";
445             $transfmt{$header}{len} = $conlen;
446         } else {
447             my $lhs = "\Q$header\E";
448             $lhs =~ s/(\\\s)+/\\s+/g; # Replace lit space with multi-space match
449             $transfmt{$header}{pat} =
450               "    s\a^\\s*$lhs\\s*\a\Q$header\E\a\n\t && return 1;\n";
451             $transfmt{$header}{len} = length( $header );
452         } 
453
454         print STDERR __PACKAGE__.": Duplicate entry: \"$header\"\n"
455             if $msg{$header};
456
457         $msg{$header} = '';
458         $seen_body = 0;
459     } 
460
461
462     close POD_DIAG unless *main::DATA eq *POD_DIAG;
463
464     die "No diagnostics?" unless %msg;
465
466     # Apply patterns in order of decreasing sum of lengths of fixed parts
467     # Seems the best way of hitting the right one.
468     for my $hdr ( sort { $transfmt{$b}{len} <=> $transfmt{$a}{len} }
469                   keys %transfmt ){
470         $transmo .= $transfmt{$hdr}{pat};
471     }
472     $transmo .= "    return 0;\n}\n";
473     print STDERR $transmo if $DEBUG;
474     eval $transmo;
475     die $@ if $@;
476 }
477
478 if ($standalone) {
479     if (!@ARGV and -t STDIN) { print STDERR "$0: Reading from STDIN\n" } 
480     while (defined (my $error = <>)) {
481         splainthis($error) || print THITHER $error;
482     } 
483     exit;
484
485
486 my $olddie;
487 my $oldwarn;
488
489 sub import {
490     shift;
491     $^W = 1; # yup, clobbered the global variable; 
492              # tough, if you want diags, you want diags.
493     return if defined $SIG{__WARN__} && ($SIG{__WARN__} eq \&warn_trap);
494
495     for (@_) {
496
497         /^-d(ebug)?$/           && do {
498                                     $DEBUG++;
499                                     next;
500                                    };
501
502         /^-v(erbose)?$/         && do {
503                                     $VERBOSE++;
504                                     next;
505                                    };
506
507         /^-p(retty)?$/          && do {
508                                     print STDERR "$0: I'm afraid it's too late for prettiness.\n";
509                                     $PRETTY++;
510                                     next;
511                                };
512         # matches trace and traceonly for legacy doc mixup reasons
513         /^-t(race(only)?)?$/    && do {
514                                     $TRACEONLY++;
515                                     next;
516                                };
517         /^-w(arntrace)?$/       && do {
518                                     $WARNTRACE++;
519                                     next;
520                                };
521
522         warn "Unknown flag: $_";
523     } 
524
525     $oldwarn = $SIG{__WARN__};
526     $olddie = $SIG{__DIE__};
527     $SIG{__WARN__} = \&warn_trap;
528     $SIG{__DIE__} = \&death_trap;
529
530
531 sub enable { &import }
532
533 sub disable {
534     shift;
535     return unless $SIG{__WARN__} eq \&warn_trap;
536     $SIG{__WARN__} = $oldwarn || '';
537     $SIG{__DIE__} = $olddie || '';
538
539
540 sub warn_trap {
541     my $warning = $_[0];
542     if (caller eq __PACKAGE__ or !splainthis($warning)) {
543         if ($WARNTRACE) {
544             print STDERR Carp::longmess($warning);
545         } else {
546             print STDERR $warning;
547         }
548     } 
549     goto &$oldwarn if defined $oldwarn and $oldwarn and $oldwarn ne \&warn_trap;
550 };
551
552 sub death_trap {
553     my $exception = $_[0];
554
555     # See if we are coming from anywhere within an eval. If so we don't
556     # want to explain the exception because it's going to get caught.
557     my $in_eval = 0;
558     my $i = 0;
559     while (my $caller = (caller($i++))[3]) {
560       if ($caller eq '(eval)') {
561         $in_eval = 1;
562         last;
563       }
564     }
565
566     splainthis($exception) unless $in_eval;
567     if (caller eq __PACKAGE__) {
568         print STDERR "INTERNAL EXCEPTION: $exception";
569     } 
570     &$olddie if defined $olddie and $olddie and $olddie ne \&death_trap;
571
572     return if $in_eval;
573
574     # We don't want to unset these if we're coming from an eval because
575     # then we've turned off diagnostics.
576
577     # Switch off our die/warn handlers so we don't wind up in our own
578     # traps.
579     $SIG{__DIE__} = $SIG{__WARN__} = '';
580
581     $exception =~ s/\n(?=.)/\n\t/gas;
582
583     die Carp::longmess("__diagnostics__")
584           =~ s/^__diagnostics__.*?line \d+\.?\n/
585                   "Uncaught exception from user code:\n\t$exception"
586               /re;
587         # up we go; where we stop, nobody knows, but i think we die now
588         # but i'm deeply afraid of the &$olddie guy reraising and us getting
589         # into an indirect recursion loop
590 };
591
592 my %exact_duplicate;
593 my %old_diag;
594 my $count;
595 my $wantspace;
596 sub splainthis {
597   return 0 if $TRACEONLY;
598   for (my $tmp = shift) {
599     local $\;
600     local $!;
601     ### &finish_compilation unless %msg;
602     s/(\.\s*)?\n+$//;
603     my $orig = $_;
604     # return unless defined;
605
606     # get rid of the where-are-we-in-input part
607     s/, <.*?> (?:line|chunk).*$//;
608
609     # Discard 1st " at <file> line <no>" and all text beyond
610     # but be aware of messages containing " at this-or-that"
611     my $real = 0;
612     my @secs = split( / at / );
613     return unless @secs;
614     $_ = $secs[0];
615     for my $i ( 1..$#secs ){
616         if( $secs[$i] =~ /.+? (?:line|chunk) \d+/ ){
617             $real = 1;
618             last;
619         } else {
620             $_ .= ' at ' . $secs[$i];
621         }
622     }
623
624     # remove parenthesis occurring at the end of some messages 
625     s/^\((.*)\)$/$1/;
626
627     if ($exact_duplicate{$orig}++) {
628         return &transmo;
629     } else {
630         return 0 unless &transmo;
631     }
632
633     my $short = shorten($orig);
634     if ($old_diag{$_}) {
635         autodescribe();
636         print THITHER "$short (#$old_diag{$_})\n";
637         $wantspace = 1;
638     } elsif (!$msg{$_} && $orig =~ /\n./s) {
639         # A multiline message, like "Attempt to reload /
640         # Compilation failed"
641         my $found;
642         for (split /^/, $orig) {
643             splainthis($_) and $found = 1;
644         }
645         return $found;
646     } else {
647         autodescribe();
648         $old_diag{$_} = ++$count;
649         print THITHER "\n" if $wantspace;
650         $wantspace = 0;
651         print THITHER "$short (#$old_diag{$_})\n";
652         if ($msg{$_}) {
653             print THITHER $msg{$_};
654         } else {
655             if (0 and $standalone) { 
656                 print THITHER "    **** Error #$old_diag{$_} ",
657                         ($real ? "is" : "appears to be"),
658                         " an unknown diagnostic message.\n\n";
659             }
660             return 0;
661         } 
662     }
663     return 1;
664   }
665
666
667 sub autodescribe {
668     if ($VERBOSE and not $count) {
669         print THITHER &{$PRETTY ? \&bold : \&noop}("DESCRIPTION OF DIAGNOSTICS"),
670                 "\n$msg{DESCRIPTION}\n";
671     } 
672
673
674 sub unescape { 
675     s {
676             E<  
677             ( [A-Za-z]+ )       
678             >   
679     } { 
680          do {   
681              exists $HTML_Escapes{$1}
682                 ? do { $HTML_Escapes{$1} }
683                 : do {
684                     warn "Unknown escape: E<$1> in $_";
685                     "E<$1>";
686                 } 
687          } 
688     }egx;
689 }
690
691 sub shorten {
692     my $line = $_[0];
693     if (length($line) > 79 and index($line, "\n") == -1) {
694         my $space_place = rindex($line, ' ', 79);
695         if ($space_place != -1) {
696             substr($line, $space_place, 1) = "\n\t";
697         } 
698     } 
699     return $line;
700
701
702
703 1 unless $standalone;  # or it'll complain about itself
704 __END__ # wish diag dbase were more accessible