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