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