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