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