« blib/lib/Perl/Lint/Policy/Modules/RequireFilenameMatchesPackage.pm
↑ Summary
blib/lib/Perl/Lint/Keywords.pm »
| 1 | package Perl::Lint::Policy::Variables::ProhibitConditionalDeclarations; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Perl::Lint::Constants::Type; | ||
| 5 | use parent "Perl::Lint::Policy"; | ||
| 6 | |||
| 7 | use constant { | ||
| 8 | DESC => q{Variable declared in conditional statement}, | ||
| 9 | EXPL => q{Declare variables outside of the condition}, | ||
| 10 | }; | ||
| 11 | |||
| 12 | sub evaluate { | ||
| 13 | my ($class, $file, $tokens) = @_; | ||
| 14 | |||
| 15 | my @violations; | ||
| 16 | my $token_num = scalar @$tokens; | ||
| 17 | for (my $i = 0; $i < $token_num; $i++) { | ||
| 18 | my $token = $tokens->[$i]; | ||
| 19 | my $token_type = $token->{type}; | ||
| 20 | |||
| 21 | if ($token_type == VAR_DECL || $token_type == OUR_DECL) { | ||
| 22 | for ($i++; $i < $token_num; $i++) { | ||
| 23 | $token = $tokens->[$i]; | ||
| 24 | |||
| 25 | if ($token->{type} == ASSIGN) { | ||
| 26 | my $is_before_right_paren = 0; | ||
| 27 | for ($i++; $i < $token_num; $i++) { | ||
| 28 | $token = $tokens->[$i]; | ||
| 29 | $token_type = $token->{type}; | ||
| 30 | |||
| 31 | if ($token_type == RIGHT_PAREN) { | ||
| 32 | $is_before_right_paren = 1; | ||
| 33 | } | ||
| 34 | elsif ( | ||
| 35 | $token_type == IF_STATEMENT || | ||
| 36 | $token_type == UNLESS_STATEMENT || | ||
| 37 | $token_type == WHILE_STATEMENT || | ||
| 38 | $token_type == FOR_STATEMENT || | ||
| 39 | $token_type == FOREACH_STATEMENT | ||
| 40 | ) { | ||
| 41 | push @violations, { | ||
| 42 | filename => $file, | ||
| 43 | line => $token->{line}, | ||
| 44 | description => DESC, | ||
| 45 | explanation => EXPL, | ||
| 46 | policy => __PACKAGE__, | ||
| 47 | }; | ||
| 48 | last; | ||
| 49 | } | ||
| 50 | else { | ||
| 51 | my $_is_before_right_paren = $is_before_right_paren; | ||
| 52 | $is_before_right_paren = 0; | ||
| 53 | if ($_is_before_right_paren && $token_type == LEFT_BRACE) { | ||
| 54 | last; | ||
| 55 | } | ||
| 56 | } | ||
| 57 | |||
| 58 | last if $token->{type} == SEMI_COLON; | ||
| 59 | } | ||
| 60 | last; | ||
| 61 | } | ||
| 62 | |||
| 63 | last if $token->{type} == SEMI_COLON; | ||
| 64 | } | ||
| 65 | } | ||
| 66 | } | ||
| 67 | |||
| 68 | return \@violations; | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; | ||
| 72 |