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