1Perl::Critic::DEVELOPERU(s3eprm)Contributed Perl DocumenPteartli:o:nCritic::DEVELOPER(3pm)
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 parent '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() method
85       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, in
160       fact, "grep".  If it's not, then we don't need to bother examining it.
161
162               return if $elem ne 'grep';
163
164       The "PPI::Token::Word" class is also used for barewords and methods
165       called on object references.  It is possible for someone to declare a
166       bareword hash key as "%hash = ( grep => 'foo')".  We don't want to test
167       those types of elements because they don't represent function calls to
168       "grep".  So we use one of handy utility functions from
169       Perl::Critic::Utils to make sure that this "grep" is actually in the
170       right context.  (The is_function_call() subroutine is brought in via
171       the ":classification" tag.)
172
173               return if ! is_function_call($elem);
174
175       Now that we know this element is a call to the "grep" function, we can
176       look at the nearby elements to see what kind of arguments are being
177       passed to it.  In the following paragraphs, we discuss how to do this
178       manually in order to explore PPI; after that, we'll show how this
179       Policy actually uses facilities provided by Perl::Critic::Utils to get
180       this done.
181
182       Every PPI element is linked to its siblings, parent, and children (if
183       it has any).  Since those siblings could just be whitespace, we use the
184       snext_sibling() to get the next code-sibling (the "s" in
185       "snext_sibling" stands for "significant").
186
187               my $sib = $elem->snext_sibling() or return;
188
189       In Perl, the parenthesis around argument lists are usually optional,
190       and PPI packs the elements into a PPI::Structure::List object when
191       parentheses are used.  So if the sibling is a "PPI::Structure::List",
192       we pull out the first (significant) child of that list.  This child
193       will be the first argument to "grep".  If parentheses were not used,
194       then the sibling itself is the first argument.
195
196               my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;
197
198       In actuality, this sort of function argument lookup is common, so there
199       is a "first_arg" in Perl::Critic::Utils subroutine available via the
200       ":ppi" tag.  So we use that instead.
201
202               my $arg = first_arg($elem);
203
204       Finally, we now have a reference to the first argument to "grep".  If
205       that argument is a block (i.e. something in curly braces), then it will
206       be a PPI::Structure::Block, in which case our Policy is satisfied and
207       we just return nothing.
208
209               return if !$arg;
210               return if $arg->isa('PPI::Structure::Block');
211
212       But if it is not a PPI::Structure::Block, then we know that this call
213       to "grep" must be using the expression form, and that violates our
214       Policy.  So we create and return a new Perl::Critic::Violation object
215       via the "violation" in Perl::Critic::Policy method, passing in the
216       description, explanation, and a reference to the PPI element that
217       caused the violation.  And that's all there is to it!
218
219               return $self->violation( $DESC, $EXPL, $elem );
220           }
221
222           1;
223
224       One last thing -- people are going to need to understand what is wrong
225       with the code when your Policy finds a problem.  It isn't reasonable to
226       include all the details in your violation description or explanation.
227       So please include a DESCRIPTION section in the POD for your Policy.  It
228       should succinctly describe the behavior and motivation for your Policy
229       and include a few examples of both good and bad code.  Here's an
230       example:
231
232           =pod
233
234           =head1 NAME
235
236           Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep
237
238
239           =head1 DESCRIPTION
240
241           The expression forms of C<grep> and C<map> are awkward and hard to read.
242           Use the block forms instead.
243
244               @matches = grep  /pattern/,    @list;        #not ok
245               @matches = grep { /pattern/ }  @list;        #ok
246
247               @mapped = map  transform($_),    @list;      #not ok
248               @mapped = map { transform($_) }  @list;      #ok
249
250           =cut
251
252       When your policy has a section like this, users can invoke perlcritic
253       with a "--verbose" parameter of 10 or 11 or with a "%d" escape to see
254       it along with the rest of the output for violations of your policy.
255

MAKING YOUR POLICY CONFIGURABLE

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

ADDITIONAL FEATURES

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

DISTRIBUTING YOUR POLICIES

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

TESTING YOUR POLICY

922       The Perl::Critic distribution also contains a framework for testing
923       your Policy.  See Perl::Critic::TestUtils for the details.
924

HINT

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

VERSION

945       This is part of Perl::Critic version 1.116.
946

SEE ALSO

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

AUTHOR

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