File: NotWithCompare.pm

package info (click to toggle)
libperl-critic-pulp-perl 96-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,684 kB
  • sloc: perl: 13,643; sh: 267; makefile: 6; ansic: 1
file content (348 lines) | stat: -rw-r--r-- 10,444 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
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
# Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Kevin Ryde

# This file is part of Perl-Critic-Pulp.

# 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::ValuesAndExpressions::NotWithCompare;
use 5.006;
use strict;
use warnings;
use List::Util qw(min max);
use base 'Perl::Critic::Policy';
# 1.100 for precedence_of() supporting -f etc filetests
use Perl::Critic::Utils 1.100 qw(is_perl_builtin
                                 is_perl_builtin_with_no_arguments
                                 precedence_of);

our $VERSION = 96;


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

my %op_postfix = ('++'  => 1,
                  '--'  => 1);

my %op_andor = ('&&'  => 1,
                '||'  => 1,
                '//'  => 1,
                'and' => 1,
                'or'  => 1,
                'xor' => 1);

my %post_control = (if      => 1,
                    unless  => 1,
                    until   => 1,
                    for     => 1,
                    foreach => 1,
                    while   => 1);

my %is_bad_precedence = (precedence_of('=~') => 1,
                         precedence_of('>')  => 1,
                         precedence_of('==') => 1);
my $stop_precedence = max (keys %is_bad_precedence);


sub violates {
  my ($self, $bang_elem, $document) = @_;
  if ($bang_elem->content ne '!') { return; }
  my $constants;

  # only report when "!" is at the start of an expression, so "-f ! $x" is
  # not applicable (though bizarre), or with "! ! $x" look only from the
  # first "!"
  if (my $prev = $bang_elem->sprevious_sibling) {
    if ($prev->isa('PPI::Token::Operator')) {
      my $op = $prev->content;
      if (! $op_andor{$op}) { # but do look following "&&" etc
        return;
      }
    }
  }

  my $state = 'prefix';
  my $seen_precedence = 1;

  my $elem = $bang_elem;
  for (;;) {
    $elem or return;  # nothing evil up to end of expression
    $elem = $elem->snext_sibling
      or return;      # nothing evil up to end of expression

    if ($elem->isa('PPI::Token::Cast')) {
      # "\ &foo" is a single form, not a function call
      $elem = _next_cast_operand ($elem);
      $state = 'postfix';
      next;
    }

    if ($elem->isa('PPI::Token::Symbol')) {
      $state = 'postfix';
      if ($elem->content =~ /^&/) {
        if (my $after = $elem->snext_sibling) {
          if ($after->isa('PPI::Structure::List')) {
            $elem = $after; # "! &foo() == 1"
            next;
          }
        }
        # "! &foo ..." varargs function call, eats to "," or ";"
        return;
      }
      next; # "! $x" etc
    }

    if ($elem->isa('PPI::Token::Operator')) {
      my $op = $elem->content;

      if ($state eq 'postfix' && $op_postfix{$op}) {
        next;  # stay in postfix state after '++' or '--'
      }
      if ($state eq 'prefix' && $op eq '<') {
        # in prefix position assume "<" is "<STDIN>" glob or readline
        $elem = _next_gt ($elem);
        $state = 'postfix';
        next;  # can leave $elem undef for something dodgy like "! < 123"
      }
      my $precedence = precedence_of($op) || return;

      if ($precedence > $stop_precedence) {
        return;  # something below "==" etc, expression to ! is ok
      }
      if (($op eq '==' || $op eq '!=') && _snext_is_bang($elem)) {
        return;  # special case "! $x == ! $y" is ok
      }
      if ($op eq '->') {
        if (my $method = $elem->snext_sibling) {
          $elem = $method;
          $state = 'postfix';
          if (my $after = $method->snext_sibling) {
            if ($after->isa('PPI::Token::Operator')) {
              next;  # "! $foo->bar == 1"
            }
            if ($after->isa('PPI::Structure::List')) {
              $elem = $after; # "! $foo->bar() == 1"
              next;
            }
            # bogosity "$foo->bar 123, 456" or the like
            return;
          }
        }
      }

      if ($seen_precedence <= $precedence && $is_bad_precedence{$precedence}) {
        # $op is a compare, so bad
        return $self->violation
          ("Logical \"!\" attempted with a compare \"$op\"",
           '', $bang_elem);
      }
      $seen_precedence = max ($precedence, $seen_precedence);
      $state = 'prefix';
      next;
    }

    if ($elem->isa('PPI::Token::Word')) {
      my $word = $elem->content;

      if ($post_control{$word}) {
        return;  # postfix control like "$foo = ! $foo if ..." ends expression
      }
      if (is_perl_builtin_with_no_arguments ($word)) {
        # eg "! time ..."
        # "time" is a single token, look at operators past it
        $state = 'postfix';
        next;
      }

      $constants ||= _constants ($document);
      if (exists $constants->{$word}) {
        # eg. use constant FOO => 456;
        #     ! FOO ...
        # the FOO is a single token, look at operators past it
        $state = 'postfix';
        next;
      }

      my $next = $elem->snext_sibling
        or return;  # "! FOO" expression ending at a bareword

      if ($next->isa('PPI::Structure::List')) {
        # "! FOO(...)" function call
        $elem = next;
        $state = 'postfix';
        next;
      }

      if (is_perl_builtin ($word)) {
        return; # builtins all taking args, eating "," or ";"
      }

      if ($next->isa('PPI::Token::Operator')) {
        my $op = $next->content;
        if ($op eq '<') {
          if (_next_gt ($next)) {
            # "! FOO <*.c>" assumed to be glob passed to varargs func, it
            # ends at "," or ";" so nothing bad for "!"
            return;
          }
        }
        # other "! FOO > 123" assumed to be a constant
        $state = 'postfix';
        next;
      }

      # otherwise word is a no parens call, like "foo 123, 456"
      # exactly how this parses depends on the prototype, but there's
      # going to be a "," or ";" terminating, so our "!" is ok
      return;
    }
  }

  return;
}

sub _snext_is_bang {
  my ($elem) = @_;
  my $next = $elem->snext_sibling;
  return ($next
          && $next->isa('PPI::Token::Operator')
          && $next eq '!');
}

# return the next ">" operator following $elem, or undef if no such
sub _next_gt {
  my ($elem) = @_;
  while ($elem = $elem->snext_sibling) {
    if ($elem->isa('PPI::Token::Operator') && $elem eq '>') {
      last;
    }
  }
  return $elem;
}

# $elem is a PPI::Token::Cast, return its operand elem, meaning the next
# non-Cast (usually a Symbol).  Return undef if no non-cast, for something
# dodgy like "\" with nothing following.
sub _next_cast_operand {
  my ($elem) = @_;
  while ($elem = $elem->snext_sibling) {
    if (! $elem->isa('PPI::Token::Cast')) {
      last;
    }
  }
  return $elem;
}

# return a hashref which has keys for all the "use constant"s defined in
# $document
sub _constants {
  my ($document) = @_;
  return ($document->{__PACKAGE__.'.NotWithCompareConstants'} ||= do {
    require Perl::Critic::Policy::ValuesAndExpressions::ConstantBeforeLt;
    my %constants;
    $document->find
      (sub {
         my ($document, $elem) = @_;
         @constants{ Perl::Critic::Policy::ValuesAndExpressions::ConstantBeforeLt::_use_constants($elem) }
           = ();  # hash slice
         return 0;  # no-match, and continue
       });
    \%constants;
  });
}

1;
__END__

=for stopwords booleans varargs builtins args Ryde

=head1 NAME

Perl::Critic::Policy::ValuesAndExpressions::NotWithCompare - logical not used with compare

=head1 DESCRIPTION

This policy is part of the L<C<Perl::Critic::Pulp>|Perl::Critic::Pulp>
add-on.  It picks up some cases of logical not C<!> used with a comparison,
like

    ! $x =~ /^[123]/  # bad
    ! $x + $y >= $z   # bad

In each case precedence means Perl parses this as C<< (!$x) >>, like

    (! $x) =~ /^[123]/
    (! $x) + $y >= $z

rather than a negated comparison.  Usually this is a mistake, so this policy
is under the "bugs" theme (see L<Perl::Critic/POLICY THEMES>).

As a special case, C<!> on both sides of C<< == >> or C<< != >> is allowed,
since it's quite a good way to compare booleans.

    !$x == !$y   # ok
    !$x != !$y   # ok

=head1 LIMITATIONS

User functions called without parentheses are assumed to be usual varargs
style.  But a prototype may mean that's not the case, letting a bad
C<!>-with-compare expression to go undetected.

    ! userfunc $x == 123   # indeterminate
    # without prototype would be ok:   ! (userfunc ($x==123))
    # with ($) prototype would be bad: (! userfunc($x)) == 123

Perl builtins with no args, and constant subs created with C<use constant>
or C<sub FOO () {...}> in the file under test are recognised.  Hopefully
anything else too weird is rare.

    ! time == 1   # bad

    use constant FIVE => 5;
    ! FIVE < 1    # bad

    sub name () { "foo" }
    ! name =~ /bar/    # bad

=head1 SEE ALSO

L<Perl::Critic::Pulp>,
L<Perl::Critic>

=head1 HOME PAGE

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

=head1 COPYRIGHT

Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 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