Login
Cleaned up trailing whitespace. Fixed typo in name of hash key
[gknop/Perl-Critic.git] / lib / Perl / Critic / Document.pm
CommitLineData
6036a254 1##############################################################################
a73f4a71
JRT
2# $URL$
3# $Date$
4# $Author$
5# $Revision$
6036a254 6##############################################################################
5bf96118
CD
7
8package Perl::Critic::Document;
9
df6dee2b 10use 5.006001;
5bf96118 11use strict;
58a9e587 12use warnings;
267b39b4
ES
13
14use List::Util qw< max >;
5bf96118 15use PPI::Document;
267b39b4
ES
16use Scalar::Util qw< weaken >;
17use version;
5bf96118 18
6036a254 19#-----------------------------------------------------------------------------
58a9e587 20
173667ce 21our $VERSION = '1.093_01';
5bf96118 22
6036a254 23#-----------------------------------------------------------------------------
5bf96118
CD
24
25our $AUTOLOAD;
937b8de0 26sub AUTOLOAD { ## no critic (ProhibitAutoloading,ArgUnpacking)
6e7d6c9f
CD
27 my ( $function_name ) = $AUTOLOAD =~ m/ ([^:\']+) \z /xms;
28 return if $function_name eq 'DESTROY';
29 my $self = shift;
30 return $self->{_doc}->$function_name(@_);
5bf96118
CD
31}
32
6036a254 33#-----------------------------------------------------------------------------
5bf96118 34
58a9e587
JRT
35sub new {
36 my ($class, $doc) = @_;
937b8de0
JRT
37 my $self = bless {}, $class;
38 $self->{_disabled_lines} = _unfix_shebang($doc);
39 $self->{_doc} = $doc;
40 return $self;
5bf96118
CD
41}
42
6036a254 43#-----------------------------------------------------------------------------
58a9e587 44
2b6293b2
CD
45sub ppi_document {
46 my ($self) = @_;
47 return $self->{_doc};
48}
49
50#-----------------------------------------------------------------------------
51
47e1ff34 52sub isa {
6e7d6c9f
CD
53 my ($self, @args) = @_;
54 return $self->SUPER::isa(@args)
55 || ( (ref $self) && $self->{_doc} && $self->{_doc}->isa(@args) );
47e1ff34
CD
56}
57
6036a254 58#-----------------------------------------------------------------------------
47e1ff34 59
5bf96118 60sub find {
6e7d6c9f 61 my ($self, $wanted, @more_args) = @_;
5bf96118 62
58a9e587
JRT
63 # This method can only find elements by their class names. For
64 # other types of searches, delegate to the PPI::Document
5bf96118 65 if ( ( ref $wanted ) || !$wanted || $wanted !~ m/ \A PPI:: /xms ) {
6e7d6c9f 66 return $self->{_doc}->find($wanted, @more_args);
5bf96118 67 }
58a9e587
JRT
68
69 # Build the class cache if it doesn't exist. This happens at most
70 # once per Perl::Critic::Document instance. %elements of will be
71 # populated as a side-effect of calling the $finder_sub coderef
72 # that is produced by the caching_finder() closure.
5bf96118 73 if ( !$self->{_elements_of} ) {
389109ec 74
58a9e587 75 my %cache = ( 'PPI::Document' => [ $self ] );
389109ec
JRT
76
77 # The cache refers to $self, and $self refers to the cache. This
78 # creates a circular reference that leaks memory (i.e. $self is not
79 # destroyed until execution is complete). By weakening the reference,
80 # we allow perl to collect the garbage properly.
81 weaken( $cache{'PPI::Document'}->[0] );
82
58a9e587
JRT
83 my $finder_coderef = _caching_finder( \%cache );
84 $self->{_doc}->find( $finder_coderef );
85 $self->{_elements_of} = \%cache;
86 }
87
88 # find() must return false-but-defined on fail
89 return $self->{_elements_of}->{$wanted} || q{};
90}
91
6036a254 92#-----------------------------------------------------------------------------
58a9e587 93
fb21e21e 94sub find_first {
6e7d6c9f 95 my ($self, $wanted, @more_args) = @_;
fb21e21e
CD
96
97 # This method can only find elements by their class names. For
98 # other types of searches, delegate to the PPI::Document
99 if ( ( ref $wanted ) || !$wanted || $wanted !~ m/ \A PPI:: /xms ) {
6e7d6c9f 100 return $self->{_doc}->find_first($wanted, @more_args);
fb21e21e
CD
101 }
102
103 my $result = $self->find($wanted);
104 return $result ? $result->[0] : $result;
105}
106
6036a254 107#-----------------------------------------------------------------------------
fb21e21e 108
f5eeac3b 109sub find_any {
6e7d6c9f 110 my ($self, $wanted, @more_args) = @_;
f5eeac3b
CD
111
112 # This method can only find elements by their class names. For
113 # other types of searches, delegate to the PPI::Document
114 if ( ( ref $wanted ) || !$wanted || $wanted !~ m/ \A PPI:: /xms ) {
6e7d6c9f 115 return $self->{_doc}->find_any($wanted, @more_args);
f5eeac3b
CD
116 }
117
118 my $result = $self->find($wanted);
119 return $result ? 1 : $result;
120}
121
6036a254 122#-----------------------------------------------------------------------------
f5eeac3b 123
60108aef
CD
124sub filename {
125 my ($self) = @_;
126 return $self->{_doc}->can('filename') ? $self->{_doc}->filename : undef;
127}
128
6036a254 129#-----------------------------------------------------------------------------
60108aef 130
267b39b4
ES
131sub highest_explicit_perl_version {
132 my ($self) = @_;
133
134 my $highest_explicit_perl_version =
135 $self->{_highest_explicit_perl_version};
136
137 if ( not exists $self->{_highest_explicit_perl_version} ) {
138 my $includes = $self->find( \&_is_a_version_statement );
139
140 if ($includes) {
1ebef5a9
ES
141 # Note: this will complain about underscores, e.g. "use
142 # 5.008_000". However, nothing important should be depending upon
143 # alpha perl versions and marking non-alpha versions as alpha is
144 # bad in and of itself. Note that this contradicts an example in
145 # perlfunc about "use".
267b39b4
ES
146 $highest_explicit_perl_version =
147 max map { version->new( $_->version() ) } @{$includes};
148 }
149 else {
150 $highest_explicit_perl_version = undef;
151 }
152
153 $self->{_highest_explicit_perl_version} =
154 $highest_explicit_perl_version;
155 }
156
157 return $highest_explicit_perl_version if $highest_explicit_perl_version;
158 return;
159}
160
937b8de0
JRT
161#-----------------------------------------------------------------------------
162
163sub mark_disabled_lines {
164 my ($self, @site_policies) = @_;
165 my %disabled_lines = _find_disabled_lines($self->{_doc}, @site_policies);
166
167 # Ick. Need to merge the disabled lines hash with the shebang lines
168 # that we alread disabled during the _unfix_shebang() process. Need
169 # to find a better way to express this.
170
171 $self->{_disabled_lines} = { %{$self->{_disabled_lines}}, %disabled_lines };
172 return $self;
173}
174
175#-----------------------------------------------------------------------------
176
afb2d8f5 177sub is_line_disabled {
937b8de0
JRT
178 my ($self, $line, $policy_name) = @_;
179 return 0 if not exists $self->{_disabled_lines}->{$line};
180 return 1 if $self->{_disabled_lines}->{$line}->{$policy_name};
181 return 1 if $self->{_disabled_lines}->{$line}->{ALL};
182 return 0;
183}
184
185#-----------------------------------------------------------------------------
186
95ebf9b0
JRT
187sub useless_no_critic_warnings {
188 my ($self, @violations) = @_;
4880392e 189
95ebf9b0
JRT
190 my %violation_lines = ();
191 for my $violation (@violations) {
192 my $line = $violation->location()->[0];
193 my $policy_name = $violation->policy();
194 $violation_lines{$policy_name}->{$line} = 1;
195 }
4880392e
JRT
196
197
95ebf9b0
JRT
198 my @warnings = ();
199 my $file = $self->filename() || 'UNKNOWN';
4880392e 200
95ebf9b0
JRT
201 my %disabled_lines = %{ $self->{_disabled_lines} };
202 for my $line (keys %disabled_lines) {
203 my %disabled_policies = %{ $disabled_lines{$line} };
204 for my $policy_name (keys %disabled_policies) {
4880392e 205
95ebf9b0
JRT
206 if ($policy_name eq 'ALL' && not exists $violation_lines{$line}) {
207 push @warnings, qq{Useless disabling of all Policies in file "$file" at line $line.};
208 }
209 elsif (not $violation_lines{$line}->{$policy_name}) {
210 push @warnings, qq{Useless disabling of $policy_name in file "$file" at line $line.};
211 }
212 }
213 }
4880392e 214
95ebf9b0
JRT
215 return @warnings;
216}
217
218#-----------------------------------------------------------------------------
219
267b39b4
ES
220sub _is_a_version_statement {
221 my (undef, $element) = @_;
222
223 return 0 if not $element->isa('PPI::Statement::Include');
224 return 1 if $element->version();
225 return 0;
226}
227
228#-----------------------------------------------------------------------------
229
58a9e587
JRT
230sub _caching_finder {
231
232 my $cache_ref = shift; # These vars will persist for the life
233 my %isa_cache = (); # of the code ref that this sub returns
234
235
236 # Gather up all the PPI elements and sort by @ISA. Note: if any
237 # instances used multiple inheritance, this implementation would
238 # lead to multiple copies of $element in the $elements_of lists.
239 # However, PPI::* doesn't do multiple inheritance, so we are safe
240
241 return sub {
6e7d6c9f 242 my (undef, $element) = @_;
58a9e587
JRT
243 my $classes = $isa_cache{ref $element};
244 if ( !$classes ) {
245 $classes = [ ref $element ];
246 # Use a C-style loop because we append to the classes array inside
247 for ( my $i = 0; $i < @{$classes}; $i++ ) { ## no critic(ProhibitCStyleForLoops)
248 no strict 'refs'; ## no critic(ProhibitNoStrict)
249 push @{$classes}, @{"$classes->[$i]::ISA"};
250 $cache_ref->{$classes->[$i]} ||= [];
5bf96118 251 }
58a9e587
JRT
252 $isa_cache{$classes->[0]} = $classes;
253 }
5bf96118 254
58a9e587
JRT
255 for my $class ( @{$classes} ) {
256 push @{$cache_ref->{$class}}, $element;
257 }
5bf96118 258
58a9e587
JRT
259 return 0; # 0 tells find() to keep traversing, but not to store this $element
260 };
5bf96118
CD
261}
262
6036a254 263#-----------------------------------------------------------------------------
58a9e587 264
937b8de0
JRT
265sub _find_disabled_lines {
266
267 my ($doc, @site_policies)= @_;
268
269 my $nodes_ref = $doc->find('PPI::Token::Comment') || return;
270 my %disabled_lines;
271
272 _disable_shebang_line($nodes_ref, \%disabled_lines, \@site_policies);
273 _disable_other_lines($nodes_ref, \%disabled_lines, \@site_policies);
274 return %disabled_lines;
275}
276
277#-----------------------------------------------------------------------------
278
279sub _disable_shebang_line {
280 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
281
282 my $shebang_no_critic = qr{\A [#]! .*? [#][#] \s* no \s+ critic}xms;
283
284 # Special case for the very beginning of the file: allow "##no critic" after the shebang
285 if (0 < @{$nodes_ref}) {
286 my $loc = $nodes_ref->[0]->location;
287 if (1 == $loc->[0] && 1 == $loc->[1] && $nodes_ref->[0] =~ $shebang_no_critic) {
288 my $pragma = shift @{$nodes_ref};
289 for my $policy (_parse_nocritic_import($pragma, $site_policies)) {
290 $disabled_lines->{ 1 }->{$policy} = 1;
291 }
292 }
293 }
294 return;
295}
296
297#-----------------------------------------------------------------------------
298
299sub _disable_other_lines {
300 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
301
302 my $no_critic = qr{\A \s* [#][#] \s* no \s+ critic}xms;
303 my $use_critic = qr{\A \s* [#][#] \s* use \s+ critic}xms;
304
305 PRAGMA:
306 for my $pragma ( grep { $_ =~ $no_critic } @{$nodes_ref} ) {
307
308 # Parse out the list of Policy names after the
309 # 'no critic' pragma. I'm thinking of this just
310 # like a an C<import> argument for real pragmas.
311 my @no_policies = _parse_nocritic_import($pragma, $site_policies);
312
313 # Grab surrounding nodes to determine the context.
314 # This determines whether the pragma applies to
315 # the current line or the block that follows.
316 my $parent = $pragma->parent();
317 my $grandparent = $parent ? $parent->parent() : undef;
318 my $sib = $pragma->sprevious_sibling();
319
320
321 # Handle single-line usage on simple statements
322 if ( $sib && $sib->location->[0] == $pragma->location->[0] ) {
323 my $line = $pragma->location->[0];
324 for my $policy ( @no_policies ) {
325 $disabled_lines->{ $line }->{$policy} = 1;
326 }
327 next PRAGMA;
328 }
329
330
331 # Handle single-line usage on compound statements
332 if ( ref $parent eq 'PPI::Structure::Block' ) {
333 if ( ref $grandparent eq 'PPI::Statement::Compound'
334 || ref $grandparent eq 'PPI::Statement::Sub' ) {
335 if ( $parent->location->[0] == $pragma->location->[0] ) {
336 my $line = $grandparent->location->[0];
337 for my $policy ( @no_policies ) {
338 $disabled_lines->{ $line }->{$policy} = 1;
339 }
340 next PRAGMA;
341 }
342 }
343 }
344
345
346 # Handle multi-line usage. This is either a "no critic" ..
347 # "use critic" region or a block where "no critic" persists
348 # until the end of the scope. The start is the always the "no
349 # critic" which we already found. So now we have to search
350 # for the end.
351
352 my $start = $pragma;
353 my $end = $pragma;
354
355 SIB:
356 while ( my $esib = $end->next_sibling() ) {
357 $end = $esib; # keep track of last sibling encountered in this scope
4880392e 358 last SIB if $esib->isa('PPI::Token::Comment') && $esib =~ $use_critic;
937b8de0
JRT
359 }
360
361 # We either found an end or hit the end of the scope.
362 # Flag all intervening lines
363 for my $line ( $start->location->[0] .. $end->location->[0] ) {
364 for my $policy ( @no_policies ) {
365 $disabled_lines->{ $line }->{$policy} = 1;
366 }
367 }
368 }
369
370 return;
371}
372
373#-----------------------------------------------------------------------------
374
375sub _parse_nocritic_import {
376
377 my ($pragma, $site_policies) = @_;
378
379 my $module = qr{ [\w:]+ }xms;
380 my $delim = qr{ \s* [,\s] \s* }xms;
381 my $qw = qr{ (?: qw )? }xms;
382 my $qualifier = qr{ $qw [(]? \s* ( $module (?: $delim $module)* ) \s* [)]? }xms;
383 my $no_critic = qr{ \#\# \s* no \s+ critic \s* $qualifier }xms; ##no critic(EscapedMetacharacters)
384
385 if ( my ($module_list) = $pragma =~ $no_critic ) {
386 my @modules = split $delim, $module_list;
387
388 # Compose the specified modules into a regex alternation. Wrap each
389 # in a no-capturing group to permit "|" in the modules specification
390 # (backward compatibility)
391 my $re = join q{|}, map {"(?:$_)"} @modules;
392 return grep {m/$re/ixms} @{$site_policies};
393 }
394
395 # Default to disabling ALL policies.
396 return qw(ALL);
397}
398
399#-----------------------------------------------------------------------------
400
401sub _unfix_shebang {
402
403 # When you install a script using ExtUtils::MakeMaker or Module::Build, it
404 # inserts some magical code into the top of the file (just after the
405 # shebang). This code allows people to call your script using a shell,
406 # like `sh my_script`. Unfortunately, this code causes several Policy
407 # violations, so we just disable it as if a "## no critic" comment had
408 # been attached.
409
410 my $doc = shift;
411 my $first_stmnt = $doc->schild(0) || return {};
412
413 # Different versions of MakeMaker and Build use slightly different shebang
414 # fixing strings. This matches most of the ones I've found in my own Perl
415 # distribution, but it may not be bullet-proof.
416
417 my $fixin_rx = qr{^eval 'exec .* \$0 \${1\+"\$@"}'\s*[\r\n]\s*if.+;}ms; ## no critic (RequireExtendedFormatting)
418 if ( $first_stmnt =~ $fixin_rx ) {
419 my $line = $first_stmnt->location()->[0];
420 return { $line => {ALL => 1}, $line + 1 => {ALL => 1} };
421 }
422
423 #No magic shebang was found!
424 return {};
425}
426
427#-----------------------------------------------------------------------------
428
5bf96118 4291;
58a9e587 430
5bf96118
CD
431__END__
432
a73f4a71
JRT
433=pod
434
435=for stopwords pre-caches
436
5bf96118
CD
437=head1 NAME
438
c728943a 439Perl::Critic::Document - Caching wrapper around a PPI::Document.
5bf96118 440
267b39b4 441
5bf96118
CD
442=head1 SYNOPSIS
443
444 use PPI::Document;
445 use Perl::Critic::Document;
446 my $doc = PPI::Document->new('Foo.pm');
447 $doc = Perl::Critic::Document->new($doc);
448 ## Then use the instance just like a PPI::Document
449
267b39b4 450
5bf96118
CD
451=head1 DESCRIPTION
452
453Perl::Critic does a lot of iterations over the PPI document tree via
454the C<PPI::Document::find()> method. To save some time, this class
455pre-caches a lot of the common C<find()> calls in a single traversal.
456Then, on subsequent requests we return the cached data.
457
458This is implemented as a facade, where method calls are handed to the
459stored C<PPI::Document> instance.
460
267b39b4 461
5bf96118
CD
462=head1 CAVEATS
463
464This facade does not implement the overloaded operators from
11f53956
ES
465L<PPI::Document|PPI::Document> (that is, the C<use overload ...>
466work). Therefore, users of this facade must not rely on that syntactic
467sugar. So, for example, instead of C<my $source = "$doc";> you should
468write C<my $source = $doc->content();>
5bf96118
CD
469
470Perhaps there is a CPAN module out there which implements a facade
471better than we do here?
472
267b39b4
ES
473
474=head1 CONSTRUCTOR
475
476=over
477
478=item C<< new($doc) >>
479
480Create a new instance referencing a PPI::Document instance.
481
482
483=back
484
485
5bf96118
CD
486=head1 METHODS
487
488=over
489
267b39b4 490=item C<< new($doc) >>
7076e807
CD
491
492Create a new instance referencing a PPI::Document instance.
493
267b39b4
ES
494
495=item C<< ppi_document() >>
2b6293b2 496
11f53956
ES
497Accessor for the wrapped PPI::Document instance. Note that altering
498this instance in any way can cause unpredictable failures in
499Perl::Critic's subsequent analysis because some caches may fall out of
500date.
2b6293b2 501
5bf96118 502
267b39b4
ES
503=item C<< find($wanted) >>
504
505=item C<< find_first($wanted) >>
fb21e21e 506
267b39b4 507=item C<< find_any($wanted) >>
f5eeac3b 508
fb21e21e 509If C<$wanted> is a simple PPI class name, then the cache is employed.
f5eeac3b
CD
510Otherwise we forward the call to the corresponding method of the
511C<PPI::Document> instance.
5bf96118 512
267b39b4
ES
513
514=item C<< filename() >>
e7f2d995
CD
515
516Returns the filename for the source code if applicable
517(PPI::Document::File) or C<undef> otherwise (PPI::Document).
518
267b39b4
ES
519
520=item C<< isa( $classname ) >>
242f7b08 521
11f53956
ES
522To be compatible with other modules that expect to get a
523PPI::Document, the Perl::Critic::Document class masquerades as the
524PPI::Document class.
242f7b08 525
267b39b4
ES
526
527=item C<< highest_explicit_perl_version() >>
528
11f53956
ES
529Returns a L<version|version> object for the highest Perl version
530requirement declared in the document via a C<use> or C<require>
531statement. Returns nothing if there is no version statement.
267b39b4
ES
532
533
937b8de0
JRT
534=item C<< mark_disabled_lines( @policy_names ) >>
535
536Scans the document for C<"## no critic"> pseudo-pragmas and builds
537an internal table of which of the listed C<@policy_names> have
538been disabled at each line. Returns C<$self>.
539
540
95ebf9b0 541=item C<< is_line_disabled($line, $policy_name) >>
937b8de0
JRT
542
543Returns true if the given C<$policy_name> has been disabled for
544at C<$line> in this document. Otherwise, returns false.
545
95ebf9b0
JRT
546=item C<< useless_no_critic_warnings(@violations) >>
547
548Given a list of violation objects that are assumed to have been found
549in this Document, returns a warning message for each line where a
550policy was disabled using a C<"##no critic"> pseudo-pragma, but
551no violation was actually found on that line. If multiple policies
552are disabled on a given line, then you'll get a warning message
553for each policy.
554
937b8de0 555
5bf96118
CD
556=back
557
267b39b4 558
5bf96118
CD
559=head1 AUTHOR
560
561Chris Dolan <cdolan@cpan.org>
562
267b39b4 563
5bf96118
CD
564=head1 COPYRIGHT
565
20dfddeb 566Copyright (c) 2006-2008 Chris Dolan. All rights reserved.
5bf96118
CD
567
568This program is free software; you can redistribute it and/or modify
569it under the same terms as Perl itself. The full text of this license
570can be found in the LICENSE file included with this module.
571
572=cut
737d3b65
CD
573
574# Local Variables:
575# mode: cperl
576# cperl-indent-level: 4
577# fill-column: 78
578# indent-tabs-mode: nil
579# c-indentation-style: bsd
580# End:
96fed375 581# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :