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