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