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