.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Perl::Critic::DEVELOPER 3pm" .TH Perl::Critic::DEVELOPER 3pm "2015-08-11" "perl v5.20.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Perl::Critic::DEVELOPER \- How to make new Perl::Critic::Policy modules. .SH "DESCRIPTION" .IX Header "DESCRIPTION" For developers who want to create custom coding standards, the following tells how to create a Policy module for Perl::Critic. Although the Perl::Critic distribution already includes a number of Policies based on Damian Conway's book \&\fIPerl Best Practices\fR (which will be referred to via "\fI\s-1PBP\s0\fR" from here on), Perl::Critic is not limited to his guidelines and can be used to enforce any practice, preference, or style that you want to follow. You can even write Policies to enforce contradictory guidelines. All you need to do is write a corresponding Perl::Critic::Policy subclass, which may require as little as 10 lines of code. .SH "BACKGROUND" .IX Header "BACKGROUND" The heart of Perl::Critic is \s-1PPI\s0, a parser and lexer for Perl. \&\s-1PPI\s0 transforms Perl source code into a Document Object Model (\s-1DOM\s0). Each token in the document is represented by a \s-1PPI\s0 class, such as PPI::Token::Operator or PPI::Token::Word, and then organized into structure classes, like PPI::Statement::Expression and PPI::Structure::Subroutine. The root node of the hierarchy is the PPI::Document. .PP The Perl::Critic engine traverses each node in the PPI::Document tree and invokes each of the Perl::Critic::Policy subclasses at the appropriate node. The Policy can inspect the node, look at the surrounding nodes, and do whatever else it wants. If the Policy decides that a coding standard has been violated, it returns one or more Perl::Critic::Violation objects. If there are no violations, then the Policy returns nothing. .PP Policies are usually written based on existing policies, so let's look at one to see how it works. The \fIRequireBlockGrep.pm\fR Policy is relatively simple and demonstrates most of the important issues. The goal of this Policy is to enforce that every call to \f(CW\*(C`grep\*(C'\fR uses a block for the first argument and not an expression. The reasons for this Policy are discussed in detail in \fI\s-1PBP\s0\fR. .SH "EXAMPLE POLICY" .IX Header "EXAMPLE POLICY" First, the Policy module needs to have a name. Perl::Critic uses Module::Pluggable to automatically discover all modules in the \f(CW\*(C`Perl::Critic::Policy\*(C'\fR namespace. Also, we've adopted the convention of grouping Policies into directories according to the chapters of \fI\s-1PBP\s0\fR. Since the goal of this Policy is to enforce the use of block arguments to \f(CW\*(C`grep\*(C'\fR and it comes from the \*(L"Builtin Functions\*(R" chapter of \fI\s-1PBP\s0\fR, we call it \&\f(CW"Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep"\fR. .PP .Vb 1 \& package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep; .Ve .PP Next, we set some pragmas and load the modules that we'll need. All Policy modules inherit from the Perl::Critic::Policy class, which provides no-op implementations of the basic methods. Our job is to override these methods to make them do something useful. .PP Technically, \f(CW\*(C`use strict\*(C'\fR and \f(CW\*(C`use warnings\*(C'\fR are optional, but we don't want Perl::Critic to be a hypocrite, now do we? .PP .Vb 2 \& use strict; \& use warnings; \& \& use Readonly; \& \& use Perl::Critic::Utils qw{ :severities :classification :ppi }; \& use base \*(AqPerl::Critic::Policy\*(Aq; \& \& our $VERSION = \*(Aq1.05\*(Aq; .Ve .PP Next, we'll declare a description and explanation for this Policy. The description is always just a string that basically says \*(L"this is what's wrong.\*(R" The explanation can be either a string with further details, or a reference to an array of integers that correspond to page numbers in \fI\s-1PBP\s0\fR. We make them read-only because they never change. (See Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma for why we don't \f(CW\*(C`use constant\*(C'\fR.) .PP .Vb 2 \& Readonly::Scalar my $DESC => q{Expression form of "grep"}; \& Readonly::Scalar my $EXPL => [ 169 ]; .Ve .PP Most policies don't need to override the \f(CW\*(C`initialize_if_enabled()\*(C'\fR method provided by Perl::Critic::Policy. However, if your Policy is configurable via \fI.perlcriticrc\fR, you should implement a \f(CW\*(C`supported_parameters()\*(C'\fR method and need to implement \f(CW\*(C`initialize_if_enabled()\*(C'\fR to examine the \f(CW$config\fR values. Since this Policy isn't configurable, we'll declare that by providing an implementation of \f(CW\*(C`supported_parameters()\*(C'\fR that returns an empty list. .PP .Vb 1 \& sub supported_parameters { return () } .Ve .PP Next, we define the \f(CW\*(C`default_severity()\*(C'\fR method, which must return an integer indicating the severity of violating this Policy. Severity values range from 1 to 5, where 5 is the \*(L"most severe.\*(R" In general, level 5 is reserved for things that are frequently misused and/or cause bugs. Level 1 is for things that are highly subjective or purely cosmetic. The Perl::Critic::Utils package exports several severity constants that you can use here via the \f(CW\*(C`:severities\*(C'\fR tag. .PP .Vb 1 \& sub default_severity { return $SEVERITY_HIGH } .Ve .PP Likewise, the \f(CW\*(C`default_themes()\*(C'\fR method returns a list of theme names. Themes are intended to be named groups of Policies. All Policies that ship with Perl::Critic have a \f(CW"core"\fR theme. Since use of \f(CW\*(C`grep\*(C'\fR without blocks often leads to bugs, we include a \&\f(CW"bugs"\fR theme. And since this Policy comes directly from \fI\s-1PBP\s0\fR, this Policy should be a member of the \f(CW"pbp"\fR theme. .PP .Vb 1 \& sub default_themes { return qw( core bugs pbp ) } .Ve .PP As a Policy author, you can assign any themes you want to the Policy. If you're publishing a suite of custom Policies, we suggest that you create a unique theme that covers all the Policies in the distribution. That way, users can easily enable or disable all of your policies at once. For example, Policies in the Perl::Critic::More distribution all have a \&\f(CW"more"\fR theme. .PP Next, we indicate what elements of the code this Policy will analyze, like statements or variables or conditionals or \s-1POD. \s0 These elements are specified as \s-1PPI\s0 classes such as PPI::Statement, PPI::Token::Symbol, PPI::Structure::Conditional or PPI::Token::Pod respectively. The \f(CW\*(C`applies_to()\*(C'\fR method returns a list of \s-1PPI\s0 package names. (You can get that list of available package names via \f(CW\*(C`perldoc PPI\*(C'\fR.) As Perl::Critic traverses the document, it will call the \f(CW\*(C`violates()\*(C'\fR method from this module whenever it encounters one of the \s-1PPI\s0 types that are given here. In this case, we just want to test calls to \f(CW\*(C`grep\*(C'\fR. Since the token \*(L"grep\*(R" is a PPI::Token::Word, we return that package name from the \f(CW\*(C`applies_to()\*(C'\fR method. .PP .Vb 1 \& sub applies_to { return \*(AqPPI::Token::Word\*(Aq } .Ve .PP If your Policy needs to analyze several different types of elements, the \f(CW\*(C`applies_to\*(C'\fR method may return the name of several \s-1PPI\s0 packages. If your Policy needs to examine the file as a whole, then the \&\f(CW\*(C`applies_to\*(C'\fR method should return PPI::Document. Since there is only one PPI::Document element, your Policy would only be invoked once per file. .PP Now comes the interesting part. The \f(CW\*(C`violates()\*(C'\fR method does all the work. It is always called with 2 arguments: a reference to the current \s-1PPI\s0 element that Perl::Critic is traversing, and a reference to the entire \s-1PPI\s0 document. [And since this is an object method, there will be an additional argument that is a reference to this object (\f(CW$self\fR), but you already knew that!] Since this Policy does not need access to the document as a whole, we ignore the last parameter by assigning to \f(CW\*(C`undef\*(C'\fR. .PP .Vb 2 \& sub violates { \& my ( $self, $elem, undef ) = @_; .Ve .PP The \f(CW\*(C`violates()\*(C'\fR method then often performs some tests to make sure we have the right \*(L"type\*(R" of element. In our example, we know that the element will be a PPI::Token::Word because that's what we declared back in the \f(CW\*(C`applies_to()\*(C'\fR method. However, we didn't specify exactly which \*(L"word\*(R" we were looking for. Evaluating a \&\s-1PPI\s0 element in a string context returns the literal form of the code. (You can also use the \f(CW\*(C`content()\*(C'\fR method.) So we make sure that this \&\f(CW\*(C`PPI::Token::Word\*(C'\fR is, in fact, \*(L"grep\*(R". If it's not, then we don't need to bother examining it. .PP .Vb 1 \& return if $elem ne \*(Aqgrep\*(Aq; .Ve .PP The \f(CW\*(C`PPI::Token::Word\*(C'\fR class is also used for barewords and methods called on object references. It is possible for someone to declare a bareword hash key as \f(CW\*(C`%hash = ( grep => \*(Aqfoo\*(Aq)\*(C'\fR. We don't want to test those types of elements because they don't represent function calls to \f(CW\*(C`grep\*(C'\fR. So we use one of handy utility functions from Perl::Critic::Utils to make sure that this \&\*(L"grep\*(R" is actually in the right context. (The \f(CW\*(C`is_function_call()\*(C'\fR subroutine is brought in via the \f(CW\*(C`:classification\*(C'\fR tag.) .PP .Vb 1 \& return if ! is_function_call($elem); .Ve .PP Now that we know this element is a call to the \f(CW\*(C`grep\*(C'\fR function, we can look at the nearby elements to see what kind of arguments are being passed to it. In the following paragraphs, we discuss how to do this manually in order to explore \s-1PPI\s0; after that, we'll show how this Policy actually uses facilities provided by Perl::Critic::Utils to get this done. .PP Every \s-1PPI\s0 element is linked to its siblings, parent, and children (if it has any). Since those siblings could just be whitespace, we use the \f(CW\*(C`snext_sibling()\*(C'\fR to get the next code-sibling (the \*(L"s\*(R" in \&\f(CW\*(C`snext_sibling\*(C'\fR stands for \*(L"significant\*(R"). .PP .Vb 1 \& my $sib = $elem\->snext_sibling() or return; .Ve .PP In Perl, the parenthesis around argument lists are usually optional, and \s-1PPI\s0 packs the elements into a PPI::Structure::List object when parentheses are used. So if the sibling is a \f(CW\*(C`PPI::Structure::List\*(C'\fR, we pull out the first (significant) child of that list. This child will be the first argument to \f(CW\*(C`grep\*(C'\fR. If parentheses were not used, then the sibling itself is the first argument. .PP .Vb 1 \& my $arg = $sib\->isa(\*(AqPPI::Structure::List\*(Aq) ? $sib\->schild(0) : $sib; .Ve .PP In actuality, this sort of function argument lookup is common, so there is a \*(L"first_arg\*(R" in Perl::Critic::Utils subroutine available via the \f(CW\*(C`:ppi\*(C'\fR tag. So we use that instead. .PP .Vb 1 \& my $arg = first_arg($elem); .Ve .PP Finally, we now have a reference to the first argument to \f(CW\*(C`grep\*(C'\fR. If that argument is a block (i.e. something in curly braces), then it will be a PPI::Structure::Block, in which case our Policy is satisfied and we just return nothing. .PP .Vb 2 \& return if !$arg; \& return if $arg\->isa(\*(AqPPI::Structure::Block\*(Aq); .Ve .PP But if it is not a PPI::Structure::Block, then we know that this call to \f(CW\*(C`grep\*(C'\fR must be using the expression form, and that violates our Policy. So we create and return a new Perl::Critic::Violation object via the \&\*(L"violation\*(R" in Perl::Critic::Policy method, passing in the description, explanation, and a reference to the \s-1PPI\s0 element that caused the violation. And that's all there is to it! .PP .Vb 2 \& return $self\->violation( $DESC, $EXPL, $elem ); \& } \& \& 1; .Ve .PP One last thing \*(-- people are going to need to understand what is wrong with the code when your Policy finds a problem. It isn't reasonable to include all the details in your violation description or explanation. So please include a \s-1DESCRIPTION\s0 section in the \s-1POD\s0 for your Policy. It should succinctly describe the behavior and motivation for your Policy and include a few examples of both good and bad code. Here's an example: .PP .Vb 1 \& =pod \& \& =head1 NAME \& \& Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep \& \& \& =head1 DESCRIPTION \& \& The expression forms of C and C are awkward and hard to read. \& Use the block forms instead. \& \& @matches = grep /pattern/, @list; #not ok \& @matches = grep { /pattern/ } @list; #ok \& \& @mapped = map transform($_), @list; #not ok \& @mapped = map { transform($_) } @list; #ok \& \& =cut .Ve .PP When your policy has a section like this, users can invoke perlcritic with a \f(CW\*(C`\-\-verbose\*(C'\fR parameter of \f(CW10\fR or \&\f(CW11\fR or with a \*(L"%d\*(R" escape to see it along with the rest of the output for violations of your policy. .SH "MAKING YOUR POLICY CONFIGURABLE" .IX Header "MAKING YOUR POLICY CONFIGURABLE" Perl::Critic takes care of gathering configuration information for your Policy, from whatever source the user specifies. (See \*(L"\s-1CONFIGURATION\*(R"\s0 in Perl::Critic for the details of how a user specifies the values you're going to receive.) What your Policy ends up receiving for the value of a parameter is a string with leading and trailing whitespace removed. By default, you will need to handle conversion of that string to a useful form yourself. However, if you provide some metadata about your parameters, the parameter handling will be taken care of for you. (Additionally, tools that deal with Policies themselves can use this information to enhance their functionality. See the perlcritic \f(CW\*(C`\-\-profile\-proto\*(C'\fR option for an example.) .PP You can look at Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse for a simple example of a configurable Policy and Perl::Critic::Policy::Documentation::RequirePodSections for a more complex one. .SS "Do It All Yourself" .IX Subsection "Do It All Yourself" The \f(CW\*(C`initialize_if_enabled()\*(C'\fR method for a Policy receives one argument: an instance of Perl::Critic::PolicyConfig. This method is only called if the user's configuration has enabled the policy. It returns a boolean stating whether the Policy should continue to be enabled. Generally, the only reason to return \f(CW$FALSE\fR is when some external requirement is missing. For example, Perl::Critic::Policy::CodeLayout::RequireTidyCode used to disable itself if Perl::Tidy was not installed (that is until we made it no longer optional for the Perl-Critic distribution). .PP A basic, do-nothing implementation of \f(CW\*(C`initialize_if_enabled()\*(C'\fR would be: .PP .Vb 1 \& use Perl::Critic::Utils qw< :booleans >; \& \& ... \& \& sub initialize_if_enabled { \& my ( $self, $config ) = @_; \& \& return $TRUE; \& } .Ve .PP As stated above, what you get in \f(CW$config\fR are trimmed strings. For example, if the user's \fI.perlcritic\fR contains .PP .Vb 4 \& [Your::Policy] \& foo = bar baz \& factor = 5.52 \& selections = 2 78 92 .Ve .PP then \f(CW$config\fR will contain the equivalent of .PP .Vb 5 \& my $config = { \& foo => \*(Aqbar baz\*(Aq, \& factor => \*(Aq5.52\*(Aq, \& selections => \*(Aq2 78 92\*(Aq, \& }; .Ve .PP To make this available to the \f(CW\*(C`violates()\*(C'\fR method, the values are usually put into \f(CW$self\fR under the name of the configuration item prefixed with an underscore. E.g. .PP .Vb 2 \& sub initialize_if_enabled { \& my ( $self, $config ) = @_; \& \& $self\->{_foo} = $config\->get{foo}; \& $self\->{_factor} = $config\->get{factor}; \& $self\->{_selections} = $config\->get{selections}; \& \& return $TRUE; \& } .Ve .PP Often, you'll want to convert the configuration values into something more useful. In this example, \f(CW\*(C`selections\*(C'\fR is supposed to be a list of integers. Perl::Critic::Utils contains a number of functions that can help you with this. Assuming that \&\f(CW\*(C`violates()\*(C'\fR wants to have \f(CW\*(C`selections\*(C'\fR as an array, you'll want to have something like this: .PP .Vb 1 \& use Perl::Critic::Utils qw{ :booleans :characters :data_conversion }; \& \& sub initialize_if_enabled { \& my ( $self, $config ) = @_; \& \& $self\->{_foo} = $config\->get{foo}; \& $self\->{_factor} = $config\->get{factor}; \& \& my $selections = $config\->get{selections}; \& $selections = defined $selections ? $selections : $EMPTY_STRING; \& $self\->{_selections} = [ words_from_string($selections) ]; \& \& return $TRUE; \& } .Ve .PP Since \f(CW\*(C`selections\*(C'\fR contains numbers, it may be desirable to change the assignment to look like .PP .Vb 1 \& $self\->{_selections} = [ map { $_ + 0 } words_from_string($selections) ]; .Ve .PP If \f(CW\*(C`violates()\*(C'\fR needs to quickly determine whether a particular value is in \f(CW\*(C`selections\*(C'\fR, you would want to use a hash instead of an array, like this: .PP .Vb 1 \& $self\->{_selections} = { hashify( words_from_string($selections) ) }; .Ve .PP For an example of a Policy that has some simple, but non-standard configuration handling, see Perl::Critic::Policy::CodeLayout::RequireTidyCode. .SS "Note On Constructors" .IX Subsection "Note On Constructors" It used to be the case that Policies handled configuration by implementing a constructor. However, there was no requirement to call the base constructor; as long as the Policy ended up being a blessed hash reference, everything was fine. Unfortunately, this meant that Policies would be loaded and their prerequisites would be \f(CW\*(C`use\*(C'\fRd, even if the Policy wasn't enabled, slowing things down. Also, this severely restricted the core of Perl::Critic's ability to enhance things. Use of constructors is deprecated and is incompatible with \f(CW\*(C`supported_parameters()\*(C'\fR metadata below. Kindly use \f(CW\*(C`initialize_if_enabled()\*(C'\fR, instead, to do any sort of set up that you need. .ie n .SS "Providing Basic Configuration Information Via ""supported_parameters()""" .el .SS "Providing Basic Configuration Information Via \f(CWsupported_parameters()\fP" .IX Subsection "Providing Basic Configuration Information Via supported_parameters()" As minimum for a well behaved Policy, you should implement \&\f(CW\*(C`supported_parameters()\*(C'\fR in order to tell the rest of \f(CW\*(C`Perl::Critic\*(C'\fR what configuration values the Policy looks for, even if it is only to say that the Policy is not configurable. In the simple form, this function returns a list of the names of the parameters the Policy supports. So, for an non-configurable Policy, as in the \&\f(CW\*(C`RequireBlockGrep\*(C'\fR example above, this looked like .PP .Vb 1 \& sub supported_parameters { return () } .Ve .PP For the example being used in the \f(CW\*(C`initialize_if_enabled()\*(C'\fR section above, this would be .PP .Vb 1 \& sub supported_parameters { return qw< foo factor selections >; } .Ve .PP Given this information, \f(CW\*(C`Perl::Critic\*(C'\fR can tell the user when they have specified a parameter for a Policy which isn't valid, e.g. when they've misspelled the name of the parameter, and can emit the parameter as part of a \fI.perlcriticrc\fR prototype. .PP You can provide even more information about your Policy's configuration by giving each parameter a description and a string representation of the default value for the parameter. You do this by having the values in the list returned by \f(CW\*(C`supported_parameters()\*(C'\fR be hash references instead of strings, with keys of \f(CW\*(C`name\*(C'\fR, \&\f(CW\*(C`description\*(C'\fR, and \f(CW\*(C`default_string\*(C'\fR. For example, .PP .Vb 10 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqallowed_values\*(Aq, \& description => \& \*(AqIndividual and ranges of values to allow, and/or "all_integers".\*(Aq, \& default_string => \*(Aq0 1 2\*(Aq, \& }, \& { \& name => \*(Aqallowed_types\*(Aq, \& description => \*(AqKind of literals to allow.\*(Aq, \& default_string => \*(AqFloat\*(Aq, \& }, \& ); \& } .Ve .PP Note that use of constructors is incompatible with specifying parameters in this way. .ie n .SS "Using ""supported_parameters()"" to Get It Done For You" .el .SS "Using \f(CWsupported_parameters()\fP to Get It Done For You" .IX Subsection "Using supported_parameters() to Get It Done For You" The \f(CW\*(C`supported_parameters()\*(C'\fR discussion above showed how you could help others with your Policy, but didn't do anything to make your life as a Policy author easier; you still need to implement \&\f(CW\*(C`initialize_if_enabled()\*(C'\fR to access any configuration that the user has specified. To have the configuration automatically handled for you, you need to declare how your parameters act by specifying a value for their \f(CW\*(C`behavior\*(C'\fR. For example, the following declares that a parameter allows the user to choose from five specific values and that the user can select any combination of them: .PP .Vb 12 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqallowed_types\*(Aq, \& description => \*(AqKind of literals to allow.\*(Aq, \& default_string => \*(AqFloat\*(Aq, \& behavior => \*(Aqenumeration\*(Aq, \& enumeration_values => [ qw{ Binary Exp Float Hex Octal } ], \& enumeration_allow_multiple_values => 1, \& }, \& ); \& } .Ve .PP When you specify a behavior, parsing and validation of the user-specified and default values is done for you and your \&\f(CW\*(C`violates()\*(C'\fR method can retrieve the value under the key of the parameter name prefixed with an underscore, e.g., for the above declaration, the parsed and validated value can be accessed via \&\f(CW\*(C`$self\->{_allowed_types}\*(C'\fR. .PP The behaviors provide additional functionality to \f(CW\*(C`Perl::Critic\*(C'\fR; for more on this, see Perl::Critic::PolicyParameter and Perl::Critic::PolicyParameter::Behavior. .PP The following discusses each of the supported behaviors and the options they support. For the full details of a behavior, see the documentation for the implementing class. .PP \fI\*(L"string\*(R"\fR .IX Subsection "string" .PP Implemented in Perl::Critic::PolicyParameter::Behavior::String. .PP The most basic of behaviors, the value of the parameter will be stored in the Policy as a string. .PP This behavior is not configurable. .PP \f(CW\*(C`supported_parameters()\*(C'\fR example .IX Subsection "supported_parameters() example" .PP .Vb 10 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqa_string\*(Aq, \& description => \*(AqAn example string.\*(Aq, \& default_string => \*(Aqblah blah blah\*(Aq, \& behavior => \*(Aqstring\*(Aq, \& }, \& ); \& } .Ve .PP Access example .IX Subsection "Access example" .PP .Vb 2 \& sub violates { \& my ($self, $element, $document) = @_; \& \& ... \& my $string = $self\->{_a_string}; \& ... \& } .Ve .PP \fI\*(L"boolean\*(R"\fR .IX Subsection "boolean" .PP Implemented in Perl::Critic::PolicyParameter::Behavior::Boolean. .PP The value of the parameter will be either \&\f(CW$TRUE\fR or \&\f(CW$FALSE\fR. .PP This behavior is not configurable. .PP \f(CW\*(C`supported_parameters()\*(C'\fR example .IX Subsection "supported_parameters() example" .PP .Vb 10 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqa_boolean\*(Aq, \& description => \*(AqAn example boolean.\*(Aq, \& default_string => \*(Aq1\*(Aq, \& behavior => \*(Aqboolean\*(Aq, \& }, \& ); \& } .Ve .PP Access example .IX Subsection "Access example" .PP .Vb 2 \& sub violates { \& my ($self, $element, $document) = @_; \& \& ... \& my $is_whatever = $self\->{_a_boolean}; \& if ($is_whatever) { \& ... \& } \& ... \& } .Ve .PP \fI\*(L"integer\*(R"\fR .IX Subsection "integer" .PP Implemented in Perl::Critic::PolicyParameter::Behavior::Integer. .PP The value is validated against \f(CW\*(C`m/ \eA [\-+]? [1\-9] [\ed_]* \ez /xms\*(C'\fR (with an special check for \*(L"0\*(R"). Notice that this means that underscores are allowed in input values as with Perl numeric literals. .PP This takes two options, \f(CW\*(C`integer_minimum\*(C'\fR and \f(CW\*(C`integer_maximum\*(C'\fR, which specify endpoints of an inclusive range to restrict the value to. Either, neither, or both may be specified. .PP \f(CW\*(C`supported_parameters()\*(C'\fR example .IX Subsection "supported_parameters() example" .PP .Vb 12 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqan_integer\*(Aq, \& description => \*(AqAn example integer.\*(Aq, \& default_string => \*(Aq5\*(Aq, \& behavior => \*(Aqinteger\*(Aq, \& integer_minimum => 0, \& integer_maximum => 10, \& }, \& ); \& } .Ve .PP Access example .IX Subsection "Access example" .PP .Vb 2 \& sub violates { \& my ($self, $element, $document) = @_; \& \& ... \& my $integer = $self\->{_an_integer}; \& if ($integer > $TURNING_POINT) { \& ... \& } \& ... \& } .Ve .PP \fI\*(L"string list\*(R"\fR .IX Subsection "string list" .PP Implemented in Perl::Critic::PolicyParameter::Behavior::StringList. .PP The values will be derived by splitting the input string on blanks. (See \*(L"words_from_string\*(R" in Perl::Critic::Utils.) The parameter will be stored as a reference to a hash, with the values being the keys. .PP This takes one optional option, \f(CW\*(C`list_always_present_values\*(C'\fR, of a reference to an array of strings that will always be included in the parameter value, e.g. if the value of this option is \f(CW\*(C`[ qw{ a b c } ]\*(C'\fR and the user specifies a value of \f(CW\*(Aqc d e\*(Aq\fR, then the value of the parameter will contain \f(CW\*(Aqa\*(Aq\fR, \f(CW\*(Aqb\*(Aq\fR, \f(CW\*(Aqc\*(Aq\fR, \f(CW\*(Aqd\*(Aq\fR, and \f(CW\*(Aqe\*(Aq\fR. .PP \f(CW\*(C`supported_parameters()\*(C'\fR example .IX Subsection "supported_parameters() example" .PP .Vb 11 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqa_string_list\*(Aq, \& description => \*(AqAn example list.\*(Aq, \& default_string => \*(Aqred pink blue\*(Aq, \& behavior => \*(Aqstring list\*(Aq, \& list_always_present_values => [ qw{ green purple} ], \& }, \& ); \& } .Ve .PP Access example .IX Subsection "Access example" .PP .Vb 2 \& sub violates { \& my ($self, $element, $document) = @_; \& \& ... \& my $list = $self\->{_a_string_list}; \& my @list = keys %{$list}; \& ... \& return if not $list\->{ $element\->content() }; \& ... \& } .Ve .PP \fI\*(L"enumeration\*(R"\fR .IX Subsection "enumeration" .PP Implemented in Perl::Critic::PolicyParameter::Behavior::Enumeration. .PP The values will be derived by splitting the input string on blanks. (See \*(L"words_from_string\*(R" in Perl::Critic::Utils.) Depending upon the value of the \f(CW\*(C`enumeration_allow_multiple_values\*(C'\fR option, the parameter will be stored as a string or a reference to a hash, with the values being the keys. .PP This behavior takes one required option and one optional one. A value for \f(CW\*(C`enumeration_values\*(C'\fR of a reference to an array of valid strings is required. A true value can be specified for \&\f(CW\*(C`enumeration_allow_multiple_values\*(C'\fR to allow the user to pick more than one value, but this defaults to false. .PP \f(CW\*(C`supported_parameters()\*(C'\fR example .IX Subsection "supported_parameters() example" .PP .Vb 1 \& use Perl::Critic::Utils qw{ :characters }; \& \& sub supported_parameters { \& return ( \& { \& name => \*(Aqa_single_valued_enumeration\*(Aq, \& description => \& \*(AqAn example enumeration that can only have a single value.\*(Aq, \& default_string => $EMPTY, \& behavior => \*(Aqenumeration\*(Aq, \& enumeration_values => [ qw{ block statement pod operator } ], \& enumeration_allow_multiple_values => 0, \& }, \& { \& name => \*(Aqa_multi_valued_enumeration\*(Aq, \& description => \& \*(AqAn example enumeration that can have multiple values.\*(Aq, \& default_string => \*(Aqfe\*(Aq, \& behavior => \*(Aqenumeration\*(Aq, \& enumeration_values => [ qw{ fe fi fo fum } ], \& enumeration_allow_multiple_values => 1, \& }, \& ); \& } .Ve .PP Access example .IX Subsection "Access example" .PP .Vb 2 \& sub violates { \& my ($self, $element, $document) = @_; \& \& ... \& my $single_value = $self\->{_a_single_valued_enumeration}; \& ... \& my $multi_value = $self\->{_a_multi_valued_enumeration}; \& if ( $multi_value\->{fum} ) { \& ... \& } \& ... \& } .Ve .SS "Using a Custom Parser" .IX Subsection "Using a Custom Parser" If none of the behaviors does exactly what you want it to, you can provide your own parser for a parameter. The reason for doing this as opposed to using an implementation of \f(CW\*(C`initialize_if_enabled()\*(C'\fR is that it allows you to use a behavior to provide its extra functionality and it provides a means for a \f(CW\*(C`Perl::Critic\*(C'\fR configuration program, e.g. an \s-1IDE\s0 that integrates \f(CW\*(C`Perl::Critic\*(C'\fR, to validate your parameter as the user modifies its value. .PP The way you declare that you have a custom parser is to include a reference to it in the parameter specification with the \f(CW\*(C`parser\*(C'\fR key. For example: .PP .Vb 11 \& sub supported_parameters { \& return ( \& { \& name => \*(Aqfile_name\*(Aq, \& description => \*(AqA file for to read a list of values from.\*(Aq, \& default_string => undef, \& behavior => \*(Aqstring\*(Aq, \& parser => \e&_parse_file_name, \& }, \& ); \& } .Ve .PP A parser is a method on a subclass of Perl::Critic::Policy that takes two parameters: the Perl::Critic::PolicyParameter that is being specified and the value string provided by the user. The method is responsible for dealing with any default value and for saving the parsed value for later use by the \f(CW\*(C`violates()\*(C'\fR method. .PP An example parser (without enough error handling) for the above example declaration: .PP .Vb 1 \& use Path::Tiny; \& \& use Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue \& qw{ throw_policy_value }; \& \& sub _parse_file_name { \& my ($self, $parameter, $config_string) = @_; \& \& my @thingies; \& \& if ($config_string) { \& if (not \-r $config_string) { \& throw_policy_value \& policy => $self\->get_short_name(), \& option_name => $parameter\->get_name(), \& option_value => $config_string, \& message_suffix => \*(Aqis not readable.\*(Aq; \& } \& \& @thingies = path($config_string)\->slurp; \& } \& \& $self\->{_thingies} = \e@thingies; \& \& return; \& } .Ve .PP Note that, if the value for the parameter is not valid, an instance of Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue is thrown. This allows \f(CW\*(C`Perl::Critic\*(C'\fR to include that problem along with any other problems found with the user's configuration in a single error message. .ie n .SS "Using Both ""supported_parameters()"" and ""initialize_if_enabled()""" .el .SS "Using Both \f(CWsupported_parameters()\fP and \f(CWinitialize_if_enabled()\fP" .IX Subsection "Using Both supported_parameters() and initialize_if_enabled()" There are cases where a Policy needs additional initialization beyond configuration or where the way it acts depends upon the combination of multiple parameters. In such situations, you will need to create an implementation of \f(CW\*(C`initialize_if_enabled()\*(C'\fR. If you want to take advantage of the supplied parameter handling from within implementation of \f(CW\*(C`initialize_if_enabled()\*(C'\fR, note that the information from \f(CW\*(C`supported_parameters()\*(C'\fR will already have been used, with user-supplied parameter values validated and placed into the Policy by the time \f(CW\*(C`initialize_if_enabled()\*(C'\fR has been called. It is likely that you will not need to refer the contents of the \&\f(CW$config\fR parameter; just pull the information you need out of \&\f(CW$self\fR. In fact, any value for the parameter values will be gone. .ie n .SS "Summary of permitted hash keys in ""supported_parameters()""." .el .SS "Summary of permitted hash keys in \f(CWsupported_parameters()\fP." .IX Subsection "Summary of permitted hash keys in supported_parameters()." \fIAll types\fR .IX Subsection "All types" .ie n .IP "\- ""name"" (mandatory)" 4 .el .IP "\- ``name'' (mandatory)" 4 .IX Item "- name (mandatory)" .PD 0 .ie n .IP "\- ""description"" (optional)" 4 .el .IP "\- ``description'' (optional)" 4 .IX Item "- description (optional)" .ie n .IP "\- ""behavior"" (optional)" 4 .el .IP "\- ``behavior'' (optional)" 4 .IX Item "- behavior (optional)" .PD Currently, one of: .RS 4 .ie n .IP """boolean""" 4 .el .IP "``boolean''" 4 .IX Item "boolean" .PD 0 .ie n .IP """enumeration""" 4 .el .IP "``enumeration''" 4 .IX Item "enumeration" .ie n .IP """integer""" 4 .el .IP "``integer''" 4 .IX Item "integer" .ie n .IP """string""" 4 .el .IP "``string''" 4 .IX Item "string" .ie n .IP """string list""" 4 .el .IP "``string list''" 4 .IX Item "string list" .RE .RS 4 .RE .ie n .IP "\- ""default_string"" (optional)" 4 .el .IP "\- ``default_string'' (optional)" 4 .IX Item "- default_string (optional)" .PD A string representation of the default value of the parameter. .ie n .IP "\- ""parser"" (optional)" 4 .el .IP "\- ``parser'' (optional)" 4 .IX Item "- parser (optional)" A code ref to a custom parser for the parameter. .PP \fIEnumerations\fR .IX Subsection "Enumerations" .ie n .IP "\- ""enumeration_values"" (mandatory)" 4 .el .IP "\- ``enumeration_values'' (mandatory)" 4 .IX Item "- enumeration_values (mandatory)" A mandatory reference to an array of strings. .ie n .IP "\- ""enumeration_allow_multiple_values"" (optional)" 4 .el .IP "\- ``enumeration_allow_multiple_values'' (optional)" 4 .IX Item "- enumeration_allow_multiple_values (optional)" Boolean indicating whether or not the user is restricted to a single value. .PP \fIIntegers\fR .IX Subsection "Integers" .ie n .IP "\- ""integer_minimum"" (optional)" 4 .el .IP "\- ``integer_minimum'' (optional)" 4 .IX Item "- integer_minimum (optional)" Minimum allowed value, inclusive. .ie n .IP "\- ""integer_maximum"" (optional)" 4 .el .IP "\- ``integer_maximum'' (optional)" 4 .IX Item "- integer_maximum (optional)" Maximum allowed value, inclusive. .PP \fIString lists\fR .IX Subsection "String lists" .ie n .IP "\- ""list_always_present_values"" (optional)" 4 .el .IP "\- ``list_always_present_values'' (optional)" 4 .IX Item "- list_always_present_values (optional)" A reference to an array of values that should always be included in the value of the parameter. .SH "ADDITIONAL FEATURES" .IX Header "ADDITIONAL FEATURES" .ie n .SS """default_maximum_violations_per_document()""" .el .SS "\f(CWdefault_maximum_violations_per_document()\fP" .IX Subsection "default_maximum_violations_per_document()" Certain problems that a Policy detects can be endemic to a particular file; if there's one violation, there's likely to be many. A good example of this is Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict; if there's one line before \*(L"use strict\*(R", there's a good chance that the entire file is missing \*(L"use strict\*(R". In such cases, it's not much help to the user to report every single violation. If you've got such a policy, you should override \&\fIdefault_maximum_violations_per_document()\fR method to provide a limit. The user can override this value with a value for \*(L"maximum_violations_per_document\*(R" in their \fI.perlcriticrc\fR. .PP See the source code for Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers and Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings for examples. .ie n .SS """is_safe()""" .el .SS "\f(CWis_safe()\fP" .IX Subsection "is_safe()" Most Perl::Critic Policies are purely \fIstatic\fR. In other words, they never compile or execute any of the source code that they analyze. However it is possible to write \fIdynamic\fR Policies that do compile or execute code, which may result in unsafe operations (see Perl::Critic::Dynamic for an example). So the \f(CW\*(C`is_safe()\*(C'\fR method is used to indicate whether a Policy can be trusted to not cause mischief. By default, \f(CW\*(C`is_safe()\*(C'\fR returns true. But if you are writing a Policy that will compile or execute any of the source code that it analyzes, then you should override the \&\f(CW\*(C`is_safe()\*(C'\fR method to return false. .SH "DISTRIBUTING YOUR POLICIES" .IX Header "DISTRIBUTING YOUR POLICIES" .SS "Create a Distribution" .IX Subsection "Create a Distribution" You need to come up with a name for your set of policies. Sets of add-on policies are generally named \f(CW\*(C`Perl::Critic::\f(CIsomething\f(CW\*(C'\fR, e.g. Perl::Critic::More. .PP The module representing the distribution will not actually have any functionality; it's just documentation and a name for users to use when installing via \s-1CPAN\s0/\s-1CPANPLUS\s0. The important part is that this will include a list of the included policies, with descriptions of each. .PP A typical implementation will look like: .PP .Vb 1 \& package Perl::Critic::Example; \& \& use strict; \& use warnings; \& \& our $VERSION = \*(Aq1.000000\*(Aq; \& \& 1; # Magic true value required at end of module \& \& _\|_END_\|_ \& \& =head1 NAME \& \& Perl::Critic::Example \- Policies for Perl::Critic that act as an example. \& \& =head1 AFFILIATION \& \& This module has no functionality, but instead contains documentation \& for this distribution and acts as a means of pulling other modules \& into a bundle. All of the Policy modules contained herein will have \& an "AFFILIATION" section announcing their participation in this \& grouping. \& \& \& =head1 SYNOPSIS \& \& Some L policies that will help you keep your \& code nice and compliant. \& \& \& =head1 DESCRIPTION \& \& The included policies are: \& \& =over \& \& =item L \& \& Complains about some example documentation issues. [Default severity: 3] \& \& \& =item L \& \& All modules must have at least one variable. [Default severity: 3] \& \& \& =back \& \& \& =head1 CONFIGURATION AND ENVIRONMENT \& \& All policies included are in the "example" theme. See the \& L documentation for how to make use of this. .Ve .SS "Themes" .IX Subsection "Themes" Users can choose which policies to enable using themes. You should implement \f(CW\*(C`default_themes()\*(C'\fR so that users can take advantage of this. In particular, you should use a theme named after your distribution in all your policies; this should match the value listed in the \f(CW\*(C`CONFIGURATION AND ENVIRONMENT\*(C'\fR \s-1POD\s0 section as shown above. .PP .Vb 1 \& default_themes { return qw< example math > } .Ve .PP If you're looking for ideas of what themes to use, have a look at the output of \f(CW\*(C`perlcritic \-\-list\-themes\*(C'\fR. .SS "Documentation" .IX Subsection "Documentation" \fI\s-1AFFILIATION\s0\fR .IX Subsection "AFFILIATION" .PP Since all policies have to go somewhere under the \&\f(CW\*(C`Perl::Critic::Policy::\*(C'\fR namespace, it isn't always clear what distribution a policy came from when browsing through their documentation. For this reason, you should include an \f(CW\*(C`AFFILIATION\*(C'\fR section in the \s-1POD\s0 for all of your policies that state where the policy comes from. For example: .PP .Vb 1 \& =head1 AFFILIATION \& \& This policy is part of L. .Ve .PP \fI\s-1CONFIGURATION\s0\fR .IX Subsection "CONFIGURATION" .PP In order to make it clear what can be done with a policy, you should always include a \f(CW\*(C`CONFIGURATION\*(C'\fR section in your \s-1POD,\s0 even if it's only to say: .PP .Vb 1 \& =head1 CONFIGURATION \& \& This Policy is not configurable except for the standard options. .Ve .SH "TESTING YOUR POLICY" .IX Header "TESTING YOUR POLICY" The Perl::Critic distribution also contains a framework for testing your Policy. See Test::Perl::Critic::Policy for the details. .SH "HINT" .IX Header "HINT" When you're trying to figure out what \s-1PPI\s0 is going to hand you for a chunk of code, there is a \fItools/ppidump\fR program in the Perl::Critic distribution that will help you. For example, when developing the above RequireBlockGrep example, you might want to try .PP .Vb 1 \& tools/ppidump \*(Aq@matches = grep /pattern/, @list;\*(Aq .Ve .PP and .PP .Vb 1 \& tools/ppidump \*(Aq@matches = grep { /pattern/ } @list;\*(Aq .Ve .PP to see the differences between the two cases. .PP Alternatively, see the \f(CW\*(C`ppi_dumper\*(C'\fR documentation at and the \f(CW\*(C`PPI::Tester\*(C'\fR documentation at . .SH "VERSION" .IX Header "VERSION" This is part of Perl::Critic version 1.116. .SH "SEE ALSO" .IX Header "SEE ALSO" Chas. Owens has a blog post about developing in-house policies at . .SH "AUTHOR" .IX Header "AUTHOR" Jeffrey Ryan Thalhammer .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 2005\-2011 Imaginative Software Systems. All rights reserved. .PP This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the \s-1LICENSE\s0 file included with this module.