This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade Scalar-List-Utils from version 1.45 to 1.46
[perl5.git] / t / porting / podcheck.t
CommitLineData
a67b1afa 1#!/usr/bin/perl -w
f7b649f0 2
c429f8ed
KW
3package main;
4
faeaf995
FC
5BEGIN {
6 chdir 't';
9224f6d1 7 @INC = "../lib";
572618de 8 # Do not require test.pl, this file has its own framework.
faeaf995
FC
9}
10
a67b1afa 11use strict;
16384ac1
KW
12use warnings;
13use feature 'unicode_strings';
14
15use Carp;
de4da25d 16use Config;
16384ac1
KW
17use Digest;
18use File::Find;
19use File::Spec;
20use Scalar::Util;
21use Text::Tabs;
22
23BEGIN {
3a73a075
BF
24 if ( $Config{usecrosscompile} ) {
25 print "1..0 # Not all files are available during cross-compilation\n";
26 exit 0;
27 }
fa2edc1a 28 if ($^O eq 'dec_osf') {
572618de
JH
29 print "1..0 # $^O cannot handle this test\n";
30 exit(0);
fa2edc1a 31 }
16384ac1
KW
32 require '../regen/regen_lib.pl';
33}
34
35sub DEBUG { 0 };
36
37=pod
38
39=head1 NAME
40
41podcheck.t - Look for possible problems in the Perl pods
42
43=head1 SYNOPSIS
44
45 cd t
d9e2eb4b 46 ./perl -I../lib porting/podcheck.t [--show_all] [--cpan] [--deltas]
0cbb9de5
BG
47 [--counts] [--pedantic] [FILE ...]
48
477100f8
KW
49 ./perl -I../lib porting/podcheck.t --add_link MODULE ...
50
16384ac1
KW
51 ./perl -I../lib porting/podcheck.t --regen
52
53=head1 DESCRIPTION
54
55podcheck.t is an extension of Pod::Checker. It looks for pod errors and
56potential errors in the files given as arguments, or if none specified, in all
bc20e6b8
KW
57pods in the distribution workspace, except certain known special ones
58(specified below). It does additional checking beyond that done by
16384ac1
KW
59Pod::Checker, and keeps a database of known potential problems, and will
60fail a pod only if the number of such problems differs from that given in the
c429f8ed 61database.
16384ac1 62
0cbb9de5 63The additional checks it always makes are:
16384ac1
KW
64
65=over
66
67=item Cross-pod link checking
68
69Pod::Checker verifies that links to an internal target in a pod are not
70broken. podcheck.t extends that (when called without FILE arguments) to
71external links. It does this by gathering up all the possible targets in the
477100f8
KW
72workspace, and cross-checking them. It also checks that a non-broken link
73points to just one target. (The destination pod could have two targets with
74the same name.)
75
76The way that the C<LE<lt>E<gt>> pod command works (for links outside the pod)
77is to actually create a link to C<search.cpan.org> with an embedded query for
78the desired pod or man page. That means that links outside the distribution
79are valid. podcheck.t doesn't verify the validity of such links, but instead
0cbb9de5 80keeps a database of those known to be valid. This means that if a link to a
477100f8
KW
81target not on the list is created, the target needs to be added to the data
82base. This is accomplished via the L<--add_link|/--add_link MODULE ...>
83option to podcheck.t, described below.
16384ac1
KW
84
85=item An internal link that isn't so specified
86
87If a link is broken, but there is an existing internal target of the same
88name, it is likely that the internal target was meant, and the C<"/"> is
89missing from the C<LE<lt>E<gt>> pod command.
90
0cbb9de5
BG
91=item Missing or duplicate NAME or missing NAME short description
92
93A pod can't be linked to unless it has a unique name.
94And a NAME should have a dash and short description after it.
95
0cbb9de5
BG
96If the C<PERL_POD_PEDANTIC> environment variable is set or the C<--pedantic>
97command line argument is provided then a few more checks are made.
98The pedantic checks are:
99
100=over
101
b879da0f 102=item Verbatim paragraphs that wrap in an 80 (including 1 spare) column window
16384ac1
KW
103
104It's annoying to have lines wrap when displaying pod documentation in a
b879da0f
KW
105terminal window. This checks that all verbatim lines fit in a standard 80
106column window, even when using a pager that reserves a column for its own use.
107(Thus the check is for a net of 79 columns.)
5b1cac40 108For those lines that don't fit, it tells you how much needs to be cut in
b879da0f 109order to fit.
16384ac1
KW
110
111Often, the easiest thing to do to gain space for these is to lower the indent
112to just one space.
113
16384ac1
KW
114=item Items that perhaps should be links
115
116There are mentions of apparent files in the pods that perhaps should be links
117instead, using C<LE<lt>...E<gt>>
118
119=item Items that perhaps should be C<FE<lt>...E<gt>>
120
121What look like path names enclosed in C<CE<lt>...E<gt>> should perhaps have
122C<FE<lt>...E<gt>> mark-up instead.
123
124=back
125
126A number of issues raised by podcheck.t and by the base Pod::Checker are not
bc20e6b8
KW
127really problems, but merely potential problems, that is, false positives.
128After inspecting them and
16384ac1 129deciding that they aren't real problems, it is possible to shut up this program
204c2383
KW
130about them, unlike base Pod::Checker. For a valid link to an outside module
131or man page, call podcheck.t with the C<--add_link> option to add it to the
132the database of known links; for other causes, call podcheck.t with the C<--regen>
133option to regenerate the entire database. This tells it that all existing
16384ac1
KW
134issues are to not be mentioned again.
135
204c2383 136C<--regen> isn't fool-proof. The database merely keeps track of the number of these
16384ac1
KW
137potential problems of each type for each pod. If a new problem of a given
138type is introduced into the pod, podcheck.t will spit out all of them. You
139then have to figure out which is the new one, and should it be changed or not.
140But doing it this way insulates the database from having to keep track of line
141numbers of problems, which may change, or the exact wording of each problem
142which might also change without affecting whether it is a problem or not.
143
144Also, if the count of potential problems of a given type for a pod decreases,
145the database must be regenerated so that it knows the new number. The program
146gives instructions when this happens.
147
bc20e6b8
KW
148Some pods will have varying numbers of problems of a given type. This can
149be handled by manually editing the database file (see L</FILES>), and setting
150the number of those problems for that pod to a negative number. This will
151cause the corresponding error to always be suppressed no matter how many there
152actually are.
153
204c2383 154Another problem is that there is currently no check that modules listed as
0cbb9de5 155valid in the database
16384ac1
KW
156actually are. Thus any errors introduced there will remain there.
157
c429f8ed
KW
158=back
159
bc20e6b8
KW
160=head2 Specially handled pods
161
162=over
163
164=item perltoc
165
166This pod is generated by pasting bits from other pods. Errors in those bits
167will show up as errors here, as well as for those other pods. Therefore
168errors here are suppressed, and the pod is checked only to verify that nodes
204c2383 169within it actually exist that are externally linked to.
bc20e6b8
KW
170
171=item perldelta
172
173The current perldelta pod is initialized from a template that contains
174placeholder text. Some of this text is in the form of links that don't really
175exist. Any such links that are listed in C<@perldelta_ignore_links> will not
176generate messages. It is presumed that these links will be cleaned up when
177the perldelta is cleaned up for release since they should be marked with
178C<XXX>.
179
180=item Porting/perldelta_template.pod
181
182This is not a pod, but a template for C<perldelta>. Any errors introduced
183here will show up when C<perldelta> is created from it.
184
185=item cpan-upstream pods
186
187See the L</--cpan> option documentation
188
189=item old perldeltas
190
191See the L</--deltas> option documentation
192
193=back
194
16384ac1
KW
195=head1 OPTIONS
196
197=over
198
477100f8
KW
199=item --add_link MODULE ...
200
201Use this option to teach podcheck.t that the C<MODULE>s or man pages actually
202exist, and to silence any messages that links to them are broken.
203
204podcheck.t checks that links within the Perl core distribution are valid, but
205it doesn't check links to man pages or external modules. When it finds
0cbb9de5 206a broken link, it checks its database of external modules and man pages,
477100f8
KW
207and only if not found there does it raise a message. This option just adds
208the list of modules and man page references that follow it on the command line
0cbb9de5 209to that database.
477100f8
KW
210
211For example,
212
213 cd t
243a655d 214 ./perl -I../lib porting/podcheck.t --add_link Unicode::Casing
477100f8 215
0cbb9de5 216causes the external module "Unicode::Casing" to be added to the database, so
12b4b03c 217C<LE<lt>Unicode::CasingE<gt>> will be considered valid.
477100f8 218
16384ac1
KW
219=item --regen
220
0cbb9de5 221Regenerate the database used by podcheck.t to include all the existing
16384ac1 222potential problems. Future runs of the program will not then flag any of
0cbb9de5 223these. Setting this option also sets C<--pedantic>.
16384ac1
KW
224
225=item --cpan
226
227Normally, all pods in the cpan directory are skipped, except to make sure that
228any blead-upstream links to such pods are valid.
bc20e6b8 229This option will cause cpan upstream pods to be fully checked.
16384ac1 230
d9e2eb4b
KW
231=item --deltas
232
233Normally, all old perldelta pods are skipped, except to make sure that
234any links to such pods are valid. This is because they are considered
235stable, and perhaps trying to fix them will cause changes that will
bc20e6b8
KW
236misrepresent Perl's history. But, this option will cause them to be fully
237checked.
d9e2eb4b 238
16384ac1
KW
239=item --show_all
240
241Normally, if the number of potential problems of a given type found for a
242pod matches the expected value in the database, they will not be displayed.
243This option forces the database to be ignored during the run, so all potential
244problems are displayed and will fail their respective pod test. Specifying
245any particular FILES to operate on automatically selects this option.
246
247=item --counts
248
249Instead of testing, this just dumps the counts of the occurrences of the
0cbb9de5
BG
250various types of potential problems in the database.
251
252=item --pedantic
253
254There are three potential problems that are not checked for by default.
255This options enables them. The environment variable C<PERL_POD_PEDANTIC>
256can be set to 1 to enable this option also.
257This option is set when C<--regen> is used.
16384ac1
KW
258
259=back
260
261=head1 FILES
262
263The database is stored in F<t/porting/known_pod_issues.dat>
264
265=head1 SEE ALSO
266
267L<Pod::Checker>
268
269=cut
270
ae54198b
KW
271# VMS builds have a '.com' appended to utility and script names, and it adds a
272# trailing dot for any other file name that doesn't have a dot in it. The db
273# is stored without those things. This regex allows for these special file
274# names to be dealt with. It needs to be interpolated into a larger regex
275# that furnishes the closing boundary.
276my $vms_re = qr/ \. (?: com )? /x;
277
278# Some filenames in the MANIFEST match $vms_re, and so must not be handled the
279# same way that that the special vms ones are. This hash lists those.
280my %special_vms_files;
281
21b63541
KW
282# This is to get this to work across multiple file systems, including those
283# that are not case sensitive. The db is stored in lower case, Un*x style,
284# and all file name comparisons are done that way.
285sub canonicalize($) {
286 my $input = shift;
287 my ($volume, $directories, $file)
288 = File::Spec->splitpath(File::Spec->canonpath($input));
289 # Assumes $volume is constant for everything in this directory structure
290 $directories = "" if ! $directories;
291 $file = "" if ! $file;
ae54198b
KW
292 $file = lc join '/', File::Spec->splitdir($directories), $file;
293 $file =~ s! / /+ !/!gx; # Multiple slashes => single slash
294
295 # The db is stored without the special suffixes that are there in VMS, so
296 # strip them off to get the comparable name. But some files on all
297 # platforms have these suffixes, so this shouldn't happen for them, as any
298 # of their db entries will have the suffixes in them. The hash has been
299 # populated with these files.
300 if ($^O eq 'VMS'
301 && $file =~ / ( $vms_re ) $ /x
302 && ! exists $special_vms_files{$file})
303 {
304 $file =~ s/ $1 $ //x;
305 }
306 return $file;
21b63541
KW
307}
308
16384ac1
KW
309#####################################################
310# HOW IT WORKS (in general)
311#
312# If not called with specific files to check, the directory structure is
313# examined for files that have pods in them. Files that might not have to be
314# fully parsed (e.g. in cpan) are parsed enough at this time to find their
315# pod's NAME, and to get a checksum.
316#
317# Those kinds of files are sorted last, but otherwise the pods are parsed with
318# the package coded here, My::Pod::Checker, which is an extension to
319# Pod::Checker that adds some tests and suppresses others that aren't
320# appropriate. The latter module has no provision for capturing diagnostics,
321# so a package, Tie_Array_to_FH, is used to force them to be placed into an
322# array instead of printed.
323#
324# Parsing the files builds up a list of links. The files are gone through
325# again, doing cross-link checking and outputting all saved-up problems with
326# each pod.
327#
328# Sorting the files last that potentially don't need to be fully parsed allows
329# us to not parse them unless there is a link to an internal anchor in them
330# from something that we have already parsed. Keeping checksums allows us to
331# not parse copies of other pods.
332#
333#####################################################
334
335# 1 => Exclude low priority messages that aren't likely to be problems, and
336# has many false positives; higher numbers give more messages.
337my $Warnings_Level = 200;
338
b9b741c8
KW
339# perldelta during construction may have place holder links. N.B. This
340# variable is referred to by name in release_managers_guide.pod
2feebde0 341our @perldelta_ignore_links = ( "XXX", "perl5YYYdelta", "perldiag/message" );
1c01047d 342
16384ac1
KW
343# To see if two pods with the same NAME are actually copies of the same pod,
344# which is not an error, it uses a checksum to save work.
345my $digest_type = "SHA-1";
346
347my $original_dir = File::Spec->rel2abs(File::Spec->curdir);
348my $data_dir = File::Spec->catdir($original_dir, 'porting');
349my $known_issues = File::Spec->catfile($data_dir, 'known_pod_issues.dat');
c3e757a4 350my $MANIFEST = File::Spec->catfile(File::Spec->updir($original_dir), 'MANIFEST');
16384ac1
KW
351my $copy_fh;
352
113a3f61 353my $MAX_LINE_LENGTH = 79; # 79 columns
46b134f4 354my $INDENT = 7; # default nroff indent
16384ac1
KW
355
356# Our warning messages. Better not have [('"] in them, as those are used as
357# delimiters for variable parts of the messages by poderror.
16384ac1
KW
358my $broken_link = "Apparent broken link";
359my $broken_internal_link = "Apparent internal link is missing its forward slash";
16384ac1
KW
360my $multiple_targets = "There is more than one target";
361my $duplicate_name = "Pod NAME already used";
16384ac1
KW
362my $no_name = "There is no NAME";
363my $missing_name_description = "The NAME should have a dash and short description after it";
0cbb9de5
BG
364# the pedantic warnings messages
365my $line_length = "Verbatim line length including indents exceeds $MAX_LINE_LENGTH by";
366my $C_not_linked = "? Should you be using L<...> instead of";
367my $C_with_slash = "? Should you be using F<...> or maybe L<...> instead of";
16384ac1 368
7f8d58fb 369# objects, tests, etc can't be pods, so don't look for them. Also skip
a71e7b2c
KW
370# files output by the patch program. Could also ignore most of .gitignore
371# files, but not all, so don't.
de4da25d
CB
372
373my $obj_ext = $Config{'obj_ext'}; $obj_ext =~ tr/.//d; # dot will be added back
374my $lib_ext = $Config{'lib_ext'}; $lib_ext =~ tr/.//d;
375my $lib_so = $Config{'so'}; $lib_so =~ tr/.//d;
376my $dl_ext = $Config{'dlext'}; $dl_ext =~ tr/.//d;
377
6981f6e4
KW
378# Not really pods, but can look like them.
379my %excluded_files = (
c841a192 380 canonicalize("lib/unicore/mktables") => 1,
a9df55d5 381 canonicalize("Porting/make-rmg-checklist") => 1,
c841a192 382 canonicalize("Porting/perldelta_template.pod") => 1,
e233f0c5 383 canonicalize("regen/feature.pl") => 1,
261a5e5f 384 canonicalize("regen/warnings.pl") => 1,
c841a192
KW
385 canonicalize("autodoc.pl") => 1,
386 canonicalize("configpm") => 1,
387 canonicalize("miniperl") => 1,
388 canonicalize("perl") => 1,
00e518b3
FR
389 canonicalize('cpan/Pod-Perldoc/corpus/no-head.pod') => 1,
390 canonicalize('cpan/Pod-Perldoc/corpus/perlfunc.pod') => 1,
391 canonicalize('cpan/Pod-Perldoc/corpus/utf8.pod') => 1,
9c3bdfaf 392 canonicalize("lib/unicore/mktables") => 1,
6981f6e4
KW
393 );
394
df80274d
KW
395# This list should not include anything for which case sensitivity is
396# important, as it won't work on VMS, and won't show up until tested on VMS.
c3e757a4
KW
397# All or almost all such files should be listed in the MANIFEST, so that can
398# be examined for them, and each such file explicitly excluded, as is done for
399# .PL files in the loop just below this. For files not catchable this way,
400# is_pod_file() can be used to exclude these at a finer grained level.
a71e7b2c 401my $non_pods = qr/ (?: \.
df80274d 402 (?: [achot] | zip | gz | bz2 | jar | tar | tgz
a71e7b2c
KW
403 | orig | rej | patch # Patch program output
404 | sw[op] | \#.* # Editor droppings
a65bcb92 405 | old # buildtoc output
de4da25d
CB
406 | xs # pod should be in the .pm file
407 | al # autosplit files
408 | bs # bootstrap files
409 | (?i:sh) # shell scripts, hints, templates
410 | lst # assorted listing files
411 | bat # Windows,Netware,OS2 batch files
412 | cmd # Windows,Netware,OS2 command files
413 | lis # VMS compiler listings
414 | map # VMS linker maps
415 | opt # VMS linker options files
416 | mms # MM(K|S) description files
417 | ts # timestamp files generated during build
418 | $obj_ext # object files
419 | exe # $Config{'exe_ext'} might be empty string
420 | $lib_ext # object libraries
421 | $lib_so # shared libraries
422 | $dl_ext # dynamic libraries
51e1fe85 423 | gif # GIF images (example files from CGI.pm)
29a45343 424 | eg # examples from libnet
a71e7b2c
KW
425 )
426 $
e0a28d18 427 ) | ~$ | \ \(Autosaved\)\.txt$ # Other editor droppings
de4da25d
CB
428 | ^cxx\$demangler_db\.$ # VMS name mangler database
429 | ^typemap\.?$ # typemap files
430 | ^(?i:Makefile\.PL)$
a71e7b2c 431 /x;
16384ac1 432
e9baa58d 433# Matches something that looks like a file name, but is enclosed in C<...>
c429f8ed 434my $C_path_re = qr{ ^
e9baa58d
KW
435 # exclude various things that have slashes
436 # in them but aren't paths
437 (?!
997990fd 438 (?: (?: s | qr | m | tr | y ) / ) # regexes
c429f8ed
KW
439 | \d+/\d+ \b # probable fractions
440 | (?: [LF] < )+
441 | OS/2 \b
442 | Perl/Tk \b
443 | origin/blead \b
444 | origin/maint \b
445
446 )
447 /? # Optional initial slash
448 \w+ # First component of path, doesn't begin with
449 # a minus
450 (?: / [-\w]+ )+ # Subsequent path components
451 (?: \. \w+ )? # Optional trailing dot and suffix
452 >* # Any enclosed L< F< have matching closing >
453 $
e9baa58d
KW
454 }x;
455
c3e757a4
KW
456# '.PL' files should be excluded, as they aren't final pods, but often contain
457# material used in generating pods, and so can look like a pod. We can't use
458# the regexp above because case sensisitivity is important for these, as some
459# '.pl' files should be examined for pods. Instead look through the MANIFEST
460# for .PL files and get their full path names, so we can exclude each such
461# file explicitly. This works because other porting tests prohibit having two
462# files with the same names except for case.
463open my $manifest_fh, '<:bytes', $MANIFEST or die "Can't open $MANIFEST";
464while (<$manifest_fh>) {
ae54198b
KW
465
466 # While we have MANIFEST open, on VMS platforms, look for files that match
467 # the magic VMS file names that have to be handled specially. Add these
468 # to the list of them.
469 if ($^O eq 'VMS' && / ^ ( [^\t]* $vms_re ) \t /x) {
470 $special_vms_files{$1} = 1;
471 }
c3e757a4
KW
472 if (/ ^ ( [^\t]* \. PL ) \t /x) {
473 $excluded_files{canonicalize($1)} = 1;
474 }
475}
476close $manifest_fh, or die "Can't close $MANIFEST";
477
16384ac1
KW
478
479# Pod::Checker messages to suppress
480my @suppressed_messages = (
c429f8ed
KW
481 # We catch independently the ones that are real problems.
482 qr/multiple occurrences \(\d+\) of link target/,
483
484 "unescaped <>", # Not every '<' or '>' need be escaped
485 qr/No items in =over/, # i.e., a blockquote, which we consider legal
16384ac1
KW
486);
487
488sub suppressed {
489 # Returns bool as to if input message is one that is to be suppressed
490
491 my $message = shift;
c429f8ed
KW
492
493 return grep { $message =~ /^$_/i } @suppressed_messages;
16384ac1
KW
494}
495
496{ # Closure to contain a simple subset of test.pl. This is to get rid of the
497 # unnecessary 'failed at' messages that would otherwise be output pointing
498 # to a particular line in this file.
a67b1afa 499
16384ac1
KW
500 my $current_test = 0;
501 my $planned;
502
503 sub plan {
504 my %plan = @_;
da33abaf
KW
505 $planned = $plan{tests} + 1; # +1 for final test that files haven't
506 # been removed
16384ac1
KW
507 print "1..$planned\n";
508 return;
509 }
510
511 sub ok {
512 my $success = shift;
513 my $message = shift;
514
515 chomp $message;
516
517 $current_test++;
518 print "not " unless $success;
519 print "ok $current_test - $message\n";
ef436c1f 520 return $success;
16384ac1
KW
521 }
522
523 sub skip {
524 my $why = shift;
525 my $n = @_ ? shift : 1;
526 for (1..$n) {
527 $current_test++;
528 print "ok $current_test # skip $why\n";
529 }
530 no warnings 'exiting';
531 last SKIP;
532 }
533
c8fbf4a0
FC
534 sub _note {
535 my ($andle, $message) = @_;
16384ac1
KW
536
537 chomp $message;
538
c8fbf4a0
FC
539 print $andle $message =~ s/^/# /mgr;
540 print $andle "\n";
16384ac1
KW
541 return;
542 }
543
c8fbf4a0
FC
544 sub note { unshift @_, \*STDOUT; goto &_note }
545
546 sub diag { unshift @_, \*STDERR; goto &_note }
547
16384ac1
KW
548 END {
549 if ($planned && $planned != $current_test) {
550 print STDERR
551 "# Looks like you planned $planned tests but ran $current_test.\n";
552 }
553 }
554}
555
16384ac1
KW
556# List of known potential problems by pod and type.
557my %known_problems;
558
559# Pods given by the keys contain an interior node that is referred to from
560# outside it.
561my %has_referred_to_node;
562
563my $show_counts = 0;
564my $regen = 0;
477100f8 565my $add_link = 0;
16384ac1 566my $show_all = 0;
0cbb9de5 567my $pedantic = 0;
16384ac1 568
d9e2eb4b
KW
569my $do_upstream_cpan = 0; # Assume that are to skip anything in /cpan
570my $do_deltas = 0; # And stable perldeltas
16384ac1
KW
571
572while (@ARGV && substr($ARGV[0], 0, 1) eq '-') {
573 my $arg = shift @ARGV;
574
575 $arg =~ s/^--/-/; # Treat '--' the same as a single '-'
576 if ($arg eq '-regen') {
577 $regen = 1;
0cbb9de5 578 $pedantic = 1;
16384ac1 579 }
477100f8
KW
580 elsif ($arg eq '-add_link') {
581 $add_link = 1;
582 }
16384ac1
KW
583 elsif ($arg eq '-cpan') {
584 $do_upstream_cpan = 1;
585 }
d9e2eb4b
KW
586 elsif ($arg eq '-deltas') {
587 $do_deltas = 1;
588 }
16384ac1
KW
589 elsif ($arg eq '-show_all') {
590 $show_all = 1;
591 }
592 elsif ($arg eq '-counts') {
593 $show_counts = 1;
594 }
0cbb9de5
BG
595 elsif ($arg eq '-pedantic') {
596 $pedantic = 1;
597 }
16384ac1
KW
598 else {
599 die <<EOF;
600Unknown option '$arg'
601
477100f8 602Usage: $0 [ --regen | --cpan | --show_all | FILE ... | --add_link MODULE ... ]\n"
0cbb9de5 603 --add_link -> Add the MODULE and man page references to the database
16384ac1 604 --regen -> Regenerate the data file for $0
477100f8 605 --cpan -> Include files in the cpan subdirectory.
d9e2eb4b 606 --deltas -> Include stable perldeltas
16384ac1
KW
607 --show_all -> Show all known potential problems
608 --counts -> Don't test, but give summary counts of the currently
609 existing database
0cbb9de5 610 --pedantic -> Check for overly long lines in verbatim blocks
16384ac1
KW
611EOF
612 }
613}
614
0cbb9de5 615$pedantic = 1 if exists $ENV{PERL_POD_PEDANTIC} and $ENV{PERL_POD_PEDANTIC};
16384ac1
KW
616my @files = @ARGV;
617
d9e2eb4b
KW
618my $cpan_or_deltas = $do_upstream_cpan || $do_deltas;
619if (($regen + $show_all + $show_counts + $add_link + $cpan_or_deltas ) > 1) {
620 croak "--regen, --show_all, --counts, and --add_link are mutually exclusive\n and none can be run with --cpan nor --deltas";
16384ac1
KW
621}
622
623my $has_input_files = @files;
624
8c791efd
KW
625
626if ($add_link) {
627 if (! $has_input_files) {
628 croak "--add_link requires at least one module or man page reference";
629 }
630}
631elsif ($has_input_files) {
83ced756
KW
632 if ($regen || $show_counts || $do_upstream_cpan || $do_deltas) {
633 croak "--regen, --counts, --deltas, and --cpan can't be used since using specific files";
634 }
635 foreach my $file (@files) {
636 croak "Can't read file '$file'" if ! -r $file;
637 }
16384ac1
KW
638}
639
640our %problems; # potential problems found in this run
641
642package My::Pod::Checker { # Extend Pod::Checker
a67b1afa
MM
643 use parent 'Pod::Checker';
644
16384ac1
KW
645 # Uses inside out hash to protect from typos
646 # For new fields, remember to add to destructor DESTROY()
c429f8ed
KW
647 my %CFL_text; # The text comprising the current C<>, F<>, or L<>
648 my %C_text; # If defined, are in a C<> section, and includes
649 # the accumulated text from that
16384ac1
KW
650 my %current_indent; # Current line's indent
651 my %filename; # The pod is store in this file
c429f8ed
KW
652 my %in_CFL; # count of stacked C<>, F<>, L<> directives
653 my %indents; # Stack of indents from =over's in effect for
654 # current line
655 my %in_for; # true if in a =for or =begin
16384ac1
KW
656 my %in_NAME; # true if within NAME section
657 my %in_begin; # true if within =begin section
c429f8ed 658 my %in_X; # true if in a X<>
16384ac1
KW
659 my %linkable_item; # Bool: if the latest =item is linkable. It isn't
660 # for bullet and number lists
661 my %linkable_nodes; # Pod::Checker adds all =items to its node list,
662 # but not all =items are linkable to
c429f8ed
KW
663 my %running_CFL_text; # The current text that is being accumulated until
664 # an end_FOO is found, and this includes any C<>,
665 # F<>, or L<> directives.
666 my %running_simple_text; # The currentt text that is being accumulated
667 # until an end_FOO is found, and all directives
668 # have been expanded into plain text
16384ac1
KW
669 my %command_count; # Number of commands seen
670 my %seen_pod_cmd; # true if have =pod earlier
c429f8ed
KW
671 my %skip; # is SKIP set for this pod
672 my %start_line; # the first input line number in the the thing
673 # currently being worked on
16384ac1
KW
674
675 sub DESTROY {
676 my $addr = Scalar::Util::refaddr $_[0];
c429f8ed
KW
677 delete $CFL_text{$addr};
678 delete $C_text{$addr};
16384ac1
KW
679 delete $command_count{$addr};
680 delete $current_indent{$addr};
681 delete $filename{$addr};
682 delete $in_begin{$addr};
c429f8ed 683 delete $in_CFL{$addr};
16384ac1 684 delete $indents{$addr};
c429f8ed 685 delete $in_for{$addr};
16384ac1 686 delete $in_NAME{$addr};
c429f8ed 687 delete $in_X{$addr};
16384ac1
KW
688 delete $linkable_item{$addr};
689 delete $linkable_nodes{$addr};
c429f8ed
KW
690 delete $running_CFL_text{$addr};
691 delete $running_simple_text{$addr};
16384ac1
KW
692 delete $seen_pod_cmd{$addr};
693 delete $skip{$addr};
c429f8ed 694 delete $start_line{$addr};
16384ac1
KW
695 return;
696 }
697
698 sub new {
699 my $class = shift;
700 my $filename = shift;
701
702 my $self = $class->SUPER::new(-quiet => 1,
703 -warnings => $Warnings_Level);
704 my $addr = Scalar::Util::refaddr $self;
705 $command_count{$addr} = 0;
706 $current_indent{$addr} = 0;
707 $filename{$addr} = $filename;
708 $in_begin{$addr} = 0;
c429f8ed
KW
709 $in_X{$addr} = 0;
710 $in_CFL{$addr} = 0;
16384ac1
KW
711 $in_NAME{$addr} = 0;
712 $linkable_item{$addr} = 0;
16384ac1 713 $seen_pod_cmd{$addr} = 0;
16384ac1
KW
714 return $self;
715 }
716
717 # re's for messages that Pod::Checker outputs
718 my $location = qr/ \b (?:in|at|on|near) \s+ /xi;
719 my $optional_location = qr/ (?: $location )? /xi;
3cb68c65 720 my $line_reference = qr/ [('"]? $optional_location \b line \s+
16384ac1
KW
721 (?: \d+ | EOF | \Q???\E | - )
722 [)'"]? /xi;
723
724 sub poderror { # Called to register a potential problem
725
726 # This adds an extra field to the parent hash, 'parameter'. It is
727 # used to extract the variable parts of a message leaving just the
728 # constant skeleton. This in turn allows the message to be
729 # categorized better, so that it shows up as a single type in our
730 # database, with the specifics of each occurrence not being stored with
731 # it.
732
733 my $self = shift;
734 my $opts = shift;
735
736 my $addr = Scalar::Util::refaddr $self;
737 return if $skip{$addr};
738
739 # Input can be a string or hash. If a string, parse it to separate
740 # out the line number and convert to a hash for easier further
741 # processing
742 my $message;
743 if (ref $opts ne 'HASH') {
744 $message = join "", $opts, @_;
745 my $line_number;
746 if ($message =~ s/\s*($line_reference)//) {
747 ($line_number = $1) =~ s/\s*$optional_location//;
748 }
749 else {
750 $line_number = '???';
751 }
752 $opts = { -msg => $message, -line => $line_number };
753 } else {
754 $message = $opts->{'-msg'};
755
756 }
757
758 $message =~ s/^\d+\s+//;
759 return if main::suppressed($message);
760
761 $self->SUPER::poderror($opts, @_);
762
763 $opts->{parameter} = "" unless $opts->{parameter};
764
765 # The variable parts of the message tend to be enclosed in '...',
766 # "....", or (...). Extract them and put them in an extra field,
767 # 'parameter'. This is trickier because the matching delimiter to a
768 # '(' is its mirror, and not itself. Text::Balanced could be used
769 # instead.
770 while ($message =~ m/ \s* $optional_location ( [('"] )/xg) {
771 my $delimiter = $1;
772 my $start = $-[0];
773 $delimiter = ')' if $delimiter eq '(';
774
775 # If there is no ending delimiter, don't consider it to be a
776 # variable part. Most likely it is a contraction like "Don't"
777 last unless $message =~ m/\G .+? \Q$delimiter/xg;
778
779 my $length = $+[0] - $start;
780
781 # Get the part up through the closing delimiter
782 my $special = substr($message, $start, $length);
783 $special =~ s/^\s+//; # No leading whitespace
784
785 # And add that variable part to the parameter, while removing it
786 # from the message. This isn't a foolproof way of finding the
787 # variable part. For example '(s)' can occur in e.g.,
788 # 'paragraph(s)'
789 if ($special ne '(s)') {
790 substr($message, $start, $length) = "";
791 pos $message = $start;
792 $opts->{-msg} = $message;
793 $opts->{parameter} .= " " if $opts->{parameter};
794 $opts->{parameter} .= $special;
795 }
796 }
797
798 # Extract any additional line number given. This is often the
799 # beginning location of something whereas the main line number gives
800 # the ending one.
801 if ($message =~ /( $line_reference )/xi) {
802 my $line_ref = $1;
803 while ($message =~ s/\s*\Q$line_ref//) {
804 $opts->{-msg} = $message;
805 $opts->{parameter} .= " " if $opts->{parameter};
806 $opts->{parameter} .= $line_ref;
807 }
808 }
809
b3fdb838 810 Carp::carp("Couldn't extract line number from '$message'") if $message =~ /line \d+/;
16384ac1
KW
811 push @{$problems{$filename{$addr}}{$message}}, $opts;
812 #push @{$problems{$self->get_filename}{$message}}, $opts;
813 }
814
c429f8ed
KW
815 # In the next subroutines, we keep track of the text of the current
816 # innermost thing, like F<fooC<bar>baz>. The things we care about raising
817 # messages about in this program all come from a single sequence of
818 # characters uninterrupted by other pod commands. Therefore we don't have
819 # to worry about recursion, and we can just set the string we care about
820 # to empty on entrance to each command.
821
822 sub handle_text {
823 # This is called by the parent class to deal with any straight text.
824 # We mostly just append this to the running current value which will
825 # be dealt with upon the end of the current construct, like a
826 # paragraph. But certain things don't contribute to checking the pod
827 # and are ignored. We also have set flags to indicate this text is
828 # going towards constructing certain constructs, and handle those
829 # specially.
16384ac1 830
c429f8ed 831 my $self = shift;
16384ac1 832 my $addr = Scalar::Util::refaddr $self;
c429f8ed
KW
833
834 my $return = $self->SUPER::handle_text(@_);
835
836 if ($in_X{$addr} || $in_for{$addr}) { # ignore
837 return $return;
838 }
839
840 my $text = join "\n", @_;
841 $running_simple_text{$addr} .= $text;
842
843 # Keep separate tabs on C<>, F<>, and L<> directives, and one
844 # especially for C<> ones.
845 if ($in_CFL{$addr}) {
846 $CFL_text{$addr} .= $text;
847 $C_text{$addr} .= $text if defined $C_text{$addr};
848 }
849 else {
850 # This variable is updated instead in the corresponding C, F, or L
851 # handler.
852 $running_CFL_text{$addr} .= $text;
853 }
854
855 return $return;
16384ac1
KW
856 }
857
c429f8ed
KW
858 # The start_FOO routines check that somehow a C<> construct hasn't escaped
859 # without being checked, and initialize things, and call the parent
860 # class's equivalent routine.
861
862 # The end_FOO routines close things off, and check the text that has been
863 # accumulated for FOO, then call the parent's corresponding routine.
16384ac1 864
c429f8ed
KW
865 sub start_Para {
866 my $self = shift;
867 check_see_but_not_link($self);
16384ac1 868
2592f3b8 869 my $addr = Scalar::Util::refaddr $self;
c429f8ed
KW
870 $start_line{$addr} = $_[0]->{start_line};
871 $running_CFL_text{$addr} = "";
872 $running_simple_text{$addr} = "";
873 return $self->SUPER::start_Para(@_);
874 }
2592f3b8 875
c429f8ed
KW
876 sub start_item_text {
877 my $self = shift;
878 check_see_but_not_link($self);
16384ac1 879
c429f8ed
KW
880 my $addr = Scalar::Util::refaddr $self;
881 $start_line{$addr} = $_[0]->{start_line};
882 $running_CFL_text{$addr} = "";
883 $running_simple_text{$addr} = "";
884
885 # This is the only =item that is linkable
886 $linkable_item{$addr} = 1;
887
888 return $self->SUPER::start_item_text(@_);
16384ac1
KW
889 }
890
c429f8ed
KW
891 sub start_item_number {
892 my $self = shift;
893 check_see_but_not_link($self);
16384ac1 894
c429f8ed
KW
895 my $addr = Scalar::Util::refaddr $self;
896 $start_line{$addr} = $_[0]->{start_line};
897 $running_CFL_text{$addr} = "";
898 $running_simple_text{$addr} = "";
899
900 return $self->SUPER::start_item_number(@_);
901 }
902
903 sub start_item_bullet {
904 my $self = shift;
905 check_see_but_not_link($self);
16384ac1 906
16384ac1 907 my $addr = Scalar::Util::refaddr $self;
c429f8ed
KW
908 $start_line{$addr} = $_[0]->{start_line};
909 $running_CFL_text{$addr} = "";
910 $running_simple_text{$addr} = "";
911
912 return $self->SUPER::start_item_bullet(@_);
913 }
914
915 sub end_item { # No difference in =item types endings
916 my $self = shift;
917 check_see_but_not_link($self);
918 return $self->SUPER::end_item(@_);
919 }
920
921 sub start_over {
922 my $self = shift;
923 check_see_but_not_link($self);
924
925 my $addr = Scalar::Util::refaddr $self;
926 $start_line{$addr} = $_[0]->{start_line};
927 $running_CFL_text{$addr} = "";
928 $running_simple_text{$addr} = "";
929
930 # Save this indent on a stack, and keep track of total indent
931 my $indent = $_[0]{'indent'};
932 push @{$indents{$addr}}, $indent;
933 $current_indent{$addr} += $indent;
934
935 return $self->SUPER::start_over(@_);
936 }
937
938 sub end_over_bullet { shift->end_over(@_) }
939 sub end_over_number { shift->end_over(@_) }
940 sub end_over_text { shift->end_over(@_) }
941 sub end_over_block { shift->end_over(@_) }
942 sub end_over_empty { shift->end_over(@_) }
943 sub end_over {
944 my $self = shift;
945 check_see_but_not_link($self);
946
947 my $addr = Scalar::Util::refaddr $self;
948
949 # Pop current indent
950 if (@{$indents{$addr}}) {
951 $current_indent{$addr} -= pop @{$indents{$addr}};
16384ac1 952 }
c429f8ed
KW
953 else {
954 # =back without corresponding =over, but should have
955 # warned already
956 $current_indent{$addr} = 0;
957 }
958 }
959
960 sub check_see_but_not_link {
113a3f61 961
c429f8ed
KW
962 # Looks through accumulated text for current element that includes the
963 # C<>, F<>, and L<> directives for ones that look like they are
964 # C<link> instead of L<link>.
965
966 my $self = shift;
967 my $addr = Scalar::Util::refaddr $self;
968
969 return unless defined $running_CFL_text{$addr};
970
971 while ($running_CFL_text{$addr} =~ m{
113a3f61
RS
972 ( (?: \w+ \s+ )* ) # The phrase before, if any
973 \b [Ss]ee \s+
974 ( ( [^L] )
975 <
976 ( [^<]*? ) # The not < excludes nested C<L<...
977 >
978 )
979 ( \s+ (?: under | in ) \s+ L< )?
c429f8ed
KW
980 }xg)
981 {
113a3f61
RS
982 my $prefix = $1 // "";
983 my $construct = $2; # The whole thing, like C<...>
984 my $type = $3;
985 my $interior = $4;
986 my $trailing = $5; # After the whole thing ending in "L<"
987
988 # If the full phrase is something like, "you might see C<", or
989 # similar, it really isn't a reference to a link. The ones I saw
990 # all had the word "you" in them; and the "you" wasn't the
991 # beginning of a sentence.
992 if ($prefix !~ / \b you \b /x) {
993
994 # Now, find what the module or man page name within the
995 # construct would be if it actually has L<> syntax. If it
996 # doesn't have that syntax, will set the module to the entire
997 # interior.
113a3f61
RS
998 if (! defined $trailing # not referring to something in another
999 # section
1000 && $interior !~ /$non_pods/
1001
113a3f61
RS
1002 # There can't be spaces (I think) in module names or man
1003 # pages
c429f8ed 1004 && $interior !~ / \s /x
113a3f61
RS
1005
1006 # F<> that end in eg \.pl are almost certainly ok, as are
1007 # those that look like a path with multiple "/" chars
1008 && ($type ne "F"
1009 || (! -e $interior
1010 && $interior !~ /\.\w+$/
1011 && $interior !~ /\/.+\//)
1012 )
1013 ) {
0cbb9de5 1014 # TODO: move the checking of $pedantic higher up
c429f8ed 1015 $self->poderror({ -line => $start_line{$addr},
0cbb9de5 1016 -msg => $C_not_linked,
113a3f61 1017 parameter => $construct
c429f8ed 1018 });
113a3f61
RS
1019 }
1020 }
1021 }
c429f8ed
KW
1022
1023 undef $running_CFL_text{$addr};
16384ac1
KW
1024 }
1025
c429f8ed
KW
1026 sub end_Para {
1027 my $self = shift;
1028 check_see_but_not_link($self);
1029
16384ac1 1030 my $addr = Scalar::Util::refaddr $self;
c429f8ed
KW
1031 if ($in_NAME{$addr}) {
1032 if ($running_simple_text{$addr} =~ /^\s*(\S+?)\s*$/) {
1033 $self->poderror({ -line => $start_line{$addr},
1034 -msg => $missing_name_description,
1035 parameter => $1});
16384ac1 1036 }
c429f8ed 1037 $in_NAME{$addr} = 0;
16384ac1 1038 }
c429f8ed
KW
1039 $self->SUPER::end_Para(@_);
1040 }
1041
1042 sub start_head1 {
1043 my $self = shift;
1044 check_see_but_not_link($self);
a67b1afa 1045
c429f8ed
KW
1046 my $addr = Scalar::Util::refaddr $self;
1047 $start_line{$addr} = $_[0]->{start_line};
1048 $running_CFL_text{$addr} = "";
1049 $running_simple_text{$addr} = "";
1050
1051 return $self->SUPER::start_head1(@_);
1052 }
1053
1054 sub end_head1 { # This is called at the end of the =head line.
1055 my $self = shift;
1056 check_see_but_not_link($self);
1057
1058 my $addr = Scalar::Util::refaddr $self;
1059
1060 $in_NAME{$addr} = 1 if $running_simple_text{$addr} eq 'NAME';
1061 return $self->SUPER::end_head(@_);
1062 }
1063
1064 sub start_Verbatim {
1065 my $self = shift;
1066 check_see_but_not_link($self);
1067
1068 my $addr = Scalar::Util::refaddr $self;
1069 $running_simple_text{$addr} = "";
1070 $start_line{$addr} = $_[0]->{start_line};
1071 return $self->SUPER::start_Verbatim(@_);
1072 }
1073
1074 sub end_Verbatim {
1075 my $self = shift;
1076 my $addr = Scalar::Util::refaddr $self;
1077
1078 # Pick up the name if it looks like one, since the parent class
1079 # doesn't handle verbatim NAMEs
1080 if ($in_NAME{$addr}
1081 && $running_simple_text{$addr} =~ /^\s*(\S+?)\s*[,-]/)
1082 {
1083 $self->name($1);
16384ac1 1084 }
c429f8ed
KW
1085
1086 my $indent = $self->get_current_indent;
1087
1088 # Look at each line to verify it is short enough
1089 my @lines = split /^/, $running_simple_text{$addr};
1090 for my $i (0 .. @lines - 1) {
1091 $lines[$i] =~ s/\s+$//;
1092 my $exceeds = length(Text::Tabs::expand($lines[$i]))
1093 + $indent - $MAX_LINE_LENGTH;
1094 next unless $exceeds > 0;
1095
1096 $self->poderror({ -line => $start_line{$addr} + $i,
1097 -msg => $line_length,
1098 parameter => "+$exceeds (including " . ($indent - $INDENT) . " from =over's)",
1099 });
16384ac1 1100 }
c429f8ed
KW
1101
1102 undef $running_simple_text{$addr};
1103
1104 # Parent class didn't bother to define this
1105 #return $self->SUPER::SUPER::end_Verbatim(@_);
1106 }
1107
1108 sub start_C {
1109 my $self = shift;
1110 my $addr = Scalar::Util::refaddr $self;
1111
1112 $C_text{$addr} = "";
1113
1114 # If not in a stacked set of C<>, F<> and L<>, initialize the text for
1115 # them.
1116 $CFL_text{$addr} = "" if ! $in_CFL{$addr};
1117 $in_CFL{$addr}++;
1118
1119 return $self->SUPER::start_C(@_);
1120 }
1121
1122 sub start_F {
1123 my $self = shift;
1124 my $addr = Scalar::Util::refaddr $self;
1125
1126 $CFL_text{$addr} = "" if ! $in_CFL{$addr};
1127 $in_CFL{$addr}++;
1128 return $self->SUPER::start_F(@_);
1129 }
1130
1131 sub start_L {
1132 my $self = shift;
1133 my $addr = Scalar::Util::refaddr $self;
1134
1135 $CFL_text{$addr} = "" if ! $in_CFL{$addr};
1136 $in_CFL{$addr}++;
1137 return $self->SUPER::start_L(@_);
1138 }
1139
1140 sub end_C {
1141 my $self = shift;
1142 my $addr = Scalar::Util::refaddr $self;
1143
1144 # Warn if looks like a file or link enclosed instead by this C<>
1145 if ($C_text{$addr} =~ qr/^ $C_path_re $/x) {
1146 # Here it does look like it could be be a file path or a link.
1147 # But some varieties of regex patterns could also fit with what we
1148 # have so far. Weed those out as best we can. '/foo/' is almost
1149 # certainly meant to be a pattern, as is '/foo/g'.
1150 my $is_pattern;
1151 if ($C_text{$addr} !~ qr| ^ / [^/]* / ( [msixpodualngcr]* ) $ |x) {
1152 $is_pattern = 0;
16384ac1
KW
1153 }
1154 else {
16384ac1 1155
c429f8ed
KW
1156 # Here, it looks like a pattern potentially followed by some
1157 # modifiers. To make doubly sure, don't count as patterns
1158 # those constructs which have more occurrences (generally 1)
1159 # of a modifier than is legal.
1160 my %counts;
1161 map { $counts{$_}++ } split "", $1;
1162 foreach my $modifier (keys %counts) {
1163 if ($counts{$modifier} > (($modifier eq 'a')
1164 ? 2
1165 : 1))
1166 {
1167 $is_pattern = 0;
1168 last;
1169 }
1170 }
1171 $is_pattern = 1 unless defined $is_pattern;
16384ac1
KW
1172 }
1173
c429f8ed
KW
1174 unless ($is_pattern) {
1175 $self->poderror({ -line => $start_line{$addr},
1176 -msg => $C_with_slash,
1177 parameter => "C<$C_text{$addr}>"
1178 });
1179 }
16384ac1 1180 }
c429f8ed
KW
1181 undef $C_text{$addr};
1182
1183 # Add the current text to the running total. This was not done in
1184 # handle_text(), because it just sees the plain text of the innermost
1185 # stacked directive. We want to keep all the directive names
1186 # enclosing the text. Otherwise the fact that C<L<foobar>> is to a
1187 # link would be lost, as the L<> would be gone.
1188 $CFL_text{$addr} = "C<$CFL_text{$addr}>";
1189
1190 # Add this text to the the whole running total only if popping this
1191 # directive off the stack leaves it empty. As long as something is on
1192 # the stack, it gets added to $CFL_text (just above). It is only
1193 # entirely constructed when the stack is empty.
1194 $in_CFL{$addr}--;
1195 $running_CFL_text{$addr} .= $CFL_text{$addr} if ! $in_CFL{$addr};
1196
1197 return $self->SUPER::end_C(@_);
1198 }
16384ac1 1199
c429f8ed
KW
1200 sub end_F {
1201 my $self = shift;
1202 my $addr = Scalar::Util::refaddr $self;
1203
1204 $CFL_text{$addr} = "F<$CFL_text{$addr}>";
1205 $in_CFL{$addr}--;
1206 $running_CFL_text{$addr} .= $CFL_text{$addr} if ! $in_CFL{$addr};
1207 return $self->SUPER::end_F(@_);
16384ac1
KW
1208 }
1209
c429f8ed 1210 sub end_L {
16384ac1 1211 my $self = shift;
c429f8ed 1212 my $addr = Scalar::Util::refaddr $self;
16384ac1 1213
c429f8ed
KW
1214 $CFL_text{$addr} = "L<$CFL_text{$addr}>";
1215 $in_CFL{$addr}--;
1216 $running_CFL_text{$addr} .= $CFL_text{$addr} if ! $in_CFL{$addr};
1217 return $self->SUPER::end_L(@_);
1218 }
1219
1220 sub start_X {
1221 my $self = shift;
1222 my $addr = Scalar::Util::refaddr $self;
1223
1224 $in_X{$addr} = 1;
1225 return $self->SUPER::start_X(@_);
1226 }
1227
1228 sub end_X {
1229 my $self = shift;
1230 my $addr = Scalar::Util::refaddr $self;
1231
1232 $in_X{$addr} = 0;
1233 return $self->SUPER::end_X(@_);
1234 }
1235
1236 sub start_for {
1237 my $self = shift;
1238 my $addr = Scalar::Util::refaddr $self;
1239
1240 $in_for{$addr} = 1;
1241 return $self->SUPER::start_for(@_);
1242 }
1243
1244 sub end_for {
1245 my $self = shift;
1246 my $addr = Scalar::Util::refaddr $self;
1247
1248 $in_for{$addr} = 0;
1249 return $self->SUPER::end_for(@_);
1250 }
1251
1252 sub hyperlink {
1253 my ($self, $link) = @_;
1254
1255 if ($link && $link->type eq 'pod') {
1256 my $page = $link->page;
1257 my $node = $link->node;
1258
1259 # If the hyperlink is to an interior node of another page, save it
1260 # so that we can see if we need to parse normally skipped files.
1261 $has_referred_to_node{$page} = 1 if $node;
02987562
KW
1262
1263 # Ignore certain placeholder links in perldelta. Check if the
1264 # link is page-level, and also check if to a node within the page
c429f8ed
KW
1265 if ( $self->name && $self->name eq "perldelta"
1266 && (( grep { $page eq $_ } @perldelta_ignore_links)
1267 || ( $node
02987562
KW
1268 && (grep { "$page/$node" eq $_ } @perldelta_ignore_links)
1269 ))) {
1270 return;
1271 }
1272 }
c429f8ed
KW
1273
1274 return $self->SUPER::hyperlink($link);
16384ac1
KW
1275 }
1276
1277 sub node {
1278 my $self = shift;
1279 my $text = $_[0];
1280 if($text) {
1281 $text =~ s/\s+$//s; # strip trailing whitespace
1282 $text =~ s/\s+/ /gs; # collapse whitespace
1283 my $addr = Scalar::Util::refaddr $self;
1284 push(@{$linkable_nodes{$addr}}, $text) if
1285 ! $current_indent{$addr}
1286 || $linkable_item{$addr};
1287 }
1288 return $self->SUPER::node($_[0]);
1289 }
1290
1291 sub get_current_indent {
1292 return $INDENT + $current_indent{Scalar::Util::refaddr $_[0]};
1293 }
1294
1295 sub get_filename {
1296 return $filename{Scalar::Util::refaddr $_[0]};
1297 }
1298
1299 sub linkable_nodes {
1300 my $linkables = $linkable_nodes{Scalar::Util::refaddr $_[0]};
1301 return undef unless $linkables;
1302 return @$linkables;
1303 }
1304
1305 sub get_skip {
1306 return $skip{Scalar::Util::refaddr $_[0]} // 0;
1307 }
1308
1309 sub set_skip {
1310 my $self = shift;
1311 $skip{Scalar::Util::refaddr $self} = shift;
1312
1313 # If skipping, no need to keep the problems for it
1314 delete $problems{$self->get_filename};
1315 return;
1316 }
48b96b3d
KW
1317
1318 sub parse_from_file {
1319 # This overrides the super class method so that if an open fails on a
1320 # transitory file, it doesn't croak. It returns 1 if it did find the
1321 # file, 0 if it didn't
1322
1323 my $self = shift;
1324 my $filename = shift;
1325 # ignores 2nd param, which is output file. Always uses undef
1326
1327 if (open my $in_fh, '<:bytes', $filename) {
c429f8ed 1328 $self->SUPER::parse_from_file($in_fh, undef);
48b96b3d
KW
1329 close $in_fh;
1330 return 1;
1331 }
1332
1333 # If couldn't open file, perhaps it was transitory, and hence not an error
1334 return 0 unless -e $filename;
1335
1336 die "Can't open '$filename': $!\n";
1337 }
16384ac1
KW
1338}
1339
1340package Tie_Array_to_FH { # So printing actually goes to an array
1341
1342 my %array;
1343
1344 sub TIEHANDLE {
1345 my $class = shift;
1346 my $array_ref = shift;
1347
1348 my $self = bless \do{ my $anonymous_scalar }, $class;
1349 $array{Scalar::Util::refaddr $self} = $array_ref;
1350
1351 return $self;
1352 }
1353
1354 sub PRINT {
a67b1afa 1355 my $self = shift;
16384ac1
KW
1356 push @{$array{Scalar::Util::refaddr $self}}, @_;
1357 return 1;
1358 }
a67b1afa
MM
1359}
1360
69f6a9a1 1361
d382c182 1362my %filename_to_checker; # Map a filename to its pod checker object
5ff1f7df
A
1363my %id_to_checker; # Map a checksum to its pod checker object
1364my %nodes; # key is filename, values are nodes in that file.
1365my %nodes_first_word; # same, but value is first word of each node
1366my %valid_modules; # List of modules known to exist outside us.
1367my %digests; # checksums of files, whose names are the keys
1368my %filename_to_pod; # Map a filename to its pod NAME
16384ac1
KW
1369my %files_with_unknown_issues;
1370my %files_with_fixes;
69f6a9a1 1371
16384ac1 1372my $data_fh;
be39e7f8 1373open $data_fh, '<:bytes', $known_issues or die "Can't open $known_issues";
69f6a9a1 1374
16384ac1
KW
1375my %counts; # For --counts param, count of each issue type
1376my %suppressed_files; # Files with at least one issue type to suppress
e57d740c
KW
1377my $HEADER = <<END;
1378# This file is the data file for $0.
1379# There are three types of lines.
1380# Comment lines are white-space only or begin with a '#', like this one. Any
1381# changes you make to the comment lines will be lost when the file is
1382# regen'd.
1383# Lines without tab characters are simply NAMES of pods that the program knows
1384# will have links to them and the program does not check if those links are
1385# valid.
1386# All other lines should have three fields, each separated by a tab. The
1387# first field is the name of a pod; the second field is an error message
1388# generated by this program; and the third field is a count of how many
1389# known instances of that message there are in the pod. -1 means that the
1390# program can expect any number of this type of message.
1391END
16384ac1 1392
e57d740c 1393my @existing_issues;
477100f8 1394
477100f8 1395
0cbb9de5 1396while (<$data_fh>) { # Read the database
69f6a9a1 1397 chomp;
16384ac1
KW
1398 next if /^\s*(?:#|$)/; # Skip comment and empty lines
1399 if (/\t/) {
1400 next if $show_all;
e57d740c
KW
1401 if ($add_link) { # The issues are saved and later output unchanged
1402 push @existing_issues, $_;
1403 next;
1404 }
16384ac1
KW
1405
1406 # Keep track of counts of each issue type for each file
1407 my ($filename, $message, $count) = split /\t/;
1408 $known_problems{$filename}{$message} = $count;
1409
1410 if ($show_counts) {
1411 if ($count < 0) { # -1 means to suppress this issue type
1412 $suppressed_files{$filename} = $filename;
1413 }
1414 else {
1415 $counts{$message} += $count;
1416 }
1417 }
1418 }
1419 else { # Lines without a tab are modules known to be valid
1420 $valid_modules{$_} = 1
1421 }
1422}
1423close $data_fh;
1424
e57d740c
KW
1425if ($add_link) {
1426 $copy_fh = open_new($known_issues);
1427
1428 # Check for basic sanity, and add each command line argument
1429 foreach my $module (@files) {
1430 die "\"$module\" does not look like a module or man page"
1431 # Must look like (A or A::B or A::B::C ..., or foo(3C)
1432 if $module !~ /^ (?: \w+ (?: :: \w+ )* | \w+ \( \d \w* \) ) $/x;
1433 $valid_modules{$module} = 1
1434 }
1435 my_safer_print($copy_fh, $HEADER);
1436 foreach (sort { lc $a cmp lc $b } keys %valid_modules) {
1437 my_safer_print($copy_fh, $_, "\n");
1438 }
1439
1440 # The rest of the db file is output unchanged.
63717411 1441 my_safer_print($copy_fh, join "\n", @existing_issues, "");
e57d740c
KW
1442
1443 close_and_rename($copy_fh);
1444 exit;
1445}
1446
16384ac1
KW
1447if ($show_counts) {
1448 my $total = 0;
1449 foreach my $message (sort keys %counts) {
1450 $total += $counts{$message};
1451 note(Text::Tabs::expand("$counts{$message}\t$message"));
1452 }
1453 note("-----\n" . Text::Tabs::expand("$total\tknown potential issues"));
1454 if (%suppressed_files) {
1455 note("\nFiles that have all messages of at least one type suppressed:");
1456 note(join ",", keys %suppressed_files);
1457 }
1458 exit 0;
1459}
1460
16384ac1
KW
1461# re to match files that are to be parsed only if there is an internal link
1462# to them. It does not include cpan, as whether those are parsed depends
0496e0bb
KW
1463# on a switch. Currently, only perltoc and the stable perldelta.pod's
1464# are included. The latter all have characters between 'perl' and
1465# 'delta'. (Actually the currently developed one matches as well, but
1466# is a duplicate of perldelta.pod, so can be skipped, so fine for it to
1467# match this.
d9e2eb4b 1468my $only_for_interior_links_re = qr/ ^ pod\/perltoc.pod $
0496e0bb 1469 /x;
d9e2eb4b
KW
1470unless ($do_deltas) {
1471 $only_for_interior_links_re = qr/$only_for_interior_links_re |
1472 \b perl \d+ delta \. pod \b
1473 /x;
1474}
16384ac1
KW
1475
1476{ # Closure
1477 my $first_time = 1;
1478
1479 sub output_thanks ($$$$) { # Called when an issue has been fixed
1480 my $filename = shift;
1481 my $original_count = shift;
1482 my $current_count = shift;
1483 my $message = shift;
1484
1485 $files_with_fixes{$filename} = 1;
1486 my $return;
1487 my $fixed_count = $original_count - $current_count;
1488 my $a_problem = ($fixed_count == 1) ? "a problem" : "multiple problems";
1489 my $another_problem = ($fixed_count == 1) ? "another problem" : "another set of problems";
1490 my $diff;
1491 if ($message) {
1492 $diff = <<EOF;
1493There were $original_count occurrences (now $current_count) in this pod of type
1494"$message",
1495EOF
1496 } else {
1497 $diff = <<EOF;
1498There are no longer any problems found in this pod!
1499EOF
1500 }
1501
1502 if ($first_time) {
1503 $first_time = 0;
1504 $return = <<EOF;
1505Thanks for fixing $a_problem!
1506$diff
1507Now you must teach $0 that this was fixed.
1508EOF
1509 }
1510 else {
1511 $return = <<EOF
1512Thanks for fixing $another_problem.
1513$diff
1514EOF
1515 }
1516
1517 return $return;
1518 }
1519}
1520
1521sub my_safer_print { # print, with error checking for outputting to db
1522 my ($fh, @lines) = @_;
1523
1524 if (! print $fh @lines) {
1525 my $save_error = $!;
1526 close($fh);
1527 die "Write failure: $save_error";
1528 }
1529}
1530
84d2ce66
KW
1531sub extract_pod { # Extracts just the pod from a file; returns undef if file
1532 # doesn't exist
16384ac1 1533 my $filename = shift;
c429f8ed 1534 use Pod::Parser;
16384ac1
KW
1535
1536 my @pod;
1537
1538 # Arrange for the output of Pod::Parser to be collected in an array we can
1539 # look at instead of being printed
1540 tie *ALREADY_FH, 'Tie_Array_to_FH', \@pod;
84d2ce66 1541 if (open my $in_fh, '<:bytes', $filename) {
6fca57a1
KW
1542 my $parser = Pod::Parser->new();
1543 $parser->parse_from_filehandle($in_fh, *ALREADY_FH);
1544 close $in_fh;
16384ac1 1545
6fca57a1 1546 return join "", @pod
84d2ce66
KW
1547 }
1548
1549 # The file should already have been opened once to get here, so if that
1550 # fails, something is wrong. It's possible that a transitory file
1551 # containing a pod would get here, so if the file no longer exists just
1552 # return undef.
1553 return unless -e $filename;
1554 die "Can't open '$filename': $!\n";
16384ac1
KW
1555}
1556
1557my $digest = Digest->new($digest_type);
1558
f2317e57
NC
1559# This is used as a callback from File::Find::find(), which always constructs
1560# pathnames using Unix separators
16384ac1 1561sub is_pod_file {
c1dcaaab
KW
1562 # If $_ is a pod file, add it to the lists and do other prep work.
1563
e42a86f0 1564 if (-d) {
16384ac1
KW
1565 # Don't look at files in directories that are for tests, nor those
1566 # beginning with a dot
f2317e57 1567 if (m!/t\z! || m!/\.!) {
16384ac1
KW
1568 $File::Find::prune = 1;
1569 }
1570 return;
1571 }
1572
e42a86f0
KW
1573 return unless -r && -s; # Can't check it if can't read it; no need to
1574 # check if 0 length
1575 return unless -f || -l; # Weird file types won't be pods
1576
f2317e57
NC
1577 my ($leaf) = m!([^/]+)\z!;
1578 if (m!/\.! # No hidden Unix files
1579 || $leaf =~ $non_pods) {
de4da25d
CB
1580 note("Not considering $_") if DEBUG;
1581 return;
1582 }
1583
16384ac1
KW
1584 my $filename = $File::Find::name;
1585
3673acb0 1586 # $filename is relative, like './path'. Strip that initial part away.
f2317e57 1587 $filename =~ s!^\./!! or die 'Unexpected pathname "$filename"';
16384ac1 1588
b3fdb838 1589 return if $excluded_files{canonicalize($filename)};
16384ac1 1590
144a708b
NC
1591 my $contents = do {
1592 local $/;
763df156
KW
1593 my $candidate;
1594 if (! open $candidate, '<:bytes', $_) {
1595
77b8b9ad
KW
1596 # If a transitory file was found earlier, the open could fail
1597 # legitimately and we just skip the file; also skip it if it is a
1598 # broken symbolic link, as it is probably just a build problem;
1599 # certainly not a file that we would want to check the pod of.
1600 # Otherwise fail it here and no reason to process it further.
1601 # (But the test count will be off too)
1602 ok(0, "Can't open '$filename': $!")
e42a86f0 1603 if -r $filename && ! -l $filename;
763df156
KW
1604 return;
1605 }
144a708b
NC
1606 <$candidate>;
1607 };
16384ac1
KW
1608
1609 # If the file is a .pm or .pod, having any initial '=' on a line is
8505a15d
KW
1610 # grounds for testing it. Otherwise, require a head1 NAME line to
1611 # consider it as a potential pod
144a708b
NC
1612 if ($filename =~ /\.(?:pm|pod)/) {
1613 return unless $contents =~ /^=/m;
1614 } else {
1615 return unless $contents =~ /^=head1 +NAME/m;
16384ac1 1616 }
144a708b
NC
1617
1618 # Here, we know that the file is a pod. Add it to the list of files
1619 # to check and create a checker object for it.
1620
1621 push @files, $filename;
1622 my $checker = My::Pod::Checker->new($filename);
1623 $filename_to_checker{$filename} = $checker;
1624
1625 # In order to detect duplicate pods and only analyze them once, we
1626 # compute checksums for the file, so don't have to do an exact
1627 # compare. Note that if the pod is just part of the file, the
1628 # checksums can differ for the same pod. That special case is handled
1629 # later, since if the checksums of the whole file are the same, that
1630 # case won't even come up. We don't need the checksums for files that
1631 # we parse only if there is a link to its interior, but we do need its
1632 # NAME, which is also retrieved in the code below.
1633
1634 if ($filename =~ / (?: ^(cpan|lib|ext|dist)\/ )
1635 | $only_for_interior_links_re
1636 /x) {
1637 $digest->add($contents);
1638 $digests{$filename} = $digest->digest;
1639
1640 # lib files aren't analyzed if they are duplicates of files copied
1641 # there from some other directory. But to determine this, we need
1642 # to know their NAMEs. We might as well find the NAME now while
1643 # the file is open. Similarly, cpan files aren't analyzed unless
1644 # we're analyzing all of them, or this particular file is linked
1645 # to by a file we are analyzing, and thus we will want to verify
1646 # that the target exists in it. We need to know at least the NAME
1647 # to see if it's worth analyzing, or so we can determine if a lib
1648 # file is a copy of a cpan one.
1649 if ($filename =~ m{ (?: ^ (?: cpan | lib ) / )
16384ac1 1650 | $only_for_interior_links_re
144a708b
NC
1651 }x) {
1652 if ($contents =~ /^=head1 +NAME.*/mg) {
1653 # The NAME is the first non-spaces on the line up to a
1654 # comma, dash or end of line. Otherwise, it's invalid and
1655 # this pod doesn't have a legal name that we're smart
1656 # enough to find currently. But the parser will later
1657 # find it if it thinks there is a legal name, and set the
1658 # name
1659 if ($contents =~ /\G # continue from the line after =head1
1660 \s* # ignore any empty lines
3a9e0de3
KW
1661
1662 # ignore =for paragraphs followed by empty
1663 # lines
1664 (?: ^ =for .*? \n (?: [^\s]*? \n )* \s* )*
1665
144a708b
NC
1666 ^ \s* ( \S+?) \s* (?: [,-] | $ )/mx) {
1667 my $name = $1;
1668 $checker->name($name);
1669 $id_to_checker{$name} = $checker
1670 if $filename =~ m{^cpan/};
16384ac1
KW
1671 }
1672 }
144a708b
NC
1673 elsif ($filename =~ m{^cpan/}) {
1674 $id_to_checker{$digests{$filename}} = $checker;
1675 }
16384ac1
KW
1676 }
1677 }
c1dcaaab
KW
1678
1679 return;
16384ac1
KW
1680} # End of is_pod_file()
1681
477100f8
KW
1682# Start of real code that isn't processing the command line (except the
1683# db is read in above, as is processing of the --add_link option).
16384ac1
KW
1684# Here, @files contains list of files on the command line. If have any of
1685# these, unconditionally test them, and show all the errors, even the known
1686# ones, and, since not testing other pods, don't do cross-pod link tests.
1687# (Could add extra code to do cross-pod tests for the ones in the list.)
477100f8 1688
16384ac1
KW
1689if ($has_input_files) {
1690 undef %known_problems;
d9e2eb4b
KW
1691 $do_upstream_cpan = $do_deltas = 1; # In case one of the inputs is one
1692 # of these types
16384ac1
KW
1693}
1694else { # No input files -- go find all the possibilities.
1695 if ($regen) {
1696 $copy_fh = open_new($known_issues);
1697 note("Regenerating $known_issues, please be patient...");
e57d740c 1698 print $copy_fh $HEADER;
16384ac1
KW
1699 }
1700
1701 # Move to the directory above us, but have to adjust @INC to account for
1702 # that.
1703 s{^\.\./lib$}{lib} for @INC;
1704 chdir File::Spec->updir;
1705
1706 # And look in this directory and all its subdirectories
f2317e57 1707 find( {wanted => \&is_pod_file, no_chdir => 1}, '.');
16384ac1
KW
1708
1709 # Add ourselves to the test
b3fdb838 1710 push @files, "t/porting/podcheck.t";
16384ac1
KW
1711}
1712
1713# Now we know how many tests there will be.
1714plan (tests => scalar @files) if ! $regen;
1715
1716
c80f3fcd
A
1717# Sort file names so we get consistent results, and to put cpan last,
1718# preceded by the ones that we don't generally parse. This is because both
1719# these classes are generally parsed only if there is a link to the interior
1720# of them, and we have to parse all others first to guarantee that they don't
1721# have such a link. 'lib' files come just before these, as some of these are
1722# duplicates of others. We already have figured this out when gathering the
1723# data as a special case for all such files, but this, while unnecessary,
1724# puts the derived file last in the output. 'readme' files come before those,
1725# as those also could be duplicates of others, which are considered the
1726# primary ones. These currently aren't figured out when gathering data, so
1727# are done here.
1728@files = sort { if ($a =~ /^cpan/) {
1729 return 1 if $b !~ /^cpan/;
1730 return lc $a cmp lc $b;
1731 }
1732 elsif ($b =~ /^cpan/) {
1733 return -1;
1734 }
1735 elsif ($a =~ /$only_for_interior_links_re/) {
1736 return 1 if $b !~ /$only_for_interior_links_re/;
1737 return lc $a cmp lc $b;
1738 }
1739 elsif ($b =~ /$only_for_interior_links_re/) {
1740 return -1;
1741 }
1742 elsif ($a =~ /^lib/) {
1743 return 1 if $b !~ /^lib/;
1744 return lc $a cmp lc $b;
1745 }
1746 elsif ($b =~ /^lib/) {
1747 return -1;
1748 } elsif ($a =~ /\breadme\b/i) {
1749 return 1 if $b !~ /\breadme\b/i;
1750 return lc $a cmp lc $b;
1751 }
1752 elsif ($b =~ /\breadme\b/i) {
1753 return -1;
1754 }
1755 else {
1756 return lc $a cmp lc $b;
1757 }
1758 }
1759 @files;
16384ac1
KW
1760
1761# Now go through all the files and parse them
c66a5b89 1762FILE:
16384ac1
KW
1763foreach my $filename (@files) {
1764 my $parsed = 0;
1765 note("parsing $filename") if DEBUG;
1766
1767 # We may have already figured out some things in the process of generating
8505a15d 1768 # the file list. If so, we have a $checker object already. But if not,
16384ac1
KW
1769 # generate one now.
1770 my $checker = $filename_to_checker{$filename};
1771 if (! $checker) {
1772 $checker = My::Pod::Checker->new($filename);
1773 $filename_to_checker{$filename} = $checker;
1774 }
1775
1776 # We have set the name in the checker object if there is a possibility
1777 # that no further parsing is necessary, but otherwise do the parsing now.
1778 if (! $checker->name) {
48b96b3d
KW
1779 if (! $checker->parse_from_file($filename, undef)) {
1780 $checker->set_skip("$filename is transitory");
1781 next FILE;
1782 }
16384ac1 1783 $parsed = 1;
48b96b3d 1784
16384ac1
KW
1785 }
1786
1787 if ($checker->num_errors() < 0) { # Returns negative if not a pod
1788 $checker->set_skip("$filename is not a pod");
1789 }
1790 else {
1791
1792 # Here, is a pod. See if it is one that has already been tested,
1793 # or should be tested under another directory. Use either its NAME
1794 # if it has one, or a checksum if not.
1795 my $name = $checker->name;
1796 my $id;
1797
1798 if ($name) {
1799 $id = $name;
1800 }
1801 else {
1802 my $digest = Digest->new($digest_type);
84d2ce66
KW
1803 my $contents = extract_pod($filename);
1804
1805 # If the return is undef, it means that $filename was a transitory
1806 # file; skip it.
1807 next FILE unless defined $contents;
1808 $digest->add($contents);
16384ac1
KW
1809 $id = $digest->digest;
1810 }
1811
1812 # If there is a match for this pod with something that we've already
1813 # processed, don't process it, and output why.
1814 my $prior_checker;
1815 if (defined ($prior_checker = $id_to_checker{$id})
1816 && $prior_checker != $checker) # Could have defined the checker
1817 # earlier without pursuing it
1818 {
1819
1820 # If the pods are identical, then it's just a copy, and isn't an
1821 # error. First use the checksums we have already computed to see
1822 # if the entire files are identical, which means that the pods are
1823 # identical too.
1824 my $prior_filename = $prior_checker->get_filename;
1825 my $same = (! $name
1826 || ($digests{$prior_filename}
1827 && $digests{$filename}
1828 && $digests{$prior_filename} eq $digests{$filename}));
1829
1830 # If they differ, it could be that the files differ for some
1831 # reason, but the pods they contain are identical. Extract the
1832 # pods and do the comparisons on just those.
1833 if (! $same && $name) {
84d2ce66
KW
1834 my $contents = extract_pod($filename);
1835
1836 # If return is <undef>, it means that $filename no longer
1837 # exists. This means it was a transitory file, and should not
1838 # be tested.
1839 next FILE unless defined $contents;
1840
1841 my $prior_contents = extract_pod($prior_filename);
1842
1843 # If return is <undef>, it means that $prior_filename no
1844 # longer exists. This means it was a transitory file, and
1845 # should not have been tested, but we already did process it.
1846 # What we should do now is to back-out its records, and
1847 # process $filename in its stead. But backing out is not so
1848 # simple, and so I'm (khw) skipping that unless and until
1849 # experience shows that it is needed. We do go process
1850 # $filename, and there are potential false positive conflicts
1851 # with the transitory $prior_contents, and rerunning the test
1852 # should cause it to succeed.
1853 goto process_this_pod unless defined $prior_contents;
1854
1855 $same = $prior_contents eq $contents;
16384ac1
KW
1856 }
1857
1310f67f 1858 use File::Basename 'basename';
16384ac1
KW
1859 if ($same) {
1860 $checker->set_skip("The pod of $filename is a duplicate of "
1861 . "the pod for $prior_filename");
1862 } elsif ($prior_filename =~ /\breadme\b/i) {
1863 $checker->set_skip("$prior_filename is a README apparently for $filename");
1864 } elsif ($filename =~ /\breadme\b/i) {
1865 $checker->set_skip("$filename is a README apparently for $prior_filename");
44b8cd40
KW
1866 } elsif (! $do_upstream_cpan
1867 && $filename =~ /^cpan/
1868 && $prior_filename =~ /^cpan/)
1869 {
ef906498 1870 $checker->set_skip("CPAN is upstream for $filename");
f5bfcfd8
DG
1871 } elsif ( $filename =~ /^utils/ or $prior_filename =~ /^utils/ ) {
1872 $checker->set_skip("$filename copy is in utils/");
1310f67f
FC
1873 } elsif ($prior_filename =~ /^(?:cpan|ext|dist)/
1874 && $filename !~ /^(?:cpan|ext|dist)/
1875 && basename($prior_filename) eq basename($filename))
1876 {
1877 $checker->set_skip("$filename: Need to run make?");
16384ac1
KW
1878 } else { # Here have two pods with identical names that differ
1879 $prior_checker->poderror(
1880 { -msg => $duplicate_name,
1881 -line => "???",
1882 parameter => "'$filename' also has NAME '$name'"
1883 });
1884 $checker->poderror(
1885 { -msg => $duplicate_name,
1886 -line => "???",
1887 parameter => "'$prior_filename' also has NAME '$name'"
1888 });
1889
1890 # Changing the names helps later.
1891 $prior_checker->name("$name version arbitrarily numbered 1");
1892 $checker->name("$name version arbitrarily numbered 2");
1893 }
1894
1895 # In any event, don't process this pod that has the same name as
1896 # another.
c66a5b89 1897 next FILE;
16384ac1
KW
1898 }
1899
84d2ce66
KW
1900 process_this_pod:
1901
16384ac1
KW
1902 # A unique pod.
1903 $id_to_checker{$id} = $checker;
1904
1905 my $parsed_for_links = ", but parsed for its interior links";
1906 if ((! $do_upstream_cpan && $filename =~ /^cpan/)
1907 || $filename =~ $only_for_interior_links_re)
1908 {
1909 if ($filename =~ /^cpan/) {
1910 $checker->set_skip("CPAN is upstream for $filename");
1911 }
35c86e19
KW
1912 elsif ($filename =~ /perl\d+delta/) {
1913 if (! $do_deltas) {
1914 $checker->set_skip("$filename is a stable perldelta");
1915 }
16384ac1 1916 }
0496e0bb
KW
1917 elsif ($filename =~ /perltoc/) {
1918 $checker->set_skip("$filename dependent on component pods");
1919 }
16384ac1
KW
1920 else {
1921 croak("Unexpected file '$filename' encountered that has parsing for interior-linking only");
1922 }
1923
1924 if ($name && $has_referred_to_node{$name}) {
1925 $checker->set_skip($checker->get_skip() . $parsed_for_links);
1926 }
1927 }
1928
1929 # Need a name in order to process it, because not meaningful
1930 # otherwise, and also can't test links to this without a name.
1931 if (!defined $name) {
1932 $checker->poderror( { -msg => $no_name,
1933 -line => '???'
1934 });
c66a5b89 1935 next FILE;
16384ac1
KW
1936 }
1937
1938 # For skipped files, just get its NAME
1939 my $skip;
1940 if (($skip = $checker->get_skip()) && $skip !~ /$parsed_for_links/)
1941 {
1942 $checker->node($name) if $name;
1943 }
48b96b3d
KW
1944 elsif (! $parsed) {
1945 if (! $checker->parse_from_file($filename, undef)) {
1946 $checker->set_skip("$filename is transitory");
1947 next FILE;
1948 }
16384ac1
KW
1949 }
1950
1951 # Go through everything in the file that could be an anchor that
1952 # could be a link target. Count how many there are of the same name.
1953 foreach my $node ($checker->linkable_nodes) {
c66a5b89 1954 next FILE if ! $node; # Can be empty is like '=item *'
d25f767e 1955 $nodes{$name}{$node}++;
16384ac1
KW
1956
1957 # Experiments have shown that cpan search can figure out the
1958 # target of a link even if the exact wording is incorrect, as long
1959 # as the first word is. This happens frequently in perlfunc.pod,
1960 # where the link will be just to the function, but the target
1961 # entry also includes parameters to the function.
1962 my $first_word = $node;
1963 if ($first_word =~ s/^(\S+)\s+\S.*/$1/) {
1964 $nodes_first_word{$name}{$first_word} = $node;
1965 }
1966 }
1967 $filename_to_pod{$filename} = $name;
1968 }
1969}
1970
1971# Here, all files have been parsed, and all links and link targets are stored.
1972# Now go through the files again and see which don't have matches.
1973if (! $has_input_files) {
1974 foreach my $filename (@files) {
1975 next if $filename_to_checker{$filename}->get_skip;
c429f8ed 1976
16384ac1 1977 my $checker = $filename_to_checker{$filename};
c429f8ed
KW
1978 foreach my $link ($checker->hyperlinks()) {
1979 my $linked_to_page = $link->page;
16384ac1
KW
1980 next unless $linked_to_page; # intra-file checks are handled by std
1981 # Pod::Checker
c429f8ed
KW
1982 # Currently, we assume all external links are valid
1983 next if $link->type eq 'url';
16384ac1
KW
1984
1985 # Initialize the potential message.
1986 my %problem = ( -msg => $broken_link,
c429f8ed 1987 -line => $link->line,
16384ac1
KW
1988 parameter => "to \"$linked_to_page\"",
1989 );
1990
1991 # See if we have found the linked-to_file in our parse
1992 if (exists $nodes{$linked_to_page}) {
c429f8ed 1993 my $node = $link->node;
16384ac1
KW
1994
1995 # If link is only to the page-level, already have it
1996 next if ! $node;
1997
16384ac1
KW
1998 # If link is to a node that exists in the file, is ok
1999 if ($nodes{$linked_to_page}{$node}) {
2000
2001 # But if the page has multiple targets with the same name,
2002 # it's ambiguous which one this should be to.
2003 if ($nodes{$linked_to_page}{$node} > 1) {
2004 $problem{-msg} = $multiple_targets;
2005 $problem{parameter} = "in $linked_to_page that $node could be pointing to";
2006 $checker->poderror(\%problem);
2007 }
2008 } elsif (! $nodes_first_word{$linked_to_page}{$node}) {
2009
2010 # Here the link target was not found, either exactly or to
2011 # the first word. Is an error.
2012 $problem{parameter} =~ s,"$,/$node",;
2013 $checker->poderror(\%problem);
2014 }
2015
2016 } # Linked-to-file not in parse; maybe is in exception list
c429f8ed 2017 elsif (! exists $valid_modules{$link->page}) {
16384ac1
KW
2018
2019 # Here, is a link to a target that we can't find. Check if
2020 # there is an internal link on the page with the target name.
2021 # If so, it could be that they just forgot the initial '/'
1c01047d
KW
2022 # But perldelta is handled specially: only do this if the
2023 # broken link isn't one of the known bad ones (that are
2024 # placemarkers and should be removed for the final)
2025 my $NAME = $filename_to_pod{$filename};
2026 if (! defined $NAME) {
2027 $checker->poderror(\%problem);
2028 }
02987562 2029 else {
1c01047d
KW
2030 if ($nodes{$NAME}{$linked_to_page}) {
2031 $problem{-msg} = $broken_internal_link;
2032 }
2033 $checker->poderror(\%problem);
16384ac1 2034 }
16384ac1
KW
2035 }
2036 }
2037 }
2038}
2039
2040# If regenerating the data file, start with the modules for which we don't
de37f83f
KW
2041# check targets. If you change the sort order, you need to run --regen before
2042# committing so that future commits that do run regen don't show irrelevant
2043# changes.
16384ac1
KW
2044if ($regen) {
2045 foreach (sort { lc $a cmp lc $b } keys %valid_modules) {
2046 my_safer_print($copy_fh, $_, "\n");
2047 }
2048}
2049
2050# Now ready to output the messages.
2051foreach my $filename (@files) {
b3fdb838 2052 my $canonical = canonicalize($filename);
16384ac1
KW
2053 SKIP: {
2054 my $skip = $filename_to_checker{$filename}->get_skip // "";
2055
2056 if ($regen) {
2057 foreach my $message ( sort keys %{$problems{$filename}}) {
2058 my $count;
2059
2060 # Preserve a negative setting.
b3fdb838
KW
2061 if ($known_problems{$canonical}{$message}
2062 && $known_problems{$canonical}{$message} < 0)
16384ac1 2063 {
b3fdb838 2064 $count = $known_problems{$canonical}{$message};
16384ac1
KW
2065 }
2066 else {
2067 $count = @{$problems{$filename}{$message}};
2068 }
24df3027 2069 my_safer_print($copy_fh, $canonical . "\t$message\t$count\n");
16384ac1
KW
2070 }
2071 next;
2072 }
2073
2074 skip($skip, 1) if $skip;
2075 my @diagnostics;
86098e45 2076 my $thankful_diagnostics = 0;
16384ac1
KW
2077 my $indent = ' ';
2078
16384ac1
KW
2079 my $total_known = 0;
2080 foreach my $message ( sort keys %{$problems{$filename}}) {
b3fdb838
KW
2081 $known_problems{$canonical}{$message} = 0
2082 if ! $known_problems{$canonical}{$message};
16384ac1
KW
2083 my $diagnostic = "";
2084 my $problem_count = scalar @{$problems{$filename}{$message}};
2085 $total_known += $problem_count;
b3fdb838
KW
2086 next if $known_problems{$canonical}{$message} < 0;
2087 if ($problem_count > $known_problems{$canonical}{$message}) {
16384ac1
KW
2088
2089 # Here we are about to output all the messages for this type,
2090 # subtract back this number we previously added in.
2091 $total_known -= $problem_count;
2092
b2bf5aea 2093 $diagnostic .= $indent . qq{"$message"};
16384ac1 2094 if ($problem_count > 2) {
b2bf5aea
DM
2095 $diagnostic .= " ($problem_count occurrences,"
2096 . " expected $known_problems{$canonical}{$message})";
16384ac1
KW
2097 }
2098 foreach my $problem (@{$problems{$filename}{$message}}) {
2099 $diagnostic .= " " if $problem_count == 1;
2100 $diagnostic .= "\n$indent$indent";
2101 $diagnostic .= "$problem->{parameter}" if $problem->{parameter};
4f38b511
FC
2102 $diagnostic .= " near line $problem->{-line} of "
2103 . $filename;
16384ac1
KW
2104 $diagnostic .= " $problem->{comment}" if $problem->{comment};
2105 }
2106 $diagnostic .= "\n";
2107 $files_with_unknown_issues{$filename} = 1;
b3fdb838
KW
2108 } elsif ($problem_count < $known_problems{$canonical}{$message}) {
2109 $diagnostic = output_thanks($filename, $known_problems{$canonical}{$message}, $problem_count, $message);
86098e45 2110 $thankful_diagnostics++;
16384ac1
KW
2111 }
2112 push @diagnostics, $diagnostic if $diagnostic;
2113 }
2114
09ea063a
KW
2115 # The above loop has output messages where there are current potential
2116 # issues. But it misses where there were some that have been entirely
2117 # fixed. For those, we need to look through the old issues
b3fdb838 2118 foreach my $message ( sort keys %{$known_problems{$canonical}}) {
09ea063a 2119 next if $problems{$filename}{$message};
b3fdb838
KW
2120 next if ! $known_problems{$canonical}{$message};
2121 next if $known_problems{$canonical}{$message} < 0; # Preserve negs
beabdcb7 2122
0cbb9de5
BG
2123 next if !$pedantic and $message =~
2124 /^(?:\Q$line_length\E|\Q$C_not_linked\E|\Q$C_with_slash\E)/;
beabdcb7 2125
b3fdb838 2126 my $diagnostic = output_thanks($filename, $known_problems{$canonical}{$message}, 0, $message);
09ea063a 2127 push @diagnostics, $diagnostic if $diagnostic;
86098e45 2128 $thankful_diagnostics++ if $diagnostic;
09ea063a
KW
2129 }
2130
16384ac1
KW
2131 my $output = "POD of $filename";
2132 $output .= ", excluding $total_known not shown known potential problems"
2133 if $total_known;
86098e45 2134 if (@diagnostics && @diagnostics == $thankful_diagnostics) {
c549afe0
FC
2135 # Output fixed issues as passing to-do tests, so they do not
2136 # cause failures, but t/harness still flags them.
2137 $output .= " # TODO"
2138 }
86098e45 2139 ok(@diagnostics == $thankful_diagnostics, $output);
16384ac1 2140 if (@diagnostics) {
c8fbf4a0 2141 diag(join "", @diagnostics,
477100f8 2142 "See end of this test output for your options on silencing this");
16384ac1 2143 }
da33abaf
KW
2144
2145 delete $known_problems{$canonical};
16384ac1
KW
2146 }
2147}
2148
ac93cf5d 2149if (! $regen
b0248dbf 2150 && ! ok (keys %known_problems == 0, "The known problems database ($data_dir/known_pod_issues.dat) includes no references to non-existent files"))
ac93cf5d 2151{
da33abaf
KW
2152 note("The following files were not found: "
2153 . join ", ", keys %known_problems);
2154 note("They will automatically be removed from the db the next time");
2155 note(" cd t; ./perl -I../lib porting/podcheck.t --regen");
2156 note("is run");
2157}
2158
16384ac1
KW
2159my $how_to = <<EOF;
2160 run this test script by hand, using the following formula (on
2161 Un*x-like machines):
2162 cd t
2163 ./perl -I../lib porting/podcheck.t --regen
2164EOF
2165
2166if (%files_with_unknown_issues) {
2167 my $were_count_files = scalar keys %files_with_unknown_issues;
2168 $were_count_files = ($were_count_files == 1)
2169 ? "was $were_count_files file"
2170 : "were $were_count_files files";
2171 my $message = <<EOF;
2172
c8fbf4a0 2173HOW TO GET ${\__FILE__} TO PASS
16384ac1 2174
477100f8 2175There $were_count_files that had new potential problems identified.
bc20e6b8 2176Some of them may be real, and some of them may be false positives because
968d3762
KW
2177this program isn't as smart as it likes to think it is. You can teach this
2178program to ignore the issues it has identified, and hence pass, by doing the
477100f8 2179following:
16384ac1 2180
477100f8
KW
21811) If a problem is about a link to an unknown module or man page that
2182 you know exists, re-run the command something like:
2183 ./perl -I../lib porting/podcheck.t --add_link MODULE man_page ...
2184 (MODULEs should look like Foo::Bar, and man_pages should look like
2185 bar(3c); don't do this for a module or man page that you aren't sure
2186 about; instead treat as another type of issue and follow the
2187 instructions below.)
16384ac1
KW
2188
21892) For other issues, decide if each should be fixed now or not. Fix the
2190 ones you decided to, and rerun this test to verify that the fixes
2191 worked.
2192
968d3762
KW
21933) If there remain false positive or problems that you don't plan to fix right
2194 now,
16384ac1 2195$how_to
477100f8
KW
2196 That should cause all current potential problems to be accepted by
2197 the program, so that the next time it runs, they won't be flagged.
16384ac1
KW
2198EOF
2199 if (%files_with_fixes) {
2200 $message .= " This step will also take care of the files that have fixes in them\n";
2201 }
2202
2203 $message .= <<EOF;
2204 For a few files, such as perltoc, certain issues will always be
2205 expected, and more of the same will be added over time. For those,
2206 before you do the regen, you can edit
2207 $known_issues
2208 and find the entry for the module's file and specific error message,
2209 and change the count of known potential problems to -1.
2210EOF
2211
c8fbf4a0 2212 diag($message);
16384ac1 2213} elsif (%files_with_fixes) {
c8fbf4a0 2214 diag(<<EOF
16384ac1
KW
2215To teach this test script that the potential problems have been fixed,
2216$how_to
2217EOF
2218 );
2219}
2220
2221if ($regen) {
2222 chdir $original_dir || die "Can't change directories to $original_dir";
2223 close_and_rename($copy_fh);
2224}
c429f8ed
KW
2225
22261;