File Coverage

blib/lib/Perl/Critic/Utils.pm
Criterion Covered Total %
statement 329 344 95.6
branch 193 246 78.4
condition 63 82 76.8
subroutine 63 68 92.6
pod 39 39 100.0
total 687 779 88.1


line stmt bran cond sub pod time code
1             # NOTE: This module is way too large. Please think about adding new
2             # functionality into a P::C::Utils::* module instead.
3              
4             package Perl::Critic::Utils;
5              
6 40     40   130351 use 5.010001;
  40         153  
7 40     40   213 use strict;
  40         70  
  40         823  
8 40     40   182 use warnings;
  40         97  
  40         1051  
9 40     40   4578 use Readonly;
  40         32657  
  40         2134  
10              
11 40     40   319 use Carp qw( confess );
  40         84  
  40         2145  
12 40     40   765 use English qw(-no_match_vars);
  40         3860  
  40         226  
13 40     40   14170 use File::Find qw();
  40         89  
  40         916  
14 40     40   249 use File::Spec qw();
  40         129  
  40         905  
15 40     40   228 use Scalar::Util qw( blessed );
  40         81  
  40         3010  
16 40     40   20904 use B::Keywords qw();
  40         72556  
  40         1156  
17 40     40   16443 use PPI::Token::Quote::Single;
  40         2466677  
  40         1821  
18 40     40   5951 use List::SomeUtils qw(any);
  40         133402  
  40         2641  
19              
20 40     40   19380 use Perl::Critic::Exception::Fatal::Generic qw{ throw_generic };
  40         121  
  40         1170  
21 40     40   19513 use Perl::Critic::Utils::PPI qw< is_ppi_expression_or_generic_statement >;
  40         133  
  40         2515  
22              
23 40     40   289 use Exporter 'import';
  40         87  
  40         249213  
24              
25             our $VERSION = '1.148';
26              
27             #-----------------------------------------------------------------------------
28             # Exportable symbols here.
29              
30             Readonly::Array our @EXPORT_OK => qw(
31             $TRUE
32             $FALSE
33              
34             $POLICY_NAMESPACE
35              
36             $SEVERITY_HIGHEST
37             $SEVERITY_HIGH
38             $SEVERITY_MEDIUM
39             $SEVERITY_LOW
40             $SEVERITY_LOWEST
41             @SEVERITY_NAMES
42              
43             $DEFAULT_VERBOSITY
44             $DEFAULT_VERBOSITY_WITH_FILE_NAME
45              
46             $COLON
47             $COMMA
48             $DQUOTE
49             $EMPTY
50             $EQUAL
51             $FATCOMMA
52             $PERIOD
53             $PIPE
54             $QUOTE
55             $BACKTICK
56             $SCOLON
57             $SPACE
58             $SLASH
59             $BSLASH
60             $LEFT_PAREN
61             $RIGHT_PAREN
62              
63             all_perl_files
64             find_keywords
65             first_arg
66             hashify
67             interpolate
68             is_assignment_operator
69             is_class_name
70             is_function_call
71             is_hash_key
72             is_in_void_context
73             is_included_module_name
74             is_integer
75             is_label_pointer
76             is_method_call
77             is_package_declaration
78             is_perl_bareword
79             is_perl_builtin
80             is_perl_builtin_with_list_context
81             is_perl_builtin_with_multiple_arguments
82             is_perl_builtin_with_no_arguments
83             is_perl_builtin_with_one_argument
84             is_perl_builtin_with_optional_argument
85             is_perl_builtin_with_zero_and_or_one_arguments
86             is_perl_filehandle
87             is_perl_global
88             is_qualified_name
89             is_script
90             is_subroutine_name
91             is_unchecked_call
92             is_valid_numeric_verbosity
93             parse_arg_list
94             policy_long_name
95             policy_short_name
96             precedence_of
97             severity_to_number
98             shebang_line
99             split_nodes_on_comma
100             verbosity_to_format
101             words_from_string
102             );
103              
104              
105             # Note: this is deprecated. This should also violate ProhibitAutomaticExportation,
106             # but at the moment, we aren't smart enough to deal with Readonly variables.
107             Readonly::Array our @EXPORT => @EXPORT_OK;
108              
109              
110             Readonly::Hash our %EXPORT_TAGS => (
111             all => [ @EXPORT_OK ],
112             booleans => [ qw{ $TRUE $FALSE } ],
113             severities => [
114             qw{
115             $SEVERITY_HIGHEST
116             $SEVERITY_HIGH
117             $SEVERITY_MEDIUM
118             $SEVERITY_LOW
119             $SEVERITY_LOWEST
120             @SEVERITY_NAMES
121             }
122             ],
123             characters => [
124             qw{
125             $COLON
126             $COMMA
127             $DQUOTE
128             $EMPTY
129             $EQUAL
130             $FATCOMMA
131             $PERIOD
132             $PIPE
133             $QUOTE
134             $BACKTICK
135             $SCOLON
136             $SPACE
137             $SLASH
138             $BSLASH
139             $LEFT_PAREN
140             $RIGHT_PAREN
141             }
142             ],
143             classification => [
144             qw{
145             is_assignment_operator
146             is_class_name
147             is_function_call
148             is_hash_key
149             is_included_module_name
150             is_integer
151             is_label_pointer
152             is_method_call
153             is_package_declaration
154             is_perl_bareword
155             is_perl_builtin
156             is_perl_filehandle
157             is_perl_global
158             is_perl_builtin_with_list_context
159             is_perl_builtin_with_multiple_arguments
160             is_perl_builtin_with_no_arguments
161             is_perl_builtin_with_one_argument
162             is_perl_builtin_with_optional_argument
163             is_perl_builtin_with_zero_and_or_one_arguments
164             is_qualified_name
165             is_script
166             is_subroutine_name
167             is_unchecked_call
168             is_valid_numeric_verbosity
169             }
170             ],
171             data_conversion => [ qw{ hashify words_from_string interpolate } ],
172             ppi => [ qw{ first_arg parse_arg_list } ],
173             internal_lookup => [ qw{ severity_to_number verbosity_to_format } ],
174             language => [ qw{ precedence_of } ],
175             deprecated => [ qw{ find_keywords } ],
176             );
177              
178             #-----------------------------------------------------------------------------
179              
180             Readonly::Scalar our $POLICY_NAMESPACE => 'Perl::Critic::Policy';
181              
182             #-----------------------------------------------------------------------------
183              
184             Readonly::Scalar our $SEVERITY_HIGHEST => 5;
185             Readonly::Scalar our $SEVERITY_HIGH => 4;
186             Readonly::Scalar our $SEVERITY_MEDIUM => 3;
187             Readonly::Scalar our $SEVERITY_LOW => 2;
188             Readonly::Scalar our $SEVERITY_LOWEST => 1;
189              
190             #-----------------------------------------------------------------------------
191              
192             Readonly::Scalar our $COMMA => q{,};
193             Readonly::Scalar our $EQUAL => q{=};
194             Readonly::Scalar our $FATCOMMA => q{=>};
195             Readonly::Scalar our $COLON => q{:};
196             Readonly::Scalar our $SCOLON => q{;};
197             Readonly::Scalar our $QUOTE => q{'};
198             Readonly::Scalar our $DQUOTE => q{"};
199             Readonly::Scalar our $BACKTICK => q{`};
200             Readonly::Scalar our $PERIOD => q{.};
201             Readonly::Scalar our $PIPE => q{|};
202             Readonly::Scalar our $SPACE => q{ };
203             Readonly::Scalar our $SLASH => q{/};
204             Readonly::Scalar our $BSLASH => q{\\};
205             Readonly::Scalar our $LEFT_PAREN => q{(};
206             Readonly::Scalar our $RIGHT_PAREN => q{)};
207             Readonly::Scalar our $EMPTY => q{};
208             Readonly::Scalar our $TRUE => 1;
209             Readonly::Scalar our $FALSE => 0;
210              
211             #-----------------------------------------------------------------------------
212              
213             #TODO: Should this include punctuations vars?
214              
215              
216              
217             #-----------------------------------------------------------------------------
218             ## no critic (ProhibitNoisyQuotes);
219              
220             Readonly::Hash my %PRECEDENCE_OF => (
221             '->' => 1,
222             '++' => 2,
223             '--' => 2,
224             '**' => 3,
225             '!' => 4,
226             '~' => 4,
227             '\\' => 4,
228             '=~' => 5,
229             '!~' => 5,
230             '*' => 6,
231             '/' => 6,
232             '%' => 6,
233             'x' => 6,
234             '+' => 7,
235             '-' => 7,
236             '.' => 7,
237             '<<' => 8,
238             '>>' => 8,
239             '-R' => 9,
240             '-W' => 9,
241             '-X' => 9,
242             '-r' => 9,
243             '-w' => 9,
244             '-x' => 9,
245             '-e' => 9,
246             '-O' => 9,
247             '-o' => 9,
248             '-z' => 9,
249             '-s' => 9,
250             '-M' => 9,
251             '-A' => 9,
252             '-C' => 9,
253             '-S' => 9,
254             '-c' => 9,
255             '-b' => 9,
256             '-f' => 9,
257             '-d' => 9,
258             '-p' => 9,
259             '-l' => 9,
260             '-u' => 9,
261             '-g' => 9,
262             '-k' => 9,
263             '-t' => 9,
264             '-T' => 9,
265             '-B' => 9,
266             '<' => 10,
267             '>' => 10,
268             '<=' => 10,
269             '>=' => 10,
270             'lt' => 10,
271             'gt' => 10,
272             'le' => 10,
273             'ge' => 10,
274             '==' => 11,
275             '!=' => 11,
276             '<=>' => 11,
277             'eq' => 11,
278             'ne' => 11,
279             'cmp' => 11,
280             '~~' => 11,
281             '&' => 12,
282             '|' => 13,
283             '^' => 13,
284             '&&' => 14,
285             '//' => 15,
286             '||' => 15,
287             '..' => 16,
288             '...' => 17,
289             '?' => 18,
290             ':' => 18,
291             '=' => 19,
292             '+=' => 19,
293             '-=' => 19,
294             '*=' => 19,
295             '/=' => 19,
296             '%=' => 19,
297             '||=' => 19,
298             '&&=' => 19,
299             '|=' => 19,
300             '&=' => 19,
301             '**=' => 19,
302             'x=' => 19,
303             '.=' => 19,
304             '^=' => 19,
305             '<<=' => 19,
306             '>>=' => 19,
307             '//=' => 19,
308             ',' => 20,
309             '=>' => 20,
310             'not' => 22,
311             'and' => 23,
312             'or' => 24,
313             'xor' => 24,
314             );
315              
316             ## use critic
317              
318             Readonly::Scalar my $MIN_PRECEDENCE_TO_TERMINATE_PARENLESS_ARG_LIST =>
319             precedence_of( 'not' );
320              
321             #-----------------------------------------------------------------------------
322              
323             sub hashify { ## no critic (ArgUnpacking)
324 39351     39351 1 94389 return map { $_ => 1 } @_;
  614488         1143379  
325             }
326              
327             #-----------------------------------------------------------------------------
328              
329             sub interpolate {
330 959     959 1 1821 my ( $literal ) = @_;
331 959   33     53294 return eval "\"$literal\"" || confess $EVAL_ERROR; ## no critic (StringyEval);
332             }
333              
334             #-----------------------------------------------------------------------------
335              
336             sub find_keywords {
337 5     5 1 8902 my ( $doc, $keyword ) = @_;
338 5         21 my $nodes_ref = $doc->find('PPI::Token::Word');
339 5 100       220 return if !$nodes_ref;
340 4         7 my @matches = grep { $_ eq $keyword } @{$nodes_ref};
  11         105  
  4         10  
341 4 100       75 return @matches ? \@matches : undef;
342             }
343              
344             #-----------------------------------------------------------------------------
345              
346             sub _name_for_sub_or_stringified_element {
347 3765     3765   5164 my $elem = shift;
348              
349 3765 100 100     20586 if ( blessed $elem and $elem->isa('PPI::Statement::Sub') ) {
350 62         168 return $elem->name();
351             }
352              
353 3703         8596 return "$elem";
354             }
355              
356             #-----------------------------------------------------------------------------
357             ## no critic (ProhibitPackageVars)
358              
359             Readonly::Hash my %BUILTINS => hashify( @B::Keywords::Functions );
360              
361             sub is_perl_builtin {
362 415     415 1 2398 my $elem = shift;
363 415 50       1161 return if !$elem;
364              
365 415         917 return exists $BUILTINS{ _name_for_sub_or_stringified_element($elem) };
366             }
367              
368             #-----------------------------------------------------------------------------
369              
370             Readonly::Hash my %BAREWORDS => hashify(
371             @B::Keywords::Barewords,
372             @B::Keywords::BarewordsExtra,
373             );
374              
375             sub is_perl_bareword {
376 1691     1691 1 5341 my $elem = shift;
377 1691 50       4004 return if !$elem;
378              
379 1691         3608 return exists $BAREWORDS{ _name_for_sub_or_stringified_element($elem) };
380             }
381              
382             #-----------------------------------------------------------------------------
383              
384             sub _build_globals_without_sigils {
385             # B::Keywords as of 1.08 forgot $\
386             my @globals =
387 40     40   228 map { substr $_, 1 }
  5960         10045  
388             @B::Keywords::Arrays,
389             @B::Keywords::Hashes,
390             @B::Keywords::Scalars,
391             '$\\'; ## no critic (RequireInterpolationOfMetachars)
392              
393             # Not all of these have sigils
394 40         189 foreach my $filehandle (@B::Keywords::Filehandles) {
395 360         790 (my $stripped = $filehandle) =~ s< \A [*] ><>xms;
396 360         830 push @globals, $stripped;
397             }
398              
399 40         1556 return @globals;
400             }
401              
402             Readonly::Array my @GLOBALS_WITHOUT_SIGILS => _build_globals_without_sigils();
403              
404             Readonly::Hash my %GLOBALS => hashify( @GLOBALS_WITHOUT_SIGILS );
405              
406             sub is_perl_global {
407 853     853 1 3260 my $elem = shift;
408 853 50       2705 return if !$elem;
409 853         1972 my $var_name = "$elem"; #Convert Token::Symbol to string
410 853         4828 $var_name =~ s{\A [\$@%*] }{}xms; #Chop off the sigil
411 853         4256 return exists $GLOBALS{ $var_name };
412             }
413              
414             #-----------------------------------------------------------------------------
415              
416             Readonly::Hash my %FILEHANDLES => hashify( @B::Keywords::Filehandles );
417              
418             sub is_perl_filehandle {
419 1580     1580 1 2524 my $elem = shift;
420 1580 50       4318 return if !$elem;
421              
422 1580         2812 return exists $FILEHANDLES{ _name_for_sub_or_stringified_element($elem) };
423             }
424              
425             ## use critic
426             #-----------------------------------------------------------------------------
427              
428             # egrep '=item.*LIST' perlfunc.pod
429             Readonly::Hash my %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT =>
430             hashify(
431             qw{
432             chmod
433             chown
434             die
435             exec
436             formline
437             grep
438             import
439             join
440             kill
441             map
442             no
443             open
444             pack
445             print
446             printf
447             push
448             reverse
449             say
450             sort
451             splice
452             sprintf
453             syscall
454             system
455             tie
456             unlink
457             unshift
458             use
459             utime
460             warn
461             },
462             );
463              
464             sub is_perl_builtin_with_list_context {
465 0     0 1 0 my $elem = shift;
466              
467             return
468             exists
469             $BUILTINS_WHICH_PROVIDE_LIST_CONTEXT{
470 0         0 _name_for_sub_or_stringified_element($elem)
471             };
472             }
473              
474             #-----------------------------------------------------------------------------
475              
476             # egrep '=item.*[A-Z],' perlfunc.pod
477             Readonly::Hash my %BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS =>
478             hashify(
479             qw{
480             accept
481             atan2
482             bind
483             binmode
484             bless
485             connect
486             crypt
487             dbmopen
488             fcntl
489             flock
490             gethostbyaddr
491             getnetbyaddr
492             getpriority
493             getservbyname
494             getservbyport
495             getsockopt
496             index
497             ioctl
498             link
499             listen
500             mkdir
501             msgctl
502             msgget
503             msgrcv
504             msgsnd
505             open
506             opendir
507             pipe
508             read
509             recv
510             rename
511             rindex
512             seek
513             seekdir
514             select
515             semctl
516             semget
517             semop
518             send
519             setpgrp
520             setpriority
521             setsockopt
522             shmctl
523             shmget
524             shmread
525             shmwrite
526             shutdown
527             socket
528             socketpair
529             splice
530             split
531             substr
532             symlink
533             sysopen
534             sysread
535             sysseek
536             syswrite
537             truncate
538             unpack
539             vec
540             waitpid
541             },
542             keys %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT
543             );
544              
545             sub is_perl_builtin_with_multiple_arguments {
546 17     17 1 501 my $elem = shift;
547              
548             return
549             exists
550             $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{
551 17         56 _name_for_sub_or_stringified_element($elem)
552             };
553             }
554              
555             #-----------------------------------------------------------------------------
556              
557             Readonly::Hash my %BUILTINS_WHICH_TAKE_NO_ARGUMENTS =>
558             hashify(
559             qw{
560             endgrent
561             endhostent
562             endnetent
563             endprotoent
564             endpwent
565             endservent
566             fork
567             format
568             getgrent
569             gethostent
570             getlogin
571             getnetent
572             getppid
573             getprotoent
574             getpwent
575             getservent
576             setgrent
577             setpwent
578             split
579             time
580             times
581             wait
582             wantarray
583             }
584             );
585              
586             sub is_perl_builtin_with_no_arguments {
587 0     0 1 0 my $elem = shift;
588              
589             return
590             exists
591             $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{
592 0         0 _name_for_sub_or_stringified_element($elem)
593             };
594             }
595              
596             #-----------------------------------------------------------------------------
597              
598             Readonly::Hash my %BUILTINS_WHICH_TAKE_ONE_ARGUMENT =>
599             hashify(
600             qw{
601             closedir
602             dbmclose
603             delete
604             each
605             exists
606             fileno
607             getgrgid
608             getgrnam
609             gethostbyname
610             getnetbyname
611             getpeername
612             getpgrp
613             getprotobyname
614             getprotobynumber
615             getpwnam
616             getpwuid
617             getsockname
618             goto
619             keys
620             local
621             prototype
622             readdir
623             readline
624             readpipe
625             rewinddir
626             scalar
627             sethostent
628             setnetent
629             setprotoent
630             setservent
631             telldir
632             tied
633             untie
634             values
635             }
636             );
637              
638             sub is_perl_builtin_with_one_argument {
639 0     0 1 0 my $elem = shift;
640              
641             return
642             exists
643             $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{
644 0         0 _name_for_sub_or_stringified_element($elem)
645             };
646             }
647              
648             #-----------------------------------------------------------------------------
649              
650             ## no critic (ProhibitPackageVars)
651             Readonly::Hash my %BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT =>
652             hashify(
653             grep { not exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $_ } }
654             grep { not exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $_ } }
655             grep { not exists $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{ $_ } }
656             @B::Keywords::Functions
657             );
658             ## use critic
659              
660             sub is_perl_builtin_with_optional_argument {
661 0     0 1 0 my $elem = shift;
662              
663             return
664             exists
665             $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{
666 0         0 _name_for_sub_or_stringified_element($elem)
667             };
668             }
669              
670             #-----------------------------------------------------------------------------
671              
672             sub is_perl_builtin_with_zero_and_or_one_arguments {
673 62     62 1 114 my $elem = shift;
674              
675 62 50       210 return if not $elem;
676              
677 62         181 my $name = _name_for_sub_or_stringified_element($elem);
678              
679             return (
680             exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $name }
681             or exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $name }
682 62   66     585 or exists $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{ $name }
683             );
684             }
685              
686             #-----------------------------------------------------------------------------
687              
688             sub is_qualified_name {
689 0     0 1 0 my $name = shift;
690              
691 0 0       0 return if not $name;
692              
693 0         0 return index ( $name, q{::} ) >= 0;
694             }
695              
696             #-----------------------------------------------------------------------------
697              
698             sub precedence_of {
699 612     612 1 1687 my $elem = shift;
700 612 50       1889 return if !$elem;
701 612 100       2783 return $PRECEDENCE_OF{ ref $elem ? "$elem" : $elem };
702             }
703              
704             #-----------------------------------------------------------------------------
705              
706             sub is_hash_key {
707 4499     4499 1 20573 my $elem = shift;
708 4499 50       11683 return if !$elem;
709              
710             #If followed by an argument list, then it's a function call, not a literal.
711 4499         10892 my $sib = $elem->snext_sibling();
712 4499 100 100     114524 return if $sib && $sib->isa('PPI::Structure::List');
713              
714             #Check curly-brace style: $hash{foo} = bar;
715 3913         9444 my $parent = $elem->parent();
716 3913 50       19410 return if !$parent;
717 3913         8565 my $grandparent = $parent->parent();
718 3913 50       17041 return if !$grandparent;
719 3913 100       12381 return 1 if $grandparent->isa('PPI::Structure::Subscript');
720              
721              
722             #Check declarative style: %hash = (foo => bar);
723 3863 100 100     19800 return 1 if $sib && $sib->isa('PPI::Token::Operator') && $sib eq '=>';
      100        
724              
725 3841         12514 return;
726             }
727              
728             #-----------------------------------------------------------------------------
729              
730             sub is_included_module_name {
731 1788     1788 1 2865 my $elem = shift;
732 1788 50       4277 return if !$elem;
733 1788         3657 my $stmnt = $elem->statement();
734 1788 50       22369 return if !$stmnt;
735 1788 100       7660 return if !$stmnt->isa('PPI::Statement::Include');
736 126         430 return $stmnt->schild(1) == $elem;
737             }
738              
739             #-----------------------------------------------------------------------------
740              
741             sub is_integer {
742 9659     9659 1 16463 my ($value) = @_;
743 9659 50       21713 return 0 if not defined $value;
744              
745 9659         59113 return $value =~ m{ \A [+-]? \d+ \z }xms;
746             }
747              
748             #-----------------------------------------------------------------------------
749              
750             sub is_label_pointer {
751 1493     1493 1 2208 my $elem = shift;
752 1493 50       4113 return if !$elem;
753              
754 1493         3149 my $statement = $elem->statement();
755 1493 50       20118 return if !$statement;
756 1493 100       6325 return if !$statement->isa('PPI::Statement::Break');
757              
758 30         118 my $psib = $elem->sprevious_sibling();
759 30 100       658 return if !$psib;
760              
761 8         40 state $redirectors = { hashify( qw( redo goto next last ) ) };
762 8         27 return exists $redirectors->{$psib};
763             }
764              
765             #-----------------------------------------------------------------------------
766              
767             sub is_method_call {
768 2142     2142 1 4444 my $elem = shift;
769 2142 50       5193 return if !$elem;
770              
771 2142         4969 return _is_dereference_operator( $elem->sprevious_sibling() );
772             }
773              
774             #-----------------------------------------------------------------------------
775              
776             sub is_class_name {
777 1551     1551 1 2345 my $elem = shift;
778 1551 50       4067 return if !$elem;
779              
780 1551   66     3858 return _is_dereference_operator( $elem->snext_sibling() )
781             && !_is_dereference_operator( $elem->sprevious_sibling() );
782             }
783              
784             #-----------------------------------------------------------------------------
785              
786             sub _is_dereference_operator {
787 3706     3706   76840 my $elem = shift;
788 3706 100       10929 return if !$elem;
789              
790 2073   100     9689 return $elem->isa('PPI::Token::Operator') && $elem eq q{->};
791             }
792              
793             #-----------------------------------------------------------------------------
794              
795             sub is_package_declaration {
796 1686     1686 1 2669 my $elem = shift;
797 1686 50       4236 return if !$elem;
798 1686         4269 my $stmnt = $elem->statement();
799 1686 50       26052 return if !$stmnt;
800 1686 50       7571 return if !$stmnt->isa('PPI::Statement::Package');
801 0         0 return $stmnt->schild(1) == $elem;
802             }
803              
804             #-----------------------------------------------------------------------------
805              
806             sub is_subroutine_name {
807 1724     1724 1 2985 my $elem = shift;
808 1724 50       4576 return if !$elem;
809 1724         3788 my $sib = $elem->sprevious_sibling();
810 1724 100       33268 return if !$sib;
811 435         1147 my $stmnt = $elem->statement();
812 435 50       6374 return if !$stmnt;
813 435   66     2106 return $stmnt->isa('PPI::Statement::Sub') && $sib eq 'sub';
814             }
815              
816             #-----------------------------------------------------------------------------
817              
818             sub is_function_call {
819 1653 50   1653 1 7761 my $elem = shift or return;
820              
821 1653 100       3783 return if is_perl_bareword($elem);
822 1580 50       21362 return if is_perl_filehandle($elem);
823 1580 50       17342 return if is_package_declaration($elem);
824 1580 100       3468 return if is_included_module_name($elem);
825 1576 100       6150 return if is_method_call($elem);
826 1551 100       6314 return if is_class_name($elem);
827 1538 100       7076 return if is_subroutine_name($elem);
828 1493 100       3017 return if is_label_pointer($elem);
829 1492 100       3242 return if is_hash_key($elem);
830              
831 1462         8007 return 1;
832             }
833              
834             #-----------------------------------------------------------------------------
835              
836             sub is_script {
837 8     8 1 9381 my $doc = shift;
838              
839 8         464 warnings::warnif(
840             'deprecated',
841             'Perl::Critic::Utils::is_script($doc) deprecated, use $doc->is_program() instead.', ## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
842             );
843              
844 8 50 33     85 return $doc->is_program()
845             if blessed($doc) && $doc->isa('Perl::Critic::Document');
846              
847 8 100       27 return 1 if shebang_line($doc);
848 3 100       21 return 1 if _is_PL_file($doc);
849 2         16 return 0;
850             }
851              
852             #-----------------------------------------------------------------------------
853              
854             sub _is_PL_file { ## no critic (NamingConventions::Capitalization)
855 3     3   10 my ($doc) = @_;
856 3 50       17 return if not $doc->can('filename');
857 3   100     9 my $filename = $doc->filename() || return;
858 1 50       18 return 1 if $filename =~ m/[.] PL \z/xms;
859 0         0 return 0;
860             }
861              
862             #-----------------------------------------------------------------------------
863              
864             sub is_in_void_context {
865 65     65 1 118 my ($token) = @_;
866              
867             # If part of a collective, can't be void.
868 65 100       140 return if $token->sprevious_sibling();
869              
870 46         849 my $parent = $token->statement()->parent();
871 46 50       745 if ($parent) {
872 46 100       143 return if $parent->isa('PPI::Structure::List');
873 34 50       125 return if $parent->isa('PPI::Structure::For');
874 34 100       120 return if $parent->isa('PPI::Structure::Condition');
875 30 100       96 return if $parent->isa('PPI::Structure::Constructor');
876 26 100       88 return if $parent->isa('PPI::Structure::Subscript');
877              
878             # If it's in a block and not the last statement then it's in void.
879 24 100 100     106 return 1 if
880             $parent->isa('PPI::Structure::Block')
881             and $token->statement()->snext_sibling();
882              
883 22         382 my $grand_parent = $parent->parent();
884 22 100       102 if ($grand_parent) {
885             return if
886 10 100 66     70 $parent->isa('PPI::Structure::Block')
887             and not $grand_parent->isa('PPI::Statement::Compound');
888             }
889             }
890              
891 20         66 return $TRUE;
892             }
893              
894             #-----------------------------------------------------------------------------
895              
896             sub policy_long_name {
897 29505     29505 1 51911 my ( $policy_name ) = @_;
898 29505 100       131870 if ( $policy_name !~ m{ \A $POLICY_NAMESPACE }xms ) {
899 3102         8966 $policy_name = $POLICY_NAMESPACE . q{::} . $policy_name;
900             }
901 29505         90017 return $policy_name;
902             }
903              
904             #-----------------------------------------------------------------------------
905              
906             sub policy_short_name {
907 176150     176150 1 290398 my ( $policy_name ) = @_;
908 176150         746576 $policy_name =~ s{\A $POLICY_NAMESPACE ::}{}xms;
909 176150         539859 return $policy_name;
910             }
911              
912             #-----------------------------------------------------------------------------
913              
914             sub first_arg {
915 231     231 1 6936 my $elem = shift;
916 231         527 my $sib = $elem->snext_sibling();
917 231 100       5027 return if !$sib;
918              
919 225 100       873 if ( $sib->isa('PPI::Structure::List') ) {
920              
921 15         146 my $expr = $sib->schild(0);
922 15 100       207 return if !$expr;
923 9 50       58 return $expr->isa('PPI::Statement') ? $expr->schild(0) : $expr;
924             }
925              
926 210         666 return $sib;
927             }
928              
929             #-----------------------------------------------------------------------------
930              
931             sub parse_arg_list {
932 445     445 1 15335 my $elem = shift;
933 445         1107 my $sib = $elem->snext_sibling();
934 445 100       9975 return if !$sib;
935              
936 441 100       1575 if ( $sib->isa('PPI::Structure::List') ) {
937              
938             #Pull siblings from list
939 191         1596 my @list_contents = $sib->schildren();
940 191 100       2002 return if not @list_contents;
941              
942 189         322 my @list_expressions;
943 189         431 foreach my $item (@list_contents) {
944 189 50       591 if (
945             is_ppi_expression_or_generic_statement($item)
946             ) {
947 189         531 push
948             @list_expressions,
949             split_nodes_on_comma( $item->schildren() );
950             }
951             else {
952 0         0 push @list_expressions, $item;
953             }
954             }
955              
956 189         634 return @list_expressions;
957             }
958             else {
959              
960             #Gather up remaining nodes in the statement
961 250         470 my $iter = $elem;
962 250         521 my @arg_list = ();
963              
964 250         622 while ($iter = $iter->snext_sibling() ) {
965 1071 100 66     27017 last if $iter->isa('PPI::Token::Structure') and $iter eq $SCOLON;
966 894 100 100     3002 last if $iter->isa('PPI::Token::Operator')
967             and $MIN_PRECEDENCE_TO_TERMINATE_PARENLESS_ARG_LIST <=
968             precedence_of( $iter );
969 829         5340 push @arg_list, $iter;
970             }
971 250         4233 return split_nodes_on_comma( @arg_list );
972             }
973             }
974              
975             #---------------------------------
976              
977             sub split_nodes_on_comma {
978 475     475 1 3019 my @nodes = @_;
979              
980 475         782 my $i = 0;
981 475         714 my @node_stacks;
982 475         991 for my $node (@nodes) {
983 1680 100 100     8250 if (
    100 100        
984             $node->isa('PPI::Token::Operator')
985             and ($node eq $COMMA or $node eq $FATCOMMA)
986             ) {
987 547 100       8179 if (@node_stacks) {
988 546         809 $i++; #Move forward to next 'node stack'
989             }
990 547         1035 next;
991             } elsif ( $node->isa('PPI::Token::QuoteLike::Words' )) {
992 25         62 my $section = $node->{sections}->[0];
993 25         74 my @words = words_from_string(substr $node->content, $section->{position}, $section->{size});
994 25         142 my $loc = $node->location;
995 25         373 for my $word (@words) {
996 28         143 my $token = PPI::Token::Quote::Single->new(q{'} . $word . q{'});
997 28         461 $token->{_location} = $loc;
998 28         52 push @{ $node_stacks[$i++] }, $token;
  28         143  
999             }
1000 25         65 next;
1001             }
1002 1108         1794 push @{ $node_stacks[$i] }, $node;
  1108         2682  
1003             }
1004 475         1789 return @node_stacks;
1005             }
1006              
1007             #-----------------------------------------------------------------------------
1008              
1009             # XXX: You must keep the regular expressions in extras/perlcritic.el in sync
1010             # if you change these.
1011             Readonly::Hash my %FORMAT_OF => (
1012             1 => "%f:%l:%c:%m\n",
1013             2 => "%f: (%l:%c) %m\n",
1014             3 => "%m at %f line %l\n",
1015             4 => "%m at line %l, column %c. %e. (Severity: %s)\n",
1016             5 => "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
1017             6 => "%m at line %l, near '%r'. (Severity: %s)\n",
1018             7 => "%f: %m at line %l near '%r'. (Severity: %s)\n",
1019             8 => "[%p] %m at line %l, column %c. (Severity: %s)\n",
1020             9 => "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
1021             10 => "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
1022             11 => "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n",
1023             );
1024              
1025             Readonly::Scalar our $DEFAULT_VERBOSITY => 4;
1026             Readonly::Scalar our $DEFAULT_VERBOSITY_WITH_FILE_NAME => 5;
1027             Readonly::Scalar my $DEFAULT_FORMAT => $FORMAT_OF{$DEFAULT_VERBOSITY};
1028              
1029             sub is_valid_numeric_verbosity {
1030 2921     2921 1 6793 my ($verbosity) = @_;
1031              
1032 2921         14445 return exists $FORMAT_OF{$verbosity};
1033             }
1034              
1035             sub verbosity_to_format {
1036 20     20 1 46 my ($verbosity) = @_;
1037 20 100       62 return $DEFAULT_FORMAT if not defined $verbosity;
1038 19 100 66     47 return $FORMAT_OF{abs int $verbosity} || $DEFAULT_FORMAT if is_integer($verbosity);
1039 17         55 return interpolate( $verbosity ); #Otherwise, treat as a format spec
1040             }
1041              
1042             #-----------------------------------------------------------------------------
1043              
1044             Readonly::Hash my %SEVERITY_NUMBER_OF => (
1045             gentle => 5,
1046             stern => 4,
1047             harsh => 3,
1048             cruel => 2,
1049             brutal => 1,
1050             );
1051              
1052             Readonly::Array our @SEVERITY_NAMES => #This is exported!
1053             sort
1054             { $SEVERITY_NUMBER_OF{$a} <=> $SEVERITY_NUMBER_OF{$b} }
1055             keys %SEVERITY_NUMBER_OF;
1056              
1057             sub severity_to_number {
1058 871     871 1 1742 my ($severity) = @_;
1059 871 100       1935 return _normalize_severity( $severity ) if is_integer( $severity );
1060 6         53 my $severity_number = $SEVERITY_NUMBER_OF{lc $severity};
1061              
1062 6 100       71 if ( not defined $severity_number ) {
1063 1         8 throw_generic qq{Invalid severity: "$severity"};
1064             }
1065              
1066 5         22 return $severity_number;
1067             }
1068              
1069             sub _normalize_severity {
1070 865   50 865   2280 my $s = shift || return $SEVERITY_HIGHEST;
1071 865 50       2231 $s = $s > $SEVERITY_HIGHEST ? $SEVERITY_HIGHEST : $s;
1072 865 50       2051 $s = $s < $SEVERITY_LOWEST ? $SEVERITY_LOWEST : $s;
1073 865         2243 return $s;
1074             }
1075              
1076             #-----------------------------------------------------------------------------
1077              
1078             Readonly::Array my @SKIP_DIR => qw( CVS RCS .svn _darcs {arch} .bzr .cdv .git .hg .pc _build blib );
1079             Readonly::Hash my %SKIP_DIR => hashify( @SKIP_DIR );
1080              
1081             sub all_perl_files {
1082 1     1 1 32 my @arg = @_;
1083 1         2 my @code_files;
1084              
1085             # The old code did a breadth-first search (documentation to the
1086             # contrary notwithstanding,) whereas File::Find does depth-first. So
1087             # there appears to be no way to use File::Find without changing the
1088             # order in which the files are returned.
1089             File::Find::find( {
1090             wanted => sub {
1091 163 50 66 163   4061 if ( -d && $SKIP_DIR{$_} ) {
    100 66        
      66        
1092 0         0 $File::Find::prune = 1;
1093             } elsif ( -f && ! _is_backup( $_ ) && _is_perl( $_ ) ) {
1094 145         328 push @code_files, $File::Find::name;
1095             }
1096 163         3206 return;
1097             },
1098 1         167 untaint => 1,
1099             },
1100             @arg,
1101             );
1102              
1103             # Use File::Spec->abs2rel() to get rid of leading './' or other OS
1104             # equivalent on relative filenames.
1105             # Use map {} to get rid of leading './', or other OS equivalent
1106 1 50       11 return ( map { File::Spec->file_name_is_absolute( $_ ) ?
  145         9355  
1107             $_ : File::Spec->abs2rel( $_ ) } @code_files );
1108             }
1109              
1110              
1111             #-----------------------------------------------------------------------------
1112             # Decide if it's some sort of backup file
1113              
1114             sub _is_backup {
1115 152     152   2280 my ($file) = @_;
1116 152 100       724 return 1 if $file =~ m{ (?: [.] swp | [.] bak | ~ ) \z}xms;
1117 149 100       298 return 1 if $file =~ m{ \A [#] .+ [#] \z}xms;
1118 148         495 return;
1119             }
1120              
1121             #-----------------------------------------------------------------------------
1122             # Returns true if the argument ends with a perl-ish file
1123             # extension, or if it has a shebang-line containing 'perl' This
1124             # subroutine was also poached from Test::Perl::Critic
1125              
1126             sub _is_perl {
1127 165     165   13333 my ($file) = @_;
1128              
1129             #Check filename extensions
1130 165 100       847 return 1 if $file =~ m{ [.] (?: PL | p[lm] | psgi | t ) \z}xms;
1131              
1132             #Check for shebang
1133 15 100       662 open my $fh, '<', $file or return;
1134 9         146 my $first = <$fh>;
1135 9 50       106 close $fh or throw_generic "unable to close $file: $OS_ERROR";
1136              
1137 9 100 66     131 return 1 if defined $first && ( $first =~ m{ \A [#]!.*perl }xms );
1138 3         32 return;
1139             }
1140              
1141             #-----------------------------------------------------------------------------
1142              
1143             sub shebang_line {
1144 2797     2797 1 8712 my $doc = shift;
1145 2797         13881 my $first_element = $doc->first_element();
1146 2797 50       18131 return if not $first_element;
1147 2797 100       16781 return if not $first_element->isa('PPI::Token::Comment');
1148 47         236 my $location = $first_element->location();
1149 47 50       1620 return if !$location;
1150             # The shebang must be the first two characters in the file, according to
1151             # http://en.wikipedia.org/wiki/Shebang_(Unix)
1152 47 50       175 return if $location->[0] != 1; # line number
1153 47 50       158 return if $location->[1] != 1; # column number
1154 47         137 my $shebang = $first_element->content;
1155 47 100       358 return if $shebang !~ m{ \A [#]! }xms;
1156 27         162 return $shebang;
1157             }
1158              
1159             #-----------------------------------------------------------------------------
1160              
1161             sub words_from_string {
1162 37172     37172 1 66146 my $str = shift;
1163              
1164 37172         126384 return split q{ }, $str; # This must be a literal space, not $SPACE
1165             }
1166              
1167             #-----------------------------------------------------------------------------
1168              
1169             Readonly::Hash my %ASSIGNMENT_OPERATORS => hashify( qw( = **= += -= .= *= /= %= x= &= |= ^= <<= >>= &&= ||= //= ) );
1170              
1171             sub is_assignment_operator {
1172 257     257 1 16343 my $elem = shift;
1173              
1174 257         995 return $ASSIGNMENT_OPERATORS{ $elem };
1175             }
1176              
1177             #-----------------------------------------------------------------------------
1178              
1179             sub is_unchecked_call {
1180 167     167 1 5550 my ( $elem, $autodie_modules ) = @_;
1181              
1182 167 100       362 return if not is_function_call( $elem );
1183              
1184             # check to see if there's an '=' or 'unless' or something before this.
1185 165 100       449 if( my $sib = $elem->sprevious_sibling() ){
1186 68 50       2045 return if $sib;
1187             }
1188              
1189              
1190 97 50       1877 if( my $statement = $elem->statement() ){
1191              
1192             # "open or die" is OK.
1193             # We can't check snext_sibling for 'or' since the next siblings are an
1194             # unknown number of arguments to the system call. Instead, check all of
1195             # the elements to this statement to see if we find 'or' or '||'.
1196              
1197             my $or_operators = sub {
1198 657     657   6927 my (undef, $elem) = @_; ## no critic(Variables::ProhibitReusedNames)
1199 657 100       2103 return if not $elem->isa('PPI::Token::Operator');
1200 68 100 100     249 return if $elem ne q{or} && $elem ne q{||};
1201 27         618 return 1;
1202 97         1635 };
1203              
1204 97 100       350 return if $statement->find( $or_operators );
1205              
1206              
1207 70 50       1300 if( my $parent = $elem->statement()->parent() ){
1208              
1209             # Check if we're in an if( open ) {good} else {bad} condition
1210 70 100       1445 return if $parent->isa('PPI::Structure::Condition');
1211              
1212             # Return val could be captured in data structure and checked later
1213 66 50       315 return if $parent->isa('PPI::Structure::Constructor');
1214              
1215             # "die if not ( open() )" - It's in list context.
1216 66 100       438 if ( $parent->isa('PPI::Structure::List') ) {
1217 6 100       51 if( my $uncle = $parent->sprevious_sibling() ){
1218 1 50       46 return if $uncle;
1219             }
1220             }
1221             }
1222             }
1223              
1224 65 100       308 return if _is_fatal($elem, $autodie_modules);
1225              
1226             # Otherwise, return. this system call is unchecked.
1227 30         165 return 1;
1228             }
1229              
1230             # Based upon autodie 2.10.
1231             Readonly::Hash my %AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP => (
1232             # Map builtins to themselves.
1233             (
1234             map { $_ => { hashify( $_ ) } }
1235             qw<
1236             accept bind binmode chdir chmod close closedir connect
1237             dbmclose dbmopen exec fcntl fileno flock fork getsockopt ioctl
1238             link listen mkdir msgctl msgget msgrcv msgsnd open opendir
1239             pipe read readlink recv rename rmdir seek semctl semget semop
1240             send setsockopt shmctl shmget shmread shutdown socketpair
1241             symlink sysopen sysread sysseek system syswrite truncate umask
1242             unlink
1243             >
1244             ),
1245              
1246             # Generate these using tools/dump-autodie-tag-contents
1247             ':threads' => { hashify( qw< fork > ) },
1248             ':system' => { hashify( qw< exec system > ) },
1249             ':dbm' => { hashify( qw< dbmclose dbmopen > ) },
1250             ':semaphore' => { hashify( qw< semctl semget semop > ) },
1251             ':shm' => { hashify( qw< shmctl shmget shmread > ) },
1252             ':msg' => { hashify( qw< msgctl msgget msgrcv msgsnd > ) },
1253             ':file' => {
1254             hashify(
1255             qw<
1256             binmode chmod close fcntl fileno flock ioctl open sysopen
1257             truncate
1258             >
1259             )
1260             },
1261             ':filesys' => {
1262             hashify(
1263             qw<
1264             chdir closedir link mkdir opendir readlink rename rmdir
1265             symlink umask unlink
1266             >
1267             )
1268             },
1269             ':ipc' => {
1270             hashify(
1271             qw<
1272             msgctl msgget msgrcv msgsnd pipe semctl semget semop shmctl
1273             shmget shmread
1274             >
1275             )
1276             },
1277             ':socket' => {
1278             hashify(
1279             qw<
1280             accept bind connect getsockopt listen recv send setsockopt
1281             shutdown socketpair
1282             >
1283             )
1284             },
1285             ':io' => {
1286             hashify(
1287             qw<
1288             accept bind binmode chdir chmod close closedir connect
1289             dbmclose dbmopen fcntl fileno flock getsockopt ioctl link
1290             listen mkdir msgctl msgget msgrcv msgsnd open opendir pipe
1291             read readlink recv rename rmdir seek semctl semget semop send
1292             setsockopt shmctl shmget shmread shutdown socketpair symlink
1293             sysopen sysread sysseek syswrite truncate umask unlink
1294             >
1295             )
1296             },
1297             ':default' => {
1298             hashify(
1299             qw<
1300             accept bind binmode chdir chmod close closedir connect
1301             dbmclose dbmopen fcntl fileno flock fork getsockopt ioctl link
1302             listen mkdir msgctl msgget msgrcv msgsnd open opendir pipe
1303             read readlink recv rename rmdir seek semctl semget semop send
1304             setsockopt shmctl shmget shmread shutdown socketpair symlink
1305             sysopen sysread sysseek syswrite truncate umask unlink
1306             >
1307             )
1308             },
1309             ':all' => {
1310             hashify(
1311             qw<
1312             accept bind binmode chdir chmod close closedir connect
1313             dbmclose dbmopen exec fcntl fileno flock fork getsockopt ioctl
1314             link listen mkdir msgctl msgget msgrcv msgsnd open opendir
1315             pipe read readlink recv rename rmdir seek semctl semget semop
1316             send setsockopt shmctl shmget shmread shutdown socketpair
1317             symlink sysopen sysread sysseek system syswrite truncate umask
1318             unlink
1319             >
1320             )
1321             },
1322             );
1323              
1324             sub _is_fatal {
1325 65     65   140 my ( $elem, $autodie_modules ) = @_;
1326              
1327 65         180 my $top = $elem->top();
1328 65 50       924 return if not $top->isa('PPI::Document');
1329              
1330 65         183 my $includes = $top->find('PPI::Statement::Include');
1331 65 100       47468 return if not $includes;
1332              
1333 45         107 for my $include (@{$includes}) {
  45         129  
1334 49 100       299 next if 'use' ne $include->type();
1335              
1336 47 100 100     1321 if ('Fatal' eq $include->module()) {
    100          
    100          
1337 18         506 my @args = parse_arg_list($include->schild(1));
1338 18 50   18   150 return $TRUE if any { $_->[0]->isa('PPI::Token::Quote') && $elem eq $_->[0]->string() } @args;
  18 100       132  
1339             }
1340             elsif ('Fatal::Exception' eq $include->module()) {
1341 6         298 my @args = parse_arg_list($include->schild(1));
1342 6         23 shift @args; # skip exception class name
1343 6 50   6   53 return $TRUE if any { $_->[0]->isa('PPI::Token::Quote') && $elem eq $_->[0]->string() } @args;
  6 50       60  
1344             }
1345 5 50   5   19 elsif ($include->pragma eq 'autodie' || any {$_ eq $include->module()} @{$autodie_modules || []}) {
  5         469  
1346 19         1472 return _is_covered_by_autodie($elem, $include);
1347             }
1348             }
1349              
1350 6         227 return;
1351             }
1352              
1353             sub _is_covered_by_autodie {
1354 19     19   53 my ($elem, $include) = @_;
1355              
1356 19         53 my $autodie = $include->schild(1);
1357 19         299 my @args = parse_arg_list($autodie);
1358 19         61 my $first_arg = first_arg($autodie);
1359              
1360             # The first argument to any `use` pragma could be a version number.
1361             # If so, then we just discard it. We only want the arguments after it.
1362 19 100 66     150 if ($first_arg and $first_arg->isa('PPI::Token::Number')){ shift @args };
  2         5  
1363              
1364 19 100       66 if (@args) {
1365 9         48 my $elem_content = $elem->content();
1366 9         65 foreach my $arg (@args) {
1367             my $builtins =
1368             $AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP{
1369 10         51 $arg->[0]->string
1370             };
1371              
1372 10 100 66     208 return $TRUE if $builtins and $builtins->{$elem_content};
1373             }
1374             }
1375             else {
1376             my $builtins =
1377 10         61 $AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP{':default'};
1378              
1379 10 50 33     129 return $TRUE if $builtins and $builtins->{$elem->content()};
1380             }
1381              
1382 4         51 return;
1383             }
1384              
1385             1;
1386              
1387             __END__
1388              
1389             =pod
1390              
1391             =head1 NAME
1392              
1393             Perl::Critic::Utils - General utility subroutines and constants for Perl::Critic and derivative distributions.
1394              
1395              
1396             =head1 DESCRIPTION
1397              
1398             This module provides several static subs and variables that are useful
1399             for developing L<Perl::Critic::Policy|Perl::Critic::Policy>
1400             subclasses. Unless you are writing Policy modules, you probably don't
1401             care about this package.
1402              
1403              
1404             =head1 INTERFACE SUPPORT
1405              
1406             This is considered to be a public module. Any changes to its
1407             interface will go through a deprecation cycle.
1408              
1409              
1410             =head1 IMPORTABLE SUBS
1411              
1412             =over
1413              
1414             =item C<find_keywords( $doc, $keyword )>
1415              
1416             B<DEPRECATED:> Since version 0.11, every Policy is evaluated at each
1417             element of the document. So you shouldn't need to go looking for a
1418             particular keyword. If you I<do> want to use this, please import it
1419             via the C<:deprecated> tag, rather than directly, to mark the module
1420             as needing updating.
1421              
1422             Given a L<PPI::Document|PPI::Document> as C<$doc>, returns a reference
1423             to an array containing all the L<PPI::Token::Word|PPI::Token::Word>
1424             elements that match C<$keyword>. This can be used to find any
1425             built-in function, method call, bareword, or reserved keyword. It
1426             will not match variables, subroutine names, literal strings, numbers,
1427             or symbols. If the document doesn't contain any matches, returns
1428             undef.
1429              
1430             =item C<is_assignment_operator( $element )>
1431              
1432             Given a L<PPI::Token::Operator|PPI::Token::Operator> or a string,
1433             returns true if that token represents one of the assignment operators
1434             (e.g. C<= &&= ||= //= += -=> etc.).
1435              
1436             =item C<is_perl_global( $element )>
1437              
1438             Given a L<PPI::Token::Symbol|PPI::Token::Symbol> or a string, returns
1439             true if that token represents one of the global variables provided by
1440             the L<English|English> module, or one of the builtin global variables
1441             like C<%SIG>, C<%ENV>, or C<@ARGV>. The sigil on the symbol is
1442             ignored, so things like C<$ARGV> or C<$ENV> will still return true.
1443              
1444              
1445             =item C<is_perl_builtin( $element )>
1446              
1447             Given a L<PPI::Token::Word|PPI::Token::Word>,
1448             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1449             that token represents a call to any of the builtin functions.
1450              
1451              
1452             =item C<is_perl_bareword( $element )>
1453              
1454             Given a L<PPI::Token::Word|PPI::Token::Word>,
1455             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1456             that token represents a bareword (e.g. "if", "else", "sub", "package").
1457              
1458              
1459             =item C<is_perl_filehandle( $element )>
1460              
1461             Given a L<PPI::Token::Word|PPI::Token::Word>, or string, returns true
1462             if that token represents one of the global filehandles (e.g. C<STDIN>,
1463             C<STDERR>, C<STDOUT>, C<ARGV>). Note
1464             that this function will return false if given a filehandle that is
1465             represented as a typeglob (e.g. C<*STDIN>)
1466              
1467              
1468             =item C<is_perl_builtin_with_list_context( $element )>
1469              
1470             Given a L<PPI::Token::Word|PPI::Token::Word>,
1471             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1472             that token represents a call to any of the builtin functions
1473             that provide a list context to the following tokens.
1474              
1475              
1476             =item C<is_perl_builtin_with_multiple_arguments( $element )>
1477              
1478             Given a L<PPI::Token::Word|PPI::Token::Word>,
1479             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1480             that token represents a call to any of the builtin functions that B<can>
1481             take multiple arguments.
1482              
1483              
1484             =item C<is_perl_builtin_with_no_arguments( $element )>
1485              
1486             Given a L<PPI::Token::Word|PPI::Token::Word>,
1487             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1488             that token represents a call to any of the builtin functions that
1489             B<cannot> take any arguments.
1490              
1491              
1492             =item C<is_perl_builtin_with_one_argument( $element )>
1493              
1494             Given a L<PPI::Token::Word|PPI::Token::Word>,
1495             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1496             that token represents a call to any of the builtin functions that takes
1497             B<one and only one> argument.
1498              
1499              
1500             =item C<is_perl_builtin_with_optional_argument( $element )>
1501              
1502             Given a L<PPI::Token::Word|PPI::Token::Word>,
1503             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1504             that token represents a call to any of the builtin functions that takes
1505             B<no more than one> argument.
1506              
1507             The sets of values for which
1508             C<is_perl_builtin_with_multiple_arguments()>,
1509             C<is_perl_builtin_with_no_arguments()>,
1510             C<is_perl_builtin_with_one_argument()>, and
1511             C<is_perl_builtin_with_optional_argument()> return true are disjoint
1512             and their union is precisely the set of values that
1513             C<is_perl_builtin()> will return true for.
1514              
1515              
1516             =item C<is_perl_builtin_with_zero_and_or_one_arguments( $element )>
1517              
1518             Given a L<PPI::Token::Word|PPI::Token::Word>,
1519             L<PPI::Statement::Sub|PPI::Statement::Sub>, or string, returns true if
1520             that token represents a call to any of the builtin functions that takes
1521             no and/or one argument.
1522              
1523             Returns true if any of C<is_perl_builtin_with_no_arguments()>,
1524             C<is_perl_builtin_with_one_argument()>, and
1525             C<is_perl_builtin_with_optional_argument()> returns true.
1526              
1527              
1528             =item C<is_qualified_name( $name )>
1529              
1530             Given a string, L<PPI::Token::Word|PPI::Token::Word>, or
1531             L<PPI::Token::Symbol|PPI::Token::Symbol>, answers whether it has a
1532             module component, i.e. contains "::".
1533              
1534              
1535             =item C<precedence_of( $element )>
1536              
1537             Given a L<PPI::Token::Operator|PPI::Token::Operator> or a string,
1538             returns the precedence of the operator, where 1 is the highest
1539             precedence. Returns undef if the precedence can't be determined
1540             (which is usually because it is not an operator).
1541              
1542              
1543             =item C<is_hash_key( $element )>
1544              
1545             Given a L<PPI::Element|PPI::Element>, returns true if the element is a
1546             literal hash key. PPI doesn't distinguish between regular barewords
1547             (like keywords or subroutine calls) and barewords in hash subscripts
1548             (which are considered literal). So this subroutine is useful if your
1549             Policy is searching for L<PPI::Token::Word|PPI::Token::Word> elements
1550             and you want to filter out the hash subscript variety. In both of the
1551             following examples, "foo" is considered a hash key:
1552              
1553             $hash1{foo} = 1;
1554             %hash2 = (foo => 1);
1555              
1556             But if the bareword is followed by an argument list, then perl treats
1557             it as a function call. So in these examples, "foo" is B<not>
1558             considered a hash key:
1559              
1560             $hash1{ foo() } = 1;
1561             &hash2 = (foo() => 1);
1562              
1563              
1564             =item C<is_included_module_name( $element )>
1565              
1566             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1567             element is the name of a module that is being included via C<use>,
1568             C<require>, or C<no>.
1569              
1570              
1571             =item C<is_integer( $value )>
1572              
1573             Answers whether the parameter, as a string, looks like an integral
1574             value.
1575              
1576              
1577             =item C<is_class_name( $element )>
1578              
1579             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1580             element that immediately follows this element is the dereference
1581             operator "->". When a bareword has a "->" on the B<right> side, it
1582             usually means that it is the name of the class (from which a method is
1583             being called).
1584              
1585              
1586             =item C<is_label_pointer( $element )>
1587              
1588             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1589             element is the label in a C<next>, C<last>, C<redo>, or C<goto>
1590             statement. Note this is not the same thing as the label declaration.
1591              
1592              
1593             =item C<is_method_call( $element )>
1594              
1595             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1596             element that immediately precedes this element is the dereference
1597             operator "->". When a bareword has a "->" on the B<left> side, it
1598             usually means that it is the name of a method (that is being called
1599             from a class).
1600              
1601              
1602             =item C<is_package_declaration( $element )>
1603              
1604             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1605             element is the name of a package that is being declared.
1606              
1607              
1608             =item C<is_subroutine_name( $element )>
1609              
1610             Given a L<PPI::Token::Word|PPI::Token::Word>, returns true if the
1611             element is the name of a subroutine declaration. This is useful for
1612             distinguishing barewords and from function calls from subroutine
1613             declarations.
1614              
1615              
1616             =item C<is_function_call( $element )>
1617              
1618             Given a L<PPI::Token::Word|PPI::Token::Word> returns true if the
1619             element appears to be call to a static function. Specifically, this
1620             function returns true if C<is_hash_key>, C<is_method_call>,
1621             C<is_subroutine_name>, C<is_included_module_name>,
1622             C<is_package_declaration>, C<is_perl_bareword>, C<is_perl_filehandle>,
1623             C<is_label_pointer> and C<is_subroutine_name> all return false for the
1624             given element.
1625              
1626              
1627             =item C<first_arg( $element )>
1628              
1629             Given a L<PPI::Element|PPI::Element> that is presumed to be a function
1630             call (which is usually a L<PPI::Token::Word|PPI::Token::Word>), return
1631             the first argument. This is similar of C<parse_arg_list()> and
1632             follows the same logic. Note that for the code:
1633              
1634             int($x + 0.5)
1635              
1636             this function will return just the C<$x>, not the whole expression.
1637             This is different from the behavior of C<parse_arg_list()>. Another
1638             caveat is:
1639              
1640             int(($x + $y) + 0.5)
1641              
1642             which returns C<($x + $y)> as a
1643             L<PPI::Structure::List|PPI::Structure::List> instance.
1644              
1645              
1646             =item C<parse_arg_list( $element )>
1647              
1648             Given a L<PPI::Element|PPI::Element> that is presumed to be a function
1649             call (which is usually a L<PPI::Token::Word|PPI::Token::Word>), splits
1650             the argument expressions into arrays of tokens. Returns a list
1651             containing references to each of those arrays. This is useful because
1652             parentheses are optional when calling a function, and PPI parses them
1653             very differently. So this method is a poor-man's parse tree of PPI
1654             nodes. It's not bullet-proof because it doesn't respect precedence.
1655             In general, I don't like the way this function works, so don't count
1656             on it to be stable (or even present).
1657              
1658              
1659             =item C<split_nodes_on_comma( @nodes )>
1660              
1661             This has the same return type as C<parse_arg_list()> but expects to be
1662             passed the nodes that represent the interior of a list, like:
1663              
1664             'foo', 1, 2, 'bar'
1665              
1666              
1667             =item C<is_script( $document )>
1668              
1669             B<This subroutine is deprecated and will be removed in a future release.> You
1670             should use the L<Perl::Critic::Document/"is_program()"> method instead.
1671              
1672              
1673             =item C<is_in_void_context( $token )>
1674              
1675             Given a L<PPI::Token|PPI::Token>, answer whether it appears to be in a
1676             void context.
1677              
1678              
1679             =item C<policy_long_name( $policy_name )>
1680              
1681             Given a policy class name in long or short form, return the long form.
1682              
1683              
1684             =item C<policy_short_name( $policy_name )>
1685              
1686             Given a policy class name in long or short form, return the short
1687             form.
1688              
1689              
1690             =item C<all_perl_files( @directories )>
1691              
1692             Given a list of directories, recursively searches through all the
1693             directories (depth first) and returns a list of paths for all the
1694             files that are Perl code files. Any administrative files for CVS or
1695             Subversion are skipped, as are things that look like temporary or
1696             backup files.
1697              
1698             A Perl code file is:
1699              
1700             =over
1701              
1702             =item * Any file that ends in F<.PL>, F<.pl>, F<.pm>, F<.psgi>, or F<.t>
1703              
1704             =item * Any file that has a first line with a shebang containing 'perl'
1705              
1706             =back
1707              
1708              
1709             =item C<severity_to_number( $severity )>
1710              
1711             If C<$severity> is given as an integer, this function returns
1712             C<$severity> but normalized to lie between C<$SEVERITY_LOWEST> and
1713             C<$SEVERITY_HIGHEST>. If C<$severity> is given as a string, this
1714             function returns the corresponding severity number. If the string
1715             doesn't have a corresponding number, this function will throw an
1716             exception.
1717              
1718              
1719             =item C<is_valid_numeric_verbosity( $severity )>
1720              
1721             Answers whether the argument has a translation to a Violation format.
1722              
1723              
1724             =item C<verbosity_to_format( $verbosity_level )>
1725              
1726             Given a verbosity level between 1 and 10, returns the corresponding
1727             predefined format string. These formats are suitable for passing to
1728             the C<set_format> method in
1729             L<Perl::Critic::Violation|Perl::Critic::Violation>. See the
1730             L<perlcritic|perlcritic> documentation for a listing of the predefined
1731             formats.
1732              
1733              
1734             =item C<hashify( @list )>
1735              
1736             Given C<@list>, return a hash where C<@list> is in the keys and each
1737             value is 1. Duplicate values in C<@list> are silently squished.
1738              
1739              
1740             =item C<interpolate( $literal )>
1741              
1742             Given a C<$literal> string that may contain control characters (e.g..
1743             '\t' '\n'), this function does a double interpolation on the string
1744             and returns it as if it had been declared in double quotes. For
1745             example:
1746              
1747             'foo \t bar \n' ...becomes... "foo \t bar \n"
1748              
1749              
1750             =item C<shebang_line( $document )>
1751              
1752             Given a L<PPI::Document|PPI::Document>, test if it starts with C<#!>.
1753             If so, return that line. Otherwise return undef.
1754              
1755              
1756             =item C<words_from_string( $str )>
1757              
1758             Given config string I<$str>, return all the words from the string.
1759             This is safer than splitting on whitespace.
1760              
1761              
1762             =item C<is_unchecked_call( $element, $autodie_modules )>
1763              
1764             Given a L<PPI::Element|PPI::Element>, test to see if it contains a
1765             function call whose return value is not checked. The second argument
1766             is an array reference of module names which export C<autodie>. The
1767             C<autodie> module is always included in this list by default.
1768              
1769              
1770             =back
1771              
1772              
1773             =head1 IMPORTABLE VARIABLES
1774              
1775             =over
1776              
1777             =item C<$COMMA>
1778              
1779             =item C<$FATCOMMA>
1780              
1781             =item C<$COLON>
1782              
1783             =item C<$SCOLON>
1784              
1785             =item C<$QUOTE>
1786              
1787             =item C<$DQUOTE>
1788              
1789             =item C<$BACKTICK>
1790              
1791             =item C<$PERIOD>
1792              
1793             =item C<$PIPE>
1794              
1795             =item C<$EMPTY>
1796              
1797             =item C<$EQUAL>
1798              
1799             =item C<$SPACE>
1800              
1801             =item C<$SLASH>
1802              
1803             =item C<$BSLASH>
1804              
1805             =item C<$LEFT_PAREN>
1806              
1807             =item C<$RIGHT_PAREN>
1808              
1809             These character constants give clear names to commonly-used strings
1810             that can be hard to read when surrounded by quotes and other
1811             punctuation. Can be imported in one go via the C<:characters> tag.
1812              
1813             =item C<$SEVERITY_HIGHEST>
1814              
1815             =item C<$SEVERITY_HIGH>
1816              
1817             =item C<$SEVERITY_MEDIUM>
1818              
1819             =item C<$SEVERITY_LOW>
1820              
1821             =item C<$SEVERITY_LOWEST>
1822              
1823             These numeric constants define the relative severity of violating each
1824             L<Perl::Critic::Policy|Perl::Critic::Policy>. The C<get_severity> and
1825             C<default_severity> methods of every Policy subclass must return one
1826             of these values. Can be imported via the C<:severities> tag.
1827              
1828             =item C<$DEFAULT_VERBOSITY>
1829              
1830             The default numeric verbosity.
1831              
1832             =item C<$DEFAULT_VERBOSITY_WITH_FILE_NAME>
1833              
1834             The numeric verbosity that corresponds to the format indicated by
1835             C<$DEFAULT_VERBOSITY>, but with the file name prefixed to it.
1836              
1837             =item C<$TRUE>
1838              
1839             =item C<$FALSE>
1840              
1841             These are simple booleans. 1 and 0 respectively. Be mindful of using
1842             these with string equality. C<$FALSE ne $EMPTY>. Can be imported via
1843             the C<:booleans> tag.
1844              
1845              
1846             =back
1847              
1848              
1849             =head1 IMPORT TAGS
1850              
1851             The following groups of functions and constants are available as
1852             parameters to a C<use Perl::Critic::Util> statement.
1853              
1854             =over
1855              
1856             =item C<:all>
1857              
1858             The lot.
1859              
1860              
1861             =item C<:booleans>
1862              
1863             Includes:
1864             C<$TRUE>, C<$FALSE>
1865              
1866              
1867             =item C<:severities>
1868              
1869             Includes:
1870             C<$SEVERITY_HIGHEST>,
1871             C<$SEVERITY_HIGH>,
1872             C<$SEVERITY_MEDIUM>,
1873             C<$SEVERITY_LOW>,
1874             C<$SEVERITY_LOWEST>,
1875             C<@SEVERITY_NAMES>
1876              
1877              
1878             =item C<:characters>
1879              
1880             Includes:
1881             C<$COLON>,
1882             C<$COMMA>,
1883             C<$DQUOTE>,
1884             C<$EMPTY>,
1885             C<$FATCOMMA>,
1886             C<$PERIOD>,
1887             C<$PIPE>,
1888             C<$QUOTE>,
1889             C<$BACKTICK>,
1890             C<$SCOLON>,
1891             C<$SPACE>,
1892             C<$SLASH>,
1893             C<$BSLASH>
1894             C<$LEFT_PAREN>
1895             C<$RIGHT_PAREN>
1896              
1897              
1898             =item C<:classification>
1899              
1900             Includes:
1901             C<is_assignment_operator>,
1902             C<is_class_name>,
1903             C<is_function_call>,
1904             C<is_hash_key>,
1905             C<is_included_module_name>,
1906             C<is_integer>,
1907             C<is_label_pointer>,
1908             C<is_method_call>,
1909             C<is_package_declaration>,
1910             C<is_perl_bareword>,
1911             C<is_perl_builtin>,
1912             C<is_perl_filehandle>,
1913             C<is_perl_global>,
1914             C<is_perl_builtin_with_list_context>
1915             C<is_perl_builtin_with_multiple_arguments>
1916             C<is_perl_builtin_with_no_arguments>
1917             C<is_perl_builtin_with_one_argument>
1918             C<is_perl_builtin_with_optional_argument>
1919             C<is_perl_builtin_with_zero_and_or_one_arguments>
1920             C<is_qualified_name>,
1921             C<is_script>,
1922             C<is_subroutine_name>,
1923             C<is_unchecked_call>
1924             C<is_valid_numeric_verbosity>
1925              
1926             See also L<Perl::Critic::Utils::PPI|Perl::Critic::Utils::PPI>.
1927              
1928              
1929             =item C<:data_conversion>
1930              
1931             Generic manipulation, not having anything specific to do with
1932             Perl::Critic.
1933              
1934             Includes:
1935             C<hashify>,
1936             C<words_from_string>,
1937             C<interpolate>
1938              
1939              
1940             =item C<:ppi>
1941              
1942             Things for dealing with L<PPI|PPI>, other than classification.
1943              
1944             Includes:
1945             C<first_arg>,
1946             C<parse_arg_list>
1947              
1948             See also L<Perl::Critic::Utils::PPI|Perl::Critic::Utils::PPI>.
1949              
1950              
1951             =item C<:internal_lookup>
1952              
1953             Translations between internal representations.
1954              
1955             Includes:
1956             C<severity_to_number>,
1957             C<verbosity_to_format>
1958              
1959              
1960             =item C<:language>
1961              
1962             Information about Perl not programmatically available elsewhere.
1963              
1964             Includes:
1965             C<precedence_of>
1966              
1967              
1968             =item C<:deprecated>
1969              
1970             Not surprisingly, things that are deprecated. It is preferred to use
1971             this tag to get to these functions, rather than the function names
1972             themselves, so as to mark any module using them as needing cleanup.
1973              
1974             Includes:
1975             C<find_keywords>
1976              
1977              
1978             =back
1979              
1980              
1981             =head1 SEE ALSO
1982              
1983             L<Perl::Critic::Utils::Constants|Perl::Critic::Utils::Constants>,
1984             L<Perl::Critic::Utils::McCabe|Perl::Critic::Utils::McCabe>,
1985             L<Perl::Critic::Utils::PPI|Perl::Critic::Utils::PPI>,
1986              
1987              
1988             =head1 AUTHOR
1989              
1990             Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>
1991              
1992              
1993             =head1 COPYRIGHT
1994              
1995             Copyright (c) 2005-2023 Imaginative Software Systems
1996              
1997             This program is free software; you can redistribute it and/or modify
1998             it under the same terms as Perl itself. The full text of this license
1999             can be found in the LICENSE file included with this module.
2000              
2001             =cut
2002              
2003             # Local Variables:
2004             # mode: cperl
2005             # cperl-indent-level: 4
2006             # fill-column: 78
2007             # indent-tabs-mode: nil
2008             # c-indentation-style: bsd
2009             # End:
2010             # ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :