File Coverage

blib/lib/Perl/Critic/Utils.pm
Criterion Covered Total %
statement 307 336 91.3
branch 146 222 65.7
condition 60 103 58.2
subroutine 62 68 91.1
pod 39 39 100.0
total 614 768 79.9


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   189757 use 5.010001;
  40         118  
7 40     40   173 use strict;
  40         59  
  40         865  
8 40     40   121 use warnings;
  40         66  
  40         1612  
9 40     40   4077 use Readonly;
  40         30761  
  40         2340  
10              
11 40     40   274 use Carp qw( confess );
  40         76  
  40         1663  
12 40     40   2227 use English qw(-no_match_vars);
  40         12617  
  40         210  
13 40     40   12142 use File::Find qw();
  40         63  
  40         584  
14 40     40   132 use File::Spec qw();
  40         71  
  40         796  
15 40     40   356 use Scalar::Util qw( blessed );
  40         103  
  40         2407  
16 40     40   18060 use B::Keywords qw();
  40         63098  
  40         1066  
17 40     40   13688 use PPI::Token::Quote::Single;
  40         2184977  
  40         1534  
18 40     40   4858 use List::SomeUtils qw(any);
  40         108679  
  40         2595  
19              
20 40     40   17230 use Perl::Critic::Exception::Fatal::Generic qw{ throw_generic };
  40         130  
  40         1074  
21 40     40   18506 use Perl::Critic::Utils::PPI qw< is_ppi_expression_or_generic_statement >;
  40         120  
  40         2565  
22              
23 40     40   291 use Exporter 'import';
  40         59  
  40         208019  
24              
25             our $VERSION = '1.156';
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             ## no critic (ProhibitNoisyQuotes);
214              
215             Readonly::Hash my %PRECEDENCE_OF => (
216             '->' => 1,
217             '++' => 2,
218             '--' => 2,
219             '**' => 3,
220             '!' => 4,
221             '~' => 4,
222             '\\' => 4,
223             '=~' => 5,
224             '!~' => 5,
225             '*' => 6,
226             '/' => 6,
227             '%' => 6,
228             'x' => 6,
229             '+' => 7,
230             '-' => 7,
231             '.' => 7,
232             '<<' => 8,
233             '>>' => 8,
234             '-R' => 9,
235             '-W' => 9,
236             '-X' => 9,
237             '-r' => 9,
238             '-w' => 9,
239             '-x' => 9,
240             '-e' => 9,
241             '-O' => 9,
242             '-o' => 9,
243             '-z' => 9,
244             '-s' => 9,
245             '-M' => 9,
246             '-A' => 9,
247             '-C' => 9,
248             '-S' => 9,
249             '-c' => 9,
250             '-b' => 9,
251             '-f' => 9,
252             '-d' => 9,
253             '-p' => 9,
254             '-l' => 9,
255             '-u' => 9,
256             '-g' => 9,
257             '-k' => 9,
258             '-t' => 9,
259             '-T' => 9,
260             '-B' => 9,
261             '<' => 10,
262             '>' => 10,
263             '<=' => 10,
264             '>=' => 10,
265             'lt' => 10,
266             'gt' => 10,
267             'le' => 10,
268             'ge' => 10,
269             '==' => 11,
270             '!=' => 11,
271             '<=>' => 11,
272             'eq' => 11,
273             'ne' => 11,
274             'cmp' => 11,
275             '~~' => 11,
276             '&' => 12,
277             '|' => 13,
278             '^' => 13,
279             '&&' => 14,
280             '//' => 15,
281             '||' => 15,
282             '..' => 16,
283             '...' => 17,
284             '?' => 18,
285             ':' => 18,
286             '=' => 19,
287             '+=' => 19,
288             '-=' => 19,
289             '*=' => 19,
290             '/=' => 19,
291             '%=' => 19,
292             '||=' => 19,
293             '&&=' => 19,
294             '|=' => 19,
295             '&=' => 19,
296             '**=' => 19,
297             'x=' => 19,
298             '.=' => 19,
299             '^=' => 19,
300             '<<=' => 19,
301             '>>=' => 19,
302             '//=' => 19,
303             ',' => 20,
304             '=>' => 20,
305             'not' => 22,
306             'and' => 23,
307             'or' => 24,
308             'xor' => 24,
309             );
310              
311             ## use critic
312              
313             Readonly::Scalar my $MIN_PRECEDENCE_TO_TERMINATE_PARENLESS_ARG_LIST =>
314             precedence_of( 'not' );
315              
316             #-----------------------------------------------------------------------------
317              
318             sub hashify { ## no critic (ArgUnpacking)
319 21119     21119 1 42692 return map { $_ => 1 } @_;
  179955         314610  
320             }
321              
322             #-----------------------------------------------------------------------------
323              
324             sub interpolate {
325 959     959 1 1443 my ( $literal ) = @_;
326 959   33     51940 return eval "\"$literal\"" || confess $EVAL_ERROR; ## no critic (StringyEval);
327             }
328              
329             #-----------------------------------------------------------------------------
330              
331             sub find_keywords {
332 5     5 1 6893 my ( $doc, $keyword ) = @_;
333 5         17 my $nodes_ref = $doc->find('PPI::Token::Word');
334 5 100       166 return if !$nodes_ref;
335 4         6 my @matches = grep { $_ eq $keyword } @{$nodes_ref};
  11         100  
  4         26  
336 4 100       61 return @matches ? \@matches : undef;
337             }
338              
339             #-----------------------------------------------------------------------------
340              
341             sub _name_for_sub_or_stringified_element {
342 1007     1007   1062 my $elem = shift;
343              
344 1007 100 100     3324 if ( blessed $elem and $elem->isa('PPI::Statement::Sub') ) {
345 17         65 return $elem->name();
346             }
347              
348 990         1536 return "$elem";
349             }
350              
351             #-----------------------------------------------------------------------------
352             ## no critic (ProhibitPackageVars)
353              
354             Readonly::Hash my %BUILTINS => hashify( @B::Keywords::Functions );
355              
356             sub is_perl_builtin {
357 264     264 1 1567 my $elem = shift;
358              
359 264   66     726 return $elem && exists $BUILTINS{ _name_for_sub_or_stringified_element($elem) };
360             }
361              
362             #-----------------------------------------------------------------------------
363              
364             Readonly::Hash my %BAREWORDS => hashify(
365             @B::Keywords::Barewords,
366             @B::Keywords::BarewordsExtra,
367             );
368              
369             sub is_perl_bareword {
370 383     383 1 1987 my $elem = shift;
371              
372 383   66     996 return $elem && exists $BAREWORDS{ _name_for_sub_or_stringified_element($elem) };
373             }
374              
375             #-----------------------------------------------------------------------------
376              
377             sub _build_globals_without_sigils {
378             # B::Keywords as of 1.08 forgot $\
379             my @globals =
380 40     40   262 map { substr $_, 1 }
  5960         7616  
381             @B::Keywords::Arrays,
382             @B::Keywords::Hashes,
383             @B::Keywords::Scalars,
384             '$\\'; ## no critic (RequireInterpolationOfMetachars)
385              
386             # Not all of these have sigils
387 40         130 foreach my $filehandle (@B::Keywords::Filehandles) {
388 360         586 (my $stripped = $filehandle) =~ s< \A [*] ><>xms;
389 360         627 push @globals, $stripped;
390             }
391              
392 40         1411 return @globals;
393             }
394              
395             Readonly::Array my @GLOBALS_WITHOUT_SIGILS => _build_globals_without_sigils();
396              
397             Readonly::Hash my %GLOBALS => hashify( @GLOBALS_WITHOUT_SIGILS );
398              
399             sub is_perl_global {
400 64     64 1 1553 my $elem = shift;
401 64 50       169 return if !$elem;
402 64         151 my $var_name = "$elem"; #Convert Token::Symbol to string
403 64         356 $var_name =~ s{\A [\$@%*] }{}xms; #Chop off the sigil
404 64         284 return exists $GLOBALS{ $var_name };
405             }
406              
407             #-----------------------------------------------------------------------------
408              
409             Readonly::Hash my %FILEHANDLES => hashify( @B::Keywords::Filehandles );
410              
411             sub is_perl_filehandle {
412 308     308 1 435 my $elem = shift;
413              
414 308   33     810 return $elem && exists $FILEHANDLES{ _name_for_sub_or_stringified_element($elem) };
415             }
416              
417             ## use critic
418             #-----------------------------------------------------------------------------
419              
420             # egrep '=item.*LIST' perlfunc.pod
421             Readonly::Hash my %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT =>
422             hashify(
423             qw{
424             chmod
425             chown
426             die
427             exec
428             formline
429             grep
430             import
431             join
432             kill
433             map
434             no
435             open
436             pack
437             print
438             printf
439             push
440             reverse
441             say
442             sort
443             splice
444             sprintf
445             syscall
446             system
447             tie
448             unlink
449             unshift
450             use
451             utime
452             warn
453             },
454             );
455              
456             sub is_perl_builtin_with_list_context {
457 0     0 1 0 my $elem = shift;
458              
459             return
460             exists
461             $BUILTINS_WHICH_PROVIDE_LIST_CONTEXT{
462 0         0 _name_for_sub_or_stringified_element($elem)
463             };
464             }
465              
466             #-----------------------------------------------------------------------------
467              
468             # egrep '=item.*[A-Z],' perlfunc.pod
469             Readonly::Hash my %BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS =>
470             hashify(
471             qw{
472             accept
473             atan2
474             bind
475             binmode
476             bless
477             connect
478             crypt
479             dbmopen
480             fcntl
481             flock
482             gethostbyaddr
483             getnetbyaddr
484             getpriority
485             getservbyname
486             getservbyport
487             getsockopt
488             index
489             ioctl
490             link
491             listen
492             mkdir
493             msgctl
494             msgget
495             msgrcv
496             msgsnd
497             open
498             opendir
499             pipe
500             read
501             recv
502             rename
503             rindex
504             seek
505             seekdir
506             select
507             semctl
508             semget
509             semop
510             send
511             setpgrp
512             setpriority
513             setsockopt
514             shmctl
515             shmget
516             shmread
517             shmwrite
518             shutdown
519             socket
520             socketpair
521             splice
522             split
523             substr
524             symlink
525             sysopen
526             sysread
527             sysseek
528             syswrite
529             truncate
530             unpack
531             vec
532             waitpid
533             },
534             keys %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT
535             );
536              
537             sub is_perl_builtin_with_multiple_arguments {
538 9     9 1 186 my $elem = shift;
539              
540             return
541             exists
542             $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{
543 9         21 _name_for_sub_or_stringified_element($elem)
544             };
545             }
546              
547             #-----------------------------------------------------------------------------
548              
549             Readonly::Hash my %BUILTINS_WHICH_TAKE_NO_ARGUMENTS =>
550             hashify(
551             qw{
552             endgrent
553             endhostent
554             endnetent
555             endprotoent
556             endpwent
557             endservent
558             fork
559             format
560             getgrent
561             gethostent
562             getlogin
563             getnetent
564             getppid
565             getprotoent
566             getpwent
567             getservent
568             setgrent
569             setpwent
570             split
571             time
572             times
573             wait
574             wantarray
575             }
576             );
577              
578             sub is_perl_builtin_with_no_arguments {
579 0     0 1 0 my $elem = shift;
580              
581             return
582             exists
583             $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{
584 0         0 _name_for_sub_or_stringified_element($elem)
585             };
586             }
587              
588             #-----------------------------------------------------------------------------
589              
590             Readonly::Hash my %BUILTINS_WHICH_TAKE_ONE_ARGUMENT =>
591             hashify(
592             qw{
593             closedir
594             dbmclose
595             delete
596             each
597             exists
598             fileno
599             getgrgid
600             getgrnam
601             gethostbyname
602             getnetbyname
603             getpeername
604             getpgrp
605             getprotobyname
606             getprotobynumber
607             getpwnam
608             getpwuid
609             getsockname
610             goto
611             keys
612             local
613             prototype
614             readdir
615             readline
616             readpipe
617             rewinddir
618             scalar
619             sethostent
620             setnetent
621             setprotoent
622             setservent
623             telldir
624             tied
625             untie
626             values
627             }
628             );
629              
630             sub is_perl_builtin_with_one_argument {
631 0     0 1 0 my $elem = shift;
632              
633             return
634             exists
635             $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{
636 0         0 _name_for_sub_or_stringified_element($elem)
637             };
638             }
639              
640             #-----------------------------------------------------------------------------
641              
642             ## no critic (ProhibitPackageVars)
643             Readonly::Hash my %BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT =>
644             hashify(
645             grep { not exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $_ } }
646             grep { not exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $_ } }
647             grep { not exists $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{ $_ } }
648             @B::Keywords::Functions
649             );
650             ## use critic
651              
652             sub is_perl_builtin_with_optional_argument {
653 0     0 1 0 my $elem = shift;
654              
655             return
656             exists
657             $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{
658 0         0 _name_for_sub_or_stringified_element($elem)
659             };
660             }
661              
662             #-----------------------------------------------------------------------------
663              
664             sub is_perl_builtin_with_zero_and_or_one_arguments {
665 43     43 1 46 my $elem = shift;
666              
667 43 50       87 return if not $elem;
668              
669 43         68 my $name = _name_for_sub_or_stringified_element($elem);
670              
671             return (
672             exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $name }
673             or exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $name }
674 43   66     217 or exists $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{ $name }
675             );
676             }
677              
678             #-----------------------------------------------------------------------------
679              
680             sub is_qualified_name {
681 0     0 1 0 my $name = shift;
682              
683 0   0     0 return $name && (index($name, q{::}) >= 0);
684             }
685              
686             #-----------------------------------------------------------------------------
687              
688             sub precedence_of {
689 208     208 1 808 my $elem = shift;
690              
691 208   33     1543 return $elem && $PRECEDENCE_OF{ ref $elem ? "$elem" : $elem };
692             }
693              
694             #-----------------------------------------------------------------------------
695              
696             sub is_hash_key {
697 730     730 1 33691 my $elem = shift;
698 730 50       1499 return if !$elem;
699              
700             #If followed by an argument list, then it's a function call, not a literal.
701 730         1330 my $sib = $elem->snext_sibling();
702 730 100 100     15870 return if $sib && $sib->isa('PPI::Structure::List');
703              
704             #Check curly-brace style: $hash{foo} = bar;
705 680         1284 my $parent = $elem->parent();
706 680 50       2371 return if !$parent;
707 680         1073 my $grandparent = $parent->parent();
708 680 50       2155 return if !$grandparent;
709 680 100       1809 if ( $grandparent->isa('PPI::Structure::Subscript') ) {
710             # If followed by a non-(fat)comma, then it's not a hash slice,
711             # so a function call without parentheses.
712 5 100 66     23 return if $sib && !($sib->isa('PPI::Token::Operator')
      100        
713             && ($sib eq $COMMA || $sib eq $FATCOMMA));
714 4         37 return 1;
715             }
716              
717             #Check declarative style: %hash = (foo => bar);
718             return
719 675   100     3135 $sib
720             && $sib->isa('PPI::Token::Operator')
721             && $sib eq $FATCOMMA
722             ;
723             }
724              
725             #-----------------------------------------------------------------------------
726              
727             sub is_included_module_name {
728 371     371 1 379 my $elem = shift;
729 371 50       760 return if !$elem;
730 371         648 my $stmnt = $elem->statement();
731 371 50       3182 return if !$stmnt;
732 371 100       1027 return if !$stmnt->isa('PPI::Statement::Include');
733 114         294 return $stmnt->schild(1) == $elem;
734             }
735              
736             #-----------------------------------------------------------------------------
737              
738             sub is_integer {
739 1734     1734 1 2617 my ($value) = @_;
740 1734 50       3037 return 0 if not defined $value;
741              
742 1734         8269 return $value =~ m{ \A [+-]? \d+ \z }xms;
743             }
744              
745             #-----------------------------------------------------------------------------
746              
747             sub is_label_pointer {
748 287     287 1 302 my $elem = shift;
749 287 50       564 return if !$elem;
750              
751 287         471 my $statement = $elem->statement();
752 287 50       2579 return if !$statement;
753 287 100       973 return if !$statement->isa('PPI::Statement::Break');
754              
755 14         26 my $psib = $elem->sprevious_sibling();
756 14         201 state $redirectors = { hashify( qw( redo goto next last ) ) };
757 14   66     54 return $psib && exists $redirectors->{$psib};
758             }
759              
760             #-----------------------------------------------------------------------------
761              
762             sub is_method_call {
763 604     604 1 704 my $elem = shift;
764              
765 604   33     1585 return $elem && _is_dereference_operator( $elem->sprevious_sibling() );
766             }
767              
768             #-----------------------------------------------------------------------------
769              
770             sub is_class_name {
771 308     308 1 342 my $elem = shift;
772              
773             return
774 308   33     834 $elem
775             && _is_dereference_operator( $elem->snext_sibling() )
776             && !_is_dereference_operator( $elem->sprevious_sibling() )
777             ;
778             }
779              
780             #-----------------------------------------------------------------------------
781              
782             sub _is_dereference_operator {
783 912     912   15010 my $elem = shift;
784              
785             return
786 912   66     3934 $elem
787             && $elem->isa('PPI::Token::Operator')
788             && $elem eq q{->}
789             ;
790             }
791              
792             #-----------------------------------------------------------------------------
793              
794             sub is_package_declaration {
795 337     337 1 344 my $elem = shift;
796 337 50       675 return if !$elem;
797 337         694 my $stmnt = $elem->statement();
798 337 50       3972 return if !$stmnt;
799 337 50       1116 return if !$stmnt->isa('PPI::Statement::Package');
800 0         0 return $stmnt->schild(1) == $elem;
801             }
802              
803             #-----------------------------------------------------------------------------
804              
805             sub is_subroutine_name {
806 357     357 1 674 my $elem = shift;
807 357 50       681 return if !$elem;
808              
809 357         704 my $sib = $elem->sprevious_sibling();
810 357 100       5407 return if !$sib;
811 70 100       165 return if $sib ne 'sub';
812              
813 22         293 my $stmnt = $elem->statement();
814 22 50       202 return if !$stmnt;
815 22         122 return $stmnt->isa('PPI::Statement::Sub');
816             }
817              
818             #-----------------------------------------------------------------------------
819              
820             sub is_function_call {
821 372 50   372 1 3170 my $elem = shift or return;
822              
823 372 100       674 return if is_perl_bareword($elem);
824 308 50       3168 return if is_perl_filehandle($elem);
825 308 50       2549 return if is_package_declaration($elem);
826 308 50       578 return if is_included_module_name($elem);
827 308 50       2286 return if is_method_call($elem);
828 308 50       568 return if is_class_name($elem);
829 308 100       689 return if is_subroutine_name($elem);
830 287 50       702 return if is_label_pointer($elem);
831 287 50       484 return if is_hash_key($elem);
832              
833 287         815 return 1;
834             }
835              
836             #-----------------------------------------------------------------------------
837              
838             sub is_script {
839 8     8 1 8737 my $doc = shift;
840              
841 8         404 warnings::warnif(
842             'deprecated',
843             'Perl::Critic::Utils::is_script($doc) deprecated, use $doc->is_program() instead.', ## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
844             );
845              
846 8 50 33     60 return $doc->is_program()
847             if blessed($doc) && $doc->isa('Perl::Critic::Document');
848              
849 8 100       18 return 1 if shebang_line($doc);
850 3 100       8 return 1 if _is_PL_file($doc);
851 2         12 return 0;
852             }
853              
854             #-----------------------------------------------------------------------------
855              
856             sub _is_PL_file { ## no critic (NamingConventions::Capitalization)
857 3     3   5 my ($doc) = @_;
858 3 50       13 return if not $doc->can('filename');
859 3   100     8 my $filename = $doc->filename() || return;
860 1 50       12 return 1 if $filename =~ m/[.] PL \z/xms;
861 0         0 return 0;
862             }
863              
864             #-----------------------------------------------------------------------------
865              
866             sub is_in_void_context {
867 0     0 1 0 my ($token) = @_;
868              
869             # If part of a collective, can't be void.
870 0 0       0 return if $token->sprevious_sibling();
871              
872 0         0 my $parent = $token->statement()->parent();
873 0 0       0 if ($parent) {
874 0 0       0 return if $parent->isa('PPI::Structure::List');
875 0 0       0 return if $parent->isa('PPI::Structure::For');
876 0 0       0 return if $parent->isa('PPI::Structure::Condition');
877 0 0       0 return if $parent->isa('PPI::Structure::Constructor');
878 0 0       0 return if $parent->isa('PPI::Structure::Subscript');
879              
880             # If it's in a block and not the last statement then it's in void.
881 0 0 0     0 return 1 if
882             $parent->isa('PPI::Structure::Block')
883             and $token->statement()->snext_sibling();
884              
885 0         0 my $grandparent = $parent->parent();
886 0 0       0 if ($grandparent) {
887             return if
888 0 0 0     0 $parent->isa('PPI::Structure::Block')
889             and not $grandparent->isa('PPI::Statement::Compound');
890             }
891             }
892              
893 0         0 return $TRUE;
894             }
895              
896             #-----------------------------------------------------------------------------
897              
898             sub policy_long_name {
899 27153     27153 1 34846 my ( $policy_name ) = @_;
900 27153 100       88390 if ( $policy_name !~ m{ \A $POLICY_NAMESPACE }xms ) {
901 460         745 $policy_name = $POLICY_NAMESPACE . q{::} . $policy_name;
902             }
903 27153         56140 return $policy_name;
904             }
905              
906             #-----------------------------------------------------------------------------
907              
908             sub policy_short_name {
909 167612     167612 1 200436 my ( $policy_name ) = @_;
910 167612         536744 $policy_name =~ s{\A $POLICY_NAMESPACE ::}{}xms;
911 167612         329837 return $policy_name;
912             }
913              
914             #-----------------------------------------------------------------------------
915              
916             sub first_arg {
917 15     15 1 6359 my $elem = shift;
918 15         42 my $sib = $elem->snext_sibling();
919 15 50       266 return if !$sib;
920              
921 15 100       48 if ( $sib->isa('PPI::Structure::List') ) {
922              
923 2         16 my $expr = $sib->schild(0);
924 2 100       20 return if !$expr;
925 1 50       5 return $expr->isa('PPI::Statement') ? $expr->schild(0) : $expr;
926             }
927              
928 13         21 return $sib;
929             }
930              
931             #-----------------------------------------------------------------------------
932              
933             sub parse_arg_list {
934 26     26 1 10766 my $elem = shift;
935 26         80 my $sib = $elem->snext_sibling();
936 26 50       674 return if !$sib;
937              
938 26 100       96 if ( $sib->isa('PPI::Structure::List') ) {
939              
940             #Pull siblings from list
941 3         26 my @list_contents = $sib->schildren();
942 3 50       33 return if not @list_contents;
943              
944 3         4 my @list_expressions;
945 3         4 foreach my $item (@list_contents) {
946 3 50       12 if (
947             is_ppi_expression_or_generic_statement($item)
948             ) {
949 3         9 push
950             @list_expressions,
951             split_nodes_on_comma( $item->schildren() );
952             }
953             else {
954 0         0 push @list_expressions, $item;
955             }
956             }
957              
958 3         10 return @list_expressions;
959             }
960             else {
961              
962             # Gather up remaining nodes in the statement.
963 23         41 my $iter = $elem;
964 23         28 my @arg_list;
965              
966 23         50 while ($iter = $iter->snext_sibling() ) {
967 58 100 66     973 last if $iter->isa('PPI::Token::Structure') and $iter eq $SCOLON;
968 35 50 66     124 last if $iter->isa('PPI::Token::Operator')
969             and $MIN_PRECEDENCE_TO_TERMINATE_PARENLESS_ARG_LIST <=
970             precedence_of( $iter );
971 35         139 push @arg_list, $iter;
972             }
973 23         323 return split_nodes_on_comma( @arg_list );
974             }
975             }
976              
977             #---------------------------------
978              
979             sub split_nodes_on_comma {
980 26     26 1 95 my @nodes = @_;
981              
982 26         36 my $i = 0;
983 26         31 my @node_stacks;
984 26         48 for my $node (@nodes) {
985 50         88 my $node_content = $node->content;
986 50 100 66     429 if (
    100 66        
987             $node->isa('PPI::Token::Operator')
988             and ($node_content eq $COMMA or $node_content eq $FATCOMMA)
989             ) {
990 10 50       18 if (@node_stacks) {
991 10         13 $i++; #Move forward to next 'node stack'
992             }
993 10         16 next;
994             } elsif ( $node->isa('PPI::Token::QuoteLike::Words' )) {
995 7         10 my $section = $node->{sections}->[0];
996 7         27 my @words = words_from_string(substr $node_content, $section->{position}, $section->{size});
997 7         45 my $loc = $node->location;
998 7         77 for my $word (@words) {
999 10         32 my $token = PPI::Token::Quote::Single->new(q{'} . $word . q{'});
1000 10         110 $token->{_location} = $loc;
1001 10         12 push @{ $node_stacks[$i++] }, $token;
  10         23  
1002             }
1003 7         13 next;
1004             }
1005 33         43 push @{ $node_stacks[$i] }, $node;
  33         87  
1006             }
1007 26         72 return @node_stacks;
1008             }
1009              
1010             #-----------------------------------------------------------------------------
1011              
1012             # XXX: You must keep the regular expressions in extras/perlcritic.el in sync
1013             # if you change these.
1014             Readonly::Hash my %FORMAT_OF => (
1015             1 => "%f:%l:%c:%m\n",
1016             2 => "%f: (%l:%c) %m\n",
1017             3 => "%m at %f line %l\n",
1018             4 => "%m at line %l, column %c. %e. (Severity: %s)\n",
1019             5 => "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
1020             6 => "%m at line %l, near '%r'. (Severity: %s)\n",
1021             7 => "%f: %m at line %l near '%r'. (Severity: %s)\n",
1022             8 => "[%p] %m at line %l, column %c. (Severity: %s)\n",
1023             9 => "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
1024             10 => "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
1025             11 => "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n",
1026             );
1027              
1028             Readonly::Scalar our $DEFAULT_VERBOSITY => 4;
1029             Readonly::Scalar our $DEFAULT_VERBOSITY_WITH_FILE_NAME => 5;
1030             Readonly::Scalar my $DEFAULT_FORMAT => $FORMAT_OF{$DEFAULT_VERBOSITY};
1031              
1032             sub is_valid_numeric_verbosity {
1033 280     280 1 587 my ($verbosity) = @_;
1034              
1035 280         1597 return exists $FORMAT_OF{$verbosity};
1036             }
1037              
1038             sub verbosity_to_format {
1039 20     20 1 53 my ($verbosity) = @_;
1040 20 100       67 return $DEFAULT_FORMAT if not defined $verbosity;
1041 19 100 66     49 return $FORMAT_OF{abs int $verbosity} || $DEFAULT_FORMAT if is_integer($verbosity);
1042 17         55 return interpolate( $verbosity ); #Otherwise, treat as a format spec
1043             }
1044              
1045             #-----------------------------------------------------------------------------
1046              
1047             Readonly::Hash my %SEVERITY_NUMBER_OF => (
1048             gentle => 5,
1049             stern => 4,
1050             harsh => 3,
1051             cruel => 2,
1052             brutal => 1,
1053             );
1054              
1055             Readonly::Array our @SEVERITY_NAMES => #This is exported!
1056             sort
1057             { $SEVERITY_NUMBER_OF{$a} <=> $SEVERITY_NUMBER_OF{$b} }
1058             keys %SEVERITY_NUMBER_OF;
1059              
1060             sub severity_to_number {
1061 871     871 1 1644 my ($severity) = @_;
1062 871 100       1852 return _normalize_severity( $severity ) if is_integer( $severity );
1063 6         29 my $severity_number = $SEVERITY_NUMBER_OF{lc $severity};
1064              
1065 6 100       70 if ( not defined $severity_number ) {
1066 1         6 throw_generic qq{Invalid severity: "$severity"};
1067             }
1068              
1069 5         15 return $severity_number;
1070             }
1071              
1072             sub _normalize_severity {
1073 865   50 865   2021 my $s = shift || return $SEVERITY_HIGHEST;
1074 865 50       2191 $s = $s > $SEVERITY_HIGHEST ? $SEVERITY_HIGHEST : $s;
1075 865 50       1877 $s = $s < $SEVERITY_LOWEST ? $SEVERITY_LOWEST : $s;
1076 865         1956 return $s;
1077             }
1078              
1079             #-----------------------------------------------------------------------------
1080              
1081             Readonly::Array my @SKIP_DIR => qw( CVS RCS .svn _darcs {arch} .bzr .cdv .git .hg .pc _build blib );
1082             Readonly::Hash my %SKIP_DIR => hashify( @SKIP_DIR );
1083              
1084             sub all_perl_files {
1085 1     1 1 21 my @arg = @_;
1086 1         3 my @code_files;
1087              
1088             # The old code did a breadth-first search (documentation to the
1089             # contrary notwithstanding,) whereas File::Find does depth-first. So
1090             # there appears to be no way to use File::Find without changing the
1091             # order in which the files are returned.
1092             File::Find::find( {
1093             wanted => sub {
1094 163 50 66 163   2702 if ( -d && $SKIP_DIR{$_} ) {
    100 66        
      66        
1095 0         0 $File::Find::prune = 1;
1096             } elsif ( -f && ! _is_backup( $_ ) && _is_perl( $_ ) ) {
1097 145         193 push @code_files, $File::Find::name;
1098             }
1099 163         5107 return;
1100             },
1101 1         180 untaint => 1,
1102             },
1103             @arg,
1104             );
1105              
1106             # Use File::Spec->abs2rel() to get rid of leading './' or other OS
1107             # equivalent on relative filenames.
1108             # Use map {} to get rid of leading './', or other OS equivalent
1109 1 50       10 return ( map { File::Spec->file_name_is_absolute( $_ ) ?
  145         4093  
1110             $_ : File::Spec->abs2rel( $_ ) } @code_files );
1111             }
1112              
1113              
1114             #-----------------------------------------------------------------------------
1115             # Decide if it's some sort of backup file
1116              
1117             sub _is_backup {
1118 152     152   2311 my ($file) = @_;
1119 152 100       381 return 1 if $file =~ m{ (?: [.] swp | [.] bak | ~ ) \z}xms;
1120 149 100       212 return 1 if $file =~ m{ \A [#] .+ [#] \z}xms;
1121 148         334 return;
1122             }
1123              
1124             #-----------------------------------------------------------------------------
1125             # Returns true if the argument ends with a perl-ish file
1126             # extension, or if it has a shebang-line containing 'perl' This
1127             # subroutine was also poached from Test::Perl::Critic
1128              
1129             sub _is_perl {
1130 165     165   17344 my ($file) = @_;
1131              
1132             #Check filename extensions
1133 165 100       597 return 1 if $file =~ m{ [.] (?: PL | p[lm] | psgi | t ) \z}xms;
1134              
1135             #Check for shebang
1136 15 100       735 open my $fh, '<', $file or return;
1137 9         100 my $first = <$fh>;
1138 9 50       80 close $fh or throw_generic "unable to close $file: $OS_ERROR";
1139              
1140 9 100 66     117 return 1 if defined $first && ( $first =~ m{ \A [#]!.*perl }xms );
1141 3         30 return;
1142             }
1143              
1144             #-----------------------------------------------------------------------------
1145              
1146             sub shebang_line {
1147 158     158 1 4356 my $doc = shift;
1148 158         731 my $first_element = $doc->first_element();
1149 158 50       920 return if not $first_element;
1150 158 100       858 return if not $first_element->isa('PPI::Token::Comment');
1151 34         121 my $location = $first_element->location();
1152 34 50       1391 return if !$location;
1153             # The shebang must be the first two characters in the file, according to
1154             # http://en.wikipedia.org/wiki/Shebang_(Unix)
1155 34 50       114 return if $location->[0] != 1; # line number
1156 34 50       81 return if $location->[1] != 1; # column number
1157 34         91 my $shebang = $first_element->content;
1158 34 100       207 return if $shebang !~ m{ \A [#]! }xms;
1159 16         84 return $shebang;
1160             }
1161              
1162             #-----------------------------------------------------------------------------
1163              
1164             sub words_from_string {
1165 6608     6608 1 9795 my $str = shift;
1166              
1167 6608         20610 return split q{ }, $str; # This must be a literal space, not $SPACE
1168             }
1169              
1170             #-----------------------------------------------------------------------------
1171              
1172             Readonly::Hash my %ASSIGNMENT_OPERATORS => hashify( qw( = **= += -= .= *= /= %= x= &= |= ^= <<= >>= &&= ||= //= ) );
1173              
1174             sub is_assignment_operator {
1175 56     56 1 16998 my $elem = shift;
1176              
1177 56         263 return $ASSIGNMENT_OPERATORS{ $elem };
1178             }
1179              
1180             #-----------------------------------------------------------------------------
1181              
1182             sub is_unchecked_call {
1183 17     17 1 3472 my ( $elem, $autodie_modules ) = @_;
1184              
1185 17 50       38 return if not is_function_call( $elem );
1186              
1187             # Check to see if there's an '=' or 'unless' or something before this.
1188 17 100       36 return if $elem->sprevious_sibling();
1189              
1190 15 50       198 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 15         151 state $or_or_or = { hashify( qw( or || ) ) };
1198             my $or_operators = sub {
1199 185     185   1405 my (undef, $elem) = @_; ## no critic(Variables::ProhibitReusedNames)
1200 185   100     416 return $elem->isa('PPI::Token::Operator') && exists $or_or_or->{$elem->content};
1201 15         77 };
1202              
1203 15 100       62 return if $statement->find( $or_operators );
1204              
1205 14 50       149 if( my $parent = $elem->statement()->parent() ){
1206              
1207             # Check if we're in an if( open ) {good} else {bad} condition
1208 14 50       202 return if $parent->isa('PPI::Structure::Condition');
1209              
1210             # Return val could be captured in data structure and checked later
1211 14 50       345 return if $parent->isa('PPI::Structure::Constructor');
1212              
1213             # "die if not ( open() )" - It's in list context.
1214 14 100       76 if ( $parent->isa('PPI::Structure::List') ) {
1215 6 100       26 if( my $uncle = $parent->sprevious_sibling() ){
1216 1 50       27 return if $uncle;
1217             }
1218             }
1219             }
1220             }
1221              
1222 13 100       139 return if _is_fatal($elem, $autodie_modules);
1223              
1224             # Otherwise, return. this system call is unchecked.
1225 6         35 return 1;
1226             }
1227              
1228             # Based upon autodie 2.10.
1229             Readonly::Hash my %AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP => (
1230             # Map builtins to themselves.
1231             (
1232             map { $_ => { hashify( $_ ) } }
1233             qw<
1234             accept bind binmode chdir chmod close closedir connect
1235             dbmclose dbmopen exec fcntl fileno flock fork getsockopt ioctl
1236             link listen mkdir msgctl msgget msgrcv msgsnd open opendir
1237             pipe read readlink recv rename rmdir seek semctl semget semop
1238             send setsockopt shmctl shmget shmread shutdown socketpair
1239             symlink sysopen sysread sysseek system syswrite truncate umask
1240             unlink
1241             >
1242             ),
1243              
1244             # Generate these using tools/dump-autodie-tag-contents
1245             ':threads' => { hashify( qw< fork > ) },
1246             ':system' => { hashify( qw< exec system > ) },
1247             ':dbm' => { hashify( qw< dbmclose dbmopen > ) },
1248             ':semaphore' => { hashify( qw< semctl semget semop > ) },
1249             ':shm' => { hashify( qw< shmctl shmget shmread > ) },
1250             ':msg' => { hashify( qw< msgctl msgget msgrcv msgsnd > ) },
1251             ':file' => {
1252             hashify(
1253             qw<
1254             binmode chmod close fcntl fileno flock ioctl open sysopen
1255             truncate
1256             >
1257             )
1258             },
1259             ':filesys' => {
1260             hashify(
1261             qw<
1262             chdir closedir link mkdir opendir readlink rename rmdir
1263             symlink umask unlink
1264             >
1265             )
1266             },
1267             ':ipc' => {
1268             hashify(
1269             qw<
1270             msgctl msgget msgrcv msgsnd pipe semctl semget semop shmctl
1271             shmget shmread
1272             >
1273             )
1274             },
1275             ':socket' => {
1276             hashify(
1277             qw<
1278             accept bind connect getsockopt listen recv send setsockopt
1279             shutdown socketpair
1280             >
1281             )
1282             },
1283             ':io' => {
1284             hashify(
1285             qw<
1286             accept bind binmode chdir chmod close closedir connect
1287             dbmclose dbmopen fcntl fileno flock getsockopt ioctl link
1288             listen mkdir msgctl msgget msgrcv msgsnd open opendir pipe
1289             read readlink recv rename rmdir seek semctl semget semop send
1290             setsockopt shmctl shmget shmread shutdown socketpair symlink
1291             sysopen sysread sysseek syswrite truncate umask unlink
1292             >
1293             )
1294             },
1295             ':default' => {
1296             hashify(
1297             qw<
1298             accept bind binmode chdir chmod close closedir connect
1299             dbmclose dbmopen fcntl fileno flock fork getsockopt ioctl link
1300             listen mkdir msgctl msgget msgrcv msgsnd open opendir pipe
1301             read readlink recv rename rmdir seek semctl semget semop send
1302             setsockopt shmctl shmget shmread shutdown socketpair symlink
1303             sysopen sysread sysseek syswrite truncate umask unlink
1304             >
1305             )
1306             },
1307             ':all' => {
1308             hashify(
1309             qw<
1310             accept bind binmode chdir chmod close closedir connect
1311             dbmclose dbmopen exec fcntl fileno flock fork getsockopt ioctl
1312             link listen mkdir msgctl msgget msgrcv msgsnd open opendir
1313             pipe read readlink recv rename rmdir seek semctl semget semop
1314             send setsockopt shmctl shmget shmread shutdown socketpair
1315             symlink sysopen sysread sysseek system syswrite truncate umask
1316             unlink
1317             >
1318             )
1319             },
1320             );
1321              
1322             sub _is_fatal {
1323 13     13   27 my ( $elem, $autodie_modules ) = @_;
1324              
1325 13         39 my $top = $elem->top();
1326 13 50       141 return if not $top->isa('PPI::Document');
1327              
1328 13         29 my $includes = $top->find('PPI::Statement::Include');
1329 13 100       8453 return if not $includes;
1330              
1331 10         15 for my $include (@{$includes}) {
  10         25  
1332 14 100       118 next if 'use' ne $include->type();
1333              
1334 12 100 66     232 if ('Fatal' eq $include->module()) {
    100          
    100          
1335 2         48 my @args = parse_arg_list($include->schild(1));
1336 2 50   2   12 return $TRUE if any { $_->[0]->isa('PPI::Token::Quote') && $elem eq $_->[0]->string() } @args;
  2 50       13  
1337             }
1338             elsif ('Fatal::Exception' eq $include->module()) {
1339 2         62 my @args = parse_arg_list($include->schild(1));
1340 2         3 shift @args; # skip exception class name
1341 2 50   2   13 return $TRUE if any { $_->[0]->isa('PPI::Token::Quote') && $elem eq $_->[0]->string() } @args;
  2 50       13  
1342             }
1343 4 50   4   11 elsif ($include->pragma eq 'autodie' || any {$_ eq $include->module()} @{$autodie_modules || []}) {
  4         240  
1344 4         221 return _is_covered_by_autodie($elem, $include);
1345             }
1346             }
1347              
1348 2         30 return;
1349             }
1350              
1351             sub _is_covered_by_autodie {
1352 4     4   9 my ($elem, $include) = @_;
1353              
1354 4         9 my $autodie = $include->schild(1);
1355 4         40 my @args = parse_arg_list($autodie);
1356 4         8 my $first_arg = first_arg($autodie);
1357              
1358             # The first argument to any `use` pragma could be a version number.
1359             # If so, then we just discard it. We only want the arguments after it.
1360 4 50 33     43 if ($first_arg and $first_arg->isa('PPI::Token::Number')) {
1361 0         0 shift @args;
1362             }
1363              
1364 4 100       9 if (@args) {
1365 3         6 my $elem_content = $elem->content();
1366 3         9 foreach my $arg (@args) {
1367             my $builtins =
1368             $AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP{
1369 4         18 $arg->[0]->string
1370             };
1371              
1372 4 100 66     52 return $TRUE if $builtins and $builtins->{$elem_content};
1373             }
1374             }
1375             else {
1376             my $builtins =
1377 1         5 $AUTODIE_PARAMETER_TO_AFFECTED_BUILTINS_MAP{':default'};
1378              
1379 1 50 33     11 return $TRUE if $builtins and $builtins->{$elem->content()};
1380             }
1381              
1382 1         9 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 :