File Coverage

blib/lib/Perl/Critic/Utils.pm
Criterion Covered Total %
statement 305 334 91.3
branch 144 220 65.4
condition 52 97 53.6
subroutine 62 68 91.1
pod 39 39 100.0
total 602 758 79.4


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