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
|
package Perl::Critic::Policy::Variables::ProhibitLoopOnHash;
our $AUTHORITY = 'cpan:XSAWYERX';
# ABSTRACT: Don't write loops on hashes, only on keys and values of hashes
$Perl::Critic::Policy::Variables::ProhibitLoopOnHash::VERSION = '0.008';
use strict;
use warnings;
use parent 'Perl::Critic::Policy';
use Carp qw< croak >;
use Perl::Critic::Utils qw< :severities :classification :ppi >;
use List::Util 'first';
use constant 'DESC' => 'Looping over hash instead of hash keys or values';
use constant 'EXPL' => 'You are accidentally looping over the hash itself '
. '(both keys and values) '
. 'instead of only keys or only values';
# \bfor(each)?(\s+my)?\s*\$\w+\s*\(\s*%
sub supported_parameters { () }
sub default_severity { $SEVERITY_HIGH }
sub default_themes { 'bugs' }
sub applies_to { 'PPI::Token::Word' }
sub violates {
my ($self, $elem) = @_;
first { $elem eq $_ } qw< for foreach >
or return ();
# This is how we do it:
# * First, we clear out scoping (like "my" for "foreach my ...")
# * Second, we clear out topical variables ("foreach $foo (...)")
# * Then we check if it's a postfix without parenthesis
# * Lastly, we handle the remaining cases
# Skip if we do not have the right type of PPI::Statement
# For example, "$var->{for}" has a PPI::Statement::Expression
# when leading for() is a PPI::Statement::Compound and
# a postfix for() is a PPI::Statement
# This was originally written as: $elem->snext_sibling or return
$elem->parent && $elem->parent->isa('PPI::Statement::Expression')
and return ();
# for \my %foo
if ( !$elem->snext_sibling ) {
my $next = $elem->next_token;
# exhaust spaces
$next = $next->next_token
while $next->isa('PPI::Token::Whitespace');
# skip the \
if ( $next eq '\\' ) {
$elem = $next->next_token;
}
}
# for Class->method($foo)
# PPI::Document
# PPI::Statement::Compound
# PPI::Token::Word 'for'
# PPI::Token::Whitespace ' '
# PPI::Statement
# PPI::Token::Word 'Class'
# PPI::Token::Operator '->'
# PPI::Token::Word 'method'
# PPI::Structure::List ( ... )
# PPI::Statement::Expression
# PPI::Token::Symbol '$foo'
# PPI::Token::Structure ';'
if ( !$elem->snext_sibling && $elem->next_token) {
# exhaust spaces
$elem = $elem->next_token
while $elem->next_token->isa('PPI::Token::Whitespace');
# just move to next token and continue from there
$elem->next_token
and $elem = $elem->next_token;
}
# for my $foo (%hash)
# we simply skip the "my"
if ( ( my $scope = $elem->snext_sibling )->isa('PPI::Token::Word') ) {
if ( first { $scope eq $_ } qw< my our local state > ) {
# for my Foo::Bar $baz (%hash)
# PPI doesn't handle this well
# as you can see from the following dump:
# PPI::Statement::Compound
# PPI::Token::Word 'for'
# PPI::Token::Whitespace ' '
# PPI::Token::Word 'my'
# PPI::Token::Whitespace ' '
# PPI::Statement
# PPI::Token::Word 'Foo::BAR'
# PPI::Token::Whitespace ' '
# PPI::Token::Symbol '$payment'
# PPI::Token::Whitespace ' '
# PPI::Structure::List ( ... )
# PPI::Statement::Expression
# PPI::Token::Symbol '@bar'
# PPI::Token::Whitespace ' '
# PPI::Structure::Block { ... }
# PPI::Token::Whitespace ' '
# First, we need to exhaust spaces
my $next = $scope;
$next = $next->next_token
while $next->next_token->isa('PPI::Token::Whitespace');
# Then we can use 'next_token' to jump to the next one,
# even if it's not a sibling
$elem = $next->next_token;
# And if it's a variable attribute, we skip it
$elem->isa('PPI::Token::Word')
and $elem = $elem->snext_sibling;
} else {
# for keys %hash
# for Class->method($foo)
}
}
# for $foo (%hash)
# we simply skip the "$foo"
if ( ( my $topical = $elem->snext_sibling )->isa('PPI::Token::Symbol') ) {
if ( $topical->snext_sibling
&& $topical->snext_sibling->isa('PPI::Structure::List') )
{
$elem = $topical;
} else {
# for $foo (%hash);
}
}
# for %hash
# (postfix without parens)
_check_symbol_or_cast( $elem->snext_sibling )
and return $self->violation( DESC(), EXPL(), $elem );
# for (%hash)
if ( ( my $list = $elem->snext_sibling )->isa('PPI::Structure::List') ) {
my @children = $list->schildren;
@children > 1
and croak "List has multiple significant children ($list)";
if ( ( my $statement = $children[0] )->isa('PPI::Statement') ) {
my @statement_args = $statement->schildren;
_check_symbol_or_cast( $statement_args[0] )
and return $self->violation( DESC(), EXPL(), $statement );
}
}
return ();
}
sub _check_symbol_or_cast {
my $arg = shift;
# This is either a variable
# or casting from a variable (or from a statement)
$arg->isa('PPI::Token::Symbol') && $arg =~ /^%/xms
or $arg->isa('PPI::Token::Cast') && $arg eq '%'
or return;
my $next_op = $arg->snext_sibling;
# If this is a cast, we want to exhaust the block
# the block could include anything, really...
if ( $arg->isa('PPI::Token::Cast') && $next_op->isa('PPI::Structure::Block') ) {
$next_op = $next_op->snext_sibling;
}
# Safe guard against operators
# for ( %hash ? ... : ... );
$next_op && $next_op->isa('PPI::Token::Operator')
and return;
return 1;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Perl::Critic::Policy::Variables::ProhibitLoopOnHash - Don't write loops on hashes, only on keys and values of hashes
=head1 VERSION
version 0.008
=head1 DESCRIPTION
When "looping over hashes," we mean looping over hash keys or hash values. If
you forgot to call C<keys> or C<values> you will accidentally loop over both.
foreach my $foo (%hash) {...} # not ok
action() for %hash; # not ok
foreach my $foo ( keys %hash ) {...} # ok
action() for values %hash; # ok
An effort is made to detect expressions:
action() for %hash ? keys %hash : (); # ok
action() for %{ $hash{'stuff'} } ? keys %{ $hash{'stuff'} } : (); # ok
(Granted, the second example there doesn't make much sense, but I have found
a variation of it in real code.)
=head1 CONFIGURATION
This policy is not configurable except for the standard options.
=head1 AUTHOR
Sawyer X, C<xsawyerx@cpan.org>
=head1 THANKS
Thank you to Ruud H.G. Van Tol.
=head1 SEE ALSO
L<Perl::Critic>
=head1 AUTHOR
Sawyer X
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2018 by Sawyer X.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|