Login
Renamed some of the Statistics methods.
[gknop/Perl-Critic.git] / lib / Perl / Critic.pm
CommitLineData
6036a254 1##############################################################################
aaa8512c
JRT
2# $URL$
3# $Date$
4# $Author$
5# $Revision$
6036a254 6##############################################################################
aaa8512c 7
59b05e08
JRT
8package Perl::Critic;
9
10use strict;
11use warnings;
f7f62580
JRT
12use base qw(Exporter);
13
dc93df4f 14use Carp;
59b05e08 15use File::Spec;
389109ec 16use Scalar::Util qw(blessed);
59b05e08
JRT
17use English qw(-no_match_vars);
18use Perl::Critic::Config;
dc93df4f 19use Perl::Critic::Violation;
5bf96118 20use Perl::Critic::Document;
bbf4108c 21use Perl::Critic::Utils qw{ :characters };
d243bfbf 22use PPI::Document;
ac468e68 23use PPI::Document::File;
59b05e08 24
6036a254 25#-----------------------------------------------------------------------------
f7f62580 26
37915b13 27our $VERSION = 1.051;
f7f62580
JRT
28our @EXPORT_OK = qw(&critique);
29
6036a254 30#-----------------------------------------------------------------------------
dff08b70 31
59b05e08 32sub new {
59b05e08 33 my ( $class, %args ) = @_;
e01de056 34 my $self = bless {}, $class;
1e7b8681 35 $self->{_config} = $args{-config} || Perl::Critic::Config->new( %args );
59b05e08
JRT
36 return $self;
37}
38
6036a254 39#-----------------------------------------------------------------------------
59b05e08 40
dff08b70
JRT
41sub config {
42 my $self = shift;
43 return $self->{_config};
44}
59b05e08 45
6036a254 46#-----------------------------------------------------------------------------
59b05e08 47
dff08b70
JRT
48sub add_policy {
49 my ( $self, @args ) = @_;
50 #Delegate to Perl::Critic::Config
51 return $self->config()->add_policy( @args );
52}
59b05e08 53
6036a254 54#-----------------------------------------------------------------------------
dff08b70
JRT
55
56sub policies {
57 my $self = shift;
58 #Delegate to Perl::Critic::Config
59 return $self->config()->policies();
59b05e08
JRT
60}
61
6036a254 62#-----------------------------------------------------------------------------
dff08b70 63
59b05e08 64sub critique {
7ed796a7 65
f7f62580
JRT
66 #-------------------------------------------------------------------
67 # This subroutine can be called as an object method or as a static
68 # function. In the latter case, the first argument can be a
69 # hashref of configuration parameters that shall be used to create
70 # an object behind the scenes. Note that this object does not
71 # persist. In other words, it is not a singleton. Here are some
72 # of the ways this subroutine might get called:
73 #
74 # #Object style...
75 # $critic->critique( $code );
76 #
77 # #Functional style...
78 # critique( $code );
79 # critique( {}, $code );
80 # critique( {-foo => bar}, $code );
81 #------------------------------------------------------------------
82
83 my ( $self, $source_code ) = @_ >= 2 ? @_ : ( {}, $_[0] );
84 $self = ref $self eq 'HASH' ? __PACKAGE__->new(%{ $self }) : $self;
dc93df4f 85 return if not $source_code; # If no code, then nothing to do.
59b05e08 86
fb1d7f95 87 my $doc = $self->_create_perl_critic_document($source_code);
576f6411
ES
88
89 return $self->_gather_violations($doc);
90}
91
576f6411
ES
92#=============================================================================
93# PRIVATE functions
94
95sub _create_perl_critic_document {
fb1d7f95 96 my ($self, $source_code) = @_;
576f6411 97
4e771b0b
JRT
98 # $source_code can be a file name, or a reference to a
99 # PPI::Document, or a reference to a scalar containing source
100 # code. In the last case, PPI handles the translation for us.
f7f62580 101
e58ec45b
JRT
102 my $doc = _is_ppi_doc( $source_code ) ? $source_code
103 : ref $source_code ? PPI::Document->new($source_code)
104 : PPI::Document::File->new($source_code);
59b05e08
JRT
105
106 # Bail on error
dc93df4f 107 if ( not defined $doc ) {
0e91e2bf
JRT
108 my $errstr = PPI::Document::errstr();
109 my $file = ref $source_code ? undef : $source_code;
110 my $for_file = $file ? qq{ for "$file"} : $EMPTY;
111 croak qq{Warning: Can't parse code: $errstr} . $for_file;
59b05e08
JRT
112 }
113
114 # Pre-index location of each node (for speed)
115 $doc->index_locations();
116
5bf96118 117 # Wrap the doc in a caching layer
576f6411
ES
118 return Perl::Critic::Document->new($doc);
119}
120
121#-----------------------------------------------------------------------------
122
123sub _gather_violations {
124 my ($self, $doc) = @_;
5bf96118 125
1bef6e21
JRT
126 # Disable the magic shebang fix
127 my %is_line_disabled = _unfix_shebang($doc);
59b05e08 128
7ed796a7 129 # Filter exempt code, if desired
dc93df4f 130 if ( not $self->config->force() ) {
410cf90b 131 my @site_policies = $self->config->site_policy_names();
1bef6e21
JRT
132 %is_line_disabled = ( %is_line_disabled,
133 _filter_code($doc, @site_policies) );
7ed796a7 134 }
1e7b8681 135
e58ec45b
JRT
136 # Evaluate each policy
137 my @pols = $self->config->policies();
138 my @violations = map { _critique( $_, $doc, \%is_line_disabled) } @pols;
dc93df4f 139
0e91e2bf
JRT
140 # Some policies emit multiple violations, which tend to drown out the
141 # others. So for those, we squelch out all but the first violation.
142 @violations = _squelch_noisy_violations( @violations );
143
e58ec45b
JRT
144 # If requested, rank violations by their severity and return the top N.
145 if ( @violations && (my $top = $self->config->top()) ) {
146 my $limit = @violations < $top ? $#violations : $top-1;
147 @violations = Perl::Critic::Violation::sort_by_severity(@violations);
148 @violations = ( reverse @violations )[ 0 .. $limit ]; #Slicing...
149 }
dc93df4f 150
e58ec45b
JRT
151 # Always return violations sorted by location
152 return Perl::Critic::Violation->sort_by_location(@violations);
153}
1bef6e21 154
576f6411 155#-----------------------------------------------------------------------------
1bef6e21 156
e58ec45b
JRT
157sub _is_ppi_doc {
158 my ($ref) = @_;
159 return blessed($ref) && $ref->isa('PPI::Document');
160}
dc93df4f 161
e58ec45b 162#-----------------------------------------------------------------------------
c70a9ff6 163
e58ec45b 164sub _critique {
30e552bf 165
e58ec45b
JRT
166 my ($policy, $doc, $is_line_disabled) = @_;
167 my @violations = ();
c70a9ff6 168
e58ec45b
JRT
169 TYPE:
170 for my $type ( $policy->applies_to() ) {
e01de056 171
e58ec45b
JRT
172 ELEMENT:
173 for my $element ( @{ $doc->find($type) || [] } ) {
174
175 # Evaluate the policy on this $element. A policy may
176 # return zero or more violations. We only want the
177 # violations that occur on lines that have not been
178 # disabled.
179
180 VIOLATION:
181 for my $violation ( $policy->violates( $element, $doc ) ) {
182 my $policy_name = ref $policy;
183 my $line = $violation->location()->[0];
184 next VIOLATION if $is_line_disabled->{$line}->{$policy_name};
185 next VIOLATION if $is_line_disabled->{$line}->{ALL};
186 push @violations, $violation;
187 }
188 }
e01de056
JRT
189 }
190
e58ec45b 191 return @violations;
59b05e08
JRT
192}
193
e58ec45b 194#-----------------------------------------------------------------------------
59b05e08
JRT
195
196sub _filter_code {
197
f4938b54 198 my ($doc, @site_policies)= @_;
59b05e08
JRT
199 my $nodes_ref = $doc->find('PPI::Token::Comment') || return;
200 my $no_critic = qr{\A \s* \#\# \s* no \s+ critic}mx;
201 my $use_critic = qr{\A \s* \#\# \s* use \s+ critic}mx;
7ed796a7
JRT
202 my %disabled_lines;
203
59b05e08
JRT
204 PRAGMA:
205 for my $pragma ( grep { $_ =~ $no_critic } @{$nodes_ref} ) {
206
c70a9ff6
JRT
207 # Parse out the list of Policy names after the
208 # 'no critic' pragma. I'm thinking of this just
209 # like a an C<import> argument for real pragmas.
210 my @no_policies = _parse_nocritic_import($pragma, @site_policies);
211
212 # Grab surrounding nodes to determine the context.
213 # This determines whether the pragma applies to
214 # the current line or the block that follows.
209eb6db
JRT
215 my $parent = $pragma->parent();
216 my $grandparent = $parent ? $parent->parent() : undef;
217 my $sib = $pragma->sprevious_sibling();
218
c70a9ff6 219
209eb6db
JRT
220 # Handle single-line usage on simple statements
221 if ( $sib && $sib->location->[0] == $pragma->location->[0] ) {
c70a9ff6
JRT
222 my $line = $pragma->location->[0];
223 for my $policy ( @no_policies ) {
224 $disabled_lines{ $line }->{$policy} = 1;
225 }
209eb6db
JRT
226 next PRAGMA;
227 }
228
229
230 # Handle single-line usage on compound statements
231 if ( ref $parent eq 'PPI::Structure::Block' ) {
5c1bf20d
JRT
232 if ( ref $grandparent eq 'PPI::Statement::Compound'
233 || ref $grandparent eq 'PPI::Statement::Sub' ) {
209eb6db 234 if ( $parent->location->[0] == $pragma->location->[0] ) {
c70a9ff6
JRT
235 my $line = $grandparent->location->[0];
236 for my $policy ( @no_policies ) {
237 $disabled_lines{ $line }->{$policy} = 1;
238 }
209eb6db
JRT
239 next PRAGMA;
240 }
59b05e08
JRT
241 }
242 }
243
209eb6db
JRT
244
245 # Handle multi-line usage. This is either a "no critic" ..
246 # "use critic" region or a block where "no critic" persists
247 # until the end of the scope. The start is the always the "no
248 # critic" which we already found. So now we have to search
249 # for the end.
7ed796a7
JRT
250
251 my $start = $pragma;
252 my $end = $pragma;
253
59b05e08 254 SIB:
7ed796a7
JRT
255 while ( my $sib = $end->next_sibling() ) {
256 $end = $sib; # keep track of last sibling encountered in this scope
257 last SIB
c70a9ff6 258 if $sib->isa('PPI::Token::Comment') && $sib =~ $use_critic;
7ed796a7
JRT
259 }
260
261 # We either found an end or hit the end of the scope.
262 # Flag all intervening lines
263 for my $line ( $start->location->[0] .. $end->location->[0] ) {
c70a9ff6
JRT
264 for my $policy ( @no_policies ) {
265 $disabled_lines{ $line }->{$policy} = 1;
266 }
59b05e08 267 }
59b05e08 268 }
dff08b70 269
7ed796a7 270 return %disabled_lines;
59b05e08 271}
dff08b70 272
6036a254 273#-----------------------------------------------------------------------------
7ed796a7 274
c70a9ff6
JRT
275sub _parse_nocritic_import {
276
c48094aa 277 my ($pragma, @site_policies) = @_;
c70a9ff6 278
c48094aa 279 my $module = qr{ [\w:]+ }mx;
57c51ff5 280 my $delim = qr{ \s* [,\s] \s* }mx;
c0137eab 281 my $qw = qr{ (?: qw )? }mx;
3cab0bc9 282 my $qualifier = qr{ $qw \(? \s* ( $module (?: $delim $module)* ) \s* \)? }mx;
c48094aa 283 my $no_critic = qr{ \A \s* \#\# \s* no \s+ critic \s* $qualifier }mx;
1bef6e21 284
c48094aa 285 if ( my ($module_list) = $pragma =~ $no_critic ) {
c0137eab 286 my @modules = split $delim, $module_list;
c48094aa 287 return map { my $req = $_; grep {m/$req/imx} @site_policies } @modules;
c70a9ff6
JRT
288 }
289
a9c73f99 290 # Default to disabling ALL policies.
c70a9ff6
JRT
291 return qw(ALL);
292}
293
6036a254 294#-----------------------------------------------------------------------------
59b05e08
JRT
295sub _unfix_shebang {
296
0e91e2bf
JRT
297 # When you install a script using ExtUtils::MakeMaker or Module::Build, it
298 # inserts some magical code into the top of the file (just after the
299 # shebang). This code allows people to call your script using a shell,
300 # like `sh my_script`. Unfortunately, this code causes several Policy
301 # violations, so we just disable it as if a "## no critic" comment had
302 # been attached.
59b05e08 303
7ed796a7 304 my $doc = shift;
59b05e08
JRT
305 my $first_stmnt = $doc->schild(0) || return;
306
0e91e2bf
JRT
307 # Different versions of MakeMaker and Build use slightly differnt shebang
308 # fixing strings. This matches most of the ones I've found in my own Perl
309 # distribution, but it may not be bullet-proof.
59b05e08
JRT
310
311 my $fixin_rx = qr{^eval 'exec .* \$0 \${1\+"\$@"}'\s*[\r\n]\s*if.+;};
7ed796a7 312 if ( $first_stmnt =~ $fixin_rx ) {
1bef6e21 313 my $line = $first_stmnt->location()->[0];
c70a9ff6 314 return ( $line => {ALL => 1}, $line + 1 => {ALL => 1} );
7ed796a7 315 }
dff08b70 316
1bef6e21 317 #No magic shebang was found!
7ed796a7 318 return;
59b05e08
JRT
319}
320
0e91e2bf
JRT
321#-----------------------------------------------------------------------------
322# TODO: This sub makes my head hurt. Refactor soon.
323
324sub _squelch_noisy_violations {
325 my @violations = @_;
326 my %seen = ();
327 return grep { my $pol = $_->policy();
328 !( _is_noisy($pol) && $seen{$pol}++ ) } @violations;
329}
330
331#-----------------------------------------------------------------------------
332
333sub _is_noisy {
334 my $policy_name = shift;
55944022
JRT
335 my $ns = 'Perl::Critic::Policy';
336 return $policy_name eq "${ns}::TestingAndDebugging::RequireUseStrict"
337 || $policy_name eq "${ns}::TestingAndDebugging::RequireUseWarnings"
338 || $policy_name eq "${ns}::Modules::RequireExplicitPackage";
0e91e2bf
JRT
339}
340
59b05e08
JRT
3411;
342
6036a254 343#-----------------------------------------------------------------------------
59b05e08
JRT
344
345__END__
346
347=pod
348
9cdbdce6 349=for stopwords DGR INI-style API -params pbp refactored -singlepolicy ben Jore
821d0eb5 350
59b05e08
JRT
351=head1 NAME
352
6ef8f5d3 353Perl::Critic - Critique Perl source code for best-practices
59b05e08
JRT
354
355=head1 SYNOPSIS
356
357 use Perl::Critic;
6bf9b465
JRT
358 my $file = shift;
359 my $critic = Perl::Critic->new();
360 my @violations = $critic->critique($file);
361 print @violations;
59b05e08
JRT
362
363=head1 DESCRIPTION
364
1edbd692
JRT
365Perl::Critic is an extensible framework for creating and applying coding
366standards to Perl source code. Essentially, it is a static source code
367analysis engine. Perl::Critic is distributed with a number of
368L<Perl::Critic::Policy> modules that attempt to enforce various coding
369guidelines. Most Policy modules are based on Damian Conway's book B<Perl Best
370Practices>. However, Perl::Critic is B<not> limited to PBP and will even
371support Policies that contradict Conway. You can enable, disable, and
372customize those Polices through the Perl::Critic interface. You can also
373create new Policy modules that suit your own tastes.
59b05e08 374
7711a331
JRT
375For a command-line interface to Perl::Critic, see the documentation for
376L<perlcritic>. If you want to integrate Perl::Critic with your build process,
377L<Test::Perl::Critic> provides an interface that is suitable for test scripts.
378For the ultimate convenience (at the expense of some flexibility) see the
379L<criticism> pragma.
0304068a 380
1edbd692
JRT
381Win32 and ActivePerl users can find PPM distributions of Perl::Critic at
382L<http://theoryx5.uwinnipeg.ca/ppms/>.
59b05e08 383
1edbd692
JRT
384If you'd like to try L<Perl::Critic> without installing anything, there is a
385web-service available at L<http://perlcritic.com>. The web-service does not
386yet support all the configuration features that are available in the native
387Perl::Critic API, but it should give you a good idea of what it does. You can
388also invoke the perlcritic web-service from the command-line by doing an
389HTTP-post, such as one of these:
e518ead4 390
7711a331
JRT
391 $> POST http://perlcritic.com/perl/critic.pl < MyModule.pm
392 $> lwp-request -m POST http://perlcritic.com/perl/critic.pl < MyModule.pm
393 $> wget -q -O - --post-file=MyModule.pm http://perlcritic.com/perl/critic.pl
e518ead4 394
1edbd692
JRT
395Please note that the perlcritic web-service is still alpha code. The URL and
396interface to the service are subject to change.
8d36cd6f 397
59b05e08
JRT
398=head1 CONSTRUCTOR
399
400=over 8
401
7b84ff16
JRT
402=item C<< new( [ -profile => $FILE, -severity => $N, -theme => $string, -include => \@PATTERNS, -exclude => \@PATTERNS, -top => $N, -only => $B, -force => $B, -verbose => $N ] ) >>
403
b4c7e33c 404=item C<< new( -config => Perl::Critic::Config->new() ) >>
7b84ff16
JRT
405
406=item C<< new() >>
59b05e08 407
1edbd692
JRT
408Returns a reference to a new Perl::Critic object. Most arguments are just
409passed directly into L<Perl::Critic::Config>, but I have described them here
410as well. The default value for all arguments can be defined in your
411F<.perlcriticrc> file. See the L<"CONFIGURATION"> section for more
412information about that. All arguments are optional key-value pairs as
413follows:
414
415B<-profile> is a path to a configuration file. If C<$FILE> is not defined,
416Perl::Critic::Config attempts to find a F<.perlcriticrc> configuration file in
417the current directory, and then in your home directory. Alternatively, you
418can set the C<PERLCRITIC> environment variable to point to a file in another
419location. If a configuration file can't be found, or if C<$FILE> is an empty
420string, then all Policies will be loaded with their default configuration.
421See L<"CONFIGURATION"> for more information.
422
423B<-severity> is the minimum severity level. Only Policy modules that have a
424severity greater than C<$N> will be applied. Severity values are integers
425ranging from 1 (least severe) to 5 (most severe). The default is 5. For a
426given C<-profile>, decreasing the C<-severity> will usually reveal more Policy
427violations. You can set the default value for this option in your
428F<.perlcriticrc> file. Users can redefine the severity level for any Policy
429in their F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
430
431If it is difficult for you to remember whether severity "5" is the most or
432least restrictive level, then you can use one of these named values:
097f3455 433
7711a331 434 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
097f3455
JRT
435 --------------------------------------------------------
436 -severity => 'gentle' -severity => 5
437 -severity => 'stern' -severity => 4
438 -severity => 'harsh' -severity => 3
439 -severity => 'cruel' -severity => 2
440 -severity => 'brutal' -severity => 1
441
1edbd692 442B<-theme> is special expression that determines which Policies to apply based
1c5955e4
JRT
443on their respective themes. For example, the following would load only
444Policies that have a 'bugs' AND 'pbp' theme:
7b84ff16 445
1c5955e4
JRT
446 my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );
447
448Unless the C<-severity> option is explicitly given, setting C<-theme> silently
1edbd692
JRT
449causes the C<-severity> to be set to 1. You can set the default value for
450this option in your F<.perlcriticrc> file. See the L<"POLICY THEMES"> section
1c5955e4 451for more information about themes.
7b84ff16 452
7b84ff16 453
1edbd692
JRT
454B<-include> is a reference to a list of string C<@PATTERNS>. Policy modules
455that match at least one C<m/$PATTERN/imx> will always be loaded, irrespective
456of all other settings. For example:
6bf9b465
JRT
457
458 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
459
1edbd692
JRT
460This would cause Perl::Critic to apply all the C<CodeLayout::*> Policy modules
461even though they have a severity level that is less than 4. You can set the
462default value for this option in your F<.perlcriticrc> file. You can also use
463C<-include> in conjunction with the C<-exclude> option. Note that C<-exclude>
464takes precedence over C<-include> when a Policy matches both patterns.
6bf9b465 465
1edbd692
JRT
466B<-exclude> is a reference to a list of string C<@PATTERNS>. Policy modules
467that match at least one C<m/$PATTERN/imx> will not be loaded, irrespective of
468all other settings. For example:
6bf9b465
JRT
469
470 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
471
1edbd692
JRT
472This would cause Perl::Critic to not apply the C<RequireUseStrict> and
473C<ProhibitNoStrict> Policy modules even though they have a severity level that
474is greater than 1. You can set the default value for this option in your
475F<.perlcriticrc> file. You can also use C<-exclude> in conjunction with the
476C<-include> option. Note that C<-exclude> takes precedence over C<-include>
477when a Policy matches both patterns.
478
479B<-singlepolicy> is a string C<PATTERN>. Only one policy that matches
480C<m/$PATTERN/imx> will be used. Policies that do not match will be excluded.
481This option has precedence over the C<-severity>, C<-theme>, C<-include>,
482C<-exclude>, and C<-only> options. You can set the default value for this
483option in your F<.perlcriticrc> file.
484
485B<-top> is the maximum number of Violations to return when ranked by their
486severity levels. This must be a positive integer. Violations are still
487returned in the order that they occur within the file. Unless the
488C<-severity> option is explicitly given, setting C<-top> silently causes the
489C<-severity> to be set to 1. You can set the default value for this option in
490your F<.perlcriticrc> file.
491
492B<-only> is a boolean value. If set to a true value, Perl::Critic will only
493choose from Policies that are mentioned in the user's profile. If set to a
494false value (which is the default), then Perl::Critic chooses from all the
495Policies that it finds at your site. You can set the default value for this
496option in your F<.perlcriticrc> file.
e01de056 497
097f3455
JRT
498B<-force> is a boolean value that controls whether Perl::Critic observes the
499magical C<"## no critic"> pseudo-pragmas in your code. If set to a true
500value, Perl::Critic will analyze all code. If set to a false value (which is
501the default) Perl::Critic will ignore code that is tagged with these comments.
1edbd692
JRT
502See L<"BENDING THE RULES"> for more information. You can set the default
503value for this option in your F<.perlcriticrc> file.
59b05e08 504
1edbd692
JRT
505B<-verbose> can be a positive integer (from 1 to 11), or a literal format
506specification. See L<Perl::Critic::Violations> for an explanation of format
507specifications. You can set the default value for this option in your
508F<.perlcriticrc> file.
7b84ff16 509
1edbd692
JRT
510B<-config> is a reference to a L<Perl::Critic::Config> object. If you have
511created your own Config object for some reason, you can pass it in here
512instead of having Perl::Critic create one for you. Using the C<-config>
513option causes all the other options to be silently ignored.
58e3f828 514
59b05e08
JRT
515=back
516
517=head1 METHODS
518
519=over 8
520
6d9feae6 521=item C<critique( $source_code )>
1e7b8681
JRT
522
523Runs the C<$source_code> through the Perl::Critic engine using all the
1edbd692
JRT
524Policies that have been loaded into this engine. If C<$source_code> is a
525scalar reference, then it is treated as a string of actual Perl code. If
526C<$source_code> is a reference to an instance of L<PPI::Document>, then that
527instance is used directly. Otherwise, it is treated as a path to a local file
528containing Perl code. This method returns a list of
529L<Perl::Critic::Violation> objects for each violation of the loaded Policies.
530The list is sorted in the order that the Violations appear in the code. If
531there are no violations, this method returns an empty list.
1e7b8681 532
520f00c6 533=item C<< add_policy( -policy => $policy_name, -params => \%param_hash ) >>
59b05e08 534
1edbd692
JRT
535Creates a Policy object and loads it into this Critic. If the object cannot
536be instantiated, it will throw a fatal exception. Otherwise, it returns a
537reference to this Critic.
59b05e08 538
1edbd692
JRT
539B<-policy> is the name of a L<Perl::Critic::Policy> subclass module. The
540C<'Perl::Critic::Policy'> portion of the name can be omitted for brevity.
541This argument is required.
59b05e08 542
1edbd692
JRT
543B<-params> is an optional reference to a hash of Policy parameters. The
544contents of this hash reference will be passed into to the constructor of the
545Policy module. See the documentation in the relevant Policy module for a
546description of the arguments it supports.
59b05e08 547
dc93df4f 548=item C< policies() >
59b05e08 549
1edbd692
JRT
550Returns a list containing references to all the Policy objects that have been
551loaded into this engine. Objects will be in the order that they were loaded.
59b05e08 552
dc93df4f 553=item C< config() >
dff08b70 554
54c10e6b
JRT
555Returns the L<Perl::Critic::Config> object that was created for or given
556to this Critic.
dff08b70 557
59b05e08
JRT
558=back
559
f7f62580
JRT
560=head1 FUNCTIONAL INTERFACE
561
1edbd692
JRT
562For those folks who prefer to have a functional interface, The C<critique>
563method can be exported on request and called as a static function. If the
564first argument is a hashref, its contents are used to construct a new
565Perl::Critic object internally. The keys of that hash should be the same as
566those supported by the C<Perl::Critic::new> method. Here are some examples:
f7f62580
JRT
567
568 use Perl::Critic qw(critique);
569
570 # Use default parameters...
571 @violations = critique( $some_file );
572
573 # Use custom parameters...
574 @violations = critique( {-severity => 2}, $some_file );
575
d47377d5
JRT
576 # As a one-liner
577 %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
578
f7f62580
JRT
579None of the other object-methods are currently supported as static
580functions. Sorry.
581
59b05e08
JRT
582=head1 CONFIGURATION
583
1edbd692
JRT
584Most of the settings for Perl::Critic and each of the Policy modules can be
585controlled by a configuration file. The default configuration file is called
586F<.perlcriticrc>. Perl::Critic will look for this file in the current
587directory first, and then in your home directory. Alternatively, you can set
588the C<PERLCRITIC> environment variable to explicitly point to a different file
589in another location. If none of these files exist, and the C<-profile> option
590is not given to the constructor, then all the modules that are found in the
7b84ff16
JRT
591Perl::Critic::Policy namespace will be loaded with their default
592configuration.
593
1edbd692
JRT
594The format of the configuration file is a series of INI-style blocks that
595contain key-value pairs separated by '='. Comments should start with '#' and
596can be placed on a separate line or after the name-value pairs if you desire.
7b84ff16 597
1c5955e4
JRT
598Default settings for Perl::Critic itself can be set B<before the first named
599block.> For example, putting any or all of these at the top of your
600configuration file will set the default value for the corresponding
601constructor argument.
7b84ff16 602
097f3455 603 severity = 3 #Integer or named level
c3b1b521
JRT
604 only = 1 #Zero or One
605 force = 0 #Zero or One
606 verbose = 4 #Integer or format spec
607 top = 50 #A positive integer
1edbd692 608 theme = (pbp || security) && bugs #A theme expression
c3b1b521
JRT
609 include = NamingConventions ClassHierarchies #Space-delimited list
610 exclude = Variables Modules::RequirePackage #Space-delimited list
7b84ff16 611
7711a331 612The remainder of the configuration file is a series of blocks like this:
59b05e08 613
7b84ff16
JRT
614 [Perl::Critic::Policy::Category::PolicyName]
615 severity = 1
4cd0567c 616 set_themes = foo bar
c94fb804 617 add_themes = baz
7b84ff16
JRT
618 arg1 = value1
619 arg2 = value2
59b05e08 620
1edbd692
JRT
621C<Perl::Critic::Policy::Category::PolicyName> is the full name of a module
622that implements the policy. The Policy modules distributed with Perl::Critic
623have been grouped into categories according to the table of contents in Damian
624Conway's book B<Perl Best Practices>. For brevity, you can omit the
625C<'Perl::Critic::Policy'> part of the module name.
59b05e08 626
1edbd692
JRT
627C<severity> is the level of importance you wish to assign to the Policy. All
628Policy modules are defined with a default severity value ranging from 1 (least
629severe) to 5 (most severe). However, you may disagree with the default
630severity and choose to give it a higher or lower severity, based on your own
631coding philosophy. You can set the C<severity> to an integer from 1 to 5, or
632use one of the equivalent names:
097f3455 633
7711a331 634 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
097f3455
JRT
635 ----------------------------------------------------
636 gentle 5
637 stern 4
638 harsh 3
639 cruel 2
640 brutal 1
641
7711a331
JRT
642C<set_themes> sets the theme for the Policy and overrides its default theme.
643The argument is a string of one or more whitespace-delimited alphanumeric
097f3455
JRT
644words. Themes are case-insensitive. See L<"POLICY THEMES"> for more
645information.
646
1edbd692
JRT
647C<add_themes> appends to the default themes for this Policy. The argument is
648a string of one or more whitespace-delimited words. Themes are
649case-insensitive. See L<"POLICY THEMES"> for more information.
59b05e08 650
1edbd692
JRT
651The remaining key-value pairs are configuration parameters that will be passed
652into the constructor for that Policy. The constructors for most Policy
653objects do not support arguments, and those that do should have reasonable
654defaults. See the documentation on the appropriate Policy module for more
655details.
59b05e08 656
1edbd692
JRT
657Instead of redefining the severity for a given Policy, you can completely
658disable a Policy by prepending a '-' to the name of the module in your
659configuration file. In this manner, the Policy will never be loaded,
660regardless of the C<-severity> given to the Perl::Critic constructor.
59b05e08
JRT
661
662A simple configuration might look like this:
663
7b84ff16
JRT
664 #--------------------------------------------------------------
665 # I think these are really important, so always load them
666
667 [TestingAndDebugging::RequireUseStrict]
668 severity = 5
59b05e08 669
7b84ff16
JRT
670 [TestingAndDebugging::RequireUseWarnings]
671 severity = 5
59b05e08 672
7b84ff16
JRT
673 #--------------------------------------------------------------
674 # I think these are less important, so only load when asked
59b05e08 675
7b84ff16
JRT
676 [Variables::ProhibitPackageVars]
677 severity = 2
59b05e08 678
7b84ff16 679 [ControlStructures::ProhibitPostfixControls]
097f3455
JRT
680 allow = if unless # My custom configuration
681 severity = cruel # Same as "severity = 2"
59b05e08 682
7b84ff16
JRT
683 #--------------------------------------------------------------
684 # Give these policies a custom theme. I can activate just
685 # these policies by saying `perlcritic -theme larry`
59b05e08 686
7b84ff16 687 [Modules::RequireFilenameMatchesPackage]
c94fb804 688 add_themes = larry
59b05e08 689
7b84ff16 690 [TestingAndDebugging::RequireTestLables]
c94fb804 691 add_themes = larry curly moe
59b05e08 692
7b84ff16
JRT
693 #--------------------------------------------------------------
694 # I do not agree with these at all, so never load them
1e7b8681 695
7b84ff16
JRT
696 [-NamingConventions::ProhibitMixedCaseVars]
697 [-NamingConventions::ProhibitMixedCaseSubs]
698
699 #--------------------------------------------------------------
700 # For all other Policies, I accept the default severity,
701 # so no additional configuration is required for them.
8bc162ba 702
b87fc7eb 703For additional configuration examples, see the F<perlcriticrc> file
16cfe89e 704that is included in this F<examples> directory of this distribution.
b87fc7eb 705
55249663
JRT
706Damian Conway's own Perl::Critic configuration is also included in this
707distribution as F<examples/perlcriticrc-conway>.
e87a2153 708
59b05e08
JRT
709=head1 THE POLICIES
710
7711a331
JRT
711A large number of Policy modules are distributed with Perl::Critic. They are
712described briefly in the companion document L<Perl::Critic::PolicySummary> and
713in more detail in the individual modules themselves. Say C<"perlcritic -doc
714PATTERN"> to see the perldoc for all Policy modules that match the regex
715C<m/PATTERN/imx>
38ce10c1 716
a41e8614
ES
717There are a number of distributions of additional policies on CPAN. If
718L<Perl::Critic> doesn't contain a policy that you want, some one may have
719already written it. Some of these can be found via L<Bundle::Perl::Critic>.
720
7b84ff16 721
7711a331 722=head1 POLICY THEMES
2c2751eb 723
7711a331
JRT
724Each Policy is defined with one or more "themes". Themes can be used to
725create arbitrary groups of Policies. They are intended to provide an
726alternative mechanism for selecting your preferred set of Policies. For
727example, you may wish disable a certain subset of Policies when analyzing test
728scripts. Conversely, you may wish to enable only a specific subset of
729Policies when analyzing modules.
7b84ff16 730
c8dbb393 731The Policies that ship with Perl::Critic are have been broken into the
7711a331
JRT
732following themes. This is just our attempt to provide some basic logical
733groupings. You are free to invent new themes that suit your needs.
c8dbb393
JRT
734
735 THEME DESCRIPTION
736 --------------------------------------------------------------------------
737 core All policies that ship with Perl::Critic
738 pbp Policies that come directly from "Perl Best Practices"
739 bugs Policies that that prevent or reveal bugs
740 maintenance Policies that affect the long-term health of the code
741 cosmetic Policies that only have a superficial effect
742 complexity Policies that specificaly relate to code complexity
7711a331 743 security Policies that relate to security issues
c8dbb393
JRT
744 tests Policies that are specific to test scripts
745
746
747Any Policy may fit into multiple themes. Say C<"perlcritic -list"> to get a
748listing of all available Policies and the themes that are associated with each
749one. You can also change the theme for any Policy in your F<.perlcriticrc>
750file. See the L<"CONFIGURATION"> section for more information about that.
7b84ff16 751
14d80662
JRT
752Using the C<-theme> option, you can create an arbitrarily complex rule that
753determines which Policies will be loaded. Precedence is the same as regular
754Perl code, and you can use parens to enforce precedence as well. Supported
755operators are:
7b84ff16 756
14d80662 757 Operator Altertative Example
c3b1b521 758 ----------------------------------------------------------------------------
14d80662
JRT
759 && and 'pbp && core'
760 || or 'pbp || (bugs && security)'
761 ! not 'pbp && ! (portability || complexity)'
7b84ff16 762
14d80662
JRT
763Theme names are case-insensitive. If the C<-theme> is set to an empty string,
764then it evaluates as true all Policies.
7b84ff16 765
59b05e08
JRT
766=head1 BENDING THE RULES
767
1edbd692
JRT
768Perl::Critic takes a hard-line approach to your code: either you comply or you
769don't. In the real world, it is not always practical (nor even possible) to
770fully comply with coding standards. In such cases, it is wise to show that
771you are knowingly violating the standards and that you have a Damn Good Reason
772(DGR) for doing so.
59b05e08 773
1edbd692
JRT
774To help with those situations, you can direct Perl::Critic to ignore certain
775lines or blocks of code by using pseudo-pragmas:
59b05e08
JRT
776
777 require 'LegacyLibaray1.pl'; ## no critic
778 require 'LegacyLibrary2.pl'; ## no critic
779
780 for my $element (@list) {
781
782 ## no critic
783
784 $foo = ""; #Violates 'ProhibitEmptyQuotes'
785 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
786 #Some more evil code...
787
788 ## use critic
789
790 #Some good code...
791 do_something($_);
792 }
793
1edbd692
JRT
794The C<"## no critic"> comments direct Perl::Critic to ignore the remaining
795lines of code until the end of the current block, or until a C<"## use
796critic"> comment is found (whichever comes first). If the C<"## no critic">
797comment is on the same line as a code statement, then only that line of code
798is overlooked. To direct perlcritic to ignore the C<"## no critic"> comments,
799use the C<-force> option.
800
801A bare C<"## no critic"> comment disables all the active Policies. If you
802wish to disable only specific Policies, add a list of Policy names as
803arguments, just as you would for the C<"no strict"> or C<"no warnings">
804pragmas. For example, this would disable the C<ProhibitEmptyQuotes> and
805C<ProhibitPostfixControls> policies until the end of the block or until the
806next C<"## use critic"> comment (whichever comes first):
c70a9ff6 807
c48094aa 808 ## no critic (EmptyQuotes, PostfixControls)
c70a9ff6 809
7711a331
JRT
810 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
811 $foo = "";
812
813 # Now exempt ControlStructures::ProhibitPostfixControls
814 $barf = bar() if $foo;
c70a9ff6 815
7711a331
JRT
816 # Still subjected to ValuesAndExpression::RequireNumberSeparators
817 $long_int = 10000000000;
818
819Since the Policy names are matched against the C<"## no critic"> arguments as
820regular expressions, you can abbreviate the Policy names or disable an entire
1bef6e21 821family of Policies in one shot like this:
c70a9ff6 822
c48094aa 823 ## no critic (NamingConventions)
c70a9ff6 824
7711a331
JRT
825 # Now exempt from NamingConventions::ProhibitMixedCaseVars
826 my $camelHumpVar = 'foo';
827
828 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
829 sub camelHumpSub {}
c70a9ff6 830
1edbd692
JRT
831The argument list must be enclosed in parens and must contain one or more
832comma-separated barewords (e.g. don't use quotes). The C<"## no critic">
833pragmas can be nested, and Policies named by an inner pragma will be disabled
834along with those already disabled an outer pragma.
c70a9ff6 835
1edbd692
JRT
836Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to an entire
837block of code. In those cases, C<"## no critic"> must appear on the line
838where the violation is reported. For example:
35892a39
JRT
839
840 sub complicated_function { ## no critic (ProhibitExcessComplexity)
841 # Your code here...
842 }
843
35892a39
JRT
844Policies such as C<Documentation::RequirePodSections> apply to the entire
845document, in which case violations are reported at line 1. But if the file
846requires a shebang line, it is impossible to put C<"## no critic"> on the
847first line of the file. This is a known limitation and it will be addressed
848in a future release. As a workaround, you can disable the affected policies
849at the command-line or in your F<.perlcriticrc> file. But beware that this
850will affect the analysis of B<all> files.
851
1edbd692
JRT
852Use this feature wisely. C<"## no critic"> should be used in the smallest
853possible scope, or only on individual lines of code. And you should always be
854as specific as possible about which policies you want to disable (i.e. never
855use a bare C<"## no critic">). If Perl::Critic complains about your code, try
856and find a compliant solution before resorting to this feature.
1c5955e4 857
21f4a0d3
JRT
858=head1 IMPORTANT CHANGES
859
1edbd692
JRT
860Perl-Critic is evolving rapidly, so some of the interfaces have changed in
861ways that are not backward-compatible. If you have been using an older
862version of Perl-Critic and/or you have been developing custom Policy modules,
863please read this section carefully.
21f4a0d3 864
cc94598c
JRT
865=head2 VERSION 0.23
866
867In version 0.23, the syntax for theme rules changed. The mathematical
868operators ( "*", "+", "-" ) are no longer supported. You must use logical
869operators instead ( "&&", "!", "||" ). However the meanings of these
1c5955e4 870operators is effectively the same. See L<"POLICY THEMES"> for more details.
cc94598c 871
c3b1b521
JRT
872=head2 VERSION 0.21
873
1edbd692
JRT
874In version 0.21, we introduced the concept of policy "themes". All you
875existing custom Policies should still be compatible. But to take advantage of
876the theme feature, you should add a C<default_themes> method to your custom
877Policy modules. See L<Perl::Critic::DEVELOPER> for an up-to-date guide on
878creating Policy modules.
c3b1b521 879
1edbd692
JRT
880The internals of Perl::Critic were also refactored significantly. The public
881API is largely unchanged, but if you've been accessing bits inside
882Perl::Critic, then you may be in for a surprise.
c3b1b521 883
1bef6e21 884=head2 VERSION 0.16
21f4a0d3 885
1edbd692
JRT
886Starting in version 0.16, you can add a list Policy names as arguments to the
887C<"## no critic"> pseudo-pragma. This feature allows you to disable specific
888policies. So if you have been in the habit of adding additional words after
889C<"no critic">, then those words might cause unexpected results. If you want
890to append other stuff to the C<"## no critic"> comment, then terminate the
891pseudo-pragma with a semi-colon, and then start another comment. For example:
1bef6e21 892
c3b1b521
JRT
893 #This may not work as expected.
894 $email = 'foo@bar.com'; ## no critic for literal '@'
1bef6e21 895
c3b1b521
JRT
896 #This will work.
897 $email = 'foo@bar.com'; ## no critic; #for literal '@'
1bef6e21 898
c3b1b521
JRT
899 #This is even better.
900 $email = 'foo@bar.com'; ## no critic (RequireInterpolation);
21f4a0d3
JRT
901
902=head2 VERSION 0.14
903
1edbd692
JRT
904Starting in version 0.14, the interface to L<Perl::Critic::Violation> changed.
905This will also break any custom Policy modules that you might have written for
906earlier modules. See L<Perl::Critic::DEVELOPER> for an up-to-date guide on
907creating Policy modules.
21f4a0d3 908
1edbd692
JRT
909The notion of "priority" was also replaced with "severity" in version 0.14.
910Consequently, the default behavior of Perl::Critic is to only load the most
911"severe" Policy modules, rather than loading all of them. This decision was
912based on user-feedback suggesting that Perl-Critic should be less critical for
913new users, and should steer them toward gradually increasing the strictness as
914they progressively adopt better coding practices.
21f4a0d3 915
1bef6e21
JRT
916=head2 VERSION 0.11
917
1edbd692
JRT
918Starting in version 0.11, the internal mechanics of Perl-Critic were rewritten
919so that only one traversal of the PPI document tree is required.
920Unfortunately, this will break any custom Policy modules that you might have
921written for earlier versions. Converting your policies to work with the new
922version is pretty easy and actually results in cleaner code. See
923L<Perl::Critic::DEVELOPER> for an up-to-date guide on creating Policy modules.
1bef6e21 924
b87b00dd
JRT
925=head1 THE L<Perl::Critic> PHILOSOPHY
926
927 Coding standards are deeply personal and highly subjective. The
1bef6e21
JRT
928 goal of Perl::Critic is to help you write code that conforms with a
929 set of best practices. Our primary goal is not to dictate what
b87b00dd 930 those practices are, but rather, to implement the practices
0c8fc9e4 931 discovered by others. Ultimately, you make the rules --
1bef6e21
JRT
932 Perl::Critic is merely a tool for encouraging consistency. If there
933 is a policy that you think is important or that we have overlooked,
934 we would be very grateful for contributions, or you can simply load
935 your own private set of policies into Perl::Critic.
b87b00dd 936
59b05e08
JRT
937=head1 EXTENDING THE CRITIC
938
1edbd692
JRT
939The modular design of Perl::Critic is intended to facilitate the addition of
940new Policies. You'll need to have some understanding of L<PPI>, but most
941Policy modules are pretty straightforward and only require about 20 lines of
942code. Please see the L<Perl::Critic::DEVELOPER> file included in this
943distribution for a step-by-step demonstration of how to create new Policy
944modules.
59b05e08 945
524bce7c
JRT
946If you develop any new Policy modules, feel free to send them to C<<
947<thaljef@cpan.org> >> and I'll be happy to put them into the Perl::Critic
948distribution. Or if you would like to work on the Perl::Critic project
949directly, check out our repository at L<http://perlcritic.tigris.org>. To
950subscribe to our mailing list, send a message to C<<
951<dev-subscribe@perlcritic.tigris.org> >>.
952
953The Perl::Critic team is also available for hire. If your organization has
954its own coding standards, we can create custom Policies to enforce your local
955guidelines. Or if your code base is prone to a particular defect pattern, we
956can design Policies that will help you catch those costly defects B<before>
7edfc889 957they go into production. To discuss your needs with the Perl::Critic team,
524bce7c 958just contact C<< <thaljef@cpan.org> >>.
59b05e08 959
59b05e08
JRT
960=head1 PREREQUISITES
961
962Perl::Critic requires the following modules:
963
1edbd692
JRT
964L<B::Keywords>
965
59b05e08
JRT
966L<Config::Tiny>
967
968L<File::Spec>
969
1e7b8681
JRT
970L<IO::String>
971
59b05e08
JRT
972L<List::Util>
973
974L<List::MoreUtils>
975
1e7b8681
JRT
976L<Module::Pluggable>
977
978L<PPI>
979
59b05e08
JRT
980L<Pod::Usage>
981
982L<Pod::PlainText>
983
59b05e08
JRT
984L<String::Format>
985
986The following modules are optional, but recommended for complete
987testing:
988
989L<Test::Pod>
990
991L<Test::Pod::Coverage>
992
59b05e08
JRT
993=head1 BUGS
994
1edbd692
JRT
995Scrutinizing Perl code is hard for humans, let alone machines. If you find
996any bugs, particularly false-positives or false-negatives from a
1bef6e21 997Perl::Critic::Policy, please submit them to
59b05e08
JRT
998L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
999
fc0fffee
ES
1000Most policies will produce false-negatives if they cannot understand a
1001particular block of code.
1002
59b05e08
JRT
1003=head1 CREDITS
1004
b87b00dd 1005Adam Kennedy - For creating L<PPI>, the heart and soul of L<Perl::Critic>.
59b05e08 1006
b87b00dd 1007Damian Conway - For writing B<Perl Best Practices>, finally :)
59b05e08 1008
b87b00dd 1009Chris Dolan - For contributing the best features and Policy modules.
59b05e08 1010
7711a331 1011Andy Lester - Wise sage and master of all-things-testing.
9cdbdce6 1012
7711a331 1013Elliot Shank - The self-proclaimed quality freak.
9cdbdce6 1014
7711a331 1015Giuseppe Maxia - For all the great ideas and positive encouragement.
9cdbdce6 1016
b87b00dd 1017and Sharon, my wife - For putting up with my all-night code sessions.
59b05e08
JRT
1018
1019=head1 AUTHOR
1020
1021Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1022
1023=head1 COPYRIGHT
1024
0d5b2dca 1025Copyright (c) 2005-2007 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08 1026
1edbd692
JRT
1027This program is free software; you can redistribute it and/or modify it under
1028the same terms as Perl itself. The full text of this license can be found in
1029the LICENSE file included with this module.
59b05e08
JRT
1030
1031=cut
737d3b65 1032
7711a331 1033##############################################################################
737d3b65
CD
1034# Local Variables:
1035# mode: cperl
1036# cperl-indent-level: 4
1037# fill-column: 78
1038# indent-tabs-mode: nil
1039# c-indentation-style: bsd
1040# End:
345c7562 1041# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab :