1Perl::Critic::DEVELOPERU(s3e)r Contributed Perl DocumentaPteiroln::Critic::DEVELOPER(3)
2
3
4

NAME

6       Perl::Critic::DEVELOPER - How to make new Perl::Critic::Policy modules.
7

DESCRIPTION

9       For developers who want to create custom coding standards, the
10       following tells how to create a Policy module for Perl::Critic.
11       Although the Perl::Critic distribution already includes a number of
12       Policies based on Damian Conway's book Perl Best Practices (which will
13       be referred to via "PBP" from here on), Perl::Critic is not limited to
14       his guidelines and can be used to enforce any practice, preference, or
15       style that you want to follow.  You can even write Policies to enforce
16       contradictory guidelines.  All you need to do is write a corresponding
17       Perl::Critic::Policy subclass, which may require as little as 10 lines
18       of code.
19

BACKGROUND

21       The heart of Perl::Critic is PPI, a parser and lexer for Perl.  PPI
22       transforms Perl source code into a Document Object Model (DOM).  Each
23       token in the document is represented by a PPI class, such as
24       PPI::Token::Operator or PPI::Token::Word, and then organized into
25       structure classes, like PPI::Statement::Expression and
26       PPI::Structure::Subroutine. The root node of the hierarchy is the
27       PPI::Document.
28
29       The Perl::Critic engine traverses each node in the PPI::Document tree
30       and invokes each of the Perl::Critic::Policy subclasses at the
31       appropriate node.  The Policy can inspect the node, look at the
32       surrounding nodes, and do whatever else it wants.  If the Policy
33       decides that a coding standard has been violated, it returns one or
34       more Perl::Critic::Violation objects.  If there are no violations, then
35       the Policy returns nothing.
36
37       Policies are usually written based on existing policies, so let's look
38       at one to see how it works.  The RequireBlockGrep.pm Policy is
39       relatively simple and demonstrates most of the important issues.  The
40       goal of this Policy is to enforce that every call to "grep" uses a
41       block for the first argument and not an expression.  The reasons for
42       this Policy are discussed in detail in PBP.
43

EXAMPLE POLICY

45       First, the Policy module needs to have a name.  Perl::Critic uses
46       Module::Pluggable to automatically discover all modules in the
47       "Perl::Critic::Policy" namespace.  Also, we've adopted the convention
48       of grouping Policies into directories according to the chapters of PBP.
49       Since the goal of this Policy is to enforce the use of block arguments
50       to "grep" and it comes from the "Builtin Functions" chapter of PBP, we
51       call it "Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep".
52
53           package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep;
54
55       Next, we set some pragmas and load the modules that we'll need.  All
56       Policy modules inherit from the Perl::Critic::Policy class, which
57       provides no-op implementations of the basic methods.  Our job is to
58       override these methods to make them do something useful.
59
60       Technically, "use strict" and "use warnings" are optional, but we don't
61       want Perl::Critic to be a hypocrite, now do we?
62
63           use strict;
64           use warnings;
65
66           use Readonly;
67
68           use Perl::Critic::Utils qw{ :severities :classification :ppi };
69           use base 'Perl::Critic::Policy';
70
71           our $VERSION = '1.05';
72
73       Next, we'll declare a description and explanation for this Policy.  The
74       description is always just a string that basically says "this is what's
75       wrong."  The explanation can be either a string with further details,
76       or a reference to an array of integers that correspond to page numbers
77       in PBP.  We make them read-only because they never change.  (See
78       Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma for
79       why we don't "use constant".)
80
81           Readonly::Scalar my $DESC => q{Expression form of "grep"};
82           Readonly::Scalar my $EXPL => [ 169 ];
83
84       Most policies don't need to override the "initialize_if_enabled()"
85       method provided by Perl::Critic::Policy.  However, if your Policy is
86       configurable via .perlcriticrc, you should implement a
87       "supported_parameters()" method and need to implement
88       "initialize_if_enabled()" to examine the $config values.  Since this
89       Policy isn't configurable, we'll declare that by providing an
90       implementation of "supported_parameters()" that returns an empty list.
91
92           sub supported_parameters { return ()                  }
93
94       Next, we define the "default_severity()" method, which must return an
95       integer indicating the severity of violating this Policy.  Severity
96       values range from 1 to 5, where 5 is the "most severe."  In general,
97       level 5 is reserved for things that are frequently misused and/or cause
98       bugs.  Level 1 is for things that are highly subjective or purely
99       cosmetic.  The Perl::Critic::Utils package exports several severity
100       constants that you can use here via the ":severities" tag.
101
102           sub default_severity     { return $SEVERITY_HIGH      }
103
104       Likewise, the "default_themes()" method returns a list of theme names.
105       Themes are intended to be named groups of Policies.  All Policies that
106       ship with Perl::Critic have a "core" theme.  Since use of "grep"
107       without blocks often leads to bugs, we include a "bugs" theme.  And
108       since this Policy comes directly from PBP, this Policy should be a
109       member of the "pbp" theme.
110
111           sub default_themes       { return qw( core bugs pbp ) }
112
113       As a Policy author, you can assign any themes you want to the Policy.
114       If you're publishing a suite of custom Policies, we suggest that you
115       create a unique theme that covers all the Policies in the distribution.
116       That way, users can easily enable or disable all of your policies at
117       once.  For example, Policies in the Perl::Critic::More distribution all
118       have a "more" theme.
119
120       Next, we indicate what elements of the code this Policy will analyze,
121       like statements or variables or conditionals or POD.  These elements
122       are specified as PPI classes such as PPI::Statement,
123       PPI::Token::Symbol, PPI::Structure::Conditional or PPI::Token::Pod
124       respectively.  The "applies_to()" method returns a list of PPI package
125       names.  (You can get that list of available package names via "perldoc
126       PPI".)  As Perl::Critic traverses the document, it will call the
127       "violates()" method from this module whenever it encounters one of the
128       PPI types that are given here.  In this case, we just want to test
129       calls to "grep".  Since the token "grep" is a PPI::Token::Word, we
130       return that package name from the "applies_to()" method.
131
132           sub applies_to           { return 'PPI::Token::Word'  }
133
134       If your Policy needs to analyze several different types of elements,
135       the "applies_to" method may return the name of several PPI packages.
136       If your Policy needs to examine the file as a whole, then the
137       "applies_to" method should return PPI::Document.  Since there is only
138       one PPI::Document element, your Policy would only be invoked once per
139       file.
140
141       Now comes the interesting part.  The "violates()" method does all the
142       work.  It is always called with 2 arguments: a reference to the current
143       PPI element that Perl::Critic is traversing, and a reference to the
144       entire PPI document. [And since this is an object method, there will be
145       an additional argument that is a reference to this object ($self), but
146       you already knew that!]  Since this Policy does not need access to the
147       document as a whole, we ignore the last parameter by assigning to
148       "undef".
149
150           sub violates {
151               my ( $self, $elem, undef ) = @_;
152
153       The "violates()" method then often performs some tests to make sure we
154       have the right "type" of element.  In our example, we know that the
155       element will be a PPI::Token::Word because that's what we declared back
156       in the "applies_to()" method.  However, we didn't specify exactly which
157       "word" we were looking for.  Evaluating a PPI element in a string
158       context returns the literal form of the code.  (You can also use the
159       "content()" method.)  So we make sure that this "PPI::Token::Word" is,
160       in fact, "grep".  If it's not, then we don't need to bother examining
161       it.
162
163               return if $elem ne 'grep';
164
165       The "PPI::Token::Word" class is also used for barewords and methods
166       called on object references.  It is possible for someone to declare a
167       bareword hash key as "%hash = ( grep => 'foo')".  We don't want to test
168       those types of elements because they don't represent function calls to
169       "grep".  So we use one of handy utility functions from
170       Perl::Critic::Utils to make sure that this "grep" is actually in the
171       right context.  (The "is_function_call()" subroutine is brought in via
172       the ":classification" tag.)
173
174               return if ! is_function_call($elem);
175
176       Now that we know this element is a call to the "grep" function, we can
177       look at the nearby elements to see what kind of arguments are being
178       passed to it.  In the following paragraphs, we discuss how to do this
179       manually in order to explore PPI; after that, we'll show how this
180       Policy actually uses facilities provided by Perl::Critic::Utils to get
181       this done.
182
183       Every PPI element is linked to its siblings, parent, and children (if
184       it has any).  Since those siblings could just be whitespace, we use the
185       "snext_sibling()" to get the next code-sibling (the "s" in
186       "snext_sibling" stands for "significant").
187
188               my $sib = $elem->snext_sibling() or return;
189
190       In Perl, the parenthesis around argument lists are usually optional,
191       and PPI packs the elements into a PPI::Structure::List object when
192       parentheses are used.  So if the sibling is a "PPI::Structure::List",
193       we pull out the first (significant) child of that list.  This child
194       will be the first argument to "grep".  If parentheses were not used,
195       then the sibling itself is the first argument.
196
197               my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;
198
199       In actuality, this sort of function argument lookup is common, so there
200       is a "first_arg" in Perl::Critic::Utils subroutine available via the
201       ":ppi" tag.  So we use that instead.
202
203               my $arg = first_arg($elem);
204
205       Finally, we now have a reference to the first argument to "grep".  If
206       that argument is a block (i.e. something in curly braces), then it will
207       be a PPI::Structure::Block, in which case our Policy is satisfied and
208       we just return nothing.
209
210               return if !$arg;
211               return if $arg->isa('PPI::Structure::Block');
212
213       But if it is not a PPI::Structure::Block, then we know that this call
214       to "grep" must be using the expression form, and that violates our
215       Policy.  So we create and return a new Perl::Critic::Violation object
216       via the "violation" in Perl::Critic::Policy method, passing in the
217       description, explanation, and a reference to the PPI element that
218       caused the violation.  And that's all there is to it!
219
220               return $self->violation( $DESC, $EXPL, $elem );
221           }
222
223           1;
224
225       One last thing -- people are going to need to understand what is wrong
226       with the code when your Policy finds a problem.  It isn't reasonable to
227       include all the details in your violation description or explanation.
228       So please include a DESCRIPTION section in the POD for your Policy.  It
229       should succinctly describe the behavior and motivation for your Policy
230       and include a few examples of both good and bad code.  Here's an
231       example:
232
233           =pod
234
235           =head1 NAME
236
237           Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep
238
239
240           =head1 DESCRIPTION
241
242           The expression forms of C<grep> and C<map> are awkward and hard to read.
243           Use the block forms instead.
244
245               @matches = grep  /pattern/,    @list;        #not ok
246               @matches = grep { /pattern/ }  @list;        #ok
247
248               @mapped = map  transform($_),    @list;      #not ok
249               @mapped = map { transform($_) }  @list;      #ok
250
251           =cut
252
253       When your policy has a section like this, users can invoke perlcritic
254       with a "--verbose" parameter of 10 or 11 or with a "%d" escape to see
255       it along with the rest of the output for violations of your policy.
256

MAKING YOUR POLICY CONFIGURABLE

258       Perl::Critic takes care of gathering configuration information for your
259       Policy, from whatever source the user specifies.  (See "CONFIGURATION"
260       in Perl::Critic for the details of how a user specifies the values
261       you're going to receive.)  What your Policy ends up receiving for the
262       value of a parameter is a string with leading and trailing whitespace
263       removed.  By default, you will need to handle conversion of that string
264       to a useful form yourself.  However, if you provide some metadata about
265       your parameters, the parameter handling will be taken care of for you.
266       (Additionally, tools that deal with Policies themselves can use this
267       information to enhance their functionality.  See the perlcritic
268       "--profile-proto" option for an example.)
269
270       You can look at
271       Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse for a
272       simple example of a configurable Policy and
273       Perl::Critic::Policy::Documentation::RequirePodSections for a more
274       complex one.
275
276   Do It All Yourself
277       The "initialize_if_enabled()" method for a Policy receives one
278       argument: an instance of Perl::Critic::PolicyConfig.  This method is
279       only called if the user's configuration has enabled the policy.  It
280       returns a boolean stating whether the Policy should continue to be
281       enabled.  Generally, the only reason to return $FALSE is when some
282       external requirement is missing.  For example,
283       Perl::Critic::Policy::CodeLayout::RequireTidyCode used to disable
284       itself if Perl::Tidy was not installed (that is until we made it no
285       longer optional for the Perl-Critic distribution).
286
287       A basic, do-nothing implementation of "initialize_if_enabled()" would
288       be:
289
290           use Perl::Critic::Utils qw< :booleans >;
291
292           ...
293
294           sub initialize_if_enabled {
295               my ( $self, $config ) = @_;
296
297               return $TRUE;
298           }
299
300       As stated above, what you get in $config are trimmed strings.  For
301       example, if the user's .perlcritic contains
302
303           [Your::Policy]
304           foo          = bar baz
305           factor   =     5.52
306           selections =   2 78 92
307
308       then $config will contain the equivalent of
309
310           my $config = {
311               foo        => 'bar baz',
312               factor     => '5.52',
313               selections => '2 78 92',
314           };
315
316       To make this available to the "violates()" method, the values are
317       usually put into $self under the name of the configuration item
318       prefixed with an underscore.  E.g.
319
320           sub initialize_if_enabled {
321               my ( $self, $config ) = @_;
322
323               $self->{_foo} = $config->get{foo};
324               $self->{_factor} = $config->get{factor};
325               $self->{_selections} = $config->get{selections};
326
327               return $TRUE;
328           }
329
330       Often, you'll want to convert the configuration values into something
331       more useful.  In this example, "selections" is supposed to be a list of
332       integers.  Perl::Critic::Utils contains a number of functions that can
333       help you with this.  Assuming that "violates()" wants to have
334       "selections" as an array, you'll want to have something like this:
335
336           use Perl::Critic::Utils qw{ :booleans :characters :data_conversion };
337
338           sub initialize_if_enabled {
339               my ( $self, $config ) = @_;
340
341               $self->{_foo} = $config->get{foo};
342               $self->{_factor} = $config->get{factor};
343
344               my $selections = $config->get{selections};
345               $selections = defined $selections ? $selections : $EMPTY_STRING;
346               $self->{_selections} = [ words_from_string($selections) ];
347
348               return $TRUE;
349           }
350
351       Since "selections" contains numbers, it may be desirable to change the
352       assignment to look like
353
354           $self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];
355
356       If "violates()" needs to quickly determine whether a particular value
357       is in "selections", you would want to use a hash instead of an array,
358       like this:
359
360           $self->{_selections} = { hashify( words_from_string($selections) ) };
361
362       For an example of a Policy that has some simple, but non-standard
363       configuration handling, see
364       Perl::Critic::Policy::CodeLayout::RequireTidyCode.
365
366   Note On Constructors
367       It used to be the case that Policies handled configuration by
368       implementing a constructor.  However, there was no requirement to call
369       the base constructor; as long as the Policy ended up being a blessed
370       hash reference, everything was fine.  Unfortunately, this meant that
371       Policies would be loaded and their prerequisites would be "use"d, even
372       if the Policy wasn't enabled, slowing things down.  Also, this severely
373       restricted the core of Perl::Critic's ability to enhance things.  Use
374       of constructors is deprecated and is incompatible with
375       "supported_parameters()" metadata below.  Kindly use
376       "initialize_if_enabled()", instead, to do any sort of set up that you
377       need.
378
379   Providing Basic Configuration Information Via "supported_parameters()"
380       As minimum for a well behaved Policy, you should implement
381       "supported_parameters()" in order to tell the rest of "Perl::Critic"
382       what configuration values the Policy looks for, even if it is only to
383       say that the Policy is not configurable.  In the simple form, this
384       function returns a list of the names of the parameters the Policy
385       supports.  So, for an non-configurable Policy, as in the
386       "RequireBlockGrep" example above, this looked like
387
388           sub supported_parameters { return ()                  }
389
390       For the example being used in the "initialize_if_enabled()" section
391       above, this would be
392
393           sub supported_parameters { return qw< foo factor selections >; }
394
395       Given this information, "Perl::Critic" can tell the user when they have
396       specified a parameter for a Policy which isn't valid, e.g. when they've
397       misspelled the name of the parameter, and can emit the parameter as
398       part of a .perlcriticrc prototype.
399
400       You can provide even more information about your Policy's configuration
401       by giving each parameter a description and a string representation of
402       the default value for the parameter.  You do this by having the values
403       in the list returned by "supported_parameters()" be hash references
404       instead of strings, with keys of "name", "description", and
405       "default_string".  For example,
406
407           sub supported_parameters {
408               return (
409                   {
410                       name           => 'allowed_values',
411                       description    =>
412                           'Individual and ranges of values to allow, and/or "all_integers".',
413                       default_string => '0 1 2',
414                   },
415                   {
416                       name           => 'allowed_types',
417                       description    => 'Kind of literals to allow.',
418                       default_string => 'Float',
419                   },
420               );
421           }
422
423       Note that use of constructors is incompatible with specifying
424       parameters in this way.
425
426   Using "supported_parameters()" to Get It Done For You
427       The "supported_parameters()" discussion above showed how you could help
428       others with your Policy, but didn't do anything to make your life as a
429       Policy author easier; you still need to implement
430       "initialize_if_enabled()" to access any configuration that the user has
431       specified.  To have the configuration automatically handled for you,
432       you need to declare how your parameters act by specifying a value for
433       their "behavior".  For example, the following declares that a parameter
434       allows the user to choose from five specific values and that the user
435       can select any combination of them:
436
437           sub supported_parameters {
438               return (
439                   {
440                       name               => 'allowed_types',
441                       description        => 'Kind of literals to allow.',
442                       default_string     => 'Float',
443                       behavior           => 'enumeration',
444                       enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
445                       enumeration_allow_multiple_values => 1,
446                   },
447               );
448           }
449
450       When you specify a behavior, parsing and validation of the user-
451       specified and default values is done for you and your "violates()"
452       method can retrieve the value under the key of the parameter name
453       prefixed with an underscore, e.g., for the above declaration, the
454       parsed and validated value can be accessed via
455       "$self->{_allowed_types}".
456
457       The behaviors provide additional functionality to "Perl::Critic"; for
458       more on this, see Perl::Critic::PolicyParameter and
459       Perl::Critic::PolicyParameter::Behavior.
460
461       The following discusses each of the supported behaviors and the options
462       they support.  For the full details of a behavior, see the
463       documentation for the implementing class.
464
465       "string"
466
467       Implemented in Perl::Critic::PolicyParameter::Behavior::String.
468
469       The most basic of behaviors, the value of the parameter will be stored
470       in the Policy as a string.
471
472       This behavior is not configurable.
473
474       "supported_parameters()" example
475
476           sub supported_parameters {
477               return (
478                   {
479                       name           => 'a_string',
480                       description    => 'An example string.',
481                       default_string => 'blah blah blah',
482                       behavior       => 'string',
483                   },
484               );
485           }
486
487       Access example
488
489           sub violates {
490               my ($self, $element, $document) = @_;
491
492               ...
493               my $string = $self->{_a_string};
494               ...
495           }
496
497       "boolean"
498
499       Implemented in Perl::Critic::PolicyParameter::Behavior::Boolean.
500
501       The value of the parameter will be either $TRUE or $FALSE.
502
503       This behavior is not configurable.
504
505       "supported_parameters()" example
506
507           sub supported_parameters {
508               return (
509                   {
510                       name           => 'a_boolean',
511                       description    => 'An example boolean.',
512                       default_string => '1',
513                       behavior       => 'boolean',
514                   },
515               );
516           }
517
518       Access example
519
520           sub violates {
521               my ($self, $element, $document) = @_;
522
523               ...
524               my $is_whatever = $self->{_a_boolean};
525               if ($is_whatever) {
526                   ...
527               }
528               ...
529           }
530
531       "integer"
532
533       Implemented in Perl::Critic::PolicyParameter::Behavior::Integer.
534
535       The value is validated against "m/ \A [-+]? [1-9] [\d_]* \z /xms" (with
536       an special check for "0").  Notice that this means that underscores are
537       allowed in input values as with Perl numeric literals.
538
539       This takes two options, "integer_minimum" and "integer_maximum", which
540       specify endpoints of an inclusive range to restrict the value to.
541       Either, neither, or both may be specified.
542
543       "supported_parameters()" example
544
545           sub supported_parameters {
546               return (
547                   {
548                       name            => 'an_integer',
549                       description     => 'An example integer.',
550                       default_string  => '5',
551                       behavior        => 'integer',
552                       integer_minimum => 0,
553                       integer_maximum => 10,
554                   },
555               );
556           }
557
558       Access example
559
560           sub violates {
561               my ($self, $element, $document) = @_;
562
563               ...
564               my $integer = $self->{_an_integer};
565               if ($integer > $TURNING_POINT) {
566                   ...
567               }
568               ...
569           }
570
571       "string list"
572
573       Implemented in Perl::Critic::PolicyParameter::Behavior::StringList.
574
575       The values will be derived by splitting the input string on blanks.
576       (See "words_from_string" in Perl::Critic::Utils.) The parameter will be
577       stored as a reference to a hash, with the values being the keys.
578
579       This takes one optional option, "list_always_present_values", of a
580       reference to an array of strings that will always be included in the
581       parameter value, e.g. if the value of this option is "[ qw{ a b c } ]"
582       and the user specifies a value of 'c d e', then the value of the
583       parameter will contain 'a', 'b', 'c', 'd', and 'e'.
584
585       "supported_parameters()" example
586
587           sub supported_parameters {
588               return (
589                   {
590                       name                  => 'a_string_list',
591                       description           => 'An example list.',
592                       default_string        => 'red pink blue',
593                       behavior              => 'string list',
594                       list_always_present_values => [ qw{ green purple} ],
595                   },
596               );
597           }
598
599       Access example
600
601           sub violates {
602               my ($self, $element, $document) = @_;
603
604               ...
605               my $list = $self->{_a_string_list};
606               my @list = keys %{$list};
607               ...
608               return if not $list->{ $element->content() };
609               ...
610           }
611
612       "enumeration"
613
614       Implemented in Perl::Critic::PolicyParameter::Behavior::Enumeration.
615
616       The values will be derived by splitting the input string on blanks.
617       (See "words_from_string" in Perl::Critic::Utils.)  Depending upon the
618       value of the "enumeration_allow_multiple_values" option, the parameter
619       will be stored as a string or a reference to a hash, with the values
620       being the keys.
621
622       This behavior takes one required option and one optional one.  A value
623       for "enumeration_values" of a reference to an array of valid strings is
624       required.  A true value can be specified for
625       "enumeration_allow_multiple_values" to allow the user to pick more than
626       one value, but this defaults to false.
627
628       "supported_parameters()" example
629
630           use Perl::Critic::Utils qw{ :characters };
631
632           sub supported_parameters {
633               return (
634                   {
635                       name               => 'a_single_valued_enumeration',
636                       description        =>
637                           'An example enumeration that can only have a single value.',
638                       default_string     => $EMPTY,
639                       behavior           => 'enumeration',
640                       enumeration_values => [ qw{ block statement pod operator } ],
641                       enumeration_allow_multiple_values => 0,
642                   },
643                   {
644                       name               => 'a_multi_valued_enumeration',
645                       description        =>
646                           'An example enumeration that can have multiple values.',
647                       default_string     => 'fe',
648                       behavior           => 'enumeration',
649                       enumeration_values => [ qw{ fe fi fo fum } ],
650                       enumeration_allow_multiple_values => 1,
651                   },
652               );
653           }
654
655       Access example
656
657           sub violates {
658               my ($self, $element, $document) = @_;
659
660               ...
661               my $single_value = $self->{_a_single_valued_enumeration};
662               ...
663               my $multi_value = $self->{_a_multi_valued_enumeration};
664               if ( $multi_value->{fum} ) {
665                   ...
666               }
667               ...
668           }
669
670   Using a Custom Parser
671       If none of the behaviors does exactly what you want it to, you can
672       provide your own parser for a parameter.  The reason for doing this as
673       opposed to using an implementation of "initialize_if_enabled()" is that
674       it allows you to use a behavior to provide its extra functionality and
675       it provides a means for a "Perl::Critic" configuration program, e.g. an
676       IDE that integrates "Perl::Critic", to validate your parameter as the
677       user modifies its value.
678
679       The way you declare that you have a custom parser is to include a
680       reference to it in the parameter specification with the "parser" key.
681       For example:
682
683           sub supported_parameters {
684               return (
685                   {
686                       name           => 'file_name',
687                       description    => 'A file for to read a list of values from.',
688                       default_string => undef,
689                       behavior       => 'string',
690                       parser         => \&_parse_file_name,
691                   },
692               );
693           }
694
695       A parser is a method on a subclass of Perl::Critic::Policy that takes
696       two parameters: the Perl::Critic::PolicyParameter that is being
697       specified and the value string provided by the user.  The method is
698       responsible for dealing with any default value and for saving the
699       parsed value for later use by the "violates()" method.
700
701       An example parser (without enough error handling) for the above example
702       declaration:
703
704           use Path::Tiny;
705
706           use Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
707               qw{ throw_policy_value };
708
709           sub _parse_file_name {
710               my ($self, $parameter, $config_string) = @_;
711
712               my @thingies;
713
714               if ($config_string) {
715                   if (not -r $config_string) {
716                       throw_policy_value
717                           policy         => $self->get_short_name(),
718                           option_name    => $parameter->get_name(),
719                           option_value   => $config_string,
720                           message_suffix => 'is not readable.';
721                   }
722
723                   @thingies = path($config_string)->slurp;
724               }
725
726               $self->{_thingies} = \@thingies;
727
728               return;
729           }
730
731       Note that, if the value for the parameter is not valid, an instance of
732       Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
733       is thrown.  This allows "Perl::Critic" to include that problem along
734       with any other problems found with the user's configuration in a single
735       error message.
736
737   Using Both "supported_parameters()" and "initialize_if_enabled()"
738       There are cases where a Policy needs additional initialization beyond
739       configuration or where the way it acts depends upon the combination of
740       multiple parameters.  In such situations, you will need to create an
741       implementation of "initialize_if_enabled()".  If you want to take
742       advantage of the supplied parameter handling from within implementation
743       of "initialize_if_enabled()", note that the information from
744       "supported_parameters()" will already have been used, with user-
745       supplied parameter values validated and placed into the Policy by the
746       time "initialize_if_enabled()" has been called.  It is likely that you
747       will not need to refer the contents of the $config parameter; just pull
748       the information you need out of $self.  In fact, any value for the
749       parameter values will be gone.
750
751   Summary of permitted hash keys in "supported_parameters()".
752       All types
753
754       - "name" (mandatory)
755       - "description" (optional)
756       - "behavior" (optional)
757           Currently, one of:
758
759           "boolean"
760           "enumeration"
761           "integer"
762           "string"
763           "string list"
764       - "default_string" (optional)
765           A string representation of the default value of the parameter.
766
767       - "parser" (optional)
768           A code ref to a custom parser for the parameter.
769
770       Enumerations
771
772       - "enumeration_values" (mandatory)
773           A mandatory reference to an array of strings.
774
775       - "enumeration_allow_multiple_values" (optional)
776           Boolean indicating whether or not the user is restricted to a
777           single value.
778
779       Integers
780
781       - "integer_minimum" (optional)
782           Minimum allowed value, inclusive.
783
784       - "integer_maximum" (optional)
785           Maximum allowed value, inclusive.
786
787       String lists
788
789       - "list_always_present_values" (optional)
790           A reference to an array of values that should always be included in
791           the value of the parameter.
792

ADDITIONAL FEATURES

794   "default_maximum_violations_per_document()"
795       Certain problems that a Policy detects can be endemic to a particular
796       file; if there's one violation, there's likely to be many.  A good
797       example of this is
798       Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict; if there's
799       one line before "use strict", there's a good chance that the entire
800       file is missing "use strict".  In such cases, it's not much help to the
801       user to report every single violation.  If you've got such a policy,
802       you should override default_maximum_violations_per_document() method to
803       provide a limit.  The user can override this value with a value for
804       "maximum_violations_per_document" in their .perlcriticrc.
805
806       See the source code for
807       Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers and
808       Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings for
809       examples.
810
811   "is_safe()"
812       Most Perl::Critic Policies are purely static.  In other words, they
813       never compile or execute any of the source code that they analyze.
814       However it is possible to write dynamic Policies that do compile or
815       execute code, which may result in unsafe operations (see
816       Perl::Critic::Dynamic for an example).  So the "is_safe()" method is
817       used to indicate whether a Policy can be trusted to not cause mischief.
818       By default, "is_safe()" returns true.  But if you are writing a Policy
819       that will compile or execute any of the source code that it analyzes,
820       then you should override the "is_safe()" method to return false.
821

DISTRIBUTING YOUR POLICIES

823   Create a Distribution
824       You need to come up with a name for your set of policies.  Sets of add-
825       on policies are generally named "Perl::Critic::something", e.g.
826       Perl::Critic::More.
827
828       The module representing the distribution will not actually have any
829       functionality; it's just documentation and a name for users to use when
830       installing via CPAN/CPANPLUS.  The important part is that this will
831       include a list of the included policies, with descriptions of each.
832
833       A typical implementation will look like:
834
835           package Perl::Critic::Example;
836
837           use strict;
838           use warnings;
839
840           our $VERSION = '1.000000';
841
842           1; # Magic true value required at end of module
843
844           __END__
845
846           =head1 NAME
847
848           Perl::Critic::Example - Policies for Perl::Critic that act as an example.
849
850           =head1 AFFILIATION
851
852           This module has no functionality, but instead contains documentation
853           for this distribution and acts as a means of pulling other modules
854           into a bundle.  All of the Policy modules contained herein will have
855           an "AFFILIATION" section announcing their participation in this
856           grouping.
857
858
859           =head1 SYNOPSIS
860
861           Some L<Perl::Critic|Perl::Critic> policies that will help you keep your
862           code nice and compliant.
863
864
865           =head1 DESCRIPTION
866
867           The included policies are:
868
869           =over
870
871           =item L<Perl::Critic::Policy::Documentation::Example|Perl::Critic::Policy::Documentation::Example>
872
873           Complains about some example documentation issues.  [Default severity: 3]
874
875
876           =item L<Perl::Critic::Policy::Variables::Example|Perl::Critic::Policy::Variables::Example>
877
878           All modules must have at least one variable.  [Default severity: 3]
879
880
881           =back
882
883
884           =head1 CONFIGURATION AND ENVIRONMENT
885
886           All policies included are in the "example" theme.  See the
887           L<Perl::Critic|Perl::Critic> documentation for how to make use of this.
888
889   Themes
890       Users can choose which policies to enable using themes.  You should
891       implement "default_themes()" so that users can take advantage of this.
892       In particular, you should use a theme named after your distribution in
893       all your policies; this should match the value listed in the
894       "CONFIGURATION AND ENVIRONMENT" POD section as shown above.
895
896           default_themes { return qw< example math > }
897
898       If you're looking for ideas of what themes to use, have a look at the
899       output of "perlcritic --list-themes".
900
901   Documentation
902       AFFILIATION
903
904       Since all policies have to go somewhere under the
905       "Perl::Critic::Policy::" namespace, it isn't always clear what
906       distribution a policy came from when browsing through their
907       documentation.  For this reason, you should include an "AFFILIATION"
908       section in the POD for all of your policies that state where the policy
909       comes from.  For example:
910
911           =head1 AFFILIATION
912
913           This policy is part of L<Perl::Critic::Example|Perl::Critic::Example>.
914
915       CONFIGURATION
916
917       In order to make it clear what can be done with a policy, you should
918       always include a "CONFIGURATION" section in your POD, even if it's only
919       to say:
920
921           =head1 CONFIGURATION
922
923           This Policy is not configurable except for the standard options.
924

TESTING YOUR POLICY

926       The Perl::Critic distribution also contains a framework for testing
927       your Policy.  See Perl::Critic::TestUtils for the details.
928

HINT

930       When you're trying to figure out what PPI is going to hand you for a
931       chunk of code, there is a tools/ppidump program in the Perl::Critic
932       distribution that will help you.  For example, when developing the
933       above RequireBlockGrep example, you might want to try
934
935           tools/ppidump '@matches = grep /pattern/, @list;'
936
937       and
938
939           tools/ppidump '@matches = grep { /pattern/ } @list;'
940
941       to see the differences between the two cases.
942
943       Alternatively, see the "ppi_dumper" documentation at
944       <http://search.cpan.org/dist/App-PPI-Dumper/script/ppi_dumper> and the
945       "PPI::Tester" documentation at
946       <http://search.cpan.org/dist/PPI-Tester/lib/PPI/Tester.pm>.
947

VERSION

949       This is part of Perl::Critic version 1.116.
950

SEE ALSO

952       Chas. Owens has a blog post about developing in-house policies at
953       <http://svok.blogspot.com/2009/09/adding-house-policies-to-perlcritic.html>.
954

AUTHOR

956       Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>
957
959       Copyright (c) 2005-2011 Imaginative Software Systems.  All rights
960       reserved.
961
962       This program is free software; you can redistribute it and/or modify it
963       under the same terms as Perl itself.  The full text of this license can
964       be found in the LICENSE file included with this module.
965
966
967
968perl v5.32.0                      2020-07-28        Perl::Critic::DEVELOPER(3)
Impressum