File Coverage

blib/lib/App/PerlNitpick/Rule/RewriteWithAssignmentOperators.pm
Criterion Covered Total %
statement 32 32 100.0
branch 5 6 83.3
condition 12 30 40.0
subroutine 5 5 100.0
pod 0 1 0.0
total 54 74 72.9


line stmt bran cond sub pod time code
1             use Moose;
2 1     1   267991 use PPI::Document;
  1         366348  
  1         5  
3 1     1   5836 use PPI::Token::Whitespace;
  1         2  
  1         23  
4 1     1   5  
  1         1  
  1         24  
5             no Moose;
6 1     1   4  
  1         2  
  1         11  
7             my ($self, $document) = @_;
8              
9 6     6 0 14963 my @found = grep {
10             # Find a statement that looks like $x = $x + $y;
11             my $c0 = $_->schild(0); # $x
12             my $c1 = $_->schild(1); # =
13 6         103 my $c2 = $_->schild(2); # $x
14 6         65 my $c3 = $_->schild(3); # +
15 6         60 my $c4 = $_->schild(4); # $y
16 6         71 my $c5 = $_->schild(5); # ;
17 6         79  
18 6         83 ($c1->isa('PPI::Token::Operator') && $c1->content eq '=') &&
19             ($c5->isa('PPI::Token::Structure') && $c5->content eq ';') &&
20 6 100 33     108 ($c3->isa('PPI::Token::Operator') && $c3->content !~ m{\A( -> | > | < | \.)\z}x) &&
      33        
      33        
      33        
      33        
      33        
      33        
      33        
      66        
      66        
21             ($c0->isa('PPI::Token::Symbol') && $c0->raw_type eq '$' &&
22             $c2->isa('PPI::Token::Symbol') && $c2->raw_type eq '$' &&
23             $c1->content && $c2->content)
24             } grep {
25             $_->schildren == 6
26             } @{ $document->find('PPI::Statement') ||[] };
27 7         1831  
28 6 50       11 return $document unless @found;
  6         18  
29              
30 6 100       195 for my $statement (@found) {
31             my @child = $statement->schildren;
32 4         9  
33 4         7 # assigment operator :)
34             my $assop = PPI::Token::Operator->new($child[3]->content . $child[1]->content);
35              
36 4         48 $child[3]->remove;
37             $child[2]->remove;
38 4         88 $child[1]->insert_after($assop);
39 4         148 $child[1]->remove;
40 4         103 }
41 4         135  
42             return $document;
43             }
44 4         125  
45             1;
46              
47              
48             =head1 DESCRIPTION
49              
50             This rule rewrites those assignments that alter a single varible with itself.
51             For example, this one:
52              
53             $x = $x + 2;
54              
55             Is rewritten with the C<+=> assignment operator, as:
56              
57             $x += 2;
58              
59             =cut