This file is indexed.

/usr/share/perl5/Perl/Critic/DEVELOPER.pod is in libperl-critic-perl 1.126-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
=pod

=for stopwords lookup RequireBlockGrep

=head1 NAME

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


=head1 DESCRIPTION

For developers who want to create custom coding standards, the
following tells how to create a Policy module for
L<Perl::Critic|Perl::Critic>.  Although the Perl::Critic distribution
already includes a number of Policies based on Damian Conway's book
I<Perl Best Practices> (which will be referred to via "I<PBP>" 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
L<Perl::Critic::Policy|Perl::Critic::Policy> subclass, which may
require as little as 10 lines of code.


=head1 BACKGROUND

The heart of Perl::Critic is L<PPI|PPI>, a parser and lexer for Perl.
PPI transforms Perl source code into a Document Object Model (DOM).
Each token in the document is represented by a PPI class, such as
L<PPI::Token::Operator|PPI::Token::Operator> or
L<PPI::Token::Word|PPI::Token::Word>, and then organized into
structure classes, like
L<PPI::Statement::Expression|PPI::Statement::Expression> and
L<PPI::Structure::Subroutine|PPI::Structure::Subroutine>. The root
node of the hierarchy is the L<PPI::Document|PPI::Document>.

The L<Perl::Critic|Perl::Critic> engine traverses each node in the
L<PPI::Document|PPI::Document> tree and invokes each of the
L<Perl::Critic::Policy|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 L<Perl::Critic::Violation|Perl::Critic::Violation> objects.
If there are no violations, then the Policy returns nothing.

Policies are usually written based on existing policies, so let's look
at one to see how it works.  The F<RequireBlockGrep.pm> Policy is
relatively simple and demonstrates most of the important issues.  The
goal of this Policy is to enforce that every call to C<grep> uses a
block for the first argument and not an expression.  The reasons for
this Policy are discussed in detail in I<PBP>.


=head1 EXAMPLE POLICY

First, the Policy module needs to have a name.  Perl::Critic uses
L<Module::Pluggable|Module::Pluggable> to automatically discover all
modules in the C<Perl::Critic::Policy> namespace.  Also, we've adopted
the convention of grouping Policies into directories according to the
chapters of I<PBP>.  Since the goal of this Policy is to enforce the
use of block arguments to C<grep> and it comes from the "Builtin
Functions" chapter of I<PBP>, we call it
C<"Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep">.

    package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep;

Next, we set some pragmas and load the modules that we'll need.  All
Policy modules inherit from the
L<Perl::Critic::Policy|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.

Technically, C<use strict> and C<use warnings> are optional, but we
don't want Perl::Critic to be a hypocrite, now do we?

    use strict;
    use warnings;

    use Readonly;

    use Perl::Critic::Utils qw{ :severities :classification :ppi };
    use base 'Perl::Critic::Policy';

    our $VERSION = '1.05';

Next, we'll declare a description and explanation for this Policy.
The description is always just a string that basically says "this is
what's wrong."  The explanation can be either a string with further
details, or a reference to an array of integers that correspond to
page numbers in I<PBP>.  We make them read-only because they never
change.  (See
L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma|Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma>
for why we don't C<use constant>.)

    Readonly::Scalar my $DESC => q{Expression form of "grep"};
    Readonly::Scalar my $EXPL => [ 169 ];

Most policies don't need to override the C<initialize_if_enabled()>
method provided by L<Perl::Critic::Policy|Perl::Critic::Policy>.
However, if your Policy is configurable via F<.perlcriticrc>, you
should implement a C<supported_parameters()> method and need to
implement C<initialize_if_enabled()> to examine the C<$config> values.
Since this Policy isn't configurable, we'll declare that by providing
an implementation of C<supported_parameters()> that returns an empty
list.

    sub supported_parameters { return ()                  }

Next, we define the C<default_severity()> method, which must return an
integer indicating the severity of violating this Policy.  Severity
values range from 1 to 5, where 5 is the "most severe."  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 L<Perl::Critic::Utils|Perl::Critic::Utils>
package exports several severity constants that you can use here via
the C<:severities> tag.

    sub default_severity     { return $SEVERITY_HIGH      }

Likewise, the C<default_themes()> 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 C<"core"> theme.  Since
use of C<grep> without blocks often leads to bugs, we include a
C<"bugs"> theme.  And since this Policy comes directly from I<PBP>,
this Policy should be a member of the C<"pbp"> theme.

    sub default_themes       { return qw( core bugs pbp ) }

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
L<Perl::Critic::More|Perl::Critic::More> distribution all have a
C<"more"> theme.

Next, we indicate what elements of the code this Policy will analyze,
like statements or variables or conditionals or POD.  These elements
are specified as PPI classes such as L<PPI::Statement|PPI::Statement>,
L<PPI::Token::Symbol|PPI::Token::Symbol>,
L<PPI::Structure::Conditional|PPI::Structure::Conditional> or
L<PPI::Token::Pod|PPI::Token::Pod> respectively.  The C<applies_to()>
method returns a list of PPI package names.  (You can get that list of
available package names via C<perldoc PPI>.)  As Perl::Critic
traverses the document, it will call the C<violates()> method from
this module whenever it encounters one of the PPI types that are given
here.  In this case, we just want to test calls to C<grep>.  Since the
token "grep" is a L<PPI::Token::Word|PPI::Token::Word>, we return that
package name from the C<applies_to()> method.

    sub applies_to           { return 'PPI::Token::Word'  }

If your Policy needs to analyze several different types of elements,
the C<applies_to> method may return the name of several PPI packages.
If your Policy needs to examine the file as a whole, then the
C<applies_to> method should return L<PPI::Document|PPI::Document>.
Since there is only one PPI::Document element, your Policy would only
be invoked once per file.

Now comes the interesting part.  The C<violates()> method does all the
work.  It is always called with 2 arguments: a reference to the
current PPI element that Perl::Critic is traversing, and a reference
to the entire PPI document. [And since this is an object method, there
will be an additional argument that is a reference to this object
(C<$self>), 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 C<undef>.

    sub violates {
        my ( $self, $elem, undef ) = @_;

The C<violates()> method then often performs some tests to make sure
we have the right "type" of element.  In our example, we know that the
element will be a L<PPI::Token::Word|PPI::Token::Word> because that's
what we declared back in the C<applies_to()> method.  However, we
didn't specify exactly which "word" we were looking for.  Evaluating a
PPI element in a string context returns the literal form of the code.
(You can also use the C<content()> method.)  So we make sure that this
C<PPI::Token::Word> is, in fact, "grep".  If it's not, then we don't
need to bother examining it.

        return if $elem ne 'grep';

The C<PPI::Token::Word> class is also used for barewords and methods
called on object references.  It is possible for someone to declare a
bareword hash key as C<< %hash = ( grep => 'foo') >>.  We don't want
to test those types of elements because they don't represent function
calls to C<grep>.  So we use one of handy utility functions from
L<Perl::Critic::Utils|Perl::Critic::Utils> to make sure that this
"grep" is actually in the right context.  (The C<is_function_call()>
subroutine is brought in via the C<:classification> tag.)

        return if ! is_function_call($elem);

Now that we know this element is a call to the C<grep> 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 L<PPI|PPI>; after that, we'll show
how this Policy actually uses facilities provided by
L<Perl::Critic::Utils|Perl::Critic::Utils> to get this done.

Every PPI element is linked to its siblings, parent, and children (if
it has any).  Since those siblings could just be whitespace, we use
the C<snext_sibling()> to get the next code-sibling (the "s" in
C<snext_sibling> stands for "significant").

        my $sib = $elem->snext_sibling() or return;

In Perl, the parenthesis around argument lists are usually optional,
and PPI packs the elements into a
L<PPI::Structure::List|PPI::Structure::List> object when parentheses
are used.  So if the sibling is a C<PPI::Structure::List>, we pull out
the first (significant) child of that list.  This child will be the
first argument to C<grep>.  If parentheses were not used, then the
sibling itself is the first argument.

        my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;

In actuality, this sort of function argument lookup is common, so
there is a L<Perl::Critic::Utils/"first_arg"> subroutine available via
the C<:ppi> tag.  So we use that instead.

        my $arg = first_arg($elem);

Finally, we now have a reference to the first argument to C<grep>.  If
that argument is a block (i.e. something in curly braces), then it
will be a L<PPI::Structure::Block|PPI::Structure::Block>, in which
case our Policy is satisfied and we just return nothing.

        return if !$arg;
        return if $arg->isa('PPI::Structure::Block');

But if it is not a L<PPI::Structure::Block|PPI::Structure::Block>,
then we know that this call to C<grep> must be using the expression
form, and that violates our Policy.  So we create and return a new
L<Perl::Critic::Violation|Perl::Critic::Violation> object via the
L<Perl::Critic::Policy/"violation"> method, passing in the
description, explanation, and a reference to the PPI element that
caused the violation.  And that's all there is to it!

        return $self->violation( $DESC, $EXPL, $elem );
    }

    1;

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 DESCRIPTION section in the POD 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:

    =pod

    =head1 NAME

    Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep


    =head1 DESCRIPTION

    The expression forms of C<grep> and C<map> 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

When your policy has a section like this, users can invoke
L<perlcritic|perlcritic> with a C<--verbose> parameter of C<10> or
C<11> or with a "%d" escape to see it along with the rest of the
output for violations of your policy.


=head1 MAKING YOUR POLICY CONFIGURABLE

L<Perl::Critic|Perl::Critic> takes care of gathering configuration
information for your Policy, from whatever source the user specifies.
(See L<Perl::Critic/"CONFIGURATION"> 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 L<perlcritic|perlcritic> C<--profile-proto>
option for an example.)

You can look at
L<Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse|Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse>
for a simple example of a configurable Policy and
L<Perl::Critic::Policy::Documentation::RequirePodSections|Perl::Critic::Policy::Documentation::RequirePodSections>
for a more complex one.

=head2 Do It All Yourself

The C<initialize_if_enabled()> method for a Policy receives one
argument: an instance of
L<Perl::Critic::PolicyConfig|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 C<$FALSE> is when some
external requirement is missing.  For example,
L<Perl::Critic::Policy::CodeLayout::RequireTidyCode|Perl::Critic::Policy::CodeLayout::RequireTidyCode>
used to disable itself if L<Perl::Tidy|Perl::Tidy> was not installed
(that is until we made it no longer optional for the Perl-Critic
distribution).

A basic, do-nothing implementation of C<initialize_if_enabled()> would
be:

    use Perl::Critic::Utils qw< :booleans >;

    ...

    sub initialize_if_enabled {
        my ( $self, $config ) = @_;

        return $TRUE;
    }

As stated above, what you get in C<$config> are trimmed strings.  For
example, if the user's F<.perlcritic> contains

    [Your::Policy]
    foo          = bar baz
    factor   =     5.52
    selections =   2 78 92

then C<$config> will contain the equivalent of

    my $config = {
        foo        => 'bar baz',
        factor     => '5.52',
        selections => '2 78 92',
    };

To make this available to the C<violates()> method, the values are
usually put into C<$self> under the name of the configuration item
prefixed with an underscore.  E.g.

    sub initialize_if_enabled {
        my ( $self, $config ) = @_;

        $self->{_foo} = $config->get{foo};
        $self->{_factor} = $config->get{factor};
        $self->{_selections} = $config->get{selections};

        return $TRUE;
    }

Often, you'll want to convert the configuration values into something
more useful.  In this example, C<selections> is supposed to be a list
of integers.  L<Perl::Critic::Utils|Perl::Critic::Utils> contains a
number of functions that can help you with this.  Assuming that
C<violates()> wants to have C<selections> as an array, you'll want to
have something like this:

    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;
    }

Since C<selections> contains numbers, it may be desirable to change
the assignment to look like

    $self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];

If C<violates()> needs to quickly determine whether a particular value
is in C<selections>, you would want to use a hash instead of an array,
like this:

    $self->{_selections} = { hashify( words_from_string($selections) ) };

For an example of a Policy that has some simple, but non-standard
configuration handling, see
L<Perl::Critic::Policy::CodeLayout::RequireTidyCode|Perl::Critic::Policy::CodeLayout::RequireTidyCode>.


=head2 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 C<use>d,
even if the Policy wasn't enabled, slowing things down.  Also, this
severely restricted the core of L<Perl::Critic|Perl::Critic>'s ability
to enhance things.  Use of constructors is deprecated and is
incompatible with C<supported_parameters()> metadata below.  Kindly
use C<initialize_if_enabled()>, instead, to do any sort of set up that
you need.



=head2 Providing Basic Configuration Information Via C<supported_parameters()>

As minimum for a well behaved Policy, you should implement
C<supported_parameters()> in order to tell the rest of C<Perl::Critic>
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
C<RequireBlockGrep> example above, this looked like

    sub supported_parameters { return ()                  }

For the example being used in the C<initialize_if_enabled()> section
above, this would be

    sub supported_parameters { return qw< foo factor selections >; }

Given this information, C<Perl::Critic> 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 F<.perlcriticrc> prototype.

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 C<supported_parameters()> be
hash references instead of strings, with keys of C<name>,
C<description>, and C<default_string>.  For example,

    sub supported_parameters {
        return (
            {
                name           => 'allowed_values',
                description    =>
                    'Individual and ranges of values to allow, and/or "all_integers".',
                default_string => '0 1 2',
            },
            {
                name           => 'allowed_types',
                description    => 'Kind of literals to allow.',
                default_string => 'Float',
            },
        );
    }

Note that use of constructors is
L<incompatible|/"Note On Constructors"> with specifying parameters in
this way.


=head2 Using C<supported_parameters()> to Get It Done For You

The C<supported_parameters()> 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
C<initialize_if_enabled()> 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 C<behavior>.  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:

    sub supported_parameters {
        return (
            {
                name               => 'allowed_types',
                description        => 'Kind of literals to allow.',
                default_string     => 'Float',
                behavior           => 'enumeration',
                enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
                enumeration_allow_multiple_values => 1,
            },
        );
    }

When you specify a behavior, parsing and validation of the
user-specified and default values is done for you and your
C<violates()> 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
C<< $self->{_allowed_types} >>.

The behaviors provide additional functionality to C<Perl::Critic>; for
more on this, see
L<Perl::Critic::PolicyParameter|Perl::Critic::PolicyParameter> and
L<Perl::Critic::PolicyParameter::Behavior|Perl::Critic::PolicyParameter::Behavior>.

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.


=head3 "string"

Implemented in
L<Perl::Critic::PolicyParameter::Behavior::String|Perl::Critic::PolicyParameter::Behavior::String>.

The most basic of behaviors, the value of the parameter will be stored
in the Policy as a string.

This behavior is not configurable.

=head4 C<supported_parameters()> example

    sub supported_parameters {
        return (
            {
                name           => 'a_string',
                description    => 'An example string.',
                default_string => 'blah blah blah',
                behavior       => 'string',
            },
        );
    }


=head4 Access example

    sub violates {
        my ($self, $element, $document) = @_;

        ...
        my $string = $self->{_a_string};
        ...
    }


=head3 "boolean"

Implemented in
L<Perl::Critic::PolicyParameter::Behavior::Boolean|Perl::Critic::PolicyParameter::Behavior::Boolean>.

The value of the parameter will be either
L<$TRUE|Perl::Critic::Utils/$TRUE> or
L<$FALSE|Perl::Critic::Utils/$FALSE>.

This behavior is not configurable.

=head4 C<supported_parameters()> example

    sub supported_parameters {
        return (
            {
                name           => 'a_boolean',
                description    => 'An example boolean.',
                default_string => '1',
                behavior       => 'boolean',
            },
        );
    }


=head4 Access example

    sub violates {
        my ($self, $element, $document) = @_;

        ...
        my $is_whatever = $self->{_a_boolean};
        if ($is_whatever) {
            ...
        }
        ...
    }


=head3 "integer"

Implemented in
L<Perl::Critic::PolicyParameter::Behavior::Integer|Perl::Critic::PolicyParameter::Behavior::Integer>.

The value is validated against C<m/ \A [-+]? [1-9] [\d_]* \z /xms>
(with an special check for "0").  Notice that this means that
underscores are allowed in input values as with Perl numeric literals.

This takes two options, C<integer_minimum> and C<integer_maximum>,
which specify endpoints of an inclusive range to restrict the value
to.  Either, neither, or both may be specified.

=head4 C<supported_parameters()> example

    sub supported_parameters {
        return (
            {
                name            => 'an_integer',
                description     => 'An example integer.',
                default_string  => '5',
                behavior        => 'integer',
                integer_minimum => 0,
                integer_maximum => 10,
            },
        );
    }


=head4 Access example

    sub violates {
        my ($self, $element, $document) = @_;

        ...
        my $integer = $self->{_an_integer};
        if ($integer > $TURNING_POINT) {
            ...
        }
        ...
    }


=head3 "string list"

Implemented in
L<Perl::Critic::PolicyParameter::Behavior::StringList|Perl::Critic::PolicyParameter::Behavior::StringList>.

The values will be derived by splitting the input string on blanks.
(See L<Perl::Critic::Utils/"words_from_string">.) The parameter will
be stored as a reference to a hash, with the values being the keys.

This takes one optional option, C<list_always_present_values>, 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 C<[ qw{ a b c }
]> and the user specifies a value of C<'c d e'>, then the value of the
parameter will contain C<'a'>, C<'b'>, C<'c'>, C<'d'>, and C<'e'>.

=head4 C<supported_parameters()> example

    sub supported_parameters {
        return (
            {
                name                  => 'a_string_list',
                description           => 'An example list.',
                default_string        => 'red pink blue',
                behavior              => 'string list',
                list_always_present_values => [ qw{ green purple} ],
            },
        );
    }


=head4 Access example

    sub violates {
        my ($self, $element, $document) = @_;

        ...
        my $list = $self->{_a_string_list};
        my @list = keys %{$list};
        ...
        return if not $list->{ $element->content() };
        ...
    }


=head3 "enumeration"

Implemented in
L<Perl::Critic::PolicyParameter::Behavior::Enumeration|Perl::Critic::PolicyParameter::Behavior::Enumeration>.

The values will be derived by splitting the input string on blanks.
(See L<Perl::Critic::Utils/"words_from_string">.)  Depending upon the
value of the C<enumeration_allow_multiple_values> option, the
parameter will be stored as a string or a reference to a hash, with
the values being the keys.

This behavior takes one required option and one optional one.  A value
for C<enumeration_values> of a reference to an array of valid strings
is required.  A true value can be specified for
C<enumeration_allow_multiple_values> to allow the user to pick more
than one value, but this defaults to false.

=head4 C<supported_parameters()> example

    use Perl::Critic::Utils qw{ :characters };

    sub supported_parameters {
        return (
            {
                name               => 'a_single_valued_enumeration',
                description        =>
                    'An example enumeration that can only have a single value.',
                default_string     => $EMPTY,
                behavior           => 'enumeration',
                enumeration_values => [ qw{ block statement pod operator } ],
                enumeration_allow_multiple_values => 0,
            },
            {
                name               => 'a_multi_valued_enumeration',
                description        =>
                    'An example enumeration that can have multiple values.',
                default_string     => 'fe',
                behavior           => 'enumeration',
                enumeration_values => [ qw{ fe fi fo fum } ],
                enumeration_allow_multiple_values => 1,
            },
        );
    }


=head4 Access example

    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} ) {
            ...
        }
        ...
    }


=head2 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 C<initialize_if_enabled()> is
that it allows you to use a behavior to provide its extra
functionality and it provides a means for a C<Perl::Critic>
configuration program, e.g. an IDE that integrates C<Perl::Critic>, to
validate your parameter as the user modifies its value.

The way you declare that you have a custom parser is to include a
reference to it in the parameter specification with the C<parser> key.
For example:

    sub supported_parameters {
        return (
            {
                name           => 'file_name',
                description    => 'A file for to read a list of values from.',
                default_string => undef,
                behavior       => 'string',
                parser         => \&_parse_file_name,
            },
        );
    }

A parser is a method on a subclass of
L<Perl::Critic::Policy|Perl::Critic::Policy> that takes two
parameters: the
L<Perl::Critic::PolicyParameter|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 C<violates()> method.

An example parser (without enough error handling) for the above
example declaration:

    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 => 'is not readable.';
            }

            @thingies = path($config_string)->slurp;
        }

        $self->{_thingies} = \@thingies;

        return;
    }

Note that, if the value for the parameter is not valid, an instance of
L<Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue|Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue>
is thrown.  This allows C<Perl::Critic> to include that problem along
with any other problems found with the user's configuration in a
single error message.


=head2 Using Both C<supported_parameters()> and C<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 C<initialize_if_enabled()>.  If you want to take
advantage of the supplied parameter handling from within
implementation of C<initialize_if_enabled()>, note that the
information from C<supported_parameters()> will already have been
used, with user-supplied parameter values validated and placed into
the Policy by the time C<initialize_if_enabled()> has been called.  It
is likely that you will not need to refer the contents of the
C<$config> parameter; just pull the information you need out of
C<$self>.  In fact, any value for the parameter values will be gone.



=head2 Summary of permitted hash keys in C<supported_parameters()>.


=head3 All types


=over

=item - "name" (mandatory)

=item - "description" (optional)

=item - "behavior" (optional)

Currently, one of:

=over

=item "boolean"

=item "enumeration"

=item "integer"

=item "string"

=item "string list"

=back

=item - "default_string" (optional)

A string representation of the default value of the parameter.

=item - "parser" (optional)

A code ref to a custom parser for the parameter.

=back

=head3 Enumerations

=over

=item - "enumeration_values" (mandatory)

A mandatory reference to an array of strings.

=item - "enumeration_allow_multiple_values" (optional)

Boolean indicating whether or not the user is restricted to a single
value.

=back

=head3 Integers

=over

=item - "integer_minimum" (optional)

Minimum allowed value, inclusive.

=item - "integer_maximum" (optional)

Maximum allowed value, inclusive.

=back

=head3 String lists

=over

=item - "list_always_present_values" (optional)

A reference to an array of values that should always be included in
the value of the parameter.

=back


=head1 ADDITIONAL FEATURES

=head2 C<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
L<Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict|Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict>;
if there's one line before L<use strict>, there's a good chance that
the entire file is missing L<use strict>.  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
L<default_maximum_violations_per_document()|Perl::Critic::Policy/"default_maximum_violations_per_document()">
method to provide a limit.  The user can override this value with a
value for "maximum_violations_per_document" in their F<.perlcriticrc>.

See the source code for
L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers|Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers>
and
L<Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings|Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings>
for examples.


=head2 C<is_safe()>

Most L<Perl::Critic> Policies are purely I<static>.  In other words,
they never compile or execute any of the source code that they
analyze.  However it is possible to write I<dynamic> Policies that do
compile or execute code, which may result in unsafe operations (see
L<Perl::Critic::Dynamic|Perl::Critic::Dynamic> for an example).  So
the C<is_safe()> method is used to indicate whether a Policy can be
trusted to not cause mischief.  By default, C<is_safe()> 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
C<is_safe()> method to return false.


=head1 DISTRIBUTING YOUR POLICIES

=head2 Create a Distribution

You need to come up with a name for your set of policies.  Sets of
add-on policies are generally named C<Perl::Critic::I<something>>,
e.g. L<Perl::Critic::More|Perl::Critic::More>.

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 L<CPAN|CPAN>/L<CPANPLUS|CPANPLUS>.  The important
part is that this will include a list of the included policies, with
descriptions of each.

A typical implementation will look like:

    package Perl::Critic::Example;

    use strict;
    use warnings;

    our $VERSION = '1.000000';

    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<Perl::Critic|Perl::Critic> policies that will help you keep your
    code nice and compliant.


    =head1 DESCRIPTION

    The included policies are:

    =over

    =item L<Perl::Critic::Policy::Documentation::Example|Perl::Critic::Policy::Documentation::Example>

    Complains about some example documentation issues.  [Default severity: 3]


    =item L<Perl::Critic::Policy::Variables::Example|Perl::Critic::Policy::Variables::Example>

    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<Perl::Critic|Perl::Critic> documentation for how to make use of this.


=head2 Themes

Users can choose which policies to enable using themes.  You should
implement C<default_themes()> 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 C<CONFIGURATION AND ENVIRONMENT> POD section as shown above.

    default_themes { return qw< example math > }

If you're looking for ideas of what themes to use, have a look at the
output of C<perlcritic --list-themes>.


=head2 Documentation

=head3 AFFILIATION

Since all policies have to go somewhere under the
C<Perl::Critic::Policy::> namespace, it isn't always clear what
distribution a policy came from when browsing through their
documentation.  For this reason, you should include an C<AFFILIATION>
section in the POD for all of your policies that state where the
policy comes from.  For example:

    =head1 AFFILIATION

    This policy is part of L<Perl::Critic::Example|Perl::Critic::Example>.


=head3 CONFIGURATION

In order to make it clear what can be done with a policy, you should
always include a C<CONFIGURATION> section in your POD, even if it's
only to say:

    =head1 CONFIGURATION

    This Policy is not configurable except for the standard options.

=head1 TESTING YOUR POLICY

The L<Perl::Critic> distribution also contains a framework for testing your
Policy.  See L<Test::Perl::Critic::Policy> for the details.

=head1 HINT

When you're trying to figure out what L<PPI|PPI> is going to hand you
for a chunk of code, there is a F<tools/ppidump> program in the
L<Perl::Critic|Perl::Critic> distribution that will help you.  For
example, when developing the above RequireBlockGrep example, you might
want to try

    tools/ppidump '@matches = grep /pattern/, @list;'

and

    tools/ppidump '@matches = grep { /pattern/ } @list;'

to see the differences between the two cases.

Alternatively, see the C<ppi_dumper> documentation at
L<http://search.cpan.org/dist/App-PPI-Dumper/script/ppi_dumper>
and the C<PPI::Tester> documentation at
L<http://search.cpan.org/dist/PPI-Tester/lib/PPI/Tester.pm>.


=head1 VERSION

This is part of L<Perl::Critic|Perl::Critic> version 1.116.


=head1 SEE ALSO

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


=head1 AUTHOR

Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>


=head1 COPYRIGHT

Copyright (c) 2005-2011 Imaginative Software Systems.  All rights reserved.

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 LICENSE file included with this module.

=cut

##############################################################################
# Local Variables:
#   mode: cperl
#   cperl-indent-level: 4
#   fill-column: 78
#   indent-tabs-mode: nil
#   c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=70 ft=pod expandtab shiftround :