File Coverage

blib/lib/Perl/Critic/Policy/Variables/ProhibitUnusedVarsStricter.pm
Criterion Covered Total %
statement 389 424 91.7
branch 214 294 72.7
condition 51 77 66.2
subroutine 45 47 95.7
pod 4 5 80.0
total 703 847 83.0


line stmt bran cond sub pod time code
1              
2             use 5.006001;
3 2     2   424860 use strict;
  2         18  
4 2     2   23 use warnings;
  2         15  
  2         58  
5 2     2   11  
  2         5  
  2         53  
6             use English qw{ -no_match_vars };
7 2     2   11  
  2         5  
  2         20  
8             use PPI::Document;
9 2     2   1072 use PPIx::QuoteLike 0.011;
  2         33095  
  2         77  
10 2     2   958 use PPIx::QuoteLike::Constant 0.011 qw{
  2         252135  
  2         106  
11 2         122 LOCATION_LINE
12             LOCATION_LOGICAL_FILE
13             LOCATION_LOGICAL_LINE
14             LOCATION_CHARACTER
15             LOCATION_COLUMN
16             };
17 2     2   19 use PPIx::Regexp 0.071;
  2         28  
18 2     2   12 use Readonly;
  2         34  
  2         46  
19 2     2   10 use Scalar::Util qw{ refaddr };
  2         6  
  2         95  
20 2     2   16  
  2         12  
  2         78  
21             use Perl::Critic::Exception::Fatal::PolicyDefinition;
22 2     2   12 use Perl::Critic::Utils qw< :booleans :characters hashify :severities >;
  2         4  
  2         70  
23 2     2   12  
  2         4  
  2         111  
24             use base 'Perl::Critic::Policy';
25 2     2   573  
  2         7  
  2         1010  
26             our $VERSION = '0.113';
27              
28             #-----------------------------------------------------------------------------
29              
30             Readonly::Scalar my $EXPL =>
31             q<Unused variables clutter code and make it harder to read>;
32              
33             # Determine whether a PPI::Statement::Variable refers to a global or a
34             # lexical variable. We need to track globals to avoid false negatives
35             # from things like
36             #
37             # my $foo;
38             # {
39             # our $foo;
40             # $foo = 'bar';
41             # }
42             #
43             # but we do not need to track 'local', because if you
44             # s/ \b our \b /local/smxg
45             # in the above, Perl complains that you can not localize a lexical
46             # variable, rather than localizing the corresponding global variable.
47             Readonly::Hash my %GLOBAL_DECLARATION => (
48             my => $FALSE,
49             state => $FALSE,
50             our => $TRUE,
51             );
52              
53             Readonly::Scalar my $CATCH => 'catch';
54              
55             Readonly::Scalar my $PACKAGE => '_' . __PACKAGE__;
56              
57             Readonly::Scalar my $LEFT_BRACE => q<{>; # } Seems P::C::U should have
58              
59             Readonly::Hash my %IS_COMMA => hashify( $COMMA, $FATCOMMA );
60             Readonly::Hash my %LOW_PRECEDENCE_BOOLEAN => hashify( qw{ and or xor } );
61              
62             Readonly::Array my @DOUBLE_QUOTISH => qw{
63             PPI::Token::Quote::Double
64             PPI::Token::Quote::Interpolate
65             PPI::Token::QuoteLike::Backtick
66             PPI::Token::QuoteLike::Command
67             PPI::Token::QuoteLike::Readline
68             PPI::Token::HereDoc
69             };
70             Readonly::Array my @REGEXP_ISH => qw{
71             PPI::Token::Regexp::Match
72             PPI::Token::Regexp::Substitute
73             PPI::Token::QuoteLike::Regexp
74             };
75              
76             #-----------------------------------------------------------------------------
77              
78             {
79             name => 'allow_if_computed_by',
80             description => 'Allow if computed by one of these',
81 59     59 0 239901 behavior => 'string list',
82             },
83             { name => 'prohibit_reference_only_variables',
84             description => 'Prohibit reference-only variables',
85             behavior => 'boolean',
86             default_string => '0',
87             },
88             { name => 'prohibit_returned_lexicals',
89             description => 'Prohibit returned lexicals',
90             behavior => 'boolean',
91             default_string => '0',
92             },
93             { name => 'allow_unused_subroutine_arguments',
94             description => 'Allow unused subroutine arguments',
95             behavior => 'boolean',
96             default_string => '0',
97             },
98             {
99             name => 'allow_state_in_expression',
100             description => 'Allow state variable with low-precedence Boolean',
101             behavior => 'boolean',
102             default_string => '0',
103             },
104             {
105             name => 'check_catch',
106             description => 'Check the catch() clause of try/catch',
107             behavior => 'boolean',
108             default_string => '0',
109             },
110             {
111             name => 'dump',
112             description => 'UNSUPPORTED: Dump symbol definitions',
113             behavior => 'boolean',
114             default_string => '0',
115             },
116             {
117             name => 'trace',
118             description => 'UNSUPPORTED: Trace variable processing',
119             behavior => 'string list',
120             },
121             ) }
122              
123              
124             #-----------------------------------------------------------------------------
125 40     40 1 2073  
126 0     0 1 0 # my ( $self, $elem, $document ) = @_;
127 58     58 1 586188 my ( $self, undef, $document ) = @_;
128              
129             $self->{$PACKAGE} = {
130             declared => {}, # Keyed by PPI::Token::Symbol->symbol().
131             # Values are a list of hashes
132             # representing declarations of the given
133 58     58 1 575 # symbol, in reverse order. In each
134             # hash:
135 58         387 # {declaration} is the PPI statement
136             # object in which the variable is
137             # declared;
138             # {element} is the PPI::Token::Symbol
139             # {is_allowed_computation} is true
140             # if the value of the symbol is
141             # initialized using one of the
142             # allowed subroutines or classes
143             # (e.g. Scope::Guard).
144             # {is_global} is true if the declaration
145             # is a global (i.e. is 'our', not 'my');
146             # {is_state_in_expression} is true if
147             # the variable is a 'state' variable
148             # and the assignment is part of an
149             # expression.
150             # {is_unpacking} is true if the
151             # declaration occurs in an argument
152             # unpacking;
153             # {taking_reference} is true if the code
154             # takes a reference to the declared
155             # variable;
156             # {used} is a count of the number of
157             # times that declaration was used,
158             # initialized to 0.
159              
160             is_declaration => {}, # Keyed by refaddr of PPI::Token::Symbol.
161             # True if the object represents a
162             # declaration.
163              
164             need_sort => $FALSE, # Boolean that says whether the symbol
165             # declarations need to be sorted in
166             # lexical order. Recording a declaration
167             # must set this. Recording a use must
168             # clear this, doing the sort if it was
169             # previously set.
170              
171             ppix_objects => {}, # Cache of PPIx::QuoteLike and
172             # PPIx::Regexp objects indexed by
173             # refaddr of parent element.
174              
175             parent_element => {}, # PPI::Element objects from which
176             # PPI::Document objects have been
177             # derived, indexed by refaddr of derived
178             # document.
179             };
180              
181             # Ensure entire document is indexed. We don't call index_locations()
182             # because that is unconditional. We wrap the whole thing in an eval
183             # because last_token() can fail under undiagnosed circumstances.
184             {
185             local $EVAL_ERROR = undef;
186             eval { ## no critic (RequireCheckingReturnValueOfEval)
187             if ( my $token = $document->last_token() ) {
188             $token->location();
189             }
190             }
191 58         127 }
  58         117  
192 58         116  
193 58 50       306 $self->_get_symbol_declarations( $document );
194 58         1594  
195             $self->_get_symbol_uses( $document );
196              
197             $self->{_dump}
198             and $self->_dump();
199 58         809  
200             return $self->_get_violations();
201 58         181  
202             }
203              
204 58 50       173 #-----------------------------------------------------------------------------
205              
206 58         140 my ( $self ) = @_;
207             foreach my $name ( sort keys %{ $self->{$PACKAGE}{declared} } ) {
208             # NOTE that 'print { STDERR } ... ' does not compile under
209             # strict refs. '{ *STDERR }' is a terser way to satisfy
210             # InputOutput::RequireBracedFileHandleWithPrint.
211             print { *STDERR } "$name\n";
212             foreach my $decl ( @{ $self->{$PACKAGE}{declared}{$name} } ) {
213 0     0   0 my $sym = $decl->{element};
214 0         0 my $fn = $sym->logical_filename();
  0         0  
215             if ( defined $fn ) {
216             $fn =~ s/ (?= [\\'] ) /\\/smxg;
217             $fn = "'$fn'";
218 0         0 } else {
  0         0  
219 0         0 $fn = 'undef';
  0         0  
220 0         0 }
221 0         0 printf { *STDERR }
222 0 0       0 " %s line %d column %d used %d\n",
223 0         0 $fn,
224 0         0 $sym->logical_line_number(),
225             $sym->column_number(),
226 0         0 $decl->{used};
227             }
228 0         0 }
229             return;
230             }
231              
232             #-----------------------------------------------------------------------------
233 0         0  
234             my ( $self, $document ) = @_;
235              
236 0         0 $self->_get_variable_declarations( $document );
237              
238             $self->_get_stray_variable_declarations( $document );
239              
240             $self->{_check_catch}
241             and $self->_get_catch_declarations( $document );
242 58     58   123  
243             return;
244 58         202  
245             }
246 58         177  
247             #-----------------------------------------------------------------------------
248              
249 58 100       164 # We assume the argument is actually eligible for this operation.
250             my ( $self, $elem ) = @_;
251 58         112 return $self->{$PACKAGE}{ppix_objects}{ refaddr $elem } ||=
252             PPIx::QuoteLike->new( $elem );
253             }
254              
255             #-----------------------------------------------------------------------------
256              
257             # We assume the argument is actually eligible for this operation. The
258             # complication here is that if we are dealing with an element of a
259 60     60   130 # Perl::Critic::Document we want to call ppix_regexp_from_element(),
260 60   66     373 # since that caches the returned object, making it available to all
261             # policies. But the ppi() method returns a PPI::Document, so the best we
262             # can do is to cache locally.
263             my ( $self, $elem ) = @_;
264             return $self->{$PACKAGE}{ppix_objects}{ refaddr $elem } ||= do {
265             my $doc = $elem->top();
266             my $code;
267             ( $code = $doc->can( 'ppix_regexp_from_element' ) ) ?
268             $code->( $doc, $elem ) :
269             PPIx::Regexp->new( $elem );
270             };
271             }
272              
273 18     18   76 #-----------------------------------------------------------------------------
274 18   66     96  
275 9         38 # Get the PPI::Document that represents a PPIx::* class that supports
276 9         93 # one. The arguments are:
277 9 50       65 # $ppix_elem - the PPIx::* element providing the document. This MUST
278             # support the ->ppi() method.
279             # $elem - the original PPI::Element from which this element was
280             # derived.
281             # NOTE that all calls to ->ppi() MUST come through here.
282             my ( $self, $ppix_elem, $elem ) = @_;
283             my $ppi = $ppix_elem->ppi()
284             or return;
285             $self->{$PACKAGE}{parent_element}{ refaddr( $ppi ) } ||= $elem;
286             return $ppi;
287             }
288              
289             #-----------------------------------------------------------------------------
290              
291             # Get the PPI::Element that is the parent of the given PPI::Element,
292             # taking into account that the given element may be a derived
293 72     72   168 # PPI::Document.
294 72 50       246 # NOTE that all calls to PPI::Element->parent() MUST come through here.
295             my ( $self, $elem ) = @_;
296 72   66     33711 if ( my $parent = $elem->parent() ) {
297 72         216 return $parent;
298             } else {
299             return $self->{$PACKAGE}{parent_element}{ refaddr( $elem ) };
300             }
301             }
302              
303             #-----------------------------------------------------------------------------
304              
305             # Get the lowest parent of the inner element that is in the same
306             # document as the outer element.
307 240     240   400 my ( $self, $inner_elem, $outer_elem ) = @_;
308 240 100       561 my $outer_top = $outer_elem->top()
309 199         1187 or return;
310             while ( 1 ) {
311 41         289 my $inner_top = $inner_elem->top()
312             or last;
313             $inner_top == $outer_top
314             and return $inner_elem;
315             $inner_elem = $self->_get_parent_element( $inner_top )
316             or last;
317             }
318             return;
319             }
320 85     85   153  
321 85 50       218 #-----------------------------------------------------------------------------
322              
323 85         834 my ( $self, $document ) = @_;
324 120 50       249  
325             my @rslt = @{ $document->find( 'PPI::Statement::Variable' ) || [] };
326 120 100       1284  
327             foreach my $class ( @DOUBLE_QUOTISH ) {
328 39 100       239 foreach my $elem ( @{ $document->find( $class ) || [] } ) {
329             my $str = $self->_get_ppix_quotelike( $elem )
330             or next;
331 4         16 foreach my $code ( @{ $str->find(
332             'PPIx::QuoteLike::Token::Interpolation' ) || [] } ) {
333             my $ppi = $self->_get_derived_ppi_document( $code, $elem )
334             or next;
335             push @rslt, $self->_get_ppi_statement_variable( $ppi );
336             }
337 94     94   182 }
338             }
339 94 100       157  
  94         228  
340             foreach my $class ( @REGEXP_ISH ) {
341 94         9878 foreach my $elem ( @{ $document->find( $class ) || [] } ) {
342 564 100       46738 my $pre = $self->_get_ppix_regexp( $elem )
  564         1157  
343 30 50       820 or next;
344             foreach my $code ( @{ $pre->find(
345 30 100       34536 'PPIx::Regexp::Token::Code' ) || [] } ) {
  30         98  
346             my $ppi = $self->_get_derived_ppi_document( $code, $elem )
347 27 50       1689 or next;
348             push @rslt, $self->_get_ppi_statement_variable( $ppi );
349 27         90 }
350             }
351             }
352              
353             return @rslt;
354 94         9037 }
355 282 100       17612  
  282         607  
356 9 50       745 #-----------------------------------------------------------------------------
357              
358 9 50       69182 # The catch() clause of try/catch is a special case because the 'my' is
  9         29  
359             # implied. Also the syntax requires you to specify a variable even if
360 9 50       2408 # you have no intention of using it.
361             # NOTE that we assume that if we get called, the check is to be done.
362 9         21 my ( $self, $document ) = @_;
363             foreach my $word ( @{ $document->find( 'PPI::Token::Word' ) || [] } ) {
364             $CATCH eq $word->content()
365             or next;
366             my $list = $word->snext_sibling()
367 94         9038 or next;
368             $list->isa( 'PPI::Structure::List' )
369             or next;
370             my $block = $list->snext_sibling()
371             or next;
372             $block->isa( 'PPI::Structure::Block' )
373             or next;
374             foreach my $sym ( @{ $list->find( 'PPI::Token::Symbol' ) || [] } ) {
375             # Should be only one, but ...
376             $self->_record_symbol_definition(
377 2     2   5 $sym, $sym->statement() );
378 2 50       4 }
  2         6  
379 7 100       70 }
380             return;
381 2 50       9 }
382              
383 2 50       57 #-----------------------------------------------------------------------------
384              
385 2 50       16 # Sorry, but this is just basicly hard.
386             my ( $self, $document ) = @_;
387 2 50       49  
388             foreach my $declaration ( $self->_get_ppi_statement_variable( $document ) ) {
389 2 50       4  
  2         6  
390             # This _should_ be the initial 'my', 'our' 'state'
391 2         447 my $elem = $declaration->schild( 0 )
392             or next;
393              
394             my $is_unpacking = $declaration->content() =~ m<
395 2         7 = \s* (?: \@_ |
396             shift (?: \s* \@_ )? ) |
397             \$_ [[] .*? []]
398             \s* ;? \z >smx;
399              
400             my $taking_reference = $self->_taking_reference_of_variable(
401             $declaration );
402 58     58   134  
403             my $returned_lexical = $self->_returned_lexical( $declaration );
404 58         161  
405             while ( 1 ) {
406              
407 98 50       1208 # Looking for 'my', 'our', or 'state'
408             $elem->isa( 'PPI::Token::Word' )
409             or next;
410 98         1301 defined( my $is_global = $GLOBAL_DECLARATION{
411             $elem->content()} )
412             or next;
413              
414             $elem = $elem->snext_sibling()
415             or last;
416 98         3852  
417             # We can't just look for symbols, since PPI parses the
418             # parens in
419 98         421 # open( my $fh, '>&', \*STDOUT )
420             # as a PPI::Statement::Variable, and we get a false positive
421 98         794 # on STDOUT.
422             my @symbol_list;
423             if ( $elem->isa( 'PPI::Token::Symbol' ) ) {
424 277 100       4394 push @symbol_list, $elem;
425             } elsif ( $elem->isa( 'PPI::Structure::List' ) ) {
426             push @symbol_list, @{
427 116 100       250 $elem->find( 'PPI::Token::Symbol' ) || [] };
428             } else {
429             next;
430 100 100       1146 }
431              
432             my ( $assign, $is_allowed_computation,
433             $is_state_in_expression );
434              
435             while ( $elem = $elem->snext_sibling() ) {
436             $elem->isa( 'PPI::Token::Operator' )
437             or next;
438 98         2040 my $content = $elem->content();
439 98 100       279 $IS_COMMA{$content}
    50          
440 89         182 and last;
441             if ( $EQUAL eq $content ) {
442             $assign = $elem;
443 9 50       102  
  9         29  
444             $is_allowed_computation = $self->_is_allowed_computation(
445 0         0 $assign );
446              
447             $is_state_in_expression = $self->_is_state_in_expression(
448 98         2677 $declaration, $assign );
449              
450             last;
451 98         220 }
452 103 100       2129 }
453              
454 85         187 foreach my $symbol ( @symbol_list ) {
455 85 100       443  
456             if ( $assign ) {
457 82 100       558 $symbol->logical_line_number() <
458 80         143 $assign->logical_line_number()
459             or $symbol->logical_line_number() ==
460 80         178 $assign->logical_line_number()
461             and $symbol->column_number() < $assign->column_number()
462             or next;
463 80         169 }
464              
465             $self->_record_symbol_definition(
466 80         2681 $symbol, $declaration,
467             is_allowed_computation => $is_allowed_computation,
468             is_global => $is_global,
469             is_state_in_expression => $is_state_in_expression,
470 98         499 is_unpacking => $is_unpacking,
471             taking_reference => $taking_reference,
472 105 100       261 returned_lexical => $returned_lexical,
473 84 50 33     214 );
      33        
474              
475             }
476              
477             } continue {
478             $elem
479             and $elem = $elem->snext_sibling()
480             or last;
481             }
482 105         5424  
483             }
484              
485             return;
486             }
487              
488             #-----------------------------------------------------------------------------
489              
490             {
491              
492             Readonly::Hash my %IS_FOR => hashify( qw{ for foreach } );
493             Readonly::Hash my %IS_RETURN => hashify( qw{ return } );
494 275 100 100     1194  
495             # Get stray declarations that do not show up in
496             # PPI::Statement::Variable statements. These show up in
497             # PPI::Statement::Compound (specifically 'for' and 'foreach'), and
498             # in PPI::Statement::Break (specifically 'return'). In the case of
499             # 'return', we do not need to descend into paren, because if there
500             # are parens, PPI produces a PPI::Statement::Variable.
501 58         944  
502             my ( $self, $document ) = @_;
503              
504             foreach (
505             [ 'PPI::Statement::Compound' => {
506             want => \%IS_FOR,
507             returned_lexical => $FALSE,
508             } ],
509             [ 'PPI::Statement::Break' => {
510             want => \%IS_RETURN,
511             returned_lexical => $TRUE,
512             } ],
513             ) {
514             my ( $class, $info ) = @{ $_ };
515             foreach my $declaration (
516             @{ $document->find( $class ) || [] }
517             ) {
518              
519 58     58   136 my $type = $declaration->schild( 0 )
520             or next;
521 58         312  
522             my $type_str = $type->content();
523              
524             if ( $info->{want}{$type_str} ) {
525              
526             my $sib = $type->snext_sibling()
527             or next;
528              
529             # We're looking for 'my', 'state', or 'our'.
530             $sib->isa( 'PPI::Token::Word' )
531 116         765 or next;
  116         267  
532 116         176 my $sib_content = $sib->content();
533 116 100       321 defined( my $is_global = $GLOBAL_DECLARATION{$sib_content} )
534             or next;
535              
536 21 50       205 my $symbol = $sib->snext_sibling()
537             or next;
538             $symbol->isa( 'PPI::Token::Symbol' )
539 21         258 or next;
540              
541 21 100       826 $self->_record_symbol_definition(
542             $symbol, $declaration,
543 9 50       62 is_global => $is_global,
544             returned_lexical => $info->{returned_lexical},
545             );
546              
547 9 100       180 }
548              
549 6         15 }
550 6 50       31  
551             }
552              
553 6 50       44 return;
554             }
555 6 50       120  
556             }
557              
558             #-----------------------------------------------------------------------------
559              
560             my ( $self, $elem ) = @_; # $elem presumed to be '='.
561              
562 6         19 my $next_sib = $elem->snext_sibling() or return;
563              
564             if ( $next_sib->isa( 'PPI::Token::Word' ) ) {
565              
566             # We are presumed to be a subroutine call.
567             my $content = $next_sib->content();
568             $self->{_allow_if_computed_by}{$content}
569             and return $content;
570 58         657  
571             } elsif ( $next_sib->isa( 'PPI::Token::Symbol' ) ) {
572              
573             # We might be a method call.
574             $next_sib = $next_sib->snext_sibling()
575             or return;
576             $next_sib->isa( 'PPI::Token::Operator' )
577             and q{->} eq $next_sib->content()
578 80     80   162 or return;
579             $next_sib = $next_sib->snext_sibling()
580 80 50       172 or return;
581             my $content = $next_sib->content();
582 80 100       1825 $self->{_allow_if_computed_by}{$content}
    100          
583             and return $content;
584             }
585 12         29  
586 12 100       60 return;
587             }
588              
589             #-----------------------------------------------------------------------------
590              
591             # Find cases where the value of a state variable is used by the
592 8 50       19 # statement that declares it, or an expression in which that statement
593             # appears. The user may wish to accept such variables even if the
594 8 50 33     172 # variable itself appears only in the statement that declares it.
595             #
596             # $declaration is assumed to be a PPI::Statement::Variable. We return
597 0 0       0 # $FALSE unless it declares state variables.
598             #
599 0         0 # $operator is the first assignment operator in $declaration.
600 0 0       0 #
601             # NOTE that this will never be called for stuff like
602             # $foo and state $bar = 42
603             # because PPI does not parse this as a PPI::Statement::Variable.
604 71         189 my ( $self, $declaration, $operator ) = @_;
605              
606             # We're only interested in state declarations.
607             q<state> eq $declaration->type()
608             or return $FALSE;
609              
610             # We accept things like
611             # state $foo = bar() and ...
612             my $next_sib = $operator;
613             while ( $next_sib = $next_sib->snext_sibling() ) {
614             $next_sib->isa( 'PPI::Token::Operator' )
615             and $LOW_PRECEDENCE_BOOLEAN{ $next_sib->content() }
616             and return $TRUE;
617             }
618              
619             # We accept things like
620             # ... ( state $foo = bar() ) ...
621             # IF at least one of the ellipses has an operator adjacent to our
622             # declaration.
623 80     80   170 my $elem = $declaration;
624             while ( $elem ) {
625             foreach my $method ( qw{ snext_sibling sprevious_sibling } ) {
626 80 100       225 my $sib = $elem->$method()
627             or next;
628             $sib->isa( 'PPI::Token::Operator' )
629             and return $TRUE;
630             }
631 5         170 $elem = $self->_get_parent_element( $elem );
632 5         16 }
633              
634 12 100 66     286 # There are no other known cases where a state variable's value can
635             # be used without the variable name appearing anywhere other than
636             # its initialization.
637             return $FALSE;
638             }
639              
640             #-----------------------------------------------------------------------------
641              
642 3         69 my ( $self, $elem ) = @_; # Expect a PPI::Statement::Variable
643 3         10 my $parent = $self->_get_parent_element( $elem )
644 6         14 or return;
645 11 100       62 my $cast;
646              
647 3 100       59 if ( $parent->isa( 'PPI::Structure::List' ) ) {
648              
649             $cast = $parent->sprevious_sibling()
650 5         69 or return;
651              
652             } elsif ( $parent->isa( 'PPI::Structure::Block' ) ) {
653              
654             my $prev = $parent->sprevious_sibling()
655             or return;
656 2         6  
657             $prev->isa( 'PPI::Token::Word' )
658             or return;
659             'do' eq $prev->content()
660             or return;
661              
662 98     98   235 $cast = $prev->sprevious_sibling()
663 98 50       253  
664             }
665 98         157  
666             $cast
667 98 100       494 or return;
    100          
668             $cast->isa( 'PPI::Token::Cast' )
669 10 100       70 or return;
670             return q<\\> eq $cast->content()
671             }
672              
673             #-----------------------------------------------------------------------------
674 23 100       75  
675             my ( $self, $elem ) = @_; # Expect a PPI::Statement::Variable
676             my $parent = $self->_get_parent_element( $elem )
677 14 100       369 or return;
678             my $stmt = $parent->statement()
679 13 100       32 or return;
680             $stmt->isa( 'PPI::Statement::Break' )
681             or return;
682 4         26 my $kind = $stmt->schild( 0 )
683             or return; # Should never happen.
684             return 'return' eq $kind->content();
685             }
686              
687 78 100       460 #-----------------------------------------------------------------------------
688 11 100       43  
689             {
690 6         14  
691             Readonly::Hash my %CAST_FOR_BARE_BRACKETED_VARIABLE => qw{
692             @ @
693             $ $
694             $$ $
695             % %
696 98     98   184 };
697 98 50       198  
698             my ( $self, $document ) = @_;
699 98 100       286  
700             foreach my $symbol (
701 34 100       551 @{ $document->find( 'PPI::Token::Symbol' ) || [] }
702             ) {
703 2 50       6 $self->{$PACKAGE}{is_declaration}->{ refaddr( $symbol ) } and next;
704              
705 2         25 $self->_record_symbol_use( $document, $symbol );
706              
707             }
708              
709             # For some reason, PPI parses '$#foo' as a
710             # PPI::Token::ArrayIndex. $#$foo is parsed as a Cast followed
711             # by a Symbol, so as long as nobody decides the '$#' cast causes
712             # $elem->symbol() to return something other than '$foo', we're
713             # cool.
714             foreach my $elem (
715             @{ $document->find( 'PPI::Token::ArrayIndex' ) || [] }
716             ) {
717              
718             my $name = $elem->content();
719             $name =~ s/ \A \$ [#] /@/smx or next;
720 97     97   192  
721             $self->_record_symbol_use( $document, $elem, $name );
722 97         172 }
723 97 100       265  
724             # Occasionally you see something like ${foo} outside quotes.
725 207 100       9844 # This is legitimate, though PPI parses it as a cast followed by
726             # a block. On the assumption that there are fewer blocks than
727 94         259 # words in most Perl, we start at the top and work down. Perl
728             # also handles punctuation variables specified this way, but
729             # since PPI goes berserk when it sees this, we won't bother.
730             #
731             # And EXTREMELY occasionally something like $${foo} gets parsed
732             # as magic followed by subscript.
733             foreach my $class ( qw{
734             PPI::Structure::Block
735             PPI::Structure::Subscript
736 97         639 }
737 97 100       265 ) {
738             foreach my $elem (
739             @{ $document->find( $class ) || [] }
740 1         13 ) {
741 1 50       18 $LEFT_BRACE eq $elem->start() # Only needed for subscript.
742             or next;
743 1         4 my $previous = $elem->sprevious_sibling()
744             or next;
745             $previous->isa( 'PPI::Token::Cast' )
746             or $previous->isa( 'PPI::Token::Magic' ) # $${foo}
747             or next;
748             my $sigil = $CAST_FOR_BARE_BRACKETED_VARIABLE{
749             $previous->content() }
750             or next;
751              
752             my @kids = $elem->schildren();
753             1 == @kids
754             or next;
755 97         9582 $kids[0]->isa( 'PPI::Statement' )
756             or next;
757              
758             my @grand_kids = $kids[0]->schildren();
759             1 == @grand_kids
760 194         8761 or next;
761 194 100       429  
762             # Yes, "${v6}_..." occurred, and was parsed as a
763 62 100       3469 # PPI::Token::Number::Version by PPI 1.270.
764             $grand_kids[0]->isa( 'PPI::Token::Word' )
765 54 100       819 or $grand_kids[0]->isa( 'PPI::Token::Number::Version' )
766             or next;
767 44 100 66     1121  
768             $self->_record_symbol_use( $document, $elem,
769             $sigil . $grand_kids[0]->content(),
770             );
771 4 50       11 }
772             }
773              
774 4         51 $self->_get_regexp_symbol_uses( $document );
775 4 50       42  
776             $self->_get_double_quotish_string_uses( $document );
777 4 50       14  
778             $self->_get_subroutine_signature_uses( $document );
779              
780 4         11 return;
781 4 50       31 }
782              
783             }
784              
785             #-----------------------------------------------------------------------------
786 4 100 66     31  
787             # Record the definition of a symbol.
788             # $symbol is the PPI::Token::Symbol
789             # $declaration is the statement that declares it
790 1         4 # %arg is optional arguments, collected and recorded to support the
791             # various configuration items.
792             my ( $self, $symbol, $declaration, %arg ) = @_;
793              
794             my $ref_addr = refaddr( $symbol );
795             my $sym_name = $symbol->symbol();
796 97         6454  
797             $self->{$PACKAGE}{is_declaration}{$ref_addr} = 1;
798 97         345  
799             $arg{declaration} = $declaration;
800 97         286 $arg{element} = $symbol;
801             $arg{used} = 0;
802 97         286  
803             foreach my $key ( qw{
804             is_allowed_computation
805             is_global
806             is_state_in_expression
807             is_unpacking
808             taking_reference
809             returned_lexical
810             } ) {
811             exists $arg{$key}
812             or $arg{$key} = $FALSE;
813             }
814              
815 118     118   602 if ( $self->{_trace}{$sym_name} ) {
816             printf { *STDERR }
817 118         311 "%s 0x%x declared at line %d col %d\n",
818 118         324 $sym_name, $ref_addr,
819             $symbol->logical_line_number(), $symbol->column_number();
820 118         4926 }
821              
822 118         222 push @{ $self->{$PACKAGE}{declared}{ $sym_name } ||= [] }, \%arg;
823 118         287  
824 118         202 $self->{$PACKAGE}{need_sort} = $TRUE;
825              
826 118         238 return;
827             }
828              
829             #-----------------------------------------------------------------------------
830              
831             my ( $self, undef, $symbol, $symbol_name ) = @_; # $document not used
832              
833             my $declaration;
834              
835 708 100       1414 defined $symbol_name
836             or $symbol_name = $symbol->symbol();
837              
838 118 50       256 if ( ! ( $declaration = $self->{$PACKAGE}{declared}{$symbol_name} ) ) {
839 0         0 # If we did not find a declaration for the symbol, it may
  0         0  
840             # have been declared en passant, as part of doing something
841             # else.
842             my $prev = $symbol->sprevious_sibling()
843             or return;
844             $prev->isa( 'PPI::Token::Word' )
845 118   100     189 or return;
  118         549  
846             my $content = $prev->content();
847 118         248 exists $GLOBAL_DECLARATION{$content}
848             or return;
849 118         317  
850             # Yup. It's a declaration. Record it.
851             $declaration = $symbol->statement();
852              
853             my $cast = $prev->sprevious_sibling();
854             if ( ! $cast ) {
855 96     96   226 my $parent;
856             $parent = $self->_get_parent_element( $prev )
857 96         151 and $cast = $parent->sprevious_sibling();
858             }
859 96 100       321  
860             $self->_record_symbol_definition(
861             $symbol, $declaration,
862 96 100       4087 is_global => $GLOBAL_DECLARATION{$content},
863             taking_reference => _element_takes_reference( $cast ),
864             );
865              
866 26 100       66 return;
867             }
868 16 100       399  
869             if ( delete $self->{$PACKAGE}{need_sort} ) {
870 8         23 # Because we need multiple passes to find all the declarations,
871 8 100       52 # we have to put them in reverse order when we're done. We need
872             # to repeat the check because of the possibility of picking up
873             # declarations made in passing while trying to find uses.
874             # Re the 'no critic' annotation: I understand that 'reverse ...'
875 5         41 # is faster and clearer than 'sort { $b cmp $a } ...', but I
876             # think the dereferenes negate this.
877 5         65 foreach my $decls ( values %{ $self->{$PACKAGE}{declared} } ) {
878 5 50       94 @{ $decls } = map { $_->[0] }
879 0         0 sort { ## no critic (ProhibitReverseSortBlock)
880 0 0       0 $b->[1][LOCATION_LOGICAL_LINE] <=>
881             $a->[1][LOCATION_LOGICAL_LINE] ||
882             $b->[1][LOCATION_CHARACTER] <=>
883             $a->[1][LOCATION_CHARACTER]
884             }
885             map { [ $_, $_->{element}->location() ] }
886 5         21 @{ $decls };
887             }
888             }
889              
890 5         14 foreach my $decl_scope ( @{ $declaration } ) {
891             $self->_derived_element_is_in_lexical_scope_after_statement_containing(
892             $symbol, $decl_scope->{declaration} )
893 70 100       180 or next;
894             $decl_scope->{used}++;
895             if ( $self->{_trace}{$symbol_name} ) {
896             my $elem = $decl_scope->{element};
897             printf { *STDERR }
898             "%s at line %d col %d refers to 0x%x at line %d col %d\n",
899             $symbol_name,
900             $symbol->logical_line_number(),
901 33         50 $symbol->column_number(),
  33         136  
902 56         156 refaddr( $elem ),
  70         510  
903             $elem->logical_line_number(),
904 14 50       207 $elem->column_number(),
905             ;
906             }
907             return;
908             }
909 70         285  
910 56         87 if ( $self->{_trace}{$symbol_name} ) {
  56         96  
911             printf { *STDERR }
912             "Failed to resolve %s at line %d col %d\n",
913             $symbol_name,
914 70         115 $symbol->logical_line_number(),
  70         158  
915             $symbol->column_number(),
916             ;
917 85 100       304 }
918 70         953  
919 70 50       158 return;
920 0         0  
921 0         0 }
  0         0  
922              
923             my ( $self, $inner_elem, $outer_elem ) = @_;
924              
925             my $effective_inner = $self->_get_lowest_in_same_doc( $inner_elem,
926             $outer_elem )
927             or return $FALSE;
928              
929             return _element_is_in_lexical_scope_after_statement_containing(
930             $effective_inner, $outer_elem );
931 70         178  
932             }
933              
934 0 0       0 #-----------------------------------------------------------------------------
935 0         0  
  0         0  
936             my ( $elem ) = @_;
937             return $elem && $elem->isa( 'PPI::Token::Cast' ) &&
938             $BSLASH eq $elem->content();
939             }
940              
941             #-----------------------------------------------------------------------------
942              
943 0         0 my ( $self, $document ) = @_;
944              
945             foreach my $class ( @DOUBLE_QUOTISH ) {
946             foreach my $double_quotish (
947             @{ $document->find( $class ) || [] }
948 85     85   164 ) {
949              
950 85 100       181 my $str = $self->_get_ppix_quotelike( $double_quotish )
951             or next;
952              
953             foreach my $interp ( @{
954 81         549 $str->find( 'PPIx::QuoteLike::Token::Interpolation' ) || [] } ) {
955              
956             my $subdoc = $self->_get_derived_ppi_document(
957             $interp, $double_quotish )
958             or next;
959              
960             $self->_get_symbol_uses( $subdoc, $double_quotish );
961              
962 5     5   11 }
963 5   33     42  
964             }
965             }
966              
967             return;
968             }
969              
970 97     97   218 #-----------------------------------------------------------------------------
971              
972 97         226 my ( $self, $document ) = @_;
973 582         48148  
974 582 100       1189 foreach my $class ( @REGEXP_ISH ) {
975              
976             foreach my $regex ( @{ $document->find( $class ) || [] } ) {
977 30 50       730  
978             my $pre = $self->_get_ppix_regexp( $regex )
979             or next;
980 30         48  
981 30 100       95 foreach my $code ( @{
982             $pre->find( 'PPIx::Regexp::Token::Code' ) || [] } ) {
983 27 50       956  
984             my $subdoc = $self->_get_derived_ppi_document( $code,
985             $regex );
986              
987 27         73 $self->_get_symbol_uses( $subdoc, $regex );
988             }
989              
990             }
991              
992             }
993              
994 97         9489 return;
995             }
996              
997             #-----------------------------------------------------------------------------
998              
999             # Stolen shamelessly from OALDERS' App::perlimports::Include
1000 97     97   195 my ( $self, $document ) = @_;
1001              
1002 97         341 # FIXME as of PPI 1.272, signatures are parsed as prototypes.
1003             foreach my $class ( qw{ PPI::Token::Prototype } ) {
1004 291 100       19246 foreach my $elem ( @{ $document->find( $class ) || [] } ) {
  291         714  
1005             my $sig = $elem->content();
1006 9 50       739  
1007             # Skip over things that might actually be prototypes. Some
1008             # of them may actually be signatures, but if so they specify
1009 9         17 # only ignored variables, or maybe magic variables like $_
1010 9 50       25 # or @_.
1011             $sig =~ m/ [[:alpha:]\d] /smx
1012 9         2457 or next;
1013              
1014             # Strip leading and trailing parens. OALDERS' comments say
1015 9         21 # that sometimes the trailing one is missing.
1016             $sig =~ s/ \A \s* [(] \s* //smx;
1017             $sig =~ s/ \s* [)] \s* \z //smx;
1018              
1019             # Rewrite the signature as statements.
1020             my @args;
1021             foreach ( split / , /smx, $sig ) {
1022 97         9573 s/ \s+ \z //smx;
1023             s/ \A \s+ //smx;
1024             # Skip unused arguments, since we're not interested in
1025             # their position in the argument list.
1026             m/ \A [\$\@%] (?: \s* = | \z ) /smx
1027             and next;
1028             # Ignore empty defaults.
1029 97     97   1683 s/ = \z //smx;
1030             # FIXME there ought to be a 'my' in front, but because
1031             # this policy has no way to find the uses of this
1032 97         191 # variable it results in false positives. MAYBE I could
1033 97 100       162 # fix this by calling _get_symbol_declarations() on
  97         241  
1034 3         30 # $subdoc (in _element_to_ppi() so it only gets called
1035             # once), but I don't think I want that in the same
1036             # commit, or even the same release, as the bug fix.
1037             push @args, "$_;";
1038             }
1039              
1040 3 50       17 my $subdoc = $self->_element_to_ppi( $elem, "@args" )
1041             or next;
1042              
1043             $self->_get_symbol_uses( $subdoc, $elem );
1044             }
1045 3         15 }
1046 3         13  
1047             return;
1048             }
1049 3         8  
1050 3         11 #-----------------------------------------------------------------------------
1051 5         13  
1052 5         13 my ( $self ) = @_;
1053              
1054             my @in_violation;
1055 5 100       17  
1056             foreach my $name ( values %{ $self->{$PACKAGE}{declared} } ) {
1057             foreach my $declaration ( @{ $name } ) {
1058 3         6 $declaration->{is_global}
1059             and next;
1060             $declaration->{used}
1061             and next;
1062             $declaration->{is_allowed_computation}
1063             and next;
1064             $declaration->{is_state_in_expression}
1065             and $self->{_allow_state_in_expression}
1066 3         11 and next;
1067             $declaration->{taking_reference}
1068             and not $self->{_prohibit_reference_only_variables}
1069 3 50       13 and next;
1070             $declaration->{returned_lexical}
1071             and not $self->{_prohibit_returned_lexicals}
1072 3         10 and next;
1073             $declaration->{is_unpacking}
1074             and $self->{_allow_unused_subroutine_arguments}
1075             and next;
1076 97         8937 push @in_violation, $declaration->{element};
1077             }
1078             }
1079              
1080             return ( map { $self->violation(
1081             sprintf( '%s is declared but not used', $_->symbol() ),
1082 58     58   112 $EXPL,
1083             $_
1084 58         175 ) } sort { $a->logical_line_number() <=> $b->logical_line_number() ||
1085             $a->column_number() <=> $b->column_number() }
1086 58         95 @in_violation );
  58         242  
1087 95         154 }
  95         163  
1088              
1089 118 100       256 #-----------------------------------------------------------------------------
1090              
1091 117 100       248 # THIS CODE HAS ABSOLUTELY NO BUSINESS BEING HERE. It should probably be
1092             # its own module; PPIx::Scope or something like that. The problem is
1093 55 100       106 # that I no longer "own" it, and am having trouble getting modifications
1094             # through. So I have stuck it here for the moment, but I hope it will
1095             # not stay here. Other than here, it appears in Perl::Critic::Document
1096 54 100 100     118 # (the copy I am trying to get modified) and Perl::ToPerl6::Document (a
1097             # cut-and-paste of an early version.)
1098             #
1099 52 100 100     125 # THIS CODE IS PRIVATE TO THIS MODULE. The author reserves the right to
1100             # change it or remove it without any notice whatsoever. YOU HAVE BEEN
1101             # WARNED.
1102 48 100 100     103 #
1103             # This got hung on the Perl::Critic::Document, rather than living in
1104             # Perl::Critic::Utils::PPI, because of the possibility that caching of scope
1105 46 100 100     111 # objects would turn out to be desirable.
1106 40         91  
1107             # sub element_is_in_lexical_scope_after_statement_containing {...}
1108             my ( $inner_elem, $outer_elem ) = @_;
1109              
1110 40         3157 $inner_elem->top() == $outer_elem->top()
1111             or Perl::Critic::Exception::Fatal::PolicyDefinition->throw(
1112             message => 'Elements must be in same document' );
1113              
1114 58 50       225 # If the outer element defines a scope, we're true if and only if
  24         367  
1115             # the outer element contains the inner element, and the inner
1116             # element is not somewhere that is hidden from the scope.
1117             if ( $outer_elem->scope() ) {
1118             return _inner_element_is_in_outer_scope_really(
1119             $inner_elem, $outer_elem );
1120             }
1121              
1122             # In the more general case:
1123              
1124             # The last element of the statement containing the outer element
1125             # must be before the inner element. If not, we know we're false,
1126             # without walking the parse tree.
1127              
1128             my $stmt = $outer_elem->statement()
1129             or return;
1130              
1131             my $last_elem = $stmt;
1132             while ( $last_elem->isa( 'PPI::Node' ) ) {
1133             $last_elem = $last_elem->last_element()
1134             or return;
1135             }
1136              
1137             my $stmt_loc = $last_elem->location()
1138             or return;
1139 81     81   153  
1140             my $inner_loc = $inner_elem->location()
1141 81 50       176 or return;
1142              
1143             $stmt_loc->[LOCATION_LINE] > $inner_loc->[LOCATION_LINE]
1144             and return;
1145             $stmt_loc->[LOCATION_LINE] == $inner_loc->[LOCATION_LINE]
1146             and $stmt_loc->[LOCATION_CHARACTER] >= $inner_loc->[LOCATION_CHARACTER]
1147             and return;
1148 81 100       1485  
1149 6         19 # Since we know the inner element is after the outer element, find
1150             # the element that defines the scope of the statement that contains
1151             # the outer element.
1152              
1153             my $parent = $stmt;
1154             while ( ! $parent->scope() ) {
1155             # Things appearing in the right-hand side of a
1156             # PPI::Statement::Variable are not in-scope to its left-hand
1157             # side. RESTRICTION -- this code does not handle truly
1158             # pathological stuff like
1159 75 50       167 # my ( $c, $d ) = qw{ e f };
1160             # my ( $a, $b ) = my ( $c, $d ) = ( $c, $d );
1161             _inner_is_defined_by_outer( $inner_elem, $parent )
1162 75         685 and _location_is_in_right_hand_side_of_assignment(
1163 75         197 $parent, $inner_elem )
1164 77 50       198 and return;
1165             $parent = $parent->parent()
1166             or return;
1167             }
1168 75 50       500  
1169             # We're true if and only if the scope of the outer element contains
1170             # the inner element.
1171 75 50       811  
1172             return $inner_elem->descendant_of( $parent );
1173              
1174 75 50       768 }
1175              
1176 75 100 100     226 # Helper for element_is_in_lexical_scope_after_statement_containing().
1177             # Return true if and only if $outer_elem is a statement that defines
1178             # variables and $inner_elem is actually a variable defined in that
1179             # statement.
1180             my ( $inner_elem, $outer_elem ) = @_;
1181             $outer_elem->isa( 'PPI::Statement::Variable' )
1182             and $inner_elem->isa( 'PPI::Token::Symbol' )
1183             or return;
1184 70         109 my %defines = hashify( $outer_elem->variables() );
1185 70         161 return $defines{$inner_elem->symbol()};
1186             }
1187              
1188             # Helper for element_is_in_lexical_scope_after_statement_containing().
1189             # Given that the outer element defines a scope, there are still things
1190             # that are lexically inside it but outside the scope. We return true if
1191             # and only if the inner element is inside the outer element, but not
1192 75 50 66     195 # inside one of the excluded elements. The cases handled so far:
1193             # for ----- the list is not part of the scope
1194             # foreach - the list is not part of the scope
1195              
1196 75 50       604 my ( $inner_elem, $outer_elem ) = @_;
1197             $outer_elem->scope()
1198             or return;
1199             $inner_elem->descendant_of( $outer_elem )
1200             or return;
1201             if ( $outer_elem->isa( 'PPI::Statement::Compound' ) ) {
1202             my $first = $outer_elem->schild( 0 )
1203 70         494 or return;
1204             if ( { for => 1, foreach => 1 }->{ $first->content() } ) {
1205             my $next = $first;
1206             while ( $next = $next->snext_sibling() ) {
1207             $next->isa( 'PPI::Structure::List' )
1208             or next;
1209             return ! $inner_elem->descendant_of( $next );
1210             }
1211             }
1212 75     75   146 }
1213 75 100 100     397 return $TRUE;
1214             }
1215              
1216 36         104 # Helper for element_is_in_lexical_scope_after_statement_containing().
1217 36         2091 # Given and element that represents an assignment or assignment-ish
1218             # statement, and a location, return true if the location is to the right
1219             # of the equals sign, and false otherwise (including the case where
1220             # there is no equals sign). Only the leftmost equals is considered. This
1221             # is a restriction.
1222             my ( $elem, $inner_elem ) = @_;
1223             my $inner_loc = $inner_elem->location();
1224             my $kid = $elem->schild( 0 );
1225             while ( $kid ) {
1226             $kid->isa( 'PPI::Token::Operator' )
1227             and q{=} eq $kid->content()
1228             or next;
1229 6     6   13 my $l = $kid->location();
1230 6 50       18 $l->[LOCATION_LINE] > $inner_loc->[LOCATION_LINE]
1231             and return;
1232 6 50       22 $l->[LOCATION_LINE] == $inner_loc->[LOCATION_LINE]
1233             and $l->[LOCATION_CHARACTER] >= $inner_loc->[LOCATION_CHARACTER]
1234 6 50       91 and return;
1235 6 50       17 return $inner_elem->descendant_of( $elem );
1236             } continue {
1237 6 50       86 $kid = $kid->snext_sibling();
1238 6         35 }
1239 6         13 return;
1240 18 100       351 }
1241              
1242 6         53 # END OF CODE THAT ABSOLUTELY SHOULD NOT BE HERE
1243              
1244             #-----------------------------------------------------------------------------
1245              
1246 0         0 # Cribbed shamelessly from PPIx::Regexp::Token::Code->ppi().
1247             # FIXME duplicate code should be consolidated somewhere, but I don't
1248             # know where. Maybe in the above scope code, since that's what I'm
1249             # trying to solve.
1250             my ( $self, $elem, $content ) = @_;
1251              
1252             exists $self->{$PACKAGE}{sub_document}{ refaddr( $elem ) }
1253             and return $self->{$PACKAGE}{sub_document}{ refaddr( $elem ) };
1254              
1255             defined $content
1256 36     36   1452 or $content = $self->content();
1257 36         82  
1258 36         375 my $doc_content;
1259 36         400  
1260 111 100 100     1515 my $location = $elem->location();
1261             if ( $location ) {
1262             my $fn;
1263 27         146 if( defined( $fn = $location->[LOCATION_LOGICAL_FILE] ) ) {
1264 27 50       276 $fn =~ s/ (?= [\\"] ) /\\/smxg;
1265             $doc_content = qq{#line $location->[LOCATION_LOGICAL_LINE] "$fn"\n};
1266 27 50 66     73 } else {
1267             $doc_content = qq{#line $location->[LOCATION_LOGICAL_LINE]\n};
1268             }
1269 27         72 $doc_content .= q< > x ( $location->[LOCATION_COLUMN] - 1 );
1270             }
1271 84         209  
1272             $doc_content .= $content;
1273 9         184  
1274             my $doc = PPI::Document->new( \$doc_content );
1275              
1276             if ( $location ) {
1277             # Generate locations now.
1278             $doc->location();
1279             # Remove the stuff we originally injected. NOTE that we can
1280             # only get away with doing this if the removal does not
1281             # invalidate the locations of the other tokens that we just
1282             # generated.
1283             my $annotation;
1284             # Remove the '#line' directive if we find it
1285 3     3   7 $annotation = $doc->child( 0 )
1286             and $annotation->isa( 'PPI::Token::Comment' )
1287             and $annotation->content() =~ m/ \A \#line\b /smx
1288 3 50       15 and $annotation->remove();
1289             # Remove the white space if we find it, and if it in fact
1290 3 50       9 # represents only the white space we injected to get the
1291             # column numbers right.
1292             my $wid = $location->[LOCATION_COLUMN] - 1;
1293 3         4 $wid
1294             and $annotation = $doc->child( 0 )
1295 3         15 and $annotation->isa( 'PPI::Token::Whitespace' )
1296 3 50       37 and $wid == length $annotation->content()
1297 3         4 and $annotation->remove();
1298 3 50       10 }
1299 0         0  
1300 0         0 $self->{$PACKAGE}{parent_element}{ refaddr( $doc ) } = $elem;
1301             return ( $self->{$PACKAGE}{sub_document}{ refaddr( $elem ) } = $doc );
1302 3         15 }
1303              
1304 3         11 1;
1305              
1306              
1307 3         7 #-----------------------------------------------------------------------------
1308              
1309 3         10 =pod
1310              
1311 3 50       3474 =head1 NAME
1312              
1313 3         11 Perl::Critic::Policy::Variables::ProhibitUnusedVarsStricter - Don't ask for storage you don't need.
1314              
1315             =head1 AFFILIATION
1316              
1317             This Policy is stand-alone, and is not part of the core
1318 3         821 L<Perl::Critic|Perl::Critic>.
1319              
1320 3 50 33     8 =head1 NOTE
      33        
1321              
1322             As of version 0.099_001, the logic that recognizes variables
1323             interpolated into double-quotish strings has been refactored into module
1324             L<PPIx::QuoteLike|PPIx::QuoteLike>.
1325              
1326             =head1 DESCRIPTION
1327 3         139  
1328 3 50 33     11 Unused variables clutter code and require the reader to do mental
      33        
      33        
1329             bookkeeping to figure out if the variable is actually used or not.
1330              
1331             Right now, this only looks for lexical variables which are unused other
1332             than in the statement that declares them.
1333              
1334             my $x; # not ok, assuming no other appearances.
1335 3         126 my @y = (); # not ok, assuming no other appearances.
1336 3         31 our $z; # ok, global.
1337             local $w; # ok, global.
1338              
1339             This policy is a variant on the core policy
1340             L<Perl::Critic::Policy::Variables::ProhibitUnusedVariables|Perl::Critic::Policy::Variables::ProhibitUnusedVariables>
1341             which attempts to be more strict in its checking of whether a variable
1342             is used. The specific differences are:
1343              
1344             * An attempt is made to take into account the scope of the declaration.
1345              
1346             * An attempt is made to find variables which are interpolated into
1347             double-quotish strings (including regexes) and here documents.
1348              
1349             * An attempt is made to find variables which are used in regular
1350             expression C<(?{...})> and C<(??{...})> constructions, and in the
1351             replacement portion of C<s/.../.../e>.
1352              
1353             * An attempt is made to find variables which are used in subroutine
1354             signatures.
1355              
1356             This policy intentionally does not report variables as unused if the
1357             code takes a reference to the variable, even if it is otherwise unused.
1358             For example things like
1359              
1360             \( my $foo = 'bar' )
1361             \do{ my $foo => 'bar' }
1362              
1363             will not be reported as a violation even if C<$foo> is otherwise unused.
1364             The reason is that this is an idiom for making a reference to a mutable
1365             string when all you have is an immutable string. This policy does not
1366             check to see if anything is done with the reference.
1367              
1368             This policy also does not detect unused variables declared inside
1369             various odd corners such as
1370              
1371             s///e
1372             qr{(?{...})}
1373             qr{(??{...})}
1374             "@{[ ... ]}"
1375             ( $foo, my $bar ) = ( 1, 2 )
1376             sub ( $foo = $bar ) { ... } # Signature, not prototype
1377              
1378             Most of these are because the PPI parse of the original document does
1379             not include the declarations. The list assignment is missed because PPI
1380             does not parse it as containing a
1381             L<PPI::Statement::Variable|PPI::Statement::Variable>. However, variables
1382             B<used> inside such constructions B<will> be detected.
1383              
1384             =head1 CONFIGURATION
1385              
1386             This policy supports the following configuration items:
1387              
1388             =head2 allow_unused_subroutine_arguments
1389              
1390             By default, this policy prohibits unused subroutine arguments -- that
1391             is, unused variables on the right-hand side of such simple assignments
1392             as
1393              
1394             my ( $foo ) = @_;
1395             my $bar = shift;
1396             my $baz = shift @_;
1397             my $burfle = $_[0];
1398              
1399             If you wish to allow unused variables in this case, you can add a block
1400             like this to your F<.perlcriticrc> file:
1401              
1402             [Variables::ProhibitUnusedVarsStricter]
1403             allow_unused_subroutine_arguments = 1
1404              
1405             =head2 prohibit_reference_only_variables
1406              
1407             By default, this policy allows otherwise-unused variables if the code
1408             takes a reference to the variable when it is created. If you wish to
1409             declare a violation in this case, you can add a block like this to your
1410             F<.perlcriticrc> file:
1411              
1412             [Variables::ProhibitUnusedVarsStricter]
1413             prohibit_reference_only_variables = 1
1414              
1415             =head2 prohibit_returned_lexicals
1416              
1417             By default, this policy allows otherwise-unused variables if they are
1418             being returned from a subroutine, under the presumption that they are
1419             going to be used as lvalues by the caller. If you wish to declare a
1420             violation in this case, you can add a block like this to your
1421             F<.perlcriticrc> file:
1422              
1423             [Variables::ProhibitUnusedVarsStricter]
1424             prohibit_returned_lexicals = 1
1425              
1426             =head2 allow_if_computed_by
1427              
1428             You may wish to allow variables to be unused when computed in certain
1429             ways. For example, you might want to allow place-holder variables in a
1430             list computed by C<stat()> or C<unpack()>. Or you may be doing
1431             end-of-scope detection with something like
1432             C<< my $foo = Scope::Guard->new( \&end_of_scope ) >>. To ignore all
1433             these, you can add a block like this to your F<.perlcriticrc> file:
1434              
1435             [Variables::ProhibitUnusedVarsStricter]
1436             allow_if_computed_by = stat unpack Scope::Guard
1437              
1438             This property takes as its value a whitespace-delimited list of class or
1439             subroutine names. Nothing complex is done to implement this -- the
1440             policy simply looks at the first word after the equals sign, if any.
1441              
1442             =head2 allow_state_in_expression
1443              
1444             By default, this policy handles C<state> variables as any other lexical,
1445             and a violation is declared if they appear only in the statement that
1446             declares them.
1447              
1448             One might, however, do something like
1449              
1450             state $foo = compute_foo() or do_something_else();
1451              
1452             In this case, C<compute_foo()> is called only once, but if it returns a
1453             false value C<do_something_else()> will be executed every time this
1454             statement is encountered.
1455              
1456             If you wish to allow such code, you can add a block like this to your
1457             F<.perlcriticrc> file:
1458              
1459             [Variables::ProhibitUnusedVarsStricter]
1460             allow_state_in_expression = 1
1461              
1462             This allows an otherwise-unused state variable if its value appears to
1463             be used in an expression -- that is, if its declaration is followed by a
1464             low-precedence boolean, or one of its ancestors is preceded or followed
1465             by any operator. The latter means that something like
1466              
1467             my $bar = ( state $foo = compute_foo() ) + 42;
1468              
1469             will be accepted.
1470              
1471             =head2 check_catch
1472              
1473             Under ordinary circumstances the C<$err> variable in
1474              
1475             try {
1476             ...
1477             } catch ( $err ) {
1478             ...
1479             }
1480              
1481             will be invisible to this policy because, although it is in fact the
1482             declaration of a lexical variable, the absence of a C<my> means it does
1483             not look like one to L<PPI|PPI>. If you want to test these, you can add
1484             a block like this to your F<.perlcriticrc> file:
1485              
1486             [Variables::ProhibitUnusedVarsStricter]
1487             check_catch = 1
1488              
1489             This option is not on by default because there appears to be no way to
1490             define a C<catch()> block without a variable, whether or not you intend
1491             to use it.
1492              
1493             B<Caveat:> if L<PPI|PPI> ever starts recognizing C<catch( $foo )> as
1494             containing a L<PPI::Statement::Variable|PPI::Statement::Variable>, this
1495             configuration variable will become moot, as the extra logic will no
1496             longer be needed. As soon as I recognize this has happened (and there
1497             B<is> an author test for it) I will document this configuration item as
1498             a no-op, deprecate it, and probably eventually retract it.
1499              
1500             =head1 AVOIDING UNUSED VARIABLES
1501              
1502             There are situations in Perl where eliminating unused variables is
1503             less straightforward than simply deleting them:
1504              
1505             =head2 List Assignments
1506              
1507             This situation typically (I believe) comes up when your code gets handed
1508             a list, and is not interested in all values in the list. You could, of
1509             course, assign the whole thing to an array and then cherry-pick the
1510             array, but there are less-obvious solutions that avoid the extra
1511             assignment.
1512              
1513             For the purpose of this discussion, I will assume code which calls the
1514             C<localtime()> built-in, but is only interested in day, month, and year.
1515             The cut-and-paste implementation (direct from C<perldoc -f localtime>,
1516             or L<https://perldoc.pl/functions/localtime> if you prefer) is:
1517              
1518             # 0 1 2 3 4 5 6 7 8
1519             my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1520             localtime();
1521              
1522             Now, you can trivially eliminate the variables after C<$year>, but that
1523             still leaves
1524              
1525             # 0 1 2 3 4 5
1526             my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
1527              
1528             with C<$sec>, C<$min>, and C<$hour> assigned-to but unused. There are
1529             two ways I know of to eliminate these:
1530              
1531             =head3 Assign to C<undef>
1532              
1533             On the left-hand side of a list assignment, C<undef> causes the
1534             corresponding right-hand value to be ignored. This makes our example
1535             look like
1536              
1537             # 0 1 2 3 4 5
1538             my (undef,undef,undef,$mday,$mon,$year) = localtime();
1539              
1540             =head2 Slice the Right-Hand Side
1541              
1542             The unwanted values can also be eliminated by slicing the right-hand
1543             side of the assignment. This looks like
1544              
1545             # 3 4 5
1546             my ($mday,$mon,$year) = ( localtime() )[ 3 .. 5 ];
1547              
1548             or, if you prefer,
1549              
1550             # 3 4 5
1551             my ($mday,$mon,$year) = ( localtime() )[ 3, 4, 5 ];
1552              
1553             =head1 SUPPORT
1554              
1555             Support is by the author. Please file bug reports at
1556             L<https://rt.cpan.org/Public/Dist/Display.html?Name=Perl-Critic-Policy-Variables-ProhibitUnusedVarsStricter>,
1557             L<https://github.com/trwyant/perl-Perl-Critic-Policy-Variables-ProhibitUnusedVarsStricter/issues>, or in
1558             electronic mail to the author.
1559              
1560             =head1 AUTHOR
1561              
1562             Thomas R. Wyant, III F<wyant at cpan dot org>
1563              
1564             =head1 COPYRIGHT
1565              
1566             Copyright (C) 2012-2022 Thomas R. Wyant, III
1567              
1568             =head1 LICENSE
1569              
1570             This program is free software; you can redistribute it and/or modify it
1571             under the same terms as Perl 5.10.0. For more details, see the full text
1572             of the licenses in the directory LICENSES.
1573              
1574             This program is distributed in the hope that it will be useful, but
1575             without any warranty; without even the implied warranty of
1576             merchantability or fitness for a particular purpose.
1577              
1578             =cut
1579              
1580             # Local Variables:
1581             # mode: cperl
1582             # cperl-indent-level: 4
1583             # fill-column: 72
1584             # indent-tabs-mode: nil
1585             # c-indentation-style: bsd
1586             # End:
1587             # ex: set ts=8 sts=4 sw=4 tw=72 ft=perl expandtab shiftround :