Login
First attempt to warn users when they have an unecessary "## 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 >;
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) = @_;
189
190
191 my %violation_lines = ();
192 for my $violation (@violations) {
193 my $line = $violation->location()->[0];
194 my $policy_name = $violation->policy();
195 $violation_lines{$policy_name}->{$line} = 1;
196 }
197
198
199 my @warnings = ();
200 my $file = $self->filename() || 'UNKNOWN';
201
202 my %disabled_lines = %{ $self->{_disabled_lines} };
203 for my $line (keys %disabled_lines) {
204 my %disabled_policies = %{ $disabled_lines{$line} };
205 for my $policy_name (keys %disabled_policies) {
206
207 if ($policy_name eq 'ALL' && not exists $violation_lines{$line}) {
208 push @warnings, qq{Useless disabling of all Policies in file "$file" at line $line.};
209 }
210 elsif (not $violation_lines{$line}->{$policy_name}) {
211 push @warnings, qq{Useless disabling of $policy_name in file "$file" at line $line.};
212 }
213 }
214 }
215
216 return @warnings;
217}
218
219#-----------------------------------------------------------------------------
220
267b39b4
ES
221sub _is_a_version_statement {
222 my (undef, $element) = @_;
223
224 return 0 if not $element->isa('PPI::Statement::Include');
225 return 1 if $element->version();
226 return 0;
227}
228
229#-----------------------------------------------------------------------------
230
58a9e587
JRT
231sub _caching_finder {
232
233 my $cache_ref = shift; # These vars will persist for the life
234 my %isa_cache = (); # of the code ref that this sub returns
235
236
237 # Gather up all the PPI elements and sort by @ISA. Note: if any
238 # instances used multiple inheritance, this implementation would
239 # lead to multiple copies of $element in the $elements_of lists.
240 # However, PPI::* doesn't do multiple inheritance, so we are safe
241
242 return sub {
6e7d6c9f 243 my (undef, $element) = @_;
58a9e587
JRT
244 my $classes = $isa_cache{ref $element};
245 if ( !$classes ) {
246 $classes = [ ref $element ];
247 # Use a C-style loop because we append to the classes array inside
248 for ( my $i = 0; $i < @{$classes}; $i++ ) { ## no critic(ProhibitCStyleForLoops)
249 no strict 'refs'; ## no critic(ProhibitNoStrict)
250 push @{$classes}, @{"$classes->[$i]::ISA"};
251 $cache_ref->{$classes->[$i]} ||= [];
5bf96118 252 }
58a9e587
JRT
253 $isa_cache{$classes->[0]} = $classes;
254 }
5bf96118 255
58a9e587
JRT
256 for my $class ( @{$classes} ) {
257 push @{$cache_ref->{$class}}, $element;
258 }
5bf96118 259
58a9e587
JRT
260 return 0; # 0 tells find() to keep traversing, but not to store this $element
261 };
5bf96118
CD
262}
263
6036a254 264#-----------------------------------------------------------------------------
58a9e587 265
937b8de0
JRT
266sub _find_disabled_lines {
267
268 my ($doc, @site_policies)= @_;
269
270 my $nodes_ref = $doc->find('PPI::Token::Comment') || return;
271 my %disabled_lines;
272
273 _disable_shebang_line($nodes_ref, \%disabled_lines, \@site_policies);
274 _disable_other_lines($nodes_ref, \%disabled_lines, \@site_policies);
275 return %disabled_lines;
276}
277
278#-----------------------------------------------------------------------------
279
280sub _disable_shebang_line {
281 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
282
283 my $shebang_no_critic = qr{\A [#]! .*? [#][#] \s* no \s+ critic}xms;
284
285 # Special case for the very beginning of the file: allow "##no critic" after the shebang
286 if (0 < @{$nodes_ref}) {
287 my $loc = $nodes_ref->[0]->location;
288 if (1 == $loc->[0] && 1 == $loc->[1] && $nodes_ref->[0] =~ $shebang_no_critic) {
289 my $pragma = shift @{$nodes_ref};
290 for my $policy (_parse_nocritic_import($pragma, $site_policies)) {
291 $disabled_lines->{ 1 }->{$policy} = 1;
292 }
293 }
294 }
295 return;
296}
297
298#-----------------------------------------------------------------------------
299
300sub _disable_other_lines {
301 my ($nodes_ref, $disabled_lines, $site_policies) = @_;
302
303 my $no_critic = qr{\A \s* [#][#] \s* no \s+ critic}xms;
304 my $use_critic = qr{\A \s* [#][#] \s* use \s+ critic}xms;
305
306 PRAGMA:
307 for my $pragma ( grep { $_ =~ $no_critic } @{$nodes_ref} ) {
308
309 # Parse out the list of Policy names after the
310 # 'no critic' pragma. I'm thinking of this just
311 # like a an C<import> argument for real pragmas.
312 my @no_policies = _parse_nocritic_import($pragma, $site_policies);
313
314 # Grab surrounding nodes to determine the context.
315 # This determines whether the pragma applies to
316 # the current line or the block that follows.
317 my $parent = $pragma->parent();
318 my $grandparent = $parent ? $parent->parent() : undef;
319 my $sib = $pragma->sprevious_sibling();
320
321
322 # Handle single-line usage on simple statements
323 if ( $sib && $sib->location->[0] == $pragma->location->[0] ) {
324 my $line = $pragma->location->[0];
325 for my $policy ( @no_policies ) {
326 $disabled_lines->{ $line }->{$policy} = 1;
327 }
328 next PRAGMA;
329 }
330
331
332 # Handle single-line usage on compound statements
333 if ( ref $parent eq 'PPI::Structure::Block' ) {
334 if ( ref $grandparent eq 'PPI::Statement::Compound'
335 || ref $grandparent eq 'PPI::Statement::Sub' ) {
336 if ( $parent->location->[0] == $pragma->location->[0] ) {
337 my $line = $grandparent->location->[0];
338 for my $policy ( @no_policies ) {
339 $disabled_lines->{ $line }->{$policy} = 1;
340 }
341 next PRAGMA;
342 }
343 }
344 }
345
346
347 # Handle multi-line usage. This is either a "no critic" ..
348 # "use critic" region or a block where "no critic" persists
349 # until the end of the scope. The start is the always the "no
350 # critic" which we already found. So now we have to search
351 # for the end.
352
353 my $start = $pragma;
354 my $end = $pragma;
355
356 SIB:
357 while ( my $esib = $end->next_sibling() ) {
358 $end = $esib; # keep track of last sibling encountered in this scope
359 last SIB
360 if $esib->isa('PPI::Token::Comment') && $esib =~ $use_critic;
361 }
362
363 # We either found an end or hit the end of the scope.
364 # Flag all intervening lines
365 for my $line ( $start->location->[0] .. $end->location->[0] ) {
366 for my $policy ( @no_policies ) {
367 $disabled_lines->{ $line }->{$policy} = 1;
368 }
369 }
370 }
371
372 return;
373}
374
375#-----------------------------------------------------------------------------
376
377sub _parse_nocritic_import {
378
379 my ($pragma, $site_policies) = @_;
380
381 my $module = qr{ [\w:]+ }xms;
382 my $delim = qr{ \s* [,\s] \s* }xms;
383 my $qw = qr{ (?: qw )? }xms;
384 my $qualifier = qr{ $qw [(]? \s* ( $module (?: $delim $module)* ) \s* [)]? }xms;
385 my $no_critic = qr{ \#\# \s* no \s+ critic \s* $qualifier }xms; ##no critic(EscapedMetacharacters)
386
387 if ( my ($module_list) = $pragma =~ $no_critic ) {
388 my @modules = split $delim, $module_list;
389
390 # Compose the specified modules into a regex alternation. Wrap each
391 # in a no-capturing group to permit "|" in the modules specification
392 # (backward compatibility)
393 my $re = join q{|}, map {"(?:$_)"} @modules;
394 return grep {m/$re/ixms} @{$site_policies};
395 }
396
397 # Default to disabling ALL policies.
398 return qw(ALL);
399}
400
401#-----------------------------------------------------------------------------
402
403sub _unfix_shebang {
404
405 # When you install a script using ExtUtils::MakeMaker or Module::Build, it
406 # inserts some magical code into the top of the file (just after the
407 # shebang). This code allows people to call your script using a shell,
408 # like `sh my_script`. Unfortunately, this code causes several Policy
409 # violations, so we just disable it as if a "## no critic" comment had
410 # been attached.
411
412 my $doc = shift;
413 my $first_stmnt = $doc->schild(0) || return {};
414
415 # Different versions of MakeMaker and Build use slightly different shebang
416 # fixing strings. This matches most of the ones I've found in my own Perl
417 # distribution, but it may not be bullet-proof.
418
419 my $fixin_rx = qr{^eval 'exec .* \$0 \${1\+"\$@"}'\s*[\r\n]\s*if.+;}ms; ## no critic (RequireExtendedFormatting)
420 if ( $first_stmnt =~ $fixin_rx ) {
421 my $line = $first_stmnt->location()->[0];
422 return { $line => {ALL => 1}, $line + 1 => {ALL => 1} };
423 }
424
425 #No magic shebang was found!
426 return {};
427}
428
429#-----------------------------------------------------------------------------
430
5bf96118 4311;
58a9e587 432
5bf96118
CD
433__END__
434
a73f4a71
JRT
435=pod
436
437=for stopwords pre-caches
438
5bf96118
CD
439=head1 NAME
440
c728943a 441Perl::Critic::Document - Caching wrapper around a PPI::Document.
5bf96118 442
267b39b4 443
5bf96118
CD
444=head1 SYNOPSIS
445
446 use PPI::Document;
447 use Perl::Critic::Document;
448 my $doc = PPI::Document->new('Foo.pm');
449 $doc = Perl::Critic::Document->new($doc);
450 ## Then use the instance just like a PPI::Document
451
267b39b4 452
5bf96118
CD
453=head1 DESCRIPTION
454
455Perl::Critic does a lot of iterations over the PPI document tree via
456the C<PPI::Document::find()> method. To save some time, this class
457pre-caches a lot of the common C<find()> calls in a single traversal.
458Then, on subsequent requests we return the cached data.
459
460This is implemented as a facade, where method calls are handed to the
461stored C<PPI::Document> instance.
462
267b39b4 463
5bf96118
CD
464=head1 CAVEATS
465
466This facade does not implement the overloaded operators from
11f53956
ES
467L<PPI::Document|PPI::Document> (that is, the C<use overload ...>
468work). Therefore, users of this facade must not rely on that syntactic
469sugar. So, for example, instead of C<my $source = "$doc";> you should
470write C<my $source = $doc->content();>
5bf96118
CD
471
472Perhaps there is a CPAN module out there which implements a facade
473better than we do here?
474
267b39b4
ES
475
476=head1 CONSTRUCTOR
477
478=over
479
480=item C<< new($doc) >>
481
482Create a new instance referencing a PPI::Document instance.
483
484
485=back
486
487
5bf96118
CD
488=head1 METHODS
489
490=over
491
267b39b4 492=item C<< new($doc) >>
7076e807
CD
493
494Create a new instance referencing a PPI::Document instance.
495
267b39b4
ES
496
497=item C<< ppi_document() >>
2b6293b2 498
11f53956
ES
499Accessor for the wrapped PPI::Document instance. Note that altering
500this instance in any way can cause unpredictable failures in
501Perl::Critic's subsequent analysis because some caches may fall out of
502date.
2b6293b2 503
5bf96118 504
267b39b4
ES
505=item C<< find($wanted) >>
506
507=item C<< find_first($wanted) >>
fb21e21e 508
267b39b4 509=item C<< find_any($wanted) >>
f5eeac3b 510
fb21e21e 511If C<$wanted> is a simple PPI class name, then the cache is employed.
f5eeac3b
CD
512Otherwise we forward the call to the corresponding method of the
513C<PPI::Document> instance.
5bf96118 514
267b39b4
ES
515
516=item C<< filename() >>
e7f2d995
CD
517
518Returns the filename for the source code if applicable
519(PPI::Document::File) or C<undef> otherwise (PPI::Document).
520
267b39b4
ES
521
522=item C<< isa( $classname ) >>
242f7b08 523
11f53956
ES
524To be compatible with other modules that expect to get a
525PPI::Document, the Perl::Critic::Document class masquerades as the
526PPI::Document class.
242f7b08 527
267b39b4
ES
528
529=item C<< highest_explicit_perl_version() >>
530
11f53956
ES
531Returns a L<version|version> object for the highest Perl version
532requirement declared in the document via a C<use> or C<require>
533statement. Returns nothing if there is no version statement.
267b39b4
ES
534
535
937b8de0
JRT
536=item C<< mark_disabled_lines( @policy_names ) >>
537
538Scans the document for C<"## no critic"> pseudo-pragmas and builds
539an internal table of which of the listed C<@policy_names> have
540been disabled at each line. Returns C<$self>.
541
542
95ebf9b0 543=item C<< is_line_disabled($line, $policy_name) >>
937b8de0
JRT
544
545Returns true if the given C<$policy_name> has been disabled for
546at C<$line> in this document. Otherwise, returns false.
547
95ebf9b0
JRT
548=item C<< useless_no_critic_warnings(@violations) >>
549
550Given a list of violation objects that are assumed to have been found
551in this Document, returns a warning message for each line where a
552policy was disabled using a C<"##no critic"> pseudo-pragma, but
553no violation was actually found on that line. If multiple policies
554are disabled on a given line, then you'll get a warning message
555for each policy.
556
937b8de0 557
5bf96118
CD
558=back
559
267b39b4 560
5bf96118
CD
561=head1 AUTHOR
562
563Chris Dolan <cdolan@cpan.org>
564
267b39b4 565
5bf96118
CD
566=head1 COPYRIGHT
567
20dfddeb 568Copyright (c) 2006-2008 Chris Dolan. All rights reserved.
5bf96118
CD
569
570This program is free software; you can redistribute it and/or modify
571it under the same terms as Perl itself. The full text of this license
572can be found in the LICENSE file included with this module.
573
574=cut
737d3b65
CD
575
576# Local Variables:
577# mode: cperl
578# cperl-indent-level: 4
579# fill-column: 78
580# indent-tabs-mode: nil
581# c-indentation-style: bsd
582# End:
96fed375 583# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :