File: ConstantPragmaHash.pm

package info (click to toggle)
libperl-critic-pulp-perl 99-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,700 kB
  • sloc: perl: 13,768; sh: 285; makefile: 6; ansic: 1
file content (256 lines) | stat: -rw-r--r-- 8,383 bytes parent folder | download
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
# Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde

# Perl-Critic-Pulp is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# Perl-Critic-Pulp is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with Perl-Critic-Pulp.  If not, see <http://www.gnu.org/licenses/>.


package Perl::Critic::Policy::Compatibility::ConstantPragmaHash;
use 5.006;
use strict;
use warnings;
use base 'Perl::Critic::Policy';
use Perl::Critic::Utils;
use Perl::Critic::Pulp::Utils;
use version (); # but don't import qv()

# uncomment this to run the ### lines
# use Smart::Comments;

our $VERSION = 99;

use constant supported_parameters => ();
use constant default_severity     => $Perl::Critic::Utils::SEVERITY_MEDIUM;
use constant default_themes       => qw(pulp compatibility);
use constant applies_to           => 'PPI::Document';

my $perl_ok_version = version->new('5.008');
my $constant_ok_version = version->new('1.03');

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

  my @violations;
  my $perlver; # a "version" object
  my $modver;  # a "version" object

  my $aref = $document->find ('PPI::Statement::Include')
    || return; # if no includes at all
  foreach my $inc (@$aref) {

    $inc->type eq 'use'
      || ($inc->type eq 'require'
          && Perl::Critic::Pulp::Utils::elem_in_BEGIN($inc))
        || next;

    if (my $ver = $inc->version) {
      # "use 5.008" etc perl version
      $ver = version->new ($ver);
      if (! defined $perlver || $ver > $perlver) {
        $perlver = $ver;

        if ($perlver >= $perl_ok_version) {
          # adequate perl version demanded, stop here
          last;
        }
      }
      next;
    }

    ($inc->module||'') eq 'constant' || next;

    if (my $ver = Perl::Critic::Pulp::Utils::include_module_version ($inc)) {
      ### $ver
      # PPI::Token::Number::Float
      $ver = version->new ($ver->content);
      if (! defined $modver || $ver > $modver) {
        $modver = $ver;

        if ($modver >= $constant_ok_version) {
          # adequate "constant" version demanded, stop here
          last;
        }
      }
    }

    if (_use_constant_is_multi ($inc)) {
      push @violations, $self->violation
        ("'use constant' with multi-constant hash requires perl 5.8 or constant 1.03 (at this point have "
         . (defined $perlver ? "perl $perlver" : "no perl version")
         . (defined $modver ? ", constant $modver)" : ", no constant version)"),
         '',
         $inc);
    }
  }

  return @violations;
}

# $inc is a PPI::Statement::Include with type "use" and module "constant".
# Return true if it has a multi-constant hash as its argument like
# "use constant { X => 1 };"
#
# The plain "use constant { x=>1 }" comes out as
#
#   PPI::Statement::Include
#     PPI::Token::Word    'use'
#     PPI::Token::Word    'constant'
#     PPI::Structure::Constructor         { ... }
#       PPI::Statement
#         PPI::Token::Word        'x'
#         PPI::Token::Operator    '=>'
#         PPI::Token::Number      '1'
#
# Or as of PPI 1.203 with a version number "use constant 1.03 { x=>1 }" is
# different
#
#   PPI::Statement::Include
#     PPI::Token::Word    'use'
#     PPI::Token::Word    'constant'
#     PPI::Token::Number::Float   '1.03'
#     PPI::Structure::Block       { ... }
#       PPI::Statement
#         PPI::Token::Word        'x'
#         PPI::Token::Operator    '=>'
#         PPI::Token::Number      '1'
#
sub _use_constant_is_multi {
  my ($inc) = @_;
  my $arg = Perl::Critic::Pulp::Utils::include_module_first_arg ($inc)
    || return 0; # empty "use constant" or version "use constant 1.05"
  return ($arg->isa('PPI::Structure::Constructor') # without version number
          || $arg->isa('PPI::Structure::Block'));  # with version number
}


1;
__END__

=for stopwords multi-constant CPAN perl ok ConstantPragmaHash backports prereqs Ryde

=head1 NAME

Perl::Critic::Policy::Compatibility::ConstantPragmaHash - new enough "constant" module for multiple constants

=head1 DESCRIPTION

This policy is part of the L<C<Perl::Critic::Pulp>|Perl::Critic::Pulp>
add-on.  It requires that when you use the hash style multiple constants of
C<use constant> that you explicitly declare either Perl 5.8 or C<constant>
1.03 or higher.

    use constant { AA => 1, BB => 2 };       # bad

    use 5.008;
    use constant { CC => 1, DD => 2 };       # ok

    use constant 1.03;
    use constant { EE => 1, FF => 2 };       # ok

    use constant 1.03 { GG => 1, HH => 2 };  # ok

The idea is to keep you from using the multi-constant feature in code which
might run on Perl 5.6, or might in principle still run there.  On that basis
this policy is under the "compatibility" theme (see L<Perl::Critic/POLICY
THEMES>).

If you declare C<constant 1.03> then the code can still run on Perl 5.6 and
perhaps earlier if the user gets a suitably newer C<constant> module from
CPAN.  Or of course for past compatibility just don't use the hash style at
all!

=head2 Details

A version declaration must be before the first multi-constant, so it's
checked before the multi-constant is attempted and gives an obscure error.

    use constant { X => 1, Y => 2 };       # bad
    use 5.008;

A C<require> for the perl version is not enough since C<use constant> is at
C<BEGIN> time, before plain code.

    require 5.008;                         # doesn't run early enough
    use constant { X => 1, Y => 2 };       # bad

But a C<require> within a C<BEGIN> block is ok (a past style, still found
occasionally).

    BEGIN { require 5.008 }
    use constant { X => 1, Y => 2 };       # ok

    BEGIN {
      require 5.008;
      and_other_setups ...;
    }
    use constant { X => 1, Y => 2 };       # ok

Currently C<ConstantPragmaHash> pays no attention to any conditionals within
the C<BEGIN>, it assumes any C<require> there always runs.  It could be
tricked by some obscure tests but hopefully anything like that is rare or
does the right thing anyway.

A quoted version number like

    use constant '1.03';    # no good

is no good, only a bare number is recognised by C<use> and acted on by
ConstantPragmaHash.  A string like that goes through to C<constant> as if a
name to define (which you'll see it objects to as soon as you try run it).

=head2 Drawbacks

Explicitly adding required version numbers in the code can be irritating,
especially if other things you're doing only run on 5.8 up anyway.  But
declaring what code needs is accurate, it allows maybe for backports of
modules, and explicit versions can be grepped out to create or check
F<Makefile.PL> or F<Build.PL> prereqs.

As always if you don't care about this or if you only ever use Perl 5.8
anyway then you can disable C<ConstantPragmaHash> from your F<.perlcriticrc>
in the usual way (see L<Perl::Critic/CONFIGURATION>),

    [-Compatibility::ConstantPragmaHash]

=head1 SEE ALSO

L<Perl::Critic::Pulp>,
L<Perl::Critic>,
L<Perl::Critic::Policy::Compatibility::ConstantLeadingUnderscore>,
L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma>,
L<Perl::Critic::Policy::Modules::RequirePerlVersion>

L<constant>,
L<perlsub/Constant Functions>

=head1 HOME PAGE

L<http://user42.tuxfamily.org/perl-critic-pulp/index.html>

=head1 COPYRIGHT

Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde

Perl-Critic-Pulp is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.

Perl-Critic-Pulp is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
more details.

You should have received a copy of the GNU General Public License along with
Perl-Critic-Pulp.  If not, see <http://www.gnu.org/licenses/>.

=cut