Diff of /inc/Pod/Checker.pm [000000] .. [e362d3]  Maximize  Restore

  Switch to unified view

a b/inc/Pod/Checker.pm
1
#############################################################################
2
# Pod/Checker.pm -- check pod documents for syntax errors
3
#
4
# Added =ff and O<> to Checker.pm to make bookchecker program
5
# work for PDL::Book pod files.  Chris Marshall, 22-Jan-2012
6
#
7
# Copyright (C) 1994-2000 by Bradford Appleton. All rights reserved.
8
# This file is part of "PodParser". PodParser is free software;
9
# you can redistribute it and/or modify it under the same terms
10
# as Perl itself.
11
#############################################################################
12
13
package Pod::Checker;
14
use strict;
15
16
use vars qw($VERSION @ISA @EXPORT %VALID_COMMANDS %VALID_SEQUENCES);
17
$VERSION = '1.45';  ## Current version of this package
18
require  5.005;    ## requires this Perl version or later
19
20
use Pod::ParseUtils; ## for hyperlinks and lists
21
22
=head1 NAME
23
24
Pod::Checker, podchecker() - check pod documents for syntax errors
25
26
=head1 SYNOPSIS
27
28
  use Pod::Checker;
29
30
  $syntax_okay = podchecker($filepath, $outputpath, %options);
31
32
  my $checker = new Pod::Checker %options;
33
  $checker->parse_from_file($filepath, \*STDERR);
34
35
=head1 OPTIONS/ARGUMENTS
36
37
C<$filepath> is the input POD to read and C<$outputpath> is
38
where to write POD syntax error messages. Either argument may be a scalar
39
indicating a file-path, or else a reference to an open filehandle.
40
If unspecified, the input-file it defaults to C<\*STDIN>, and
41
the output-file defaults to C<\*STDERR>.
42
43
=head2 podchecker()
44
45
This function can take a hash of options:
46
47
=over 4
48
49
=item B<-warnings> =E<gt> I<val>
50
51
Turn warnings on/off. I<val> is usually 1 for on, but higher values
52
trigger additional warnings. See L<"Warnings">.
53
54
=back
55
56
=head1 DESCRIPTION
57
58
B<podchecker> will perform syntax checking of Perl5 POD format documentation.
59
60
Curious/ambitious users are welcome to propose additional features they wish
61
to see in B<Pod::Checker> and B<podchecker> and verify that the checks are
62
consistent with L<perlpod>.
63
64
The following checks are currently performed:
65
66
=over 4
67
68
=item *
69
70
Unknown '=xxxx' commands, unknown 'XE<lt>...E<gt>' interior-sequences,
71
and unterminated interior sequences.
72
73
=item *
74
75
Check for proper balancing of C<=begin> and C<=end>. The contents of such
76
a block are generally ignored, i.e. no syntax checks are performed.
77
78
=item *
79
80
Check for proper nesting and balancing of C<=over>, C<=item> and C<=back>.
81
82
=item *
83
84
Check for same nested interior-sequences (e.g.
85
C<LE<lt>...LE<lt>...E<gt>...E<gt>>).
86
87
=item *
88
89
Check for malformed or non-existing entities C<EE<lt>...E<gt>>.
90
91
=item *
92
93
Check for correct syntax of hyperlinks C<LE<lt>...E<gt>>. See L<perlpod>
94
for details.
95
96
=item *
97
98
Check for unresolved document-internal links. This check may also reveal
99
misspelled links that seem to be internal links but should be links
100
to something else.
101
102
=back
103
104
=head1 DIAGNOSTICS
105
106
=head2 Errors
107
108
=over 4
109
110
=item * empty =headn
111
112
A heading (C<=head1> or C<=head2>) without any text? That ain't no
113
heading!
114
115
=item * =over on line I<N> without closing =back
116
117
The C<=over> command does not have a corresponding C<=back> before the
118
next heading (C<=head1> or C<=head2>) or the end of the file.
119
120
=item * =item without previous =over
121
122
=item * =back without previous =over
123
124
An C<=item> or C<=back> command has been found outside a
125
C<=over>/C<=back> block.
126
127
=item * No argument for =begin
128
129
A C<=begin> command was found that is not followed by the formatter
130
specification.
131
132
=item * =end without =begin
133
134
A standalone C<=end> command was found.
135
136
=item * Nested =begin's
137
138
There were at least two consecutive C<=begin> commands without
139
the corresponding C<=end>. Only one C<=begin> may be active at
140
a time.
141
142
=item * =for without formatter specification
143
144
There is no specification of the formatter after the C<=for> command.
145
146
=item * unresolved internal link I<NAME>
147
148
The given link to I<NAME> does not have a matching node in the current
149
POD. This also happened when a single word node name is not enclosed in
150
C<"">.
151
152
=item * Unknown command "I<CMD>"
153
154
An invalid POD command has been found. Valid are C<=head1>, C<=head2>,
155
C<=head3>, C<=head4>, C<=over>, C<=item>, C<=back>, C<=begin>, C<=end>,
156
C<=for>, C<=pod>, C<=cut>
157
158
=item * Unknown interior-sequence "I<SEQ>"
159
160
An invalid markup command has been encountered. Valid are:
161
C<BE<lt>E<gt>>, C<CE<lt>E<gt>>, C<EE<lt>E<gt>>, C<FE<lt>E<gt>>,
162
C<IE<lt>E<gt>>, C<LE<lt>E<gt>>, C<SE<lt>E<gt>>, C<XE<lt>E<gt>>,
163
C<ZE<lt>E<gt>>
164
165
=item * nested commands I<CMD>E<lt>...I<CMD>E<lt>...E<gt>...E<gt>
166
167
Two nested identical markup commands have been found. Generally this
168
does not make sense.
169
170
=item * garbled entity I<STRING>
171
172
The I<STRING> found cannot be interpreted as a character entity.
173
174
=item * Entity number out of range
175
176
An entity specified by number (dec, hex, oct) is out of range (1-255).
177
178
=item * malformed link LE<lt>E<gt>
179
180
The link found cannot be parsed because it does not conform to the
181
syntax described in L<perlpod>.
182
183
=item * nonempty ZE<lt>E<gt>
184
185
The C<ZE<lt>E<gt>> sequence is supposed to be empty.
186
187
=item * empty XE<lt>E<gt>
188
189
The index entry specified contains nothing but whitespace.
190
191
=item * Spurious text after =pod / =cut
192
193
The commands C<=pod> and C<=cut> do not take any arguments.
194
195
=item * Spurious character(s) after =back
196
197
The C<=back> command does not take any arguments.
198
199
=back
200
201
=head2 Warnings
202
203
These may not necessarily cause trouble, but indicate mediocre style.
204
205
=over 4
206
207
=item * multiple occurrence of link target I<name>
208
209
The POD file has some C<=item> and/or C<=head> commands that have
210
the same text. Potential hyperlinks to such a text cannot be unique then.
211
This warning is printed only with warning level greater than one.
212
213
=item * line containing nothing but whitespace in paragraph
214
215
There is some whitespace on a seemingly empty line. POD is very sensitive
216
to such things, so this is flagged. B<vi> users switch on the B<list>
217
option to avoid this problem.
218
219
=begin _disabled_
220
221
=item * file does not start with =head
222
223
The file starts with a different POD directive than head.
224
This is most probably something you do not want.
225
226
=end _disabled_
227
228
=item * previous =item has no contents
229
230
There is a list C<=item> right above the flagged line that has no
231
text contents. You probably want to delete empty items.
232
233
=item * preceding non-item paragraph(s)
234
235
A list introduced by C<=over> starts with a text or verbatim paragraph,
236
but continues with C<=item>s. Move the non-item paragraph out of the
237
C<=over>/C<=back> block.
238
239
=item * =item type mismatch (I<one> vs. I<two>)
240
241
A list started with e.g. a bullet-like C<=item> and continued with a
242
numbered one. This is obviously inconsistent. For most translators the
243
type of the I<first> C<=item> determines the type of the list.
244
245
=item * I<N> unescaped C<E<lt>E<gt>> in paragraph
246
247
Angle brackets not written as C<E<lt>ltE<gt>> and C<E<lt>gtE<gt>>
248
can potentially cause errors as they could be misinterpreted as
249
markup commands. This is only printed when the -warnings level is
250
greater than 1.
251
252
=item * Unknown entity
253
254
A character entity was found that does not belong to the standard
255
ISO set or the POD specials C<verbar> and C<sol>.
256
257
=item * No items in =over
258
259
The list opened with C<=over> does not contain any items.
260
261
=item * No argument for =item
262
263
C<=item> without any parameters is deprecated. It should either be followed
264
by C<*> to indicate an unordered list, by a number (optionally followed
265
by a dot) to indicate an ordered (numbered) list or simple text for a
266
definition list.
267
268
=item * empty section in previous paragraph
269
270
The previous section (introduced by a C<=head> command) does not contain
271
any text. This usually indicates that something is missing. Note: A
272
C<=head1> followed immediately by C<=head2> does not trigger this warning.
273
274
=item * Verbatim paragraph in NAME section
275
276
The NAME section (C<=head1 NAME>) should consist of a single paragraph
277
with the script/module name, followed by a dash `-' and a very short
278
description of what the thing is good for.
279
280
=item * =headI<n> without preceding higher level
281
282
For example if there is a C<=head2> in the POD file prior to a
283
C<=head1>.
284
285
=back
286
287
=head2 Hyperlinks
288
289
There are some warnings with respect to malformed hyperlinks:
290
291
=over 4
292
293
=item * ignoring leading/trailing whitespace in link
294
295
There is whitespace at the beginning or the end of the contents of
296
LE<lt>...E<gt>.
297
298
=item * (section) in '$page' deprecated
299
300
There is a section detected in the page name of LE<lt>...E<gt>, e.g.
301
C<LE<lt>passwd(2)E<gt>>. POD hyperlinks may point to POD documents only.
302
Please write C<CE<lt>passwd(2)E<gt>> instead. Some formatters are able
303
to expand this to appropriate code. For links to (builtin) functions,
304
please say C<LE<lt>perlfunc/mkdirE<gt>>, without ().
305
306
=item * alternative text/node '%s' contains non-escaped | or /
307
308
The characters C<|> and C</> are special in the LE<lt>...E<gt> context.
309
Although the hyperlink parser does its best to determine which "/" is
310
text and which is a delimiter in case of doubt, one ought to escape
311
these literal characters like this:
312
313
  /     E<sol>
314
  |     E<verbar>
315
316
=back
317
318
=head1 RETURN VALUE
319
320
B<podchecker> returns the number of POD syntax errors found or -1 if
321
there were no POD commands at all found in the file.
322
323
=head1 EXAMPLES
324
325
See L</SYNOPSIS>
326
327
=head1 INTERFACE
328
329
While checking, this module collects document properties, e.g. the nodes
330
for hyperlinks (C<=headX>, C<=item>) and index entries (C<XE<lt>E<gt>>).
331
POD translators can use this feature to syntax-check and get the nodes in
332
a first pass before actually starting to convert. This is expensive in terms
333
of execution time, but allows for very robust conversions.
334
335
Since PodParser-1.24 the B<Pod::Checker> module uses only the B<poderror>
336
method to print errors and warnings. The summary output (e.g.
337
"Pod syntax OK") has been dropped from the module and has been included in
338
B<podchecker> (the script). This allows users of B<Pod::Checker> to
339
control completely the output behavior. Users of B<podchecker> (the script)
340
get the well-known behavior.
341
342
=cut
343
344
#############################################################################
345
346
#use diagnostics;
347
use Carp qw(croak);
348
use Exporter;
349
use Pod::Parser;
350
351
@ISA = qw(Pod::Parser);
352
@EXPORT = qw(&podchecker);
353
354
my %VALID_COMMANDS = (
355
    'pod'    =>  1,
356
    'cut'    =>  1,
357
    'head1'  =>  1,
358
    'head2'  =>  1,
359
    'head3'  =>  1,
360
    'head4'  =>  1,
361
    'over'   =>  1,
362
    'back'   =>  1,
363
    'item'   =>  1,
364
    'for'    =>  1,
365
    'begin'  =>  1,
366
    'end'    =>  1,
367
    'encoding' =>  1,
368
    'ff'       =>  1,  # from pod2pdf
369
);
370
371
my %VALID_SEQUENCES = (
372
    'I'  =>  1,
373
    'B'  =>  1,
374
    'S'  =>  1,
375
    'C'  =>  1,
376
    'L'  =>  1,
377
    'F'  =>  1,
378
    'X'  =>  1,
379
    'Z'  =>  1,
380
    'E'  =>  1,
381
    'O'  =>  1,  # from pod2pdf
382
);
383
384
# stolen from HTML::Entities
385
my %ENTITIES = (
386
 # Some normal chars that have special meaning in SGML context
387
 amp    => '&',  # ampersand
388
'gt'    => '>',  # greater than
389
'lt'    => '<',  # less than
390
 quot   => '"',  # double quote
391
392
 # PUBLIC ISO 8879-1986//ENTITIES Added Latin 1//EN//HTML
393
 AElig  => 'Ć',  # capital AE diphthong (ligature)
394
 Aacute => 'Á',  # capital A, acute accent
395
 Acirc  => 'Â',  # capital A, circumflex accent
396
 Agrave => 'Ŕ',  # capital A, grave accent
397
 Aring  => 'Ĺ',  # capital A, ring
398
 Atilde => 'Ă',  # capital A, tilde
399
 Auml   => 'Ä',  # capital A, dieresis or umlaut mark
400
 Ccedil => 'Ç',  # capital C, cedilla
401
 ETH    => 'Đ',  # capital Eth, Icelandic
402
 Eacute => 'É',  # capital E, acute accent
403
 Ecirc  => 'Ę',  # capital E, circumflex accent
404
 Egrave => 'Č',  # capital E, grave accent
405
 Euml   => 'Ë',  # capital E, dieresis or umlaut mark
406
 Iacute => 'Í',  # capital I, acute accent
407
 Icirc  => 'Î',  # capital I, circumflex accent
408
 Igrave => 'Ě',  # capital I, grave accent
409
 Iuml   => 'Ď',  # capital I, dieresis or umlaut mark
410
 Ntilde => 'Ń',  # capital N, tilde
411
 Oacute => 'Ó',  # capital O, acute accent
412
 Ocirc  => 'Ô',  # capital O, circumflex accent
413
 Ograve => 'Ň',  # capital O, grave accent
414
 Oslash => 'Ř',  # capital O, slash
415
 Otilde => 'Ő',  # capital O, tilde
416
 Ouml   => 'Ö',  # capital O, dieresis or umlaut mark
417
 THORN  => 'Ţ',  # capital THORN, Icelandic
418
 Uacute => 'Ú',  # capital U, acute accent
419
 Ucirc  => 'Ű',  # capital U, circumflex accent
420
 Ugrave => 'Ů',  # capital U, grave accent
421
 Uuml   => 'Ü',  # capital U, dieresis or umlaut mark
422
 Yacute => 'Ý',  # capital Y, acute accent
423
 aacute => 'á',  # small a, acute accent
424
 acirc  => 'â',  # small a, circumflex accent
425
 aelig  => 'ć',  # small ae diphthong (ligature)
426
 agrave => 'ŕ',  # small a, grave accent
427
 aring  => 'ĺ',  # small a, ring
428
 atilde => 'ă',  # small a, tilde
429
 auml   => 'ä',  # small a, dieresis or umlaut mark
430
 ccedil => 'ç',  # small c, cedilla
431
 eacute => 'é',  # small e, acute accent
432
 ecirc  => 'ę',  # small e, circumflex accent
433
 egrave => 'č',  # small e, grave accent
434
 eth    => 'đ',  # small eth, Icelandic
435
 euml   => 'ë',  # small e, dieresis or umlaut mark
436
 iacute => 'í',  # small i, acute accent
437
 icirc  => 'î',  # small i, circumflex accent
438
 igrave => 'ě',  # small i, grave accent
439
 iuml   => 'ď',  # small i, dieresis or umlaut mark
440
 ntilde => 'ń',  # small n, tilde
441
 oacute => 'ó',  # small o, acute accent
442
 ocirc  => 'ô',  # small o, circumflex accent
443
 ograve => 'ň',  # small o, grave accent
444
 oslash => 'ř',  # small o, slash
445
 otilde => 'ő',  # small o, tilde
446
 ouml   => 'ö',  # small o, dieresis or umlaut mark
447
 szlig  => 'ß',  # small sharp s, German (sz ligature)
448
 thorn  => 'ţ',  # small thorn, Icelandic
449
 uacute => 'ú',  # small u, acute accent
450
 ucirc  => 'ű',  # small u, circumflex accent
451
 ugrave => 'ů',  # small u, grave accent
452
 uuml   => 'ü',  # small u, dieresis or umlaut mark
453
 yacute => 'ý',  # small y, acute accent
454
 yuml   => '˙',  # small y, dieresis or umlaut mark
455
456
 # Some extra Latin 1 chars that are listed in the HTML3.2 draft (21-May-96)
457
 copy   => 'Š',  # copyright sign
458
 reg    => 'Ž',  # registered sign
459
 nbsp   => "\240", # non breaking space
460
461
 # Additional ISO-8859/1 entities listed in rfc1866 (section 14)
462
 iexcl  => 'Ą',
463
 cent   => '˘',
464
 pound  => 'Ł',
465
 curren => '¤',
466
 yen    => 'Ľ',
467
 brvbar => 'Ś',
468
 sect   => '§',
469
 uml    => '¨',
470
 ordf   => 'Ş',
471
 laquo  => 'Ť',
472
'not'   => 'Ź',    # not is a keyword in perl
473
 shy    => '­',
474
 macr   => 'Ż',
475
 deg    => '°',
476
 plusmn => 'ą',
477
 sup1   => 'š',
478
 sup2   => '˛',
479
 sup3   => 'ł',
480
 acute  => '´',
481
 micro  => 'ľ',
482
 para   => 'ś',
483
 middot => 'ˇ',
484
 cedil  => '¸',
485
 ordm   => 'ş',
486
 raquo  => 'ť',
487
 frac14 => 'ź',
488
 frac12 => '˝',
489
 frac34 => 'ž',
490
 iquest => 'ż',
491
'times' => '×',    # times is a keyword in perl
492
 divide => '÷',
493
494
# some POD special entities
495
 verbar => '|',
496
 sol => '/'
497
);
498
499
##---------------------------------------------------------------------------
500
501
##---------------------------------
502
## Function definitions begin here
503
##---------------------------------
504
505
sub podchecker {
506
    my ($infile, $outfile, %options) = @_;
507
    local $_;
508
509
    ## Set defaults
510
    $infile  ||= \*STDIN;
511
    $outfile ||= \*STDERR;
512
513
    ## Now create a pod checker
514
    my $checker = new Pod::Checker(%options);
515
516
    ## Now check the pod document for errors
517
    $checker->parse_from_file($infile, $outfile);
518
519
    ## Return the number of errors found
520
    return $checker->num_errors();
521
}
522
523
##---------------------------------------------------------------------------
524
525
##-------------------------------
526
## Method definitions begin here
527
##-------------------------------
528
529
##################################
530
531
=over 4
532
533
=item C<Pod::Checker-E<gt>new( %options )>
534
535
Return a reference to a new Pod::Checker object that inherits from
536
Pod::Parser and is used for calling the required methods later. The
537
following options are recognized:
538
539
C<-warnings =E<gt> num>
540
  Print warnings if C<num> is true. The higher the value of C<num>,
541
the more warnings are printed. Currently there are only levels 1 and 2.
542
543
C<-quiet =E<gt> num>
544
  If C<num> is true, do not print any errors/warnings. This is useful
545
when Pod::Checker is used to munge POD code into plain text from within
546
POD formatters.
547
548
=cut
549
550
## sub new {
551
##     my $this = shift;
552
##     my $class = ref($this) || $this;
553
##     my %params = @_;
554
##     my $self = {%params};
555
##     bless $self, $class;
556
##     $self->initialize();
557
##     return $self;
558
## }
559
560
sub initialize {
561
    my $self = shift;
562
    ## Initialize number of errors, and setup an error function to
563
    ## increment this number and then print to the designated output.
564
    $self->{_NUM_ERRORS} = 0;
565
    $self->{_NUM_WARNINGS} = 0;
566
    $self->{-quiet} ||= 0;
567
    # set the error handling subroutine
568
    $self->errorsub($self->{-quiet} ? sub { 1; } : 'poderror');
569
    $self->{_commands} = 0; # total number of POD commands encountered
570
    $self->{_list_stack} = []; # stack for nested lists
571
    $self->{_have_begin} = ''; # stores =begin
572
    $self->{_links} = []; # stack for internal hyperlinks
573
    $self->{_nodes} = []; # stack for =head/=item nodes
574
    $self->{_index} = []; # text in X<>
575
    # print warnings?
576
    $self->{-warnings} = 1 unless(defined $self->{-warnings});
577
    $self->{_current_head1} = ''; # the current =head1 block
578
    $self->parseopts(-process_cut_cmd => 1, -warnings => $self->{-warnings});
579
}
580
581
##################################
582
583
=item C<$checker-E<gt>poderror( @args )>
584
585
=item C<$checker-E<gt>poderror( {%opts}, @args )>
586
587
Internal method for printing errors and warnings. If no options are
588
given, simply prints "@_". The following options are recognized and used
589
to form the output:
590
591
  -msg
592
593
A message to print prior to C<@args>.
594
595
  -line
596
597
The line number the error occurred in.
598
599
  -file
600
601
The file (name) the error occurred in.
602
603
  -severity
604
605
The error level, should be 'WARNING' or 'ERROR'.
606
607
=cut
608
609
# Invoked as $self->poderror( @args ), or $self->poderror( {%opts}, @args )
610
sub poderror {
611
    my $self = shift;
612
    my %opts = (ref $_[0]) ? %{shift()} : ();
613
614
    ## Retrieve options
615
    chomp( my $msg  = ($opts{-msg} || '')."@_" );
616
    my $line = (exists $opts{-line}) ? " at line $opts{-line}" : '';
617
    my $file = (exists $opts{-file}) ? " in file $opts{-file}" : '';
618
    unless (exists $opts{-severity}) {
619
       ## See if can find severity in message prefix
620
       $opts{-severity} = $1  if ( $msg =~ s/^\**\s*([A-Z]{3,}):\s+// );
621
    }
622
    my $severity = (exists $opts{-severity}) ? "*** $opts{-severity}: " : '';
623
624
    ## Increment error count and print message "
625
    ++($self->{_NUM_ERRORS})
626
        if(!%opts || ($opts{-severity} && $opts{-severity} eq 'ERROR'));
627
    ++($self->{_NUM_WARNINGS})
628
        if(!%opts || ($opts{-severity} && $opts{-severity} eq 'WARNING'));
629
    unless($self->{-quiet}) {
630
      my $out_fh = $self->output_handle() || \*STDERR;
631
      print $out_fh ($severity, $msg, $line, $file, "\n")
632
        if($self->{-warnings} || !%opts || $opts{-severity} ne 'WARNING');
633
    }
634
}
635
636
##################################
637
638
=item C<$checker-E<gt>num_errors()>
639
640
Set (if argument specified) and retrieve the number of errors found.
641
642
=cut
643
644
sub num_errors {
645
   return (@_ > 1) ? ($_[0]->{_NUM_ERRORS} = $_[1]) : $_[0]->{_NUM_ERRORS};
646
}
647
648
##################################
649
650
=item C<$checker-E<gt>num_warnings()>
651
652
Set (if argument specified) and retrieve the number of warnings found.
653
654
=cut
655
656
sub num_warnings {
657
   return (@_ > 1) ? ($_[0]->{_NUM_WARNINGS} = $_[1]) : $_[0]->{_NUM_WARNINGS};
658
}
659
660
##################################
661
662
=item C<$checker-E<gt>name()>
663
664
Set (if argument specified) and retrieve the canonical name of POD as
665
found in the C<=head1 NAME> section.
666
667
=cut
668
669
sub name {
670
    return (@_ > 1 && $_[1]) ?
671
        ($_[0]->{-name} = $_[1]) : $_[0]->{-name};
672
}
673
674
##################################
675
676
=item C<$checker-E<gt>node()>
677
678
Add (if argument specified) and retrieve the nodes (as defined by C<=headX>
679
and C<=item>) of the current POD. The nodes are returned in the order of
680
their occurrence. They consist of plain text, each piece of whitespace is
681
collapsed to a single blank.
682
683
=cut
684
685
sub node {
686
    my ($self,$text) = @_;
687
    if(defined $text) {
688
        $text =~ s/\s+$//s; # strip trailing whitespace
689
        $text =~ s/\s+/ /gs; # collapse whitespace
690
        # add node, order important!
691
        push(@{$self->{_nodes}}, $text);
692
        # keep also a uniqueness counter
693
        $self->{_unique_nodes}->{$text}++ if($text !~ /^\s*$/s);
694
        return $text;
695
    }
696
    @{$self->{_nodes}};
697
}
698
699
##################################
700
701
=item C<$checker-E<gt>idx()>
702
703
Add (if argument specified) and retrieve the index entries (as defined by
704
C<XE<lt>E<gt>>) of the current POD. They consist of plain text, each piece
705
of whitespace is collapsed to a single blank.
706
707
=cut
708
709
# set/return index entries of current POD
710
sub idx {
711
    my ($self,$text) = @_;
712
    if(defined $text) {
713
        $text =~ s/\s+$//s; # strip trailing whitespace
714
        $text =~ s/\s+/ /gs; # collapse whitespace
715
        # add node, order important!
716
        push(@{$self->{_index}}, $text);
717
        # keep also a uniqueness counter
718
        $self->{_unique_nodes}->{$text}++ if($text !~ /^\s*$/s);
719
        return $text;
720
    }
721
    @{$self->{_index}};
722
}
723
724
##################################
725
726
=item C<$checker-E<gt>hyperlink()>
727
728
Add (if argument specified) and retrieve the hyperlinks (as defined by
729
C<LE<lt>E<gt>>) of the current POD. They consist of a 2-item array: line
730
number and C<Pod::Hyperlink> object.
731
732
=back
733
734
=cut
735
736
# set/return hyperlinks of the current POD
737
sub hyperlink {
738
    my $self = shift;
739
    if($_[0]) {
740
        push(@{$self->{_links}}, $_[0]);
741
        return $_[0];
742
    }
743
    @{$self->{_links}};
744
}
745
746
## overrides for Pod::Parser
747
748
sub end_pod {
749
    ## Do some final checks and
750
    ## print the number of errors found
751
    my $self   = shift;
752
    my $infile = $self->input_file();
753
754
    if(@{$self->{_list_stack}}) {
755
        my $list;
756
        while(($list = $self->_close_list('EOF',$infile)) &&
757
          $list->indent() ne 'auto') {
758
            $self->poderror({ -line => 'EOF', -file => $infile,
759
                -severity => 'ERROR', -msg => '=over on line ' .
760
                $list->start() . ' without closing =back' });
761
        }
762
    }
763
764
    # check validity of document internal hyperlinks
765
    # first build the node names from the paragraph text
766
    my %nodes;
767
    foreach($self->node()) {
768
        $nodes{$_} = 1;
769
        if(/^(\S+)\s+\S/) {
770
            # we have more than one word. Use the first as a node, too.
771
            # This is used heavily in perlfunc.pod
772
            $nodes{$1} ||= 2; # derived node
773
        }
774
    }
775
    foreach($self->idx()) {
776
        $nodes{$_} = 3; # index node
777
    }
778
    foreach($self->hyperlink()) {
779
        my ($line,$link) = @$_;
780
        # _TODO_ what if there is a link to the page itself by the name,
781
        # e.g. in Tk::Pod : L<Tk::Pod/"DESCRIPTION">
782
        if($link->node() && !$link->page() && $link->type() ne 'hyperlink') {
783
            my $node = $self->_check_ptree($self->parse_text($link->node(),
784
                $line), $line, $infile, 'L');
785
            if($node && !$nodes{$node}) {
786
                $self->poderror({ -line => $line || '', -file => $infile,
787
                    -severity => 'ERROR',
788
                    -msg => "unresolved internal link '$node'"});
789
            }
790
        }
791
    }
792
793
    # check the internal nodes for uniqueness. This pertains to
794
    # =headX, =item and X<...>
795
    if($self->{-warnings} && $self->{-warnings}>1) {
796
      foreach(grep($self->{_unique_nodes}->{$_} > 1,
797
        keys %{$self->{_unique_nodes}})) {
798
          $self->poderror({ -line => '-', -file => $infile,
799
            -severity => 'WARNING',
800
            -msg => "multiple occurrence of link target '$_'"});
801
      }
802
    }
803
804
    # no POD found here
805
    $self->num_errors(-1) if($self->{_commands} == 0);
806
}
807
808
# check a POD command directive
809
sub command {
810
    my ($self, $cmd, $paragraph, $line_num, $pod_para) = @_;
811
    my ($file, $line) = $pod_para->file_line;
812
    ## Check the command syntax
813
    my $arg; # this will hold the command argument
814
    if (! $VALID_COMMANDS{$cmd}) {
815
       $self->poderror({ -line => $line, -file => $file, -severity => 'ERROR',
816
                         -msg => "Unknown command '$cmd'" });
817
    }
818
    else { # found a valid command
819
        $self->{_commands}++; # delete this line if below is enabled again
820
821
        ##### following check disabled due to strong request
822
        #if(!$self->{_commands}++ && $cmd !~ /^head/) {
823
        #    $self->poderror({ -line => $line, -file => $file,
824
        #         -severity => 'WARNING',
825
        #         -msg => "file does not start with =head" });
826
        #}
827
828
        # check syntax of particular command
829
        if($cmd eq 'over') {
830
            # check for argument
831
            $arg = $self->interpolate_and_check($paragraph, $line,$file);
832
            my $indent = 4; # default
833
            if($arg && $arg =~ /^\s*(\d+)\s*$/) {
834
                $indent = $1;
835
            }
836
            # start a new list
837
            $self->_open_list($indent,$line,$file);
838
        }
839
        elsif($cmd eq 'item') {
840
            # are we in a list?
841
            unless(@{$self->{_list_stack}}) {
842
                $self->poderror({ -line => $line, -file => $file,
843
                     -severity => 'ERROR',
844
                     -msg => '=item without previous =over' });
845
                # auto-open in case we encounter many more
846
                $self->_open_list('auto',$line,$file);
847
            }
848
            my $list = $self->{_list_stack}->[0];
849
            # check whether the previous item had some contents
850
            if(defined $self->{_list_item_contents} &&
851
              $self->{_list_item_contents} == 0) {
852
                $self->poderror({ -line => $line, -file => $file,
853
                     -severity => 'WARNING',
854
                     -msg => 'previous =item has no contents' });
855
            }
856
            if($list->{_has_par}) {
857
                $self->poderror({ -line => $line, -file => $file,
858
                     -severity => 'WARNING',
859
                     -msg => 'preceding non-item paragraph(s)' });
860
                delete $list->{_has_par};
861
            }
862
            # check for argument
863
            $arg = $self->interpolate_and_check($paragraph, $line, $file);
864
            if($arg && $arg =~ /(\S+)/) {
865
                $arg =~ s/[\s\n]+$//;
866
                my $type;
867
                if($arg =~ /^[*]\s*(\S*.*)/) {
868
                  $type = 'bullet';
869
                  $self->{_list_item_contents} = $1 ? 1 : 0;
870
                  $arg = $1;
871
                }
872
                elsif($arg =~ /^\d+\.?\s+(\S*)/) {
873
                  $type = 'number';
874
                  $self->{_list_item_contents} = $1 ? 1 : 0;
875
                  $arg = $1;
876
                }
877
                else {
878
                  $type = 'definition';
879
                  $self->{_list_item_contents} = 1;
880
                }
881
                my $first = $list->type();
882
                if($first && $first ne $type) {
883
                    $self->poderror({ -line => $line, -file => $file,
884
                       -severity => 'WARNING',
885
                       -msg => "=item type mismatch ('$first' vs. '$type')"});
886
                }
887
                else { # first item
888
                    $list->type($type);
889
                }
890
            }
891
            else {
892
                $self->poderror({ -line => $line, -file => $file,
893
                     -severity => 'WARNING',
894
                     -msg => 'No argument for =item' });
895
                $arg = ' '; # empty
896
                $self->{_list_item_contents} = 0;
897
            }
898
            # add this item
899
            $list->item($arg);
900
            # remember this node
901
            $self->node($arg);
902
        }
903
        elsif($cmd eq 'back') {
904
            # check if we have an open list
905
            unless(@{$self->{_list_stack}}) {
906
                $self->poderror({ -line => $line, -file => $file,
907
                         -severity => 'ERROR',
908
                         -msg => '=back without previous =over' });
909
            }
910
            else {
911
                # check for spurious characters
912
                $arg = $self->interpolate_and_check($paragraph, $line,$file);
913
                if($arg && $arg =~ /\S/) {
914
                    $self->poderror({ -line => $line, -file => $file,
915
                         -severity => 'ERROR',
916
                         -msg => 'Spurious character(s) after =back' });
917
                }
918
                # close list
919
                my $list = $self->_close_list($line,$file);
920
                # check for empty lists
921
                if(!$list->item() && $self->{-warnings}) {
922
                    $self->poderror({ -line => $line, -file => $file,
923
                         -severity => 'WARNING',
924
                         -msg => 'No items in =over (at line ' .
925
                         $list->start() . ') / =back list'});
926
                }
927
            }
928
        }
929
        elsif($cmd =~ /^head(\d+)/) {
930
            my $hnum = $1;
931
            $self->{"_have_head_$hnum"}++; # count head types
932
            if($hnum > 1 && !$self->{'_have_head_'.($hnum -1)}) {
933
              $self->poderror({ -line => $line, -file => $file,
934
                   -severity => 'WARNING',
935
                   -msg => "=head$hnum without preceding higher level"});
936
            }
937
            # check whether the previous =head section had some contents
938
            if(defined $self->{_commands_in_head} &&
939
              $self->{_commands_in_head} == 0 &&
940
              defined $self->{_last_head} &&
941
              $self->{_last_head} >= $hnum) {
942
                $self->poderror({ -line => $line, -file => $file,
943
                     -severity => 'WARNING',
944
                     -msg => 'empty section in previous paragraph'});
945
            }
946
            $self->{_commands_in_head} = -1;
947
            $self->{_last_head} = $hnum;
948
            # check if there is an open list
949
            if(@{$self->{_list_stack}}) {
950
                my $list;
951
                while(($list = $self->_close_list($line,$file)) &&
952
                  $list->indent() ne 'auto') {
953
                    $self->poderror({ -line => $line, -file => $file,
954
                         -severity => 'ERROR',
955
                         -msg => '=over on line '. $list->start() .
956
                         " without closing =back (at $cmd)" });
957
                }
958
            }
959
            # remember this node
960
            $arg = $self->interpolate_and_check($paragraph, $line,$file);
961
            $arg =~ s/[\s\n]+$//s;
962
            $self->node($arg);
963
            unless(length($arg)) {
964
                $self->poderror({ -line => $line, -file => $file,
965
                     -severity => 'ERROR',
966
                     -msg => "empty =$cmd"});
967
            }
968
            if($cmd eq 'head1') {
969
                $self->{_current_head1} = $arg;
970
            } else {
971
                $self->{_current_head1} = '';
972
            }
973
        }
974
        elsif($cmd eq 'begin') {
975
            if($self->{_have_begin}) {
976
                # already have a begin
977
                $self->poderror({ -line => $line, -file => $file,
978
                     -severity => 'ERROR',
979
                     -msg => q{Nested =begin's (first at line } .
980
                     $self->{_have_begin} . ')'});
981
            }
982
            else {
983
                # check for argument
984
                $arg = $self->interpolate_and_check($paragraph, $line,$file);
985
                unless($arg && $arg =~ /(\S+)/) {
986
                    $self->poderror({ -line => $line, -file => $file,
987
                         -severity => 'ERROR',
988
                         -msg => 'No argument for =begin'});
989
                }
990
                # remember the =begin
991
                $self->{_have_begin} = "$line:$1";
992
            }
993
        }
994
        elsif($cmd eq 'end') {
995
            if($self->{_have_begin}) {
996
                # close the existing =begin
997
                $self->{_have_begin} = '';
998
                # check for spurious characters
999
                $arg = $self->interpolate_and_check($paragraph, $line,$file);
1000
                # the closing argument is optional
1001
                #if($arg && $arg =~ /\S/) {
1002
                #    $self->poderror({ -line => $line, -file => $file,
1003
                #         -severity => 'WARNING',
1004
                #         -msg => "Spurious character(s) after =end" });
1005
                #}
1006
            }
1007
            else {
1008
                # don't have a matching =begin
1009
                $self->poderror({ -line => $line, -file => $file,
1010
                     -severity => 'ERROR',
1011
                     -msg => '=end without =begin' });
1012
            }
1013
        }
1014
        elsif($cmd eq 'for') {
1015
            unless($paragraph =~ /\s*(\S+)\s*/) {
1016
                $self->poderror({ -line => $line, -file => $file,
1017
                     -severity => 'ERROR',
1018
                     -msg => '=for without formatter specification' });
1019
            }
1020
            $arg = ''; # do not expand paragraph below
1021
        }
1022
        elsif($cmd =~ /^(pod|cut)$/) {
1023
            # check for argument
1024
            $arg = $self->interpolate_and_check($paragraph, $line,$file);
1025
            if($arg && $arg =~ /(\S+)/) {
1026
                $self->poderror({ -line => $line, -file => $file,
1027
                      -severity => 'ERROR',
1028
                      -msg => "Spurious text after =$cmd"});
1029
            }
1030
        }
1031
    $self->{_commands_in_head}++;
1032
    ## Check the interior sequences in the command-text
1033
    $self->interpolate_and_check($paragraph, $line,$file)
1034
        unless(defined $arg);
1035
    }
1036
}
1037
1038
sub _open_list
1039
{
1040
    my ($self,$indent,$line,$file) = @_;
1041
    my $list = Pod::List->new(
1042
           -indent => $indent,
1043
           -start => $line,
1044
           -file => $file);
1045
    unshift(@{$self->{_list_stack}}, $list);
1046
    undef $self->{_list_item_contents};
1047
    $list;
1048
}
1049
1050
sub _close_list
1051
{
1052
    my ($self,$line,$file) = @_;
1053
    my $list = shift(@{$self->{_list_stack}});
1054
    if(defined $self->{_list_item_contents} &&
1055
      $self->{_list_item_contents} == 0) {
1056
        $self->poderror({ -line => $line, -file => $file,
1057
            -severity => 'WARNING',
1058
            -msg => 'previous =item has no contents' });
1059
    }
1060
    undef $self->{_list_item_contents};
1061
    $list;
1062
}
1063
1064
# process a block of some text
1065
sub interpolate_and_check {
1066
    my ($self, $paragraph, $line, $file) = @_;
1067
    ## Check the interior sequences in the command-text
1068
    # and return the text
1069
    $self->_check_ptree(
1070
        $self->parse_text($paragraph,$line), $line, $file, '');
1071
}
1072
1073
sub _check_ptree {
1074
    my ($self,$ptree,$line,$file,$nestlist) = @_;
1075
    local($_);
1076
    my $text = '';
1077
    # process each node in the parse tree
1078
    foreach(@$ptree) {
1079
        # regular text chunk
1080
        unless(ref) {
1081
            # count the unescaped angle brackets
1082
            # complain only when warning level is greater than 1
1083
            if($self->{-warnings} && $self->{-warnings}>1) {
1084
              my $count;
1085
              if($count = tr/<>/<>/) {
1086
                $self->poderror({ -line => $line, -file => $file,
1087
                     -severity => 'WARNING',
1088
                     -msg => "$count unescaped <> in paragraph" });
1089
                }
1090
            }
1091
            $text .= $_;
1092
            next;
1093
        }
1094
        # have an interior sequence
1095
        my $cmd = $_->cmd_name();
1096
        my $contents = $_->parse_tree();
1097
        ($file,$line) = $_->file_line();
1098
        # check for valid tag
1099
        if (! $VALID_SEQUENCES{$cmd}) {
1100
            $self->poderror({ -line => $line, -file => $file,
1101
                 -severity => 'ERROR',
1102
                 -msg => qq(Unknown interior-sequence '$cmd')});
1103
            # expand it anyway
1104
            $text .= $self->_check_ptree($contents, $line, $file, "$nestlist$cmd");
1105
            next;
1106
        }
1107
        if($nestlist =~ /$cmd/) {
1108
            $self->poderror({ -line => $line, -file => $file,
1109
                 -severity => 'WARNING',
1110
                 -msg => "nested commands $cmd<...$cmd<...>...>"});
1111
            # _TODO_ should we add the contents anyway?
1112
            # expand it anyway, see below
1113
        }
1114
        if($cmd eq 'E') {
1115
            # preserve entities
1116
            if(@$contents > 1 || ref $$contents[0] || $$contents[0] !~ /^\w+$/) {
1117
                $self->poderror({ -line => $line, -file => $file,
1118
                    -severity => 'ERROR',
1119
                    -msg => 'garbled entity ' . $_->raw_text()});
1120
                next;
1121
            }
1122
            my $ent = $$contents[0];
1123
            my $val;
1124
            if($ent =~ /^0x[0-9a-f]+$/i) {
1125
                # hexadec entity
1126
                $val = hex($ent);
1127
            }
1128
            elsif($ent =~ /^0\d+$/) {
1129
                # octal
1130
                $val = oct($ent);
1131
            }
1132
            elsif($ent =~ /^\d+$/) {
1133
                # numeric entity
1134
                $val = $ent;
1135
            }
1136
            if(defined $val) {
1137
                if($val>0 && $val<256) {
1138
                    $text .= chr($val);
1139
                }
1140
                else {
1141
                    $self->poderror({ -line => $line, -file => $file,
1142
                        -severity => 'ERROR',
1143
                        -msg => 'Entity number out of range ' . $_->raw_text()});
1144
                }
1145
            }
1146
            elsif($ENTITIES{$ent}) {
1147
                # known ISO entity
1148
                $text .= $ENTITIES{$ent};
1149
            }
1150
            else {
1151
                $self->poderror({ -line => $line, -file => $file,
1152
                    -severity => 'WARNING',
1153
                    -msg => 'Unknown entity ' . $_->raw_text()});
1154
                $text .= "E<$ent>";
1155
            }
1156
        }
1157
        elsif($cmd eq 'L') {
1158
            # try to parse the hyperlink
1159
            my $link = Pod::Hyperlink->new($contents->raw_text());
1160
            unless(defined $link) {
1161
                $self->poderror({ -line => $line, -file => $file,
1162
                    -severity => 'ERROR',
1163
                    -msg => 'malformed link ' . $_->raw_text() ." : $@"});
1164
                next;
1165
            }
1166
            $link->line($line); # remember line
1167
            if($self->{-warnings}) {
1168
                foreach my $w ($link->warning()) {
1169
                    $self->poderror({ -line => $line, -file => $file,
1170
                        -severity => 'WARNING',
1171
                        -msg => $w });
1172
                }
1173
            }
1174
            # check the link text
1175
            $text .= $self->_check_ptree($self->parse_text($link->text(),
1176
                $line), $line, $file, "$nestlist$cmd");
1177
            # remember link
1178
            $self->hyperlink([$line,$link]);
1179
        }
1180
        elsif($cmd =~ /[BCFIOS]/) {
1181
            # add the guts
1182
            $text .= $self->_check_ptree($contents, $line, $file, "$nestlist$cmd");
1183
        }
1184
        elsif($cmd eq 'Z') {
1185
            if(length($contents->raw_text())) {
1186
                $self->poderror({ -line => $line, -file => $file,
1187
                    -severity => 'ERROR',
1188
                    -msg => 'Nonempty Z<>'});
1189
            }
1190
        }
1191
        elsif($cmd eq 'X') {
1192
            my $idx = $self->_check_ptree($contents, $line, $file, "$nestlist$cmd");
1193
            if($idx =~ /^\s*$/s) {
1194
                $self->poderror({ -line => $line, -file => $file,
1195
                    -severity => 'ERROR',
1196
                    -msg => 'Empty X<>'});
1197
            }
1198
            else {
1199
                # remember this node
1200
                $self->idx($idx);
1201
            }
1202
        }
1203
        else {
1204
            # not reached
1205
            croak 'internal error';
1206
        }
1207
    }
1208
    $text;
1209
}
1210
1211
# process a block of verbatim text
1212
sub verbatim {
1213
    ## Nothing particular to check
1214
    my ($self, $paragraph, $line_num, $pod_para) = @_;
1215
1216
    $self->_preproc_par($paragraph);
1217
1218
    if($self->{_current_head1} eq 'NAME') {
1219
        my ($file, $line) = $pod_para->file_line;
1220
        $self->poderror({ -line => $line, -file => $file,
1221
            -severity => 'WARNING',
1222
            -msg => 'Verbatim paragraph in NAME section' });
1223
    }
1224
}
1225
1226
# process a block of regular text
1227
sub textblock {
1228
    my ($self, $paragraph, $line_num, $pod_para) = @_;
1229
    my ($file, $line) = $pod_para->file_line;
1230
1231
    $self->_preproc_par($paragraph);
1232
1233
    # skip this paragraph if in a =begin block
1234
    unless($self->{_have_begin}) {
1235
        my $block = $self->interpolate_and_check($paragraph, $line,$file);
1236
        if($self->{_current_head1} eq 'NAME') {
1237
            if($block =~ /^\s*(\S+?)\s*[,-]/) {
1238
                # this is the canonical name
1239
                $self->{-name} = $1 unless(defined $self->{-name});
1240
            }
1241
        }
1242
    }
1243
}
1244
1245
sub _preproc_par
1246
{
1247
    my $self = shift;
1248
    $_[0] =~ s/[\s\n]+$//;
1249
    if($_[0]) {
1250
        $self->{_commands_in_head}++;
1251
        $self->{_list_item_contents}++ if(defined $self->{_list_item_contents});
1252
        if(@{$self->{_list_stack}} && !$self->{_list_stack}->[0]->item()) {
1253
            $self->{_list_stack}->[0]->{_has_par} = 1;
1254
        }
1255
    }
1256
}
1257
1258
1;
1259
1260
__END__
1261
1262
=head1 AUTHOR
1263
1264
Please report bugs using L<http://rt.cpan.org>.
1265
1266
Brad Appleton E<lt>bradapp@enteract.comE<gt> (initial version),
1267
Marek Rouchal E<lt>marekr@cpan.orgE<gt>
1268
1269
Based on code for B<Pod::Text::pod2text()> written by
1270
Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
1271
1272
=cut
1273

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks