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 / DEVELOPER.pod
1 ##############################################################################
2 #      $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/Perl-Critic/lib/Perl/Critic/DEVELOPER.pod $
3 #     $Date: 2008-07-03 10:19:10 -0500 (Thu, 03 Jul 2008) $
4 #   $Author: clonezone $
5 # $Revision: 2489 $
6 ##############################################################################
7
8 =pod
9
10 =for stopwords lookup RequireBlockGrep
11
12 =head1 NAME
13
14 Perl::Critic::DEVELOPER - How to make new Perl::Critic::Policy modules.
15
16
17 =head1 DESCRIPTION
18
19 For developers who want to create custom coding standards, the
20 following tells how to create a Policy module for L<Perl::Critic>.
21 Although the Perl::Critic distribution already includes a number of
22 Policies based on Damian Conway's book I<Perl Best Practices> (which
23 will be referred to via "I<PBP>" from here on), Perl::Critic is not
24 limited to his guidelines and can be used to enforce any practice,
25 preference, or style that you want to follow.  You can even write
26 Policies to enforce contradictory guidelines.  All you need to do is
27 write a corresponding L<Perl::Critic::Policy> subclass, which may
28 require as little as 10 lines of code.
29
30
31 =head1 BACKGROUND
32
33 The heart of Perl::Critic is L<PPI>, a parser and lexer for Perl.  PPI
34 transforms Perl source code into a Document Object Model (DOM).  Each
35 token in the document is represented by a PPI class, such as
36 L<PPI::Token::Operator> or L<PPI::Token::Word>, and then organized
37 into structure classes, like L<PPI::Statement::Expression> and
38 L<PPI::Structure::Subroutine>. The root node of the hierarchy is the
39 L<PPI::Document>.
40
41 The L<Perl::Critic> engine traverses each node in the L<PPI::Document>
42 tree and invokes each of the L<Perl::Critic::Policy> subclasses at the
43 appropriate node.  The Policy can inspect the node, look at the
44 surrounding nodes, and do whatever else it wants.  If the Policy
45 decides that that a coding standard has been violated, it returns one
46 or more L<Perl::Critic::Violation> objects.  If there are no
47 violations, then the Policy returns nothing.
48
49 Policies are usually written based on existing policies, so let's look
50 at one to see how it works.  The F<RequireBlockGrep.pm> Policy is
51 relatively simple and demonstrates most of the important issues.  The
52 goal of this Policy is to enforce that every call to C<grep> uses a
53 block for the first argument and not an expression.  The reasons for
54 this Policy are discussed in detail in I<PBP>.
55
56
57 =head1 EXAMPLE POLICY
58
59 First, the Policy module needs to have a name.  Perl::Critic uses
60 L<Module::Pluggable> to automatically discover all modules in the
61 C<Perl::Critic::Policy> namespace.  Also, we've adopted the convention
62 of grouping Policies into directories according to the chapters of
63 I<PBP>.  Since the goal of this Policy is to enforce the use of block
64 arguments to C<grep> and it comes from the "Builtin Functions" chapter
65 of I<PBP>, we call it
66 C<"Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep">.
67
68     package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep;
69
70 Next, we set some pragmas and load the modules that we'll need.  All
71 Policy modules inherit from the L<Perl::Critic::Policy> class, which
72 provides no-op implementations of the basic methods.  Our job is to
73 override these methods to make them do something useful.
74
75 Technically, C<use strict> and C<use warnings> are optional, but we
76 don't want Perl::Critic to be a hypocrite, now do we?
77
78     use strict;
79     use warnings;
80
81     use Readonly;
82
83     use Perl::Critic::Utils qw{ :severities :classification :ppi };
84     use base 'Perl::Critic::Policy';
85
86     our $VERSION = '1.05';
87
88 Next, we'll declare a description and explanation for this Policy.
89 The description is always just a string that basically says "this is
90 what's wrong."  The explanation can be either a string with further
91 details, or a reference to an array of integers that correspond to
92 page numbers in I<PBP>.  We make them read-only because they never
93 change.  (See
94 L<Perl::Critic::ValuesAndExpressions::ProhibitConstantPragma> for why
95 we don't C<use constant>.)
96
97     Readonly::Scalar my $DESC => q{Expression form of "grep"};
98     Readonly::Scalar my $EXPL => [ 169 ];
99
100 Most policies don't need to override the C<initialize_if_enabled()>
101 method provided by L<Perl::Critic::Policy>.  However, if your Policy
102 is configurable via F<.perlcriticrc>, you should implement a
103 C<supported_parameters()> method and need to implement
104 C<initialize_if_enabled()> to examine the C<$config> values.  Since
105 this Policy isn't configurable, we'll declare that by providing an
106 implementation of C<supported_parameters()> that returns an empty
107 list.
108
109     sub supported_parameters { return ()                  }
110
111 Next, we define the C<default_severity()> method, which must return an
112 integer indicating the severity of violating this Policy.  Severity
113 values range from 1 to 5, where 5 is the "most severe."  In general,
114 level 5 is reserved for things that are frequently misused and/or
115 cause bugs.  Level 1 is for things that are highly subjective or
116 purely cosmetic.  The L<Perl::Critic::Utils> package exports several
117 severity constants that you can use here via the C<:severities> tag.
118
119     sub default_severity     { return $SEVERITY_HIGH      }
120
121 Likewise, the C<default_themes()> method returns a list of theme
122 names.  Themes are intended to be named groups of Policies.  All
123 Policies that ship with Perl::Critic have a C<"core"> theme.  Since
124 use of C<grep> without blocks often leads to bugs, we include a
125 C<"bugs"> theme.  And since this Policy comes directly from I<PBP>,
126 this Policy should be a member of the C<"pbp"> theme.
127
128     sub default_themes       { return qw( core bugs pbp ) }
129
130 As a Policy author, you can assign any themes you want to the Policy.
131 If you're publishing a suite of custom Policies, we suggest that you
132 create a unique theme that covers all the Policies in the
133 distribution.  That way, users can easily enable or disable all of
134 your policies at once.  For example, Policies in the
135 L<Perl::Critic::More> distribution all have a C<"more"> theme.
136
137 Next, we indicate what elements of the code this Policy will analyze,
138 like statements or variables or conditionals or POD.  These elements
139 are specified as PPI classes such as L<PPI::Statement>,
140 L<PPI::Token::Symbol>, L<PPI::Structure::Conditional> or
141 L<PPI::Token::Pod> respectively.  The applies_to() method returns a
142 list of PPI package names.  (You can get that list of available
143 package names via C<perldoc PPI>.)  As Perl::Critic traverses the
144 document, it will call the C<violates()> method from this module
145 whenever it encounters one of the PPI types that are given here.  In
146 this case, we just want to test calls to C<grep>.  Since the token
147 "grep" is a L<PPI::Token::Word>, we return that package name from the
148 C<applies_to()> method.
149
150     sub applies_to           { return 'PPI::Token::Word'  }
151
152 If your Policy needs to analyze several different types of elements,
153 the C<applies_to> method may return the name of several PPI packages.
154 If your Policy needs to examine the file as a whole, then the
155 C<applies_to> method should return L<PPI::Document>.  Since there is
156 only one PPI::Document element, your Policy would only be invoked once
157 per file.
158
159 Now comes the interesting part.  The C<violates()> method does all the
160 work.  It is always called with 2 arguments: a reference to the
161 current PPI element that Perl::Critic is traversing, and a reference
162 to the entire PPI document. [And since this is an object method, there
163 will be an additional argument that is a reference to this object
164 (C<$self>), but you already knew that!]  Since this Policy does not
165 need access to the document as a whole, we ignore the last parameter
166 by assigning to C<undef>.
167
168     sub violates {
169         my ( $self, $elem, undef ) = @_;
170
171 The violates() method then often performs some tests to make sure we
172 have the right "type" of element.  In our example, we know that the
173 element will be a L<PPI::Token::Word> because that's what we declared
174 back in the C<applies_to()> method.  However, we didn't specify
175 exactly which "word" we were looking for.  Evaluating a PPI element in
176 a string context returns the literal form of the code.  (You can also
177 use the c<content()> method.)  So we make sure that this
178 PPI::Token::Word is, in fact, "grep".  If it's not, then we don't'
179 need to bother examining it.
180
181         return if $elem ne 'grep';
182
183 The C<PPI::Token::Word> class is also used for barewords and methods
184 called on object references.  It is possible for someone to declare a
185 bareword hash key as C<<%hash = ( grep => 'foo' )>>.  We don't want to
186 test those types of elements because they don't represent function
187 calls to C<grep>.  So we use one of handy utility functions from
188 L<Perl::Critic::Utils> to make sure that this "grep" is actually in
189 the right context.  (The C<is_function_call()> subroutine is brought
190 in via the C<:classification> tag.)
191
192         return if ! is_function_call($elem);
193
194 Now that we know this element is a call to the C<grep> function, we
195 can look at the nearby elements to see what kind of arguments are
196 being passed to it.  In the following paragraphs, we discuss how to do
197 this manually in order to explore L<PPI>; after that, we'll show how
198 this Policy actually uses facilities provided by
199 L<Perl::Critic::Utils> to get this done.
200
201 Every PPI element is linked to its siblings, parent, and children (if
202 it has any).  Since those siblings could just be whitespace, we use
203 the C<snext_sibling()> to get the next code-sibling (the "s" in
204 C<snext_sibling> stands for "significant").
205
206         my $sib = $elem->snext_sibling() or return;
207
208 In Perl, the parenthesis around argument lists are usually optional,
209 and PPI packs the elements into a L<PPI::Structure::List> object when
210 parentheses are used.  So if the sibling is a PPI::Structure::List, we
211 pull out the first (significant) child of that list.  This child will
212 be the first argument to C<grep>.  If parentheses were not used, then
213 the sibling itself is the first argument.
214
215         my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;
216
217 In actuality, this sort of function argument lookup is common, so
218 there is a L<Perl::Critic::Utils/"first_arg"> subroutine available via
219 the C<:ppi> tag.  So we use that instead.
220
221         my $arg = first_arg($elem);
222
223 Finally, we now have a reference to the first argument to C<grep>.  If
224 that argument is a block (i.e. something in curly braces), then it
225 will be a L<PPI::Structure::Block>, in which case our Policy is
226 satisfied and we just return nothing.
227
228         return if !$arg;
229         return if $arg->isa('PPI::Structure::Block');
230
231 But if it is not a L<PPI::Structure::Block>, then we know that this
232 call to C<grep> must be using the expression form, and that violates
233 our Policy.  So we create and return a new L<Perl::Critic::Violation>
234 object via the L<Perl::Critic::Policy/"violation"> method, passing in
235 the description, explanation, and a reference to the PPI element that
236 caused the violation.  And that's all there is to it!
237
238         return $self->violation( $DESC, $EXPL, $elem );
239     }
240
241     1;
242
243 One last thing -- people are going to need to understand what is wrong
244 with the code when your Policy finds a problem.  It isn't reasonable
245 to include all the details in your violation description or
246 explanation.  So please include a DESCRIPTION section in the POD for
247 your Policy.  It should succinctly describe the behavior and
248 motivation for your Policy and include a few examples of both good and
249 bad code.  Here's an example:
250
251     =pod
252
253     =head1 NAME
254
255     Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep
256
257
258     =head1 DESCRIPTION
259
260     The expression forms of C<grep> and C<map> are awkward and hard to read.
261     Use the block forms instead.
262
263         @matches = grep  /pattern/,    @list;        #not ok
264         @matches = grep { /pattern/ }  @list;        #ok
265
266         @mapped = map  transform($_),    @list;      #not ok
267         @mapped = map { transform($_) }  @list;      #ok
268
269     =cut
270
271 When your policy has a section like this, users can invoke
272 L<perlcritic> with a C<--verbose> parameter of C<10> or C<11> to see
273 it along with the rest of the output for violations of your policy.
274
275
276 =head1 MAKING YOUR POLICY CONFIGURABLE
277
278 L<Perl::Critic> takes care of gathering configuration information for
279 your Policy, from whatever source the user specifies.  (See
280 L<Perl::Critic/"CONFIGURATION"> for the details of how a user specifies
281 the values you're going to receive.)  What your Policy ends up
282 receiving for the value of a parameter is a string with leading and
283 trailing whitespace removed.  By default, you will need to handle
284 conversion of that string to a useful form yourself.  However, if you
285 provide some metadata about your parameters, the parameter handling
286 will be taken care of for you.  (Additionally, tools that deal with
287 Policies themselves can use this information to enhance their
288 functionality.  See the L<perlcritic> C<--profile-proto> option for an
289 example.)
290
291 You can look at
292 L<Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse>
293 for a simple example of a configurable Policy and
294 L<Perl::Critic::Policy::Documentation::RequirePodSections> for a more
295 complex one.
296
297 =head2 Do It All Yourself
298
299 The C<initialize_if_enabled()> method for a Policy receives one
300 argument: an instance of L<Perl::Critic::PolicyConfig>.  This method
301 is only called if the user's configuration has enabled the policy.  It
302 returns a boolean stating whether the Policy should continue to be
303 enabled.  Generally, the only reason to return C<$FALSE> is when some
304 external requirement is missing.  For example,
305 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode> disables itself
306 if L<Perl::Tidy> is not installed.
307
308 A basic, do-nothing implementation of C<initialize_if_enabled()> would
309 be:
310
311     use Perl::Critic::Utils qw< :booleans >;
312
313     ...
314
315     sub initialize_if_enabled {
316         my ( $self, $config ) = @_;
317
318         return $TRUE;
319     }
320
321 As stated above, what you get in C<$config> are trimmed strings.  For
322 example, if the user's F<.perlcritic> contains
323
324     [Your::Policy]
325     foo          = bar baz
326     factor   =     5.52
327     selections =   2 78 92
328
329 then C<$config> will contain the equivalent of
330
331     my $config = {
332         foo        => 'bar baz',
333         factor     => '5.52',
334         selections => '2 78 92',
335     };
336
337 To make this available to the C<violates()> method, the values are
338 usually put into C<$self> under the name of the configuration item
339 prefixed with an underscore.  E.g.
340
341     sub initialize_if_enabled {
342         my ( $self, $config ) = @_;
343
344         $self->{_foo} = $config->get{foo};
345         $self->{_factor} = $config->get{factor};
346         $self->{_selections} = $config->get{selections};
347
348         return $TRUE;
349     }
350
351 Often, you'll want to convert the configuration values into something
352 more useful.  In this example, C<selections> is supposed to be a list
353 of integers.  L<Perl::Critic::Utils> contains a number of functions
354 that can help you with this.  Assuming that C<violates()> wants to
355 have C<selections> as an array, you'll want to have something like
356 this:
357
358     use Perl::Critic::Utils qw{ :booleans :characters :data_conversion };
359
360     sub initialize_if_enabled {
361         my ( $self, $config ) = @_;
362
363         $self->{_foo} = $config->get{foo};
364         $self->{_factor} = $config->get{factor};
365
366         my $selections = $config->get{selections};
367         $selections = defined $selections ? $selections : $EMPTY_STRING;
368         $self->{_selections} = [ words_from_string($selections) ];
369
370         return $TRUE;
371     }
372
373 Since C<selections> contains numbers, it may be desirable to change
374 the assignment to look like
375
376     $self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];
377
378 If C<violates()> needs to quickly determine whether a particular value
379 is in C<selections>, you would want to use a hash instead of an array,
380 like this:
381
382     $self->{_selections} = { hashify( words_from_string($selections) ) };
383
384 For an example of a Policy that has some simple, but non-standard
385 configuration handling, see
386 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode>.
387
388
389 =head2 Note On Constructors
390
391 It used to be the case that Policies handled configuration by
392 implementing a constructor.  However, there was no requirement to call
393 the base constructor; as long as the Policy ended up being a blessed
394 hash reference, everything was fine.  Unfortunately, this meant that
395 Policies would be loaded and their prerequisites would be C<use>d,
396 even if the Policy wasn't enabled, slowing things down.  Also, this
397 severely restricted the core of L<Perl::Critic>'s ability to enhance
398 things.  Use of constructors is deprecated and is incompatible with
399 C<supported_parameters()> metadata below.  Kindly use
400 C<initialize_if_enabled()>, instead, to do any sort of set up that you
401 need.
402
403
404
405 =head2 Providing Basic Configuration Information Via C<supported_parameters()>
406
407 As minimum for a well behaved Policy, you should implement
408 C<supported_parameters()> in order to tell the rest of C<Perl::Critic>
409 what configuration values the Policy looks for, even if it is only to say
410 that the Policy is not configurable.  In the simple form, this
411 function returns a list of the names of the parameters the Policy
412 supports.  So, for an non-configurable Policy, as in the
413 C<RequireBlockGrep> example above, this looked like
414
415     sub supported_parameters { return ()                  }
416
417 For the example being used in the C<initialize_if_enabled()> section
418 above, this would be
419
420     sub supported_parameters { return qw< foo factor selections >; }
421
422 Given this information, C<Perl::Critic> can tell the user when they
423 have specified a parameter for a Policy which isn't valid, e.g. when
424 they've misspelled the name of the parameter, and can emit the
425 parameter as part of a F<.perlcritic> prototype.
426
427 You can provide even more information about your Policy's
428 configuration by giving each parameter a description and a string
429 representation of the default value for the parameter.  You do this by
430 having the values in the list returned by C<supported_parameters()> be
431 hash references instead of strings, with keys of C<name>,
432 C<description>, and C<default_string>.  For example,
433
434     sub supported_parameters {
435         return (
436             {
437                 name           => 'allowed_values',
438                 description    =>
439                     'Individual and ranges of values to allow, and/or "all_integers".',
440                 default_string => '0 1 2',
441             },
442             {
443                 name           => 'allowed_types',
444                 description    => 'Kind of literals to allow.',
445                 default_string => 'Float',
446             },
447         );
448     }
449
450 Note that use of constructors is
451 L<incompatible|/"Note On Constructors"> with specifying parameters in
452 this way.
453
454
455 =head2 Using C<supported_parameters()> to Get It Done For You
456
457 The C<supported_parameters()> discussion above showed how you could
458 help others with your Policy, but didn't do anything to make your life
459 as a Policy author easier; you still need to implement
460 C<initialize_if_enabled()> to access any configuration that the user
461 has specified.  To have the configuration automatically handled for
462 you, you need to declare how your parameters act by specifying a value
463 for their C<behavior>.  For example, the following declares that a
464 parameter allows the user to choose from five specific values and that
465 the user can select any combination of them:
466
467     sub supported_parameters {
468         return (
469             {
470                 name               => 'allowed_types',
471                 description        => 'Kind of literals to allow.',
472                 default_string     => 'Float',
473                 behavior           => 'enumeration',
474                 enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
475                 enumeration_allow_multiple_values => 1,
476             },
477         );
478     }
479
480 When you specify a behavior, parsing and validation of the
481 user-specified and default values is done for you and your
482 C<violates()> method can retrieve the value under the key of the
483 parameter name prefixed with an underscore, e.g., for the above
484 declaration, the parsed and validated value can be accessed via
485 C<<$self->{_allowed_types}>>.
486
487 The behaviors provide additional functionality to C<Perl::Critic>; for
488 more on this, see L<Perl::Critic::PolicyParameter> and
489 L<Perl::Critic::PolicyParameter::Behavior>.
490
491 The following discusses each of the supported behaviors and the
492 options they support.  For the full details of a behavior, see the
493 documentation for the implementing class.
494
495
496 =head3 "string"
497
498 Implemented in L<Perl::Critic::PolicyParameter::Behavior::String>.
499
500 The most basic of behaviors, the value of the parameter will be stored
501 in the Policy as a string.
502
503 This behavior is not configurable.
504
505 =head4 C<supported_parameters()> example
506
507     sub supported_parameters {
508         return (
509             {
510                 name           => 'a_string',
511                 description    => 'An example string.',
512                 default_string => 'blah blah blah',
513                 behavior       => 'string',
514             },
515         );
516     }
517
518
519 =head4 Access example
520
521     sub violates {
522         my ($self, $element, $document) = @_;
523
524         ...
525         my $string = $self->{_a_string};
526         ...
527     }
528
529
530 =head3 "boolean"
531
532 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Boolean>.
533
534 The value of the parameter will be either L<Perl::Critic::Utils/$TRUE>
535 or L<Perl::Critic::Utils/$FALSE>.
536
537 This behavior is not configurable.
538
539 =head4 C<supported_parameters()> example
540
541     sub supported_parameters {
542         return (
543             {
544                 name           => 'a_boolean',
545                 description    => 'An example boolean.',
546                 default_string => '1',
547                 behavior       => 'boolean',
548             },
549         );
550     }
551
552
553 =head4 Access example
554
555     sub violates {
556         my ($self, $element, $document) = @_;
557
558         ...
559         my $is_whatever = $self->{_a_boolean};
560         if ($is_whatever) {
561             ...
562         }
563         ...
564     }
565
566
567 =head3 "integer"
568
569 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Integer>.
570
571 The value is validated against C<m/ \A [-+]? [1-9] [\d_]* \z /xms>
572 (with an special check for "0").  Notice that this means that
573 underscores are allowed in input values as with Perl numeric literals.
574
575 This takes two options, C<integer_minimum> and
576 C<integer_maximum>, which specify endpoints of an inclusive range to
577 restrict the value to.  Either, neither, or both may be specified.
578
579 =head4 C<supported_parameters()> example
580
581     sub supported_parameters {
582         return (
583             {
584                 name            => 'an_integer',
585                 description     => 'An example integer.',
586                 default_string  => '5',
587                 behavior        => 'integer',
588                 integer_minimum => 0,
589                 integer_maximum => 10,
590             },
591         );
592     }
593
594
595 =head4 Access example
596
597     sub violates {
598         my ($self, $element, $document) = @_;
599
600         ...
601         my $integer = $self->{_an_integer};
602         if ($integer > $TURNING_POINT) {
603             ...
604         }
605         ...
606     }
607
608
609 =head3 "string list"
610
611 Implemented in L<Perl::Critic::PolicyParameter::Behavior::StringList>.
612
613 The values will be derived by splitting the input string on blanks.
614 (See L<Perl::Critic::Utils/"words_from_string">.) The parameter will
615 be stored as a reference to a hash, with the values being the keys.
616
617 This takes one optional option, C<always_present_values>, of a
618 reference to an array of strings that will always be included in the
619 parameter value, e.g. if the value of this option is
620 C<[ qw{ a b c } ]> and the user specifies a value of C<'c d e'>, then
621 the value of the parameter will contain C<'a'>, C<'b'>, C<'c'>,
622 C<'d'>, and C<'e'>.
623
624 =head4 C<supported_parameters()> example
625
626     sub supported_parameters {
627         return (
628             {
629                 name                  => 'a_string_list',
630                 description           => 'An example list.',
631                 default_string        => 'red pink blue',
632                 behavior              => 'string list',
633                 always_present_values => [ qw{ green purple} ],
634             },
635         );
636     }
637
638
639 =head4 Access example
640
641     sub violates {
642         my ($self, $element, $document) = @_;
643
644         ...
645         my $list = $self->{_a_string_list};
646         my @list = keys %{$list};
647         ...
648         return if not $list->{ $element->content() };
649         ...
650     }
651
652
653 =head3 "enumeration"
654
655 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Enumeration>.
656
657 The values will be derived by splitting the input string on blanks.
658 (See L<Perl::Critic::Utils/"words_from_string">.)  Depending upon the
659 value of the C<enumeration_allow_multiple_values> option, the
660 parameter will be stored as a string or a reference to a hash, with
661 the values being the keys.
662
663 This behavior takes one required option and one optional one.  A value
664 for C<enumeration_values> of a reference to an array of valid strings
665 is required.  A true value can be specified for
666 C<enumeration_allow_multiple_values> to allow the user to pick more
667 than one value, but this defaults to false.
668
669 =head4 C<supported_parameters()> example
670
671     use Perl::Critic::Utils qw{ :characters };
672
673     sub supported_parameters {
674         return (
675             {
676                 name               => 'a_single_valued_enumeration',
677                 description        =>
678                     'An example enumeration that can only have a single value.',
679                 default_string     => $EMPTY,
680                 behavior           => 'enumeration',
681                 enumeration_values => [ qw{ block statement pod operator } ],
682                 enumeration_allow_multiple_values => 0,
683             },
684             {
685                 name               => 'a_multi_valued_enumeration',
686                 description        =>
687                     'An example enumeration that can have multiple values.',
688                 default_string     => 'fe',
689                 behavior           => 'enumeration',
690                 enumeration_values => [ qw{ fe fi fo fum } ],
691                 enumeration_allow_multiple_values => 1,
692             },
693         );
694     }
695
696
697 =head4 Access example
698
699     sub violates {
700         my ($self, $element, $document) = @_;
701
702         ...
703         my $single_value = $self->{_a_single_valued_enumeration};
704         ...
705         my $multi_value = $self->{_a_multi_valued_enumeration};
706         if ( $multi_value->{fum} ) {
707             ...
708         }
709         ...
710     }
711
712
713 =head2 Using a Custom Parser
714
715 If none of the behaviors does exactly what you want it to, you can
716 provide your own parser for a parameter.  The reason for doing this as
717 opposed to using an implementation of C<initialize_if_enabled()> is
718 that it allows you to use a behavior to provide its extra
719 functionality and it provides a means for a C<Perl::Critic>
720 configuration program, e.g. an IDE that integrates C<Perl::Critic>, to
721 validate your parameter as the user modifies its value.
722
723 The way you declare that you have a custom parser is to include a
724 reference to it in the parameter specification with the C<parser> key.
725 For example:
726
727     sub supported_parameters {
728         return (
729             {
730                 name           => 'file_name',
731                 description    => 'A file for to read a list of values from.',
732                 default_string => undef,
733                 behavior       => 'string',
734                 parser         => \&_parse_file_name,
735             },
736         );
737     }
738
739 A parser is a method on a subclass of L<Perl::Critic::Policy> that
740 takes two parameters: the L<Perl::Critic::PolicyParameter> that is
741 being specified and the value string provided by the user.  The method
742 is responsible for dealing with any default value and for saving the
743 parsed value for later use by the C<violates()> method.
744
745 An example parser (without enough error handling) for the above
746 example declaration:
747
748     use File::Slurp qw< slurp >;
749
750     use Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
751         qw{ throw_policy_value };
752
753     sub _parse_file_name {
754         my ($self, $parameter, $config_string) = @_;
755
756         my @thingies;
757
758         if ($config_string) {
759             if (not -r $config_string) {
760                 throw_policy_value
761                     policy         => $self->get_short_name(),
762                     option_name    => $parameter->get_name(),
763                     option_value   => $config_string,
764                     message_suffix => 'is not readable.';
765             }
766
767             @thingies = slurp $config_string;
768         }
769
770         $self->{_thingies} = \@thingies;
771
772         return;
773     }
774
775 Note that, if the value for the parameter is not valid, an instance of
776 L<Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue>
777 is thrown.  This allows C<Perl::Critic> to include that problem along
778 with any other problems found with the user's configuration in a
779 single error message.
780
781
782 =head2 Using Both C<supported_parameters()> and C<initialize_if_enabled()>
783
784 There are cases where a Policy needs additional initialization beyond
785 configuration or where the way it acts depends upon the combination of
786 multiple parameters.  In such situations, you will need to create an
787 implementation of C<initialize_if_enabled()>.  If you want to take
788 advantage of the supplied parameter handling from within
789 implementation of C<initialize_if_enabled()>, note that the
790 information from C<supported_parameters()> will already have been
791 used, with user-supplied parameter values validated and placed into
792 the Policy by the time C<initialize_if_enabled()> has been called.  It
793 is likely that you will not need to refer the contents of the
794 C<$config> parameter; just pull the information you need out of
795 C<$self>.  In fact, any value for the parameter values will be gone.
796
797
798
799 =head2 Summary of permitted hash keys in C<supported_parameters()>.
800
801
802 =head3 All types
803
804
805 =over
806
807 =item - "name" (mandatory)
808
809 =item - "description" (optional)
810
811 =item - "behavior" (optional)
812
813 Currently, one of:
814
815 =over
816
817 =item "boolean"
818
819 =item "enumeration"
820
821 =item "integer"
822
823 =item "string"
824
825 =item "string list"
826
827 =back
828
829 =item - "default_string" (optional)
830
831 A string representation of the default value of the parameter.
832
833 =item - "parser" (optional)
834
835 A code ref to a custom parser for the parameter.
836
837 =back
838
839 =head3 Enumerations
840
841 =over
842
843 =item - "enumeration_values" (mandatory)
844
845 A mandatory reference to an array of strings.
846
847 =item - "enumeration_allow_multiple_values" (optional)
848
849 Boolean indicating whether or not the user is restricted to a single
850 value.
851
852 =back
853
854 =head3 Integers
855
856 =over
857
858 =item - "integer_minimum" (optional)
859
860 Minimum allowed value, inclusive.
861
862 =item - "integer_maximum" (optional)
863
864 Maximum allowed value, inclusive.
865
866 =back
867
868 =head3 String lists
869
870 =over
871
872 =item - "list_always_present_values" (optional)
873
874 A reference to an array of values that should always be included in
875 the value of the parameter.
876
877 =back
878
879
880 =head1 ADDITIONAL FEATURES
881
882 =head2 C<default_maximum_violations_per_document()>
883
884 Certain problems that a Policy detects can be endemic to a particular
885 file; if there's one violation, there's likely to be many.  A good
886 example of this is
887 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict>; if
888 there's one line before L<use strict>, there's a good chance that the
889 entire file is missing L<use strict>.  In such cases, it's not much
890 help to the user to report every single violation.  If you've got such
891 a policy, you should override
892 L<default_maximum_violations_per_document()|Perl::Critic::Policy/"default_maximum_violations_per_document()">
893 method to provide a limit.  The user can override this value with a
894 value for "maximum_violations_per_document" in their F<.perlcriticrc>.
895
896 See the source code for
897 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers>
898 and L<Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings>
899 for examples.
900
901
902 =head1 DISTRIBUTING YOUR POLICIES
903
904 =head2 Create a Distribution
905
906 You need to come up with a name for your set of policies.  Sets of
907 add-on policies are generally named C<Perl::Critic::I<something>>,
908 e.g. L<Perl::Critic::More>.
909
910 The module representing the distribution will not actually have any
911 functionality; it's just documentation and a name for users to use
912 when installing via L<CPAN>/L<CPANPLUS>.  The important part is that
913 this will include a list of the included policies, with descriptions
914 of each.
915
916 A typical implementation will look like:
917
918     package Perl::Critic::Example;
919
920     use strict;
921     use warnings;
922
923     our $VERSION = '1.000000';
924
925     1; # Magic true value required at end of module
926
927     __END__
928
929     =head1 NAME
930
931     Perl::Critic::Example - Policies for Perl::Critic that act as an example.
932
933     =head1 AFFILIATION
934
935     This module has no functionality, but instead contains documentation
936     for this distribution and acts as a means of pulling other modules
937     into a bundle.  All of the Policy modules contained herein will have
938     an "AFFILIATION" section announcing their participation in this
939     grouping.
940
941
942     =head1 SYNOPSIS
943
944     Some L<Perl::Critic> policies that will help you keep your code
945     nice and compliant.
946
947
948     =head1 DESCRIPTION
949
950     The included policies are:
951
952     =over
953
954     =item L<Perl::Critic::Policy::Documentation::Example>
955
956     Complains about some example documentation issues.  [Severity: 3]
957
958
959     =item L<Perl::Critic::Policy::Variables::Example>
960
961     All modules must have at least one variable.  [Severity: 3]
962
963
964     =back
965
966
967     =head1 CONFIGURATION AND ENVIRONMENT
968
969     All policies included are in the "example" theme.  See the
970     L<Perl::Critic> documentation for how to make use of this.
971
972
973 =head2 Themes
974
975 Users can choose which policies to enable using themes.  You should
976 implement C<default_themes()> so that users can take advantage of
977 this.  In particular, you should use a theme named after your
978 distribution in all your policies; this should match the value listed
979 in the C<CONFIGURATION AND ENVIRONMENT> POD section as shown above.
980
981     default_themes { return qw< example math > }
982
983 If you're looking for ideas of what themes to do, have a look at the
984 output of C<perlcritic --list-themes>.
985
986
987 =head2 Documentation
988
989 =head3 AFFILIATION
990
991 Since all policies have to go somewhere under the
992 C<Perl::Critic::Policy::> namespace, it isn't always clear what
993 distribution a policy came from when browsing through their
994 documentation.  For this reason, you should include an C<AFFILIATION>
995 section in the POD for all of your policies that state where the
996 policy comes from.  For example:
997
998     =head1 AFFILIATION
999
1000     This policy is part of L<Perl::Critic::Example>.
1001
1002
1003 =head3 CONFIGURATION
1004
1005 In order to make it clear what can be done with a policy, you should
1006 always include a C<CONFIGURATION> section in your POD, even if it's
1007 only to say:
1008
1009     =head1 CONFIGURATION
1010
1011     This Policy is not configurable except for the standard options.
1012
1013
1014 =head1 HINT
1015
1016 When you're trying to figure out what L<PPI> is going to hand you for
1017 a chunk of code, there is a F<tools/ppidump> program in the
1018 L<Perl::Critic> distribution that will help you.  For example, when
1019 developing the above RequireBlockGrep example, you might want to try
1020
1021     tools/ppidump '@matches = grep /pattern/, @list;'
1022
1023 and
1024
1025     tools/ppidump '@matches = grep { /pattern/ } @list;'
1026
1027 to see the differences between the two cases.
1028
1029
1030 =head1 VERSION
1031
1032 This is part of L<Perl::Critic> version 1.088.
1033
1034
1035 =head1 AUTHOR
1036
1037 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1038
1039
1040 =head1 COPYRIGHT
1041
1042 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer.  All rights reserved.
1043
1044 This program is free software; you can redistribute it and/or modify
1045 it under the same terms as Perl itself.  The full text of this license
1046 can be found in the LICENSE file included with this module.
1047
1048 =cut
1049
1050 ##############################################################################
1051 # Local Variables:
1052 #   mode: cperl
1053 #   cperl-indent-level: 4
1054 #   fill-column: 78
1055 #   indent-tabs-mode: nil
1056 #   c-indentation-style: bsd
1057 # End:
1058 # ex: set ts=8 sts=4 sw=4 tw=70 ft=pod expandtab shiftround :