This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
podcheck.t: White-space only changes
[perl5.git] / t / porting / podcheck.t
1 #!/usr/bin/perl -w
2
3 use strict;
4 use warnings;
5 use feature 'unicode_strings';
6
7 use Carp;
8 use Digest;
9 use File::Find;
10 use File::Spec;
11 use Scalar::Util;
12 use Text::Tabs;
13
14 BEGIN {
15     require '../regen/regen_lib.pl';
16 }
17
18 sub DEBUG { 0 };
19
20 =pod
21
22 =head1 NAME
23
24 podcheck.t - Look for possible problems in the Perl pods
25
26 =head1 SYNOPSIS
27
28  cd t
29  ./perl -I../lib porting/podcheck.t [--show_all] [--cpan] [--counts]
30                                                             [ FILE ...]
31  ./perl -I../lib porting/podcheck.t --add_link MODULE ...
32
33  ./perl -I../lib porting/podcheck.t --regen
34
35 =head1 DESCRIPTION
36
37 podcheck.t is an extension of Pod::Checker.  It looks for pod errors and
38 potential errors in the files given as arguments, or if none specified, in all
39 pods in the distribution workspace, except those in the cpan directory (unless
40 C<--cpan> is specified).  It does additional checking beyond that done by
41 Pod::Checker, and keeps a database of known potential problems, and will
42 fail a pod only if the number of such problems differs from that given in the
43 database.  It also suppresses the C<(section) deprecated> message from
44 Pod::Checker, since specifying the man page section number is quite proper to do.
45
46 The additional checks it makes are:
47
48 =over
49
50 =item Cross-pod link checking
51
52 Pod::Checker verifies that links to an internal target in a pod are not
53 broken.  podcheck.t extends that (when called without FILE arguments) to
54 external links.  It does this by gathering up all the possible targets in the
55 workspace, and cross-checking them.  It also checks that a non-broken link
56 points to just one target.  (The destination pod could have two targets with
57 the same name.)
58
59 The way that the C<LE<lt>E<gt>> pod command works (for links outside the pod)
60 is to actually create a link to C<search.cpan.org> with an embedded query for
61 the desired pod or man page.  That means that links outside the distribution
62 are valid.  podcheck.t doesn't verify the validity of such links, but instead
63 keeps a data base of those known to be valid.  This means that if a link to a
64 target not on the list is created, the target needs to be added to the data
65 base.  This is accomplished via the L<--add_link|/--add_link MODULE ...>
66 option to podcheck.t, described below.
67
68 =item An internal link that isn't so specified
69
70 If a link is broken, but there is an existing internal target of the same
71 name, it is likely that the internal target was meant, and the C<"/"> is
72 missing from the C<LE<lt>E<gt>> pod command.
73
74 =item Verbatim paragraphs that wrap in an 80 column window
75
76 It's annoying to have lines wrap when displaying pod documentation in a
77 terminal window.  This checks that all such lines fit, and for those that
78 don't, it tells you how much needs to be cut in order to fit.  However,
79 if you're fixing these, keep in mind that some terminal/pager combinations
80 require really a maximum of 79 or 78 columns to display properly.
81
82 Often, the easiest thing to do to gain space for these is to lower the indent
83 to just one space.
84
85 =item Missing or duplicate NAME or missing NAME short description
86
87 A pod can't be linked to unless it has a unique name.
88 And a NAME should have a dash and short description after it.
89
90 =item =encoding statement issues
91
92 This indicates if an C<=encoding> statement should be present, or moved to the
93 front of the pod.
94
95 =item Items that perhaps should be links
96
97 There are mentions of apparent files in the pods that perhaps should be links
98 instead, using C<LE<lt>...E<gt>>
99
100 =item Items that perhaps should be C<FE<lt>...E<gt>>
101
102 What look like path names enclosed in C<CE<lt>...E<gt>> should perhaps have
103 C<FE<lt>...E<gt>> mark-up instead.
104
105 =back
106
107 A number of issues raised by podcheck.t and by the base Pod::Checker are not
108 really problems, but merely potential problems.  After inspecting them and
109 deciding that they aren't real problems, it is possible to shut up this program
110 about them, unlike base Pod::Checker.  To do this, call podcheck.t with the
111 C<--regen> option to regenerate the database.  This tells it that all existing
112 issues are to not be mentioned again.
113
114 This isn't fool-proof.  The database merely keeps track of the number of these
115 potential problems of each type for each pod.  If a new problem of a given
116 type is introduced into the pod, podcheck.t will spit out all of them.  You
117 then have to figure out which is the new one, and should it be changed or not.
118 But doing it this way insulates the database from having to keep track of line
119 numbers of problems, which may change, or the exact wording of each problem
120 which might also change without affecting whether it is a problem or not.
121
122 Also, if the count of potential problems of a given type for a pod decreases,
123 the database must be regenerated so that it knows the new number.  The program
124 gives instructions when this happens.
125
126 There is currently no check that modules listed as valid in the data base
127 actually are.  Thus any errors introduced there will remain there.
128
129 =head1 OPTIONS
130
131 =over
132
133 =item --add_link MODULE ...
134
135 Use this option to teach podcheck.t that the C<MODULE>s or man pages actually
136 exist, and to silence any messages that links to them are broken.
137
138 podcheck.t checks that links within the Perl core distribution are valid, but
139 it doesn't check links to man pages or external modules.  When it finds
140 a broken link, it checks its data base of external modules and man pages,
141 and only if not found there does it raise a message.  This option just adds
142 the list of modules and man page references that follow it on the command line
143 to that data base.
144
145 For example,
146
147     cd t
148     ./perl -I../lib porting/podcheck.t --add_link Unicode::Casing
149
150 causes the external module "Unicode::Casing" to be added to the data base, so
151 C<LE<lt>Unicode::Casing<gt>> will be considered valid.
152
153 =item --regen
154
155 Regenerate the data base used by podcheck.t to include all the existing
156 potential problems.  Future runs of the program will not then flag any of
157 these.
158
159 =item --cpan
160
161 Normally, all pods in the cpan directory are skipped, except to make sure that
162 any blead-upstream links to such pods are valid.
163 This option will cause cpan upstream pods to be checked.
164
165 =item --show_all
166
167 Normally, if the number of potential problems of a given type found for a
168 pod matches the expected value in the database, they will not be displayed.
169 This option forces the database to be ignored during the run, so all potential
170 problems are displayed and will fail their respective pod test.  Specifying
171 any particular FILES to operate on automatically selects this option.
172
173 =item --counts
174
175 Instead of testing, this just dumps the counts of the occurrences of the
176 various types of potential problems in the data base.
177
178 =back
179
180 =head1 FILES
181
182 The database is stored in F<t/porting/known_pod_issues.dat>
183
184 =head1 SEE ALSO
185
186 L<Pod::Checker>
187
188 =cut
189
190 #####################################################
191 # HOW IT WORKS (in general)
192 #
193 # If not called with specific files to check, the directory structure is
194 # examined for files that have pods in them.  Files that might not have to be
195 # fully parsed (e.g. in cpan) are parsed enough at this time to find their
196 # pod's NAME, and to get a checksum.
197 #
198 # Those kinds of files are sorted last, but otherwise the pods are parsed with
199 # the package coded here, My::Pod::Checker, which is an extension to
200 # Pod::Checker that adds some tests and suppresses others that aren't
201 # appropriate.  The latter module has no provision for capturing diagnostics,
202 # so a package, Tie_Array_to_FH, is used to force them to be placed into an
203 # array instead of printed.
204 #
205 # Parsing the files builds up a list of links.  The files are gone through
206 # again, doing cross-link checking and outputting all saved-up problems with
207 # each pod.
208 #
209 # Sorting the files last that potentially don't need to be fully parsed allows
210 # us to not parse them unless there is a link to an internal anchor in them
211 # from something that we have already parsed.  Keeping checksums allows us to
212 # not parse copies of other pods.
213 #
214 #####################################################
215
216 # 1 => Exclude low priority messages that aren't likely to be problems, and
217 # has many false positives; higher numbers give more messages.
218 my $Warnings_Level = 200;
219
220 # perldelta during construction may have place holder links.
221 our @perldelta_ignore_links = ( "XXX", "perl5YYYdelta" );
222
223 # To see if two pods with the same NAME are actually copies of the same pod,
224 # which is not an error, it uses a checksum to save work.
225 my $digest_type = "SHA-1";
226
227 my $original_dir = File::Spec->rel2abs(File::Spec->curdir);
228 my $data_dir = File::Spec->catdir($original_dir, 'porting');
229 my $known_issues = File::Spec->catfile($data_dir, 'known_pod_issues.dat');
230 my $copy_fh;
231
232 my $MAX_LINE_LENGTH = 80;   # 80 columns
233 my $INDENT = 8;             # default nroff indent
234
235 # Our warning messages.  Better not have [('"] in them, as those are used as
236 # delimiters for variable parts of the messages by poderror.
237 my $line_length = "Verbatim line length including indents exceeds $MAX_LINE_LENGTH by";
238 my $broken_link = "Apparent broken link";
239 my $broken_internal_link = "Apparent internal link is missing its forward slash";
240 my $see_not_linked = "? Should you be using L<...> instead of";
241 my $C_with_slash = "? Should you be using F<...> or maybe L<...> instead of";
242 my $multiple_targets = "There is more than one target";
243 my $duplicate_name = "Pod NAME already used";
244 my $need_encoding = "Should have =encoding statement because have non-ASCII";
245 my $encoding_first = "=encoding must be first command (if present)";
246 my $no_name = "There is no NAME";
247 my $missing_name_description = "The NAME should have a dash and short description after it";
248
249 # objects, tests, etc can't be pods, so don't look for them. Also skip
250 # files output by the patch program.  Could also ignore most of .gitignore
251 # files, but not all, so don't.
252 my $non_pods = qr/ (?: \.
253                        (?: [achot]  | zip | gz | bz2 | jar | tar | tgz | PL | so
254                            | orig | rej | patch   # Patch program output
255                            | sw[op] | \#.*  # Editor droppings
256                        )
257                        $
258                     ) | ~$      # Another editor dropping
259                 /x;
260
261
262 # Pod::Checker messages to suppress
263 my @suppressed_messages = (
264     "(section) in",                         # Checker is wrong to flag this
265     "multiple occurrence of link target",   # We catch independently the ones
266                                             # that are real problems.
267     "unescaped <>",
268     "Entity number out of range",   # Checker outputs this for anything above
269                                     # 255, and all Unicode is valid
270 );
271
272 sub suppressed {
273     # Returns bool as to if input message is one that is to be suppressed
274
275     my $message = shift;
276     return grep { $message =~ /^\Q$_/i } @suppressed_messages;
277 }
278
279 {   # Closure to contain a simple subset of test.pl.  This is to get rid of the
280     # unnecessary 'failed at' messages that would otherwise be output pointing
281     # to a particular line in this file.
282
283     my $current_test = 0;
284     my $planned;
285
286     sub plan {
287         my %plan = @_;
288         $planned = $plan{tests};
289         print "1..$planned\n";
290         return;
291     }
292
293     sub ok {
294         my $success = shift;
295         my $message = shift;
296
297         chomp $message;
298
299         $current_test++;
300         print "not " unless $success;
301         print "ok $current_test - $message\n";
302         return;
303     }
304
305     sub skip {
306         my $why = shift;
307         my $n    = @_ ? shift : 1;
308         for (1..$n) {
309             $current_test++;
310             print "ok $current_test # skip $why\n";
311         }
312         no warnings 'exiting';
313         last SKIP;
314     }
315
316     sub note {
317         my $message = shift;
318
319         chomp $message;
320
321         print $message =~ s/^/# /mgr;
322         print "\n";
323         return;
324     }
325
326     END {
327         if ($planned && $planned != $current_test) {
328             print STDERR
329             "# Looks like you planned $planned tests but ran $current_test.\n";
330         }
331     }
332 }
333
334 # This is to get this to work across multiple file systems, including those
335 # that are not case sensitive.  The db is stored in lower case, Un*x style,
336 # and all file name comparisons are done that way.
337 sub canonicalize($) {
338     my $input = shift;
339     my ($volume, $directories, $file)
340                     = File::Spec->splitpath(File::Spec->canonpath($input));
341     # Assumes $volume is constant for everything in this directory structure
342     $directories = "" if ! $directories;
343     $file = "" if ! $file;
344     my $output = lc join '/', File::Spec->splitdir($directories), $file;
345     $output =~ s! / /+ !/!gx;       # Multiple slashes => single slash
346     return $output;
347 }
348
349
350 # List of known potential problems by pod and type.
351 my %known_problems;
352
353 # Pods given by the keys contain an interior node that is referred to from
354 # outside it.
355 my %has_referred_to_node;
356
357 my $show_counts = 0;
358 my $regen = 0;
359 my $add_link = 0;
360 my $show_all = 0;
361
362 # Assume that are to skip anything in /cpan
363 my $do_upstream_cpan = 0;
364
365 while (@ARGV && substr($ARGV[0], 0, 1) eq '-') {
366     my $arg = shift @ARGV;
367
368     $arg =~ s/^--/-/; # Treat '--' the same as a single '-'
369     if ($arg eq '-regen') {
370         $regen = 1;
371     }
372     elsif ($arg eq '-add_link') {
373         $add_link = 1;
374     }
375     elsif ($arg eq '-cpan') {
376         $do_upstream_cpan = 1;
377     }
378     elsif ($arg eq '-show_all') {
379         $show_all = 1;
380     }
381     elsif ($arg eq '-counts') {
382         $show_counts = 1;
383     }
384     else {
385         die <<EOF;
386 Unknown option '$arg'
387
388 Usage: $0 [ --regen | --cpan | --show_all | FILE ... | --add_link MODULE ... ]\n"
389     --add_link -> Add the MODULE and man page references to the data base
390     --regen    -> Regenerate the data file for $0
391     --cpan     -> Include files in the cpan subdirectory.
392     --show_all -> Show all known potential problems
393     --counts   -> Don't test, but give summary counts of the currently
394                   existing database
395 EOF
396     }
397 }
398
399 my @files = @ARGV;
400
401 if (($regen + $show_all + $show_counts + $do_upstream_cpan + $add_link) > 1) {
402     croak "--regen, --show_all, --cpan, --counts, and --add_link are mutually exclusive";
403 }
404
405 my $has_input_files = @files;
406
407 if ($has_input_files && ($regen || $show_counts || $do_upstream_cpan)) {
408     croak "--regen, --counts and --cpan can't be used since using specific files";
409 }
410
411 if ($add_link && ! $has_input_files) {
412     croak "--add_link requires at least one module or man page reference";
413 }
414
415 our %problems;  # potential problems found in this run
416
417 package My::Pod::Checker {      # Extend Pod::Checker
418     use parent 'Pod::Checker';
419
420     # Uses inside out hash to protect from typos
421     # For new fields, remember to add to destructor DESTROY()
422     my %indents;            # Stack of indents from =over's in effect for
423                             # current line
424     my %current_indent;     # Current line's indent
425     my %filename;           # The pod is store in this file
426     my %skip;               # is SKIP set for this pod
427     my %in_NAME;            # true if within NAME section
428     my %in_begin;           # true if within =begin section
429     my %linkable_item;      # Bool: if the latest =item is linkable.  It isn't
430                             # for bullet and number lists
431     my %linkable_nodes;     # Pod::Checker adds all =items to its node list,
432                             # but not all =items are linkable to
433     my %seen_encoding_cmd;  # true if have =encoding earlier
434     my %command_count;      # Number of commands seen
435     my %seen_pod_cmd;       # true if have =pod earlier
436     my %warned_encoding;    # true if already have warned about =encoding
437                             # problems
438
439     sub DESTROY {
440         my $addr = Scalar::Util::refaddr $_[0];
441         delete $command_count{$addr};
442         delete $current_indent{$addr};
443         delete $filename{$addr};
444         delete $in_begin{$addr};
445         delete $indents{$addr};
446         delete $in_NAME{$addr};
447         delete $linkable_item{$addr};
448         delete $linkable_nodes{$addr};
449         delete $seen_encoding_cmd{$addr};
450         delete $seen_pod_cmd{$addr};
451         delete $skip{$addr};
452         delete $warned_encoding{$addr};
453         return;
454     }
455
456     sub new {
457         my $class = shift;
458         my $filename = shift;
459
460         my $self = $class->SUPER::new(-quiet => 1,
461                                      -warnings => $Warnings_Level);
462         my $addr = Scalar::Util::refaddr $self;
463         $command_count{$addr} = 0;
464         $current_indent{$addr} = 0;
465         $filename{$addr} = $filename;
466         $in_begin{$addr} = 0;
467         $in_NAME{$addr} = 0;
468         $linkable_item{$addr} = 0;
469         $seen_encoding_cmd{$addr} = 0;
470         $seen_pod_cmd{$addr} = 0;
471         $warned_encoding{$addr} = 0;
472         return $self;
473     }
474
475     # re's for messages that Pod::Checker outputs
476     my $location = qr/ \b (?:in|at|on|near) \s+ /xi;
477     my $optional_location = qr/ (?: $location )? /xi;
478     my $line_reference = qr/ [('"]? $optional_location \b line \s+
479                              (?: \d+ | EOF | \Q???\E | - )
480                              [)'"]? /xi;
481
482     sub poderror {  # Called to register a potential problem
483
484         # This adds an extra field to the parent hash, 'parameter'.  It is
485         # used to extract the variable parts of a message leaving just the
486         # constant skeleton.  This in turn allows the message to be
487         # categorized better, so that it shows up as a single type in our
488         # database, with the specifics of each occurrence not being stored with
489         # it.
490
491         my $self = shift;
492         my $opts = shift;
493
494         my $addr = Scalar::Util::refaddr $self;
495         return if $skip{$addr};
496
497         # Input can be a string or hash.  If a string, parse it to separate
498         # out the line number and convert to a hash for easier further
499         # processing
500         my $message;
501         if (ref $opts ne 'HASH') {
502             $message = join "", $opts, @_;
503             my $line_number;
504             if ($message =~ s/\s*($line_reference)//) {
505                 ($line_number = $1) =~ s/\s*$optional_location//;
506             }
507             else {
508                 $line_number = '???';
509             }
510             $opts = { -msg => $message, -line => $line_number };
511         } else {
512             $message = $opts->{'-msg'};
513
514         }
515
516         $message =~ s/^\d+\s+//;
517         return if main::suppressed($message);
518
519         $self->SUPER::poderror($opts, @_);
520
521         $opts->{parameter} = "" unless $opts->{parameter};
522
523         # The variable parts of the message tend to be enclosed in '...',
524         # "....", or (...).  Extract them and put them in an extra field,
525         # 'parameter'.  This is trickier because the matching delimiter to a
526         # '(' is its mirror, and not itself.  Text::Balanced could be used
527         # instead.
528         while ($message =~ m/ \s* $optional_location ( [('"] )/xg) {
529             my $delimiter = $1;
530             my $start = $-[0];
531             $delimiter = ')' if $delimiter eq '(';
532
533             # If there is no ending delimiter, don't consider it to be a
534             # variable part.  Most likely it is a contraction like "Don't"
535             last unless $message =~ m/\G .+? \Q$delimiter/xg;
536
537             my $length = $+[0] - $start;
538
539             # Get the part up through the closing delimiter
540             my $special = substr($message, $start, $length);
541             $special =~ s/^\s+//;   # No leading whitespace
542
543             # And add that variable part to the parameter, while removing it
544             # from the message.  This isn't a foolproof way of finding the
545             # variable part.  For example '(s)' can occur in e.g.,
546             # 'paragraph(s)'
547             if ($special ne '(s)') {
548                 substr($message, $start, $length) = "";
549                 pos $message = $start;
550                 $opts->{-msg} = $message;
551                 $opts->{parameter} .= " " if $opts->{parameter};
552                 $opts->{parameter} .= $special;
553             }
554         }
555
556         # Extract any additional line number given.  This is often the
557         # beginning location of something whereas the main line number gives
558         # the ending one.
559         if ($message =~ /( $line_reference )/xi) {
560             my $line_ref = $1;
561             while ($message =~ s/\s*\Q$line_ref//) {
562                 $opts->{-msg} = $message;
563                 $opts->{parameter} .= " " if $opts->{parameter};
564                 $opts->{parameter} .= $line_ref;
565             }
566         }
567
568         Carp::carp("Couldn't extract line number from '$message'") if $message =~ /line \d+/;
569         push @{$problems{$filename{$addr}}{$message}}, $opts;
570         #push @{$problems{$self->get_filename}{$message}}, $opts;
571     }
572
573     sub check_encoding {    # Does it need an =encoding statement?
574         my ($self, $paragraph, $line_num, $pod_para) = @_;
575
576         # Do nothing if there is an =encoding in the file, or if the line
577         # doesn't require an =encoding, or have already warned.
578         my $addr = Scalar::Util::refaddr $self;
579         return if $seen_encoding_cmd{$addr}
580                     || $warned_encoding{$addr}
581                     || $paragraph !~ /\P{ASCII}/;
582
583         $warned_encoding{$addr} = 1;
584         my ($file, $line) = $pod_para->file_line;
585         $self->poderror({ -line => $line, -file => $file,
586                           -msg => $need_encoding
587                         });
588         return;
589     }
590
591     sub verbatim {
592         my ($self, $paragraph, $line_num, $pod_para) = @_;
593         $self->check_encoding($paragraph, $line_num, $pod_para);
594
595         $self->SUPER::verbatim($paragraph, $line_num, $pod_para);
596
597         my $addr = Scalar::Util::refaddr $self;
598
599         # Pick up the name, since the parent class doesn't in verbatim
600         # NAMEs; so treat as non-verbatim.  The parent class only allows one
601         # paragraph in a NAME section, so if there is an extra blank line, it
602         # will trigger a message, but such a blank line is harmless, so skip
603         # in that case.
604         if ($in_NAME{$addr} && $paragraph =~ /\S/) {
605             $self->textblock($paragraph, $line_num, $pod_para);
606         }
607
608         my @lines = split /^/, $paragraph;
609         for my $i (0 .. @lines - 1) {
610             if ( my $encoding = $seen_encoding_cmd{$addr} ) {
611               require Encode;
612               $lines[$i] = Encode::decode($encoding, $lines[$i]);
613             }
614             $lines[$i] =~ s/\s+$//;
615             my $indent = $self->get_current_indent;
616             my $exceeds = length(Text::Tabs::expand($lines[$i]))
617                           + $indent - $MAX_LINE_LENGTH;
618             next unless $exceeds > 0;
619             my ($file, $line) = $pod_para->file_line;
620             $self->poderror({ -line => $line + $i, -file => $file,
621                 -msg => $line_length,
622                 parameter => "+$exceeds (including " . ($indent - $INDENT) . " from =over's)",
623             });
624         }
625     }
626
627     sub textblock {
628         my ($self, $paragraph, $line_num, $pod_para) = @_;
629         $self->check_encoding($paragraph, $line_num, $pod_para);
630
631         $self->SUPER::textblock($paragraph, $line_num, $pod_para);
632
633         my ($file, $line) = $pod_para->file_line;
634         my $addr = Scalar::Util::refaddr $self;
635         if ($in_NAME{$addr}) {
636             if (! $self->name) {
637                 my $text = $self->interpolate($paragraph, $line_num);
638                 if ($text =~ /^\s*(\S+?)\s*$/) {
639                     $self->name($1);
640                     $self->poderror({ -line => $line, -file => $file,
641                         -msg => $missing_name_description,
642                         parameter => $1});
643                 }
644             }
645         }
646         $paragraph = join " ", split /^/, $paragraph;
647
648         # Matches something that looks like a file name, but is enclosed in
649         # C<...>
650         my $C_path_re = qr{ \b ( C<
651                                 # exclude regexes and 'OS/2'
652                                 (?! (?: (?: s | qr | m) / ) | OS/2 > )
653                                 [-\w]+ (?: / [-\w]+ )+ (?: \. \w+ )? > )
654                           }x;
655
656         # If looks like a reference to other documentation by containing the
657         # word 'See' and then a likely pod directive, warn.
658         while ($paragraph =~ m{
659                                 ( (?: \w+ \s+ )* )  # The phrase before, if any
660                                 \b [Ss]ee \s+
661                                 ( ( [^L] )
662                                   <
663                                   ( [^<]*? )  # The not < excludes nested C<L<...
664                                   >
665                                 )
666                                 ( \s+ (?: under | in ) \s+ L< )?
667                             }xg) {
668             my $prefix = $1 // "";
669             my $construct = $2;     # The whole thing, like C<...>
670             my $type = $3;
671             my $interior = $4;
672             my $trailing = $5;      # After the whole thing ending in "L<"
673
674             # If the full phrase is something like, "you might see C<", or
675             # similar, it really isn't a reference to a link.  The ones I saw
676             # all had the word "you" in them; and the "you" wasn't the
677             # beginning of a sentence.
678             if ($prefix !~ / \b you \b /x) {
679
680                 # Now, find what the module or man page name within the
681                 # construct would be if it actually has L<> syntax.  If it
682                 # doesn't have that syntax, will set the module to the entire
683                 # interior.
684                 $interior =~ m/ ^
685                                 (?: [^|]+ \| )? # Optional arbitrary text ending
686                                                 # in "|"
687                                 ( .+? )         # module, etc. name
688                                 (?: \/ .+ )?    # target within module
689                                 $
690                             /xs;
691                 my $module = $1;
692                 if (! defined $trailing # not referring to something in another
693                                         # section
694                     && $interior !~ /$non_pods/
695
696                     # C<> that look like files have their own message below, so
697                     # exclude them
698                     && $construct !~ /$C_path_re/g
699
700                     # There can't be spaces (I think) in module names or man
701                     # pages
702                     && $module !~ / \s /x
703
704                     # F<> that end in eg \.pl are almost certainly ok, as are
705                     # those that look like a path with multiple "/" chars
706                     && ($type ne "F"
707                         || (! -e $interior
708                             && $interior !~ /\.\w+$/
709                             && $interior !~ /\/.+\//)
710                     )
711                 ) {
712                     $self->poderror({ -line => $line, -file => $file,
713                         -msg => $see_not_linked,
714                         parameter => $construct
715                     });
716                 }
717             }
718         }
719         while ($paragraph =~ m/$C_path_re/g) {
720             my $construct = $1;
721             $self->poderror({ -line => $line, -file => $file,
722                 -msg => $C_with_slash,
723                 parameter => $construct
724             });
725         }
726         return;
727     }
728
729     sub command {
730         my ($self, $cmd, $paragraph, $line_num, $pod_para) = @_;
731         my $addr = Scalar::Util::refaddr $self;
732         if ($cmd eq "pod") {
733             $seen_pod_cmd{$addr}++;
734         }
735         elsif ($cmd eq "encoding") {
736             my ($file, $line) = $pod_para->file_line;
737             $seen_encoding_cmd{$addr} = $paragraph; # for later decoding
738             if ($command_count{$addr} != 1 && $seen_pod_cmd{$addr}) {
739                 $self->poderror({ -line => $line, -file => $file,
740                                   -msg => $encoding_first
741                                 });
742             }
743         }
744         $self->check_encoding($paragraph, $line_num, $pod_para);
745
746         # Pod::Check treats all =items as linkable, but the bullet and
747         # numbered lists really aren't.  So keep our own list.  This has to be
748         # processed before SUPER is called so that the list is started before
749         # the rest of it gets parsed.
750         if ($cmd eq 'item') { # Not linkable if item begins with * or a digit
751             $linkable_item{$addr} = ($paragraph !~ / ^ \s*
752                                                    (?: [*]
753                                                    | \d+ \.? (?: \$ | \s+ )
754                                                    )/x)
755                                   ? 1
756                                   : 0;
757
758         }
759         $self->SUPER::command($cmd, $paragraph, $line_num, $pod_para);
760
761         $command_count{$addr}++;
762
763         $in_NAME{$addr} = 0;    # Will change to 1 below if necessary
764         $in_begin{$addr} = 0;   # ibid
765         if ($cmd eq 'over') {
766             my $text = $self->interpolate($paragraph, $line_num);
767             my $indent = 4; # default
768             $indent = $1 if $text && $text =~ /^\s*(\d+)\s*$/;
769             push @{$indents{$addr}}, $indent;
770             $current_indent{$addr} += $indent;
771         }
772         elsif ($cmd eq 'back') {
773             if (@{$indents{$addr}}) {
774                 $current_indent{$addr} -= pop @{$indents{$addr}};
775             }
776             else {
777                  # =back without corresponding =over, but should have
778                  # warned already
779                 $current_indent{$addr} = 0;
780             }
781         }
782         elsif ($cmd =~ /^head/) {
783             if (! $in_begin{$addr}) {
784
785                 # If a particular formatter, then this command doesn't really
786                 # apply
787                 $current_indent{$addr} = 0;
788                 undef @{$indents{$addr}};
789             }
790
791             my $text = $self->interpolate($paragraph, $line_num);
792             $in_NAME{$addr} = 1 if $cmd eq 'head1'
793                                    && $text && $text =~ /^NAME\b/;
794         }
795         elsif ($cmd eq 'begin') {
796             $in_begin{$addr} = 1;
797         }
798
799         return;
800     }
801
802     sub hyperlink {
803         my $self = shift;
804
805         # If the hyperlink is to an interior node of another page, save it
806         # so that we can see if we need to parse normally skipped files.
807         $has_referred_to_node{$_[0][1]{'-page'}} = 1
808                             if $_[0] && $_[0][1]{'-page'} && $_[0][1]{'-node'};
809         return $self->SUPER::hyperlink($_[0]);
810     }
811
812     sub node {
813         my $self = shift;
814         my $text = $_[0];
815         if($text) {
816             $text =~ s/\s+$//s; # strip trailing whitespace
817             $text =~ s/\s+/ /gs; # collapse whitespace
818             my $addr = Scalar::Util::refaddr $self;
819             push(@{$linkable_nodes{$addr}}, $text) if
820                                     ! $current_indent{$addr}
821                                     || $linkable_item{$addr};
822         }
823         return $self->SUPER::node($_[0]);
824     }
825
826     sub get_current_indent {
827         return $INDENT + $current_indent{Scalar::Util::refaddr $_[0]};
828     }
829
830     sub get_filename {
831         return $filename{Scalar::Util::refaddr $_[0]};
832     }
833
834     sub linkable_nodes {
835         my $linkables = $linkable_nodes{Scalar::Util::refaddr $_[0]};
836         return undef unless $linkables;
837         return @$linkables;
838     }
839
840     sub get_skip {
841         return $skip{Scalar::Util::refaddr $_[0]} // 0;
842     }
843
844     sub set_skip {
845         my $self = shift;
846         $skip{Scalar::Util::refaddr $self} = shift;
847
848         # If skipping, no need to keep the problems for it
849         delete $problems{$self->get_filename};
850         return;
851     }
852 }
853
854 package Tie_Array_to_FH {  # So printing actually goes to an array
855
856     my %array;
857
858     sub TIEHANDLE {
859         my $class = shift;
860         my $array_ref = shift;
861
862         my $self = bless \do{ my $anonymous_scalar }, $class;
863         $array{Scalar::Util::refaddr $self} = $array_ref;
864
865         return $self;
866     }
867
868     sub PRINT {
869         my $self = shift;
870         push @{$array{Scalar::Util::refaddr $self}}, @_;
871         return 1;
872     }
873 }
874
875
876 my %filename_to_checker; # Map a filename to it's pod checker object
877 my %id_to_checker;      # Map a checksum to it's pod checker object
878 my %nodes;              # key is filename, values are nodes in that file.
879 my %nodes_first_word;   # same, but value is first word of each node
880 my %valid_modules;      # List of modules known to exist outside us.
881 my %digests;            # checksums of files, whose names are the keys
882 my %filename_to_pod;    # Map a filename to its pod NAME
883 my %files_with_unknown_issues;
884 my %files_with_fixes;
885
886 my $data_fh;
887 open $data_fh, '<:bytes', $known_issues or die "Can't open $known_issues";
888
889 my %counts; # For --counts param, count of each issue type
890 my %suppressed_files;   # Files with at least one issue type to suppress
891
892
893 if ($add_link) {
894     $copy_fh = open_new($known_issues);
895     my @existing_db = <$data_fh>;
896     my_safer_print($copy_fh, @existing_db);
897
898     foreach my $module (@files) {
899         die "\"$module\" does not look like a module or man page"
900             # Must look like (A or A::B or A::B::C ..., or foo(3C)
901             if $module !~ /^ (?: \w+ (?: :: \w+ )* | \w+ \( \d \w* \) ) $/x;
902         $module .= "\n";
903         next if grep { $module eq $_ } @existing_db;
904         my_safer_print($copy_fh, $module);
905     }
906     close_and_rename($copy_fh);
907     exit;
908 }
909
910 while (<$data_fh>) {    # Read the data base
911     chomp;
912     next if /^\s*(?:#|$)/;  # Skip comment and empty lines
913     if (/\t/) {
914         next if $show_all;
915
916         # Keep track of counts of each issue type for each file
917         my ($filename, $message, $count) = split /\t/;
918         $known_problems{$filename}{$message} = $count;
919
920         if ($show_counts) {
921             if ($count < 0) {   # -1 means to suppress this issue type
922                 $suppressed_files{$filename} = $filename;
923             }
924             else {
925                 $counts{$message} += $count;
926             }
927         }
928     }
929     else {  # Lines without a tab are modules known to be valid
930         $valid_modules{$_} = 1
931     }
932 }
933 close $data_fh;
934
935 if ($show_counts) {
936     my $total = 0;
937     foreach my $message (sort keys %counts) {
938         $total += $counts{$message};
939         note(Text::Tabs::expand("$counts{$message}\t$message"));
940     }
941     note("-----\n" . Text::Tabs::expand("$total\tknown potential issues"));
942     if (%suppressed_files) {
943         note("\nFiles that have all messages of at least one type suppressed:");
944         note(join ",", keys %suppressed_files);
945     }
946     exit 0;
947 }
948
949
950 my %excluded_files = (
951                         "lib/unicore/mktables" => 1,
952                         "Porting/perldelta_template.pod" => 1,
953                         "autodoc.pl" => 1,
954                         "configpm" => 1,
955                         "miniperl" => 1,
956                         "perl" => 1,
957                     );
958
959 # Convert to more generic form.
960 foreach my $file (keys %excluded_files) {
961     delete $excluded_files{$file};
962     $excluded_files{canonicalize($file)} = 1;
963 }
964
965 # re to match files that are to be parsed only if there is an internal link
966 # to them.  It does not include cpan, as whether those are parsed depends
967 # on a switch.  Currently, only perltoc and the stable perldelta.pod's
968 # are included.  The latter all have characters between 'perl' and
969 # 'delta'.  (Actually the currently developed one matches as well, but
970 # is a duplicate of perldelta.pod, so can be skipped, so fine for it to
971 # match this.
972 my $only_for_interior_links_re = qr/ \b perl \d+ delta \. pod \b
973                                      | ^ pod\/perltoc.pod $
974                                    /x;
975
976 { # Closure
977     my $first_time = 1;
978
979     sub output_thanks ($$$$) {  # Called when an issue has been fixed
980         my $filename = shift;
981         my $original_count = shift;
982         my $current_count = shift;
983         my $message = shift;
984
985         $files_with_fixes{$filename} = 1;
986         my $return;
987         my $fixed_count = $original_count - $current_count;
988         my $a_problem = ($fixed_count == 1) ? "a problem" : "multiple problems";
989         my $another_problem = ($fixed_count == 1) ? "another problem" : "another set of problems";
990         my $diff;
991         if ($message) {
992             $diff = <<EOF;
993 There were $original_count occurrences (now $current_count) in this pod of type
994 "$message",
995 EOF
996         } else {
997             $diff = <<EOF;
998 There are no longer any problems found in this pod!
999 EOF
1000         }
1001
1002         if ($first_time) {
1003             $first_time = 0;
1004             $return = <<EOF;
1005 Thanks for fixing $a_problem!
1006 $diff
1007 Now you must teach $0 that this was fixed.
1008 EOF
1009         }
1010         else {
1011             $return = <<EOF
1012 Thanks for fixing $another_problem.
1013 $diff
1014 EOF
1015         }
1016
1017         return $return;
1018     }
1019 }
1020
1021 sub my_safer_print {    # print, with error checking for outputting to db
1022     my ($fh, @lines) = @_;
1023
1024     if (! print $fh @lines) {
1025         my $save_error = $!;
1026         close($fh);
1027         die "Write failure: $save_error";
1028     }
1029 }
1030
1031 sub extract_pod {   # Extracts just the pod from a file
1032     my $filename = shift;
1033
1034     my @pod;
1035
1036     # Arrange for the output of Pod::Parser to be collected in an array we can
1037     # look at instead of being printed
1038     tie *ALREADY_FH, 'Tie_Array_to_FH', \@pod;
1039     open my $in_fh, '<:bytes', $filename
1040
1041         # The file should already have been opened once to get here, so if
1042         # fails, just die.  It's possible that a transitory file containing a
1043         # pod would get here, but not bothering to add code for that very
1044         # unlikely event.
1045         or die "Can't open '$filename': $!\n";
1046
1047     my $parser = Pod::Parser->new();
1048     $parser->parse_from_filehandle($in_fh, *ALREADY_FH);
1049     close $in_fh;
1050
1051     return join "", @pod
1052 }
1053
1054 my $digest = Digest->new($digest_type);
1055
1056 sub is_pod_file {
1057     # If $_ is a pod file, add it to the lists and do other prep work.
1058
1059     if (-d $_) {
1060         # Don't look at files in directories that are for tests, nor those
1061         # beginning with a dot
1062         if ($_ eq 't' || $_ =~ /^\../) {
1063             $File::Find::prune = 1;
1064         }
1065         return;
1066     }
1067
1068     return if $_ =~ /^\./;           # No hidden Unix files
1069     return if $_ =~ $non_pods;
1070
1071     my $filename = $File::Find::name;
1072
1073     # Assumes that the path separator is exactly one character.
1074     $filename =~ s/^\..//;
1075
1076     return if $excluded_files{canonicalize($filename)};
1077
1078     my $contents = do {
1079         local $/;
1080         my $candidate;
1081         if (! open $candidate, '<:bytes', $_) {
1082
1083             # If a transitory file was found earlier, the open could fail
1084             # legitimately and we just skip the file; also skip it if it is a
1085             # broken symbolic link, as it is probably just a build problem;
1086             # certainly not a file that we would want to check the pod of.
1087             # Otherwise fail it here and no reason to process it further.
1088             # (But the test count will be off too)
1089             ok(0, "Can't open '$filename': $!")
1090                                             if -e $filename && ! -l $filename;
1091             return;
1092         }
1093         <$candidate>;
1094     };
1095
1096     # If the file is a .pm or .pod, having any initial '=' on a line is
1097     # grounds for testing it.  Otherwise, require a head1 NAME line to view it
1098     # as a potential pod
1099     if ($filename =~ /\.(?:pm|pod)/) {
1100         return unless $contents =~ /^=/m;
1101     } else {
1102         return unless $contents =~ /^=head1 +NAME/m;
1103     }
1104
1105     # Here, we know that the file is a pod.  Add it to the list of files
1106     # to check and create a checker object for it.
1107
1108     push @files, $filename;
1109     my $checker = My::Pod::Checker->new($filename);
1110     $filename_to_checker{$filename} = $checker;
1111
1112     # In order to detect duplicate pods and only analyze them once, we
1113     # compute checksums for the file, so don't have to do an exact
1114     # compare.  Note that if the pod is just part of the file, the
1115     # checksums can differ for the same pod.  That special case is handled
1116     # later, since if the checksums of the whole file are the same, that
1117     # case won't even come up.  We don't need the checksums for files that
1118     # we parse only if there is a link to its interior, but we do need its
1119     # NAME, which is also retrieved in the code below.
1120
1121     if ($filename =~ / (?: ^(cpan|lib|ext|dist)\/ )
1122                         | $only_for_interior_links_re
1123                     /x) {
1124         $digest->add($contents);
1125         $digests{$filename} = $digest->digest;
1126
1127         # lib files aren't analyzed if they are duplicates of files copied
1128         # there from some other directory.  But to determine this, we need
1129         # to know their NAMEs.  We might as well find the NAME now while
1130         # the file is open.  Similarly, cpan files aren't analyzed unless
1131         # we're analyzing all of them, or this particular file is linked
1132         # to by a file we are analyzing, and thus we will want to verify
1133         # that the target exists in it.  We need to know at least the NAME
1134         # to see if it's worth analyzing, or so we can determine if a lib
1135         # file is a copy of a cpan one.
1136         if ($filename =~ m{ (?: ^ (?: cpan | lib ) / )
1137                             | $only_for_interior_links_re
1138                             }x) {
1139             if ($contents =~ /^=head1 +NAME.*/mg) {
1140                 # The NAME is the first non-spaces on the line up to a
1141                 # comma, dash or end of line.  Otherwise, it's invalid and
1142                 # this pod doesn't have a legal name that we're smart
1143                 # enough to find currently.  But the  parser will later
1144                 # find it if it thinks there is a legal name, and set the
1145                 # name
1146                 if ($contents =~ /\G    # continue from the line after =head1
1147                                   \s*   # ignore any empty lines
1148                                   ^ \s* ( \S+?) \s* (?: [,-] | $ )/mx) {
1149                     my $name = $1;
1150                     $checker->name($name);
1151                     $id_to_checker{$name} = $checker
1152                         if $filename =~ m{^cpan/};
1153                 }
1154             }
1155             elsif ($filename =~ m{^cpan/}) {
1156                 $id_to_checker{$digests{$filename}} = $checker;
1157             }
1158         }
1159     }
1160
1161     return;
1162 } # End of is_pod_file()
1163
1164 # Start of real code that isn't processing the command line (except the
1165 # db is read in above, as is processing of the --add_link option).
1166 # Here, @files contains list of files on the command line.  If have any of
1167 # these, unconditionally test them, and show all the errors, even the known
1168 # ones, and, since not testing other pods, don't do cross-pod link tests.
1169 # (Could add extra code to do cross-pod tests for the ones in the list.)
1170
1171 if ($has_input_files) {
1172     undef %known_problems;
1173     $do_upstream_cpan = 1;  # In case one of the inputs is from cpan
1174
1175 }
1176 else { # No input files -- go find all the possibilities.
1177     if ($regen) {
1178         $copy_fh = open_new($known_issues);
1179         note("Regenerating $known_issues, please be patient...");
1180         print $copy_fh <<END;
1181 # This file is the data file for $0.
1182 # There are three types of lines.
1183 # Comment lines are white-space only or begin with a '#', like this one.  Any
1184 #   changes you make to the comment lines will be lost when the file is
1185 #   regen'd.
1186 # Lines without tab characters are simply NAMES of pods that the program knows
1187 #   will have links to them and the program does not check if those links are
1188 #   valid.
1189 # All other lines should have three fields, each separated by a tab.  The
1190 #   first field is the name of a pod; the second field is an error message
1191 #   generated by this program; and the third field is a count of how many
1192 #   known instances of that message there are in the pod.  -1 means that the
1193 #   program can expect any number of this type of message.
1194 END
1195     }
1196
1197     # Move to the directory above us, but have to adjust @INC to account for
1198     # that.
1199     s{^\.\./lib$}{lib} for @INC;
1200     chdir File::Spec->updir;
1201
1202     # And look in this directory and all its subdirectories
1203     find( \&is_pod_file, '.');
1204
1205     # Add ourselves to the test
1206     push @files, "t/porting/podcheck.t";
1207 }
1208
1209 # Now we know how many tests there will be.
1210 plan (tests => scalar @files) if ! $regen;
1211
1212
1213  # Sort file names so we get consistent results, and to put cpan last,
1214  # preceeded by the ones that we don't generally parse.  This is because both
1215  # these classes are generally parsed only if there is a link to the interior
1216  # of them, and we have to parse all others first to guarantee that they don't
1217  # have such a link. 'lib' files come just before these, as some of these are
1218  # duplicates of others.  We already have figured this out when gathering the
1219  # data as a special case for all such files, but this, while unnecessary,
1220  # puts the derived file last in the output.  'readme' files come before those,
1221  # as those also could be duplicates of others, which are considered the
1222  # primary ones.  These currently aren't figured out when gathering data, so
1223  # are done here.
1224  @files = sort { if ($a =~ /^cpan/) {
1225                     return 1 if $b !~ /^cpan/;
1226                     return $a cmp $b;
1227                 }
1228                 elsif ($b =~ /^cpan/) {
1229                     return -1;
1230                 }
1231                 elsif ($a =~ /$only_for_interior_links_re/) {
1232                     return 1 if $b !~ /$only_for_interior_links_re/;
1233                     return $a cmp $b;
1234                 }
1235                 elsif ($b =~ /$only_for_interior_links_re/) {
1236                     return -1;
1237                 }
1238                 elsif ($a =~ /^lib/) {
1239                     return 1 if $b !~ /^lib/;
1240                     return $a cmp $b;
1241                 }
1242                 elsif ($b =~ /^lib/) {
1243                     return -1;
1244                 } elsif ($a =~ /\breadme\b/i) {
1245                     return 1 if $b !~ /\breadme\b/i;
1246                     return $a cmp $b;
1247                 }
1248                 elsif ($b =~ /\breadme\b/i) {
1249                     return -1;
1250                 }
1251                 else {
1252                     return lc $a cmp lc $b;
1253                 }
1254             }
1255             @files;
1256
1257 # Now go through all the files and parse them
1258 foreach my $filename (@files) {
1259     my $parsed = 0;
1260     note("parsing $filename") if DEBUG;
1261
1262     # We may have already figured out some things in the process of generating
1263     # the file list.  If so, have a $checker object already.  But if not,
1264     # generate one now.
1265     my $checker = $filename_to_checker{$filename};
1266     if (! $checker) {
1267         $checker = My::Pod::Checker->new($filename);
1268         $filename_to_checker{$filename} = $checker;
1269     }
1270
1271     # We have set the name in the checker object if there is a possibility
1272     # that no further parsing is necessary, but otherwise do the parsing now.
1273     if (! $checker->name) {
1274         $parsed = 1;
1275         $checker->parse_from_file($filename, undef);
1276     }
1277
1278     if ($checker->num_errors() < 0) {   # Returns negative if not a pod
1279         $checker->set_skip("$filename is not a pod");
1280     }
1281     else {
1282
1283         # Here, is a pod.  See if it is one that has already been tested,
1284         # or should be tested under another directory.  Use either its NAME
1285         # if it has one, or a checksum if not.
1286         my $name = $checker->name;
1287         my $id;
1288
1289         if ($name) {
1290             $id = $name;
1291         }
1292         else {
1293             my $digest = Digest->new($digest_type);
1294             $digest->add(extract_pod($filename));
1295             $id = $digest->digest;
1296         }
1297
1298         # If there is a match for this pod with something that we've already
1299         # processed, don't process it, and output why.
1300         my $prior_checker;
1301         if (defined ($prior_checker = $id_to_checker{$id})
1302             && $prior_checker != $checker)  # Could have defined the checker
1303                                             # earlier without pursuing it
1304         {
1305
1306             # If the pods are identical, then it's just a copy, and isn't an
1307             # error.  First use the checksums we have already computed to see
1308             # if the entire files are identical, which means that the pods are
1309             # identical too.
1310             my $prior_filename = $prior_checker->get_filename;
1311             my $same = (! $name
1312                         || ($digests{$prior_filename}
1313                             && $digests{$filename}
1314                             && $digests{$prior_filename} eq $digests{$filename}));
1315
1316             # If they differ, it could be that the files differ for some
1317             # reason, but the pods they contain are identical.  Extract the
1318             # pods and do the comparisons on just those.
1319             if (! $same && $name) {
1320                 $same = extract_pod($prior_filename) eq extract_pod($filename);
1321             }
1322
1323             if ($same) {
1324                 $checker->set_skip("The pod of $filename is a duplicate of "
1325                                     . "the pod for $prior_filename");
1326             } elsif ($prior_filename =~ /\breadme\b/i) {
1327                 $checker->set_skip("$prior_filename is a README apparently for $filename");
1328             } elsif ($filename =~ /\breadme\b/i) {
1329                 $checker->set_skip("$filename is a README apparently for $prior_filename");
1330             } elsif (! $do_upstream_cpan && $filename =~ /^cpan/) {
1331                 $checker->set_skip("CPAN is upstream for $filename");
1332             } else { # Here have two pods with identical names that differ
1333                 $prior_checker->poderror(
1334                         { -msg => $duplicate_name,
1335                             -line => "???",
1336                             parameter => "'$filename' also has NAME '$name'"
1337                         });
1338                 $checker->poderror(
1339                     { -msg => $duplicate_name,
1340                         -line => "???",
1341                         parameter => "'$prior_filename' also has NAME '$name'"
1342                     });
1343
1344                 # Changing the names helps later.
1345                 $prior_checker->name("$name version arbitrarily numbered 1");
1346                 $checker->name("$name version arbitrarily numbered 2");
1347             }
1348
1349             # In any event, don't process this pod that has the same name as
1350             # another.
1351             next;
1352         }
1353
1354         # A unique pod.
1355         $id_to_checker{$id} = $checker;
1356
1357         my $parsed_for_links = ", but parsed for its interior links";
1358         if ((! $do_upstream_cpan && $filename =~ /^cpan/)
1359              || $filename =~ $only_for_interior_links_re)
1360         {
1361             if ($filename =~ /^cpan/) {
1362                 $checker->set_skip("CPAN is upstream for $filename");
1363             }
1364             elsif ($filename =~ /perl\d+delta/) {
1365                 $checker->set_skip("$filename is a stable perldelta");
1366             }
1367             elsif ($filename =~ /perltoc/) {
1368                 $checker->set_skip("$filename dependent on component pods");
1369             }
1370             else {
1371                 croak("Unexpected file '$filename' encountered that has parsing for interior-linking only");
1372             }
1373
1374             if ($name && $has_referred_to_node{$name}) {
1375                 $checker->set_skip($checker->get_skip() . $parsed_for_links);
1376             }
1377         }
1378
1379         # Need a name in order to process it, because not meaningful
1380         # otherwise, and also can't test links to this without a name.
1381         if (!defined $name) {
1382             $checker->poderror( { -msg => $no_name,
1383                                   -line => '???'
1384                                 });
1385             next;
1386         }
1387
1388         # For skipped files, just get its NAME
1389         my $skip;
1390         if (($skip = $checker->get_skip()) && $skip !~ /$parsed_for_links/)
1391         {
1392             $checker->node($name) if $name;
1393         }
1394         else {
1395             $checker->parse_from_file($filename, undef) if ! $parsed;
1396         }
1397
1398         # Go through everything in the file that could be an anchor that
1399         # could be a link target.  Count how many there are of the same name.
1400         foreach my $node ($checker->linkable_nodes) {
1401             next if ! $node;        # Can be empty is like '=item *'
1402             if (exists $nodes{$name}{$node}) {
1403                 $nodes{$name}{$node}++;
1404             }
1405             else {
1406                 $nodes{$name}{$node} = 1;
1407             }
1408
1409             # Experiments have shown that cpan search can figure out the
1410             # target of a link even if the exact wording is incorrect, as long
1411             # as the first word is.  This happens frequently in perlfunc.pod,
1412             # where the link will be just to the function, but the target
1413             # entry also includes parameters to the function.
1414             my $first_word = $node;
1415             if ($first_word =~ s/^(\S+)\s+\S.*/$1/) {
1416                 $nodes_first_word{$name}{$first_word} = $node;
1417             }
1418         }
1419         $filename_to_pod{$filename} = $name;
1420     }
1421 }
1422
1423 # Here, all files have been parsed, and all links and link targets are stored.
1424 # Now go through the files again and see which don't have matches.
1425 if (! $has_input_files) {
1426     foreach my $filename (@files) {
1427         next if $filename_to_checker{$filename}->get_skip;
1428         my $checker = $filename_to_checker{$filename};
1429         foreach my $link ($checker->hyperlink) {
1430             my $linked_to_page = $link->[1]->page;
1431             next unless $linked_to_page;   # intra-file checks are handled by std
1432                                            # Pod::Checker
1433
1434             # Initialize the potential message.
1435             my %problem = ( -msg => $broken_link,
1436                             -line => $link->[0],
1437                             parameter => "to \"$linked_to_page\"",
1438                         );
1439
1440             # See if we have found the linked-to_file in our parse
1441             if (exists $nodes{$linked_to_page}) {
1442                 my $node = $link->[1]->node;
1443
1444                 # If link is only to the page-level, already have it
1445                 next if ! $node;
1446
1447                 # Transform pod language to what we are expecting
1448                 $node =~ s,E<sol>,/,g;
1449                 $node =~ s/E<verbar>/|/g;
1450
1451                 # If link is to a node that exists in the file, is ok
1452                 if ($nodes{$linked_to_page}{$node}) {
1453
1454                     # But if the page has multiple targets with the same name,
1455                     # it's ambiguous which one this should be to.
1456                     if ($nodes{$linked_to_page}{$node} > 1) {
1457                         $problem{-msg} = $multiple_targets;
1458                         $problem{parameter} = "in $linked_to_page that $node could be pointing to";
1459                         $checker->poderror(\%problem);
1460                     }
1461                 } elsif (! $nodes_first_word{$linked_to_page}{$node}) {
1462
1463                     # Here the link target was not found, either exactly or to
1464                     # the first word.  Is an error.
1465                     $problem{parameter} =~ s,"$,/$node",;
1466                     $checker->poderror(\%problem);
1467                 }
1468
1469             } # Linked-to-file not in parse; maybe is in exception list
1470             elsif (! exists $valid_modules{$link->[1]->page}) {
1471
1472                 # Here, is a link to a target that we can't find.  Check if
1473                 # there is an internal link on the page with the target name.
1474                 # If so, it could be that they just forgot the initial '/'
1475                 # But perldelta is handled specially: only do this if the
1476                 # broken link isn't one of the known bad ones (that are
1477                 # placemarkers and should be removed for the final)
1478                 my $NAME = $filename_to_pod{$filename};
1479                 if (! defined $NAME) {
1480                     $checker->poderror(\%problem);
1481                 }
1482                 elsif ($NAME ne "perldelta"
1483                     || ! grep { $linked_to_page eq $_ } @perldelta_ignore_links)
1484                 {
1485                     if ($nodes{$NAME}{$linked_to_page}) {
1486                         $problem{-msg} =  $broken_internal_link;
1487                     }
1488                     $checker->poderror(\%problem);
1489                 }
1490             }
1491         }
1492     }
1493 }
1494
1495 # If regenerating the data file, start with the modules for which we don't
1496 # check targets
1497 if ($regen) {
1498     foreach (sort { lc $a cmp lc $b } keys %valid_modules) {
1499         my_safer_print($copy_fh, $_, "\n");
1500     }
1501 }
1502
1503 # Now ready to output the messages.
1504 foreach my $filename (@files) {
1505     my $test_name = "POD of $filename";
1506     my $canonical = canonicalize($filename);
1507     SKIP: {
1508         my $skip = $filename_to_checker{$filename}->get_skip // "";
1509
1510         if ($regen) {
1511             foreach my $message ( sort keys %{$problems{$filename}}) {
1512                 my $count;
1513
1514                 # Preserve a negative setting.
1515                 if ($known_problems{$canonical}{$message}
1516                     && $known_problems{$canonical}{$message} < 0)
1517                 {
1518                     $count = $known_problems{$canonical}{$message};
1519                 }
1520                 else {
1521                     $count = @{$problems{$filename}{$message}};
1522                 }
1523                 my_safer_print($copy_fh, canonicalize($filename) . "\t$message\t$count\n");
1524             }
1525             next;
1526         }
1527
1528         skip($skip, 1) if $skip;
1529         my @diagnostics;
1530         my $indent = '  ';
1531
1532         my $total_known = 0;
1533         foreach my $message ( sort keys %{$problems{$filename}}) {
1534             $known_problems{$canonical}{$message} = 0
1535                                     if ! $known_problems{$canonical}{$message};
1536             my $diagnostic = "";
1537             my $problem_count = scalar @{$problems{$filename}{$message}};
1538             $total_known += $problem_count;
1539             next if $known_problems{$canonical}{$message} < 0;
1540             if ($problem_count > $known_problems{$canonical}{$message}) {
1541
1542                 # Here we are about to output all the messages for this type,
1543                 # subtract back this number we previously added in.
1544                 $total_known -= $problem_count;
1545
1546                 $diagnostic .= $indent . $message;
1547                 if ($problem_count > 2) {
1548                     $diagnostic .= "  ($problem_count occurrences)";
1549                 }
1550                 foreach my $problem (@{$problems{$filename}{$message}}) {
1551                     $diagnostic .= " " if $problem_count == 1;
1552                     $diagnostic .= "\n$indent$indent";
1553                     $diagnostic .= "$problem->{parameter}" if $problem->{parameter};
1554                     $diagnostic .= " near line $problem->{-line}";
1555                     $diagnostic .= " $problem->{comment}" if $problem->{comment};
1556                 }
1557                 $diagnostic .= "\n";
1558                 $files_with_unknown_issues{$filename} = 1;
1559             } elsif ($problem_count < $known_problems{$canonical}{$message}) {
1560                $diagnostic = output_thanks($filename, $known_problems{$canonical}{$message}, $problem_count, $message);
1561             }
1562             push @diagnostics, $diagnostic if $diagnostic;
1563         }
1564
1565         # The above loop has output messages where there are current potential
1566         # issues.  But it misses where there were some that have been entirely
1567         # fixed.  For those, we need to look through the old issues
1568         foreach my $message ( sort keys %{$known_problems{$canonical}}) {
1569             next if $problems{$filename}{$message};
1570             next if ! $known_problems{$canonical}{$message};
1571             next if $known_problems{$canonical}{$message} < 0; # Preserve negs
1572             my $diagnostic = output_thanks($filename, $known_problems{$canonical}{$message}, 0, $message);
1573             push @diagnostics, $diagnostic if $diagnostic;
1574         }
1575
1576         my $output = "POD of $filename";
1577         $output .= ", excluding $total_known not shown known potential problems"
1578                                                                 if $total_known;
1579         ok(@diagnostics == 0, $output);
1580         if (@diagnostics) {
1581             note(join "", @diagnostics,
1582             "See end of this test output for your options on silencing this");
1583         }
1584     }
1585 }
1586
1587 my $how_to = <<EOF;
1588    run this test script by hand, using the following formula (on
1589    Un*x-like machines):
1590         cd t
1591         ./perl -I../lib porting/podcheck.t --regen
1592 EOF
1593
1594 if (%files_with_unknown_issues) {
1595     my $were_count_files = scalar keys %files_with_unknown_issues;
1596     $were_count_files = ($were_count_files == 1)
1597                         ? "was $were_count_files file"
1598                         : "were $were_count_files files";
1599     my $message = <<EOF;
1600
1601 HOW TO GET THIS .t TO PASS
1602
1603 There $were_count_files that had new potential problems identified.
1604 Some of them may be real, and some of them may be because this program
1605 isn't as smart as it likes to think it is.  You can teach this program
1606 to ignore the issues it has identified, and hence pass, by doing the
1607 following:
1608
1609 1) If a problem is about a link to an unknown module or man page that
1610    you know exists, re-run the command something like:
1611       ./perl -I../lib porting/podcheck.t --add_link MODULE man_page ...
1612    (MODULEs should look like Foo::Bar, and man_pages should look like
1613    bar(3c); don't do this for a module or man page that you aren't sure
1614    about; instead treat as another type of issue and follow the
1615    instructions below.)
1616
1617 2) For other issues, decide if each should be fixed now or not.  Fix the
1618    ones you decided to, and rerun this test to verify that the fixes
1619    worked.
1620
1621 3) If there remain potential problems that you don't plan to fix right
1622    now (or aren't really problems),
1623 $how_to
1624    That should cause all current potential problems to be accepted by
1625    the program, so that the next time it runs, they won't be flagged.
1626 EOF
1627     if (%files_with_fixes) {
1628         $message .= "   This step will also take care of the files that have fixes in them\n";
1629     }
1630
1631     $message .= <<EOF;
1632    For a few files, such as perltoc, certain issues will always be
1633    expected, and more of the same will be added over time.  For those,
1634    before you do the regen, you can edit
1635    $known_issues
1636    and find the entry for the module's file and specific error message,
1637    and change the count of known potential problems to -1.
1638 EOF
1639
1640     note($message);
1641 } elsif (%files_with_fixes) {
1642     note(<<EOF
1643 To teach this test script that the potential problems have been fixed,
1644 $how_to
1645 EOF
1646     );
1647 }
1648
1649 if ($regen) {
1650     chdir $original_dir || die "Can't change directories to $original_dir";
1651     close_and_rename($copy_fh);
1652 }