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