File: ProhibitMismatchedOperators.pm

package info (click to toggle)
libperl-critic-perl 1.156-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,544 kB
  • sloc: perl: 24,092; lisp: 341; makefile: 7
file content (246 lines) | stat: -rw-r--r-- 7,416 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
package Perl::Critic::Policy::ValuesAndExpressions::ProhibitMismatchedOperators;
use 5.010001;
use strict;
use warnings;
use Readonly;

use Perl::Critic::Utils qw{ :booleans :severities hashify };
use parent 'Perl::Critic::Policy';

our $VERSION = '1.156';

#-----------------------------------------------------------------------------

Readonly::Scalar my $DESC => q<Mismatched operator>;
Readonly::Scalar my $EXPL => q<Numeric/string operators and operands should match>;

# token compatibility [ numeric, string ]
Readonly::Hash my %TOKEN_COMPATIBILITY => (
    'PPI::Token::Number' => [$TRUE,  $FALSE],
    'PPI::Token::Symbol' => [$TRUE,  $TRUE ],
    'PPI::Token::Quote'  => [$FALSE, $TRUE ],
);

Readonly::Hash my %FILE_OPERATOR_COMPATIBILITY =>
    map {; "-$_" => [$TRUE, $FALSE] }
        qw< r w x o R W X O e z s f d l p S b c t u g k T B M A >;

Readonly::Scalar my $TOKEN_COMPATIBILITY_INDEX_NUMERIC => 0;
Readonly::Scalar my $TOKEN_COMPATIBILITY_INDEX_STRING  => 1;

Readonly::Hash my %OPERATOR_TYPES => (
    # numeric
    (
        map { $_ => $TOKEN_COMPATIBILITY_INDEX_NUMERIC }
            qw[ == != > >= < <= + - * / += -= *= /= ]
    ),
    # string
    map { $_ => $TOKEN_COMPATIBILITY_INDEX_STRING }
        qw< eq ne lt gt le ge . .= >,
);

Readonly::Scalar my $TOKEN_COMPATIBILITY_SPECIAL_STRING_OPERATOR => qw{+};
Readonly::Hash my %SPECIAL_STRING_VALUES =>
    hashify( qw('nan' 'inf' '-inf' '+inf') );

#-----------------------------------------------------------------------------

sub supported_parameters { return ()                     }
sub default_severity     { return $SEVERITY_MEDIUM       }
sub default_themes       { return qw< core bugs certrule >        }
sub applies_to           { return 'PPI::Token::Operator' }

#-----------------------------------------------------------------------------

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

    my $elem_text = $elem->content();

    return if not exists $OPERATOR_TYPES{$elem_text};

    my $leading_operator = _get_potential_leading_operator($elem)
        or return;

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

    if ( $next_elem->isa('PPI::Token::Operator') ) {
        $elem_text .= $next_elem->content();
        $next_elem = $next_elem->snext_sibling();
    }

    return if not exists $OPERATOR_TYPES{$elem_text};
    my $operator_type = $OPERATOR_TYPES{$elem_text};

    my $leading_operator_compatibility = _get_token_compatibility($leading_operator);
    my $next_compatibility = _get_token_compatibility($next_elem);

    return if
            (
                    ! defined $leading_operator_compatibility
                ||  $leading_operator_compatibility->[$operator_type]
            )
        &&  (
                    ! defined $next_compatibility
                ||  $next_compatibility->[$operator_type]
            );

    return if
            $operator_type
        &&  defined $leading_operator_compatibility
        &&  ! $leading_operator_compatibility->[$operator_type]
        &&  _have_stringy_x($leading_operator); # RT 54524

    return if $self->_is_special_string_number_addion($elem_text, $leading_operator, $next_elem);

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

#-----------------------------------------------------------------------------

sub _get_token_compatibility {
    my ($elem) = @_;

    return $FILE_OPERATOR_COMPATIBILITY{ $elem->content() }
        if _is_file_operator($elem);

    for my $class (keys %TOKEN_COMPATIBILITY) {
        return $TOKEN_COMPATIBILITY{$class} if $elem->isa($class);
    }

    return;
}

#-----------------------------------------------------------------------------

sub _have_stringy_x {
    my ($elem) = @_;

    return if not $elem;

    my $prev_oper = $elem->sprevious_sibling() or return;

    return if not $prev_oper->isa('PPI::Token::Operator');
    return if 'x' ne $prev_oper->content();

    return !! $prev_oper->sprevious_sibling();
}

#-----------------------------------------------------------------------------

sub _get_potential_leading_operator {
    my ($elem) = @_;

    my $previous_element = $elem->sprevious_sibling() or return;

    if ( _get_token_compatibility($previous_element) ) {
        my $previous_sibling = $previous_element->sprevious_sibling();
        if (
            $previous_sibling and _is_file_operator($previous_sibling)
        ) {
            $previous_element = $previous_sibling;
        }
    }

    return $previous_element;
}

#-----------------------------------------------------------------------------

sub _is_file_operator {
    my ($elem) = @_;

    return if not $elem;
    return if not $elem->isa('PPI::Token::Operator');
    return !! $FILE_OPERATOR_COMPATIBILITY{ $elem->content() };
}

#-----------------------------------------------------------------------------

sub _is_special_string_number_addion {
    my ($self, $elem_operator, $element_1, $element_2, $check_recursive) = @_;

    return 1 if $elem_operator
        &&  $elem_operator eq $TOKEN_COMPATIBILITY_SPECIAL_STRING_OPERATOR
        &&  $SPECIAL_STRING_VALUES{lc($element_1->content()//0)}
        &&  $element_2->isa('PPI::Token::Number')
        &&  $element_2->content() == 0;
    return 1 if !$check_recursive && $self->_is_special_string_number_addion($elem_operator, $element_2, $element_1, 1);

    return;
}

1;

__END__

#-----------------------------------------------------------------------------

=pod

=head1 NAME

Perl::Critic::Policy::ValuesAndExpressions::ProhibitMismatchedOperators - Don't mix numeric operators with string operands, or vice-versa.


=head1 AFFILIATION

This Policy is part of the core L<Perl::Critic|Perl::Critic>
distribution.


=head1 DESCRIPTION

Using the wrong operator type for a value can obscure coding intent
and possibly lead to subtle errors.  An example of this is mixing a
string equality operator with a numeric value, or vice-versa.

    if ($foo == 'bar') {}     #not ok
    if ($foo eq 'bar') {}     #ok
    if ($foo eq 123) {}       #not ok
    if ($foo == 123) {}       #ok


=head1 CONFIGURATION

This Policy is not configurable except for the standard options.

=for stopwords NaN struct

=head1 NOTES

If L<warnings|warnings> are enabled, the Perl interpreter usually
warns you about using mismatched operators at run-time.  This Policy
does essentially the same thing, but at author-time.  That way, you
can find out about them sooner.

Perl handles the strings 'NaN' and 'inf' as special numbers and creates an NV struct when compared with a numeric operator.
Although not necessary it is allowed to write code such as:
    my $i = 'inf'+0;
This pattern helps others understand that the variable is indeed the Infinite or NaN numbers as Perl interprets them.
Only these two special string numbers are allowed to have the '+' operator which would otherwise be allowed only for strings.


=head1 AUTHOR

Peter Guzis <pguzis@cpan.org>


=head1 COPYRIGHT

Copyright (c) 2006-2023 Peter Guzis.  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=78 ft=perl expandtab shiftround :