1 ##############################################################################
2 # $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/Perl-Critic/lib/Perl/Critic/Utils.pm $
3 # $Date: 2008-07-03 10:19:10 -0500 (Thu, 03 Jul 2008) $
6 ##############################################################################
8 # NOTE: This module is way too large. Please think about adding new
9 # functionality into a P::C::Utils::* module instead.
11 package Perl::Critic::Utils;
19 use Scalar::Util qw( blessed );
21 use PPI::Token::Quote::Single;
23 use Perl::Critic::Exception::Fatal::Generic qw{ throw_generic };
24 use Perl::Critic::Utils::PPI qw< is_ppi_expression_or_generic_statement >;
28 our $VERSION = '1.088';
30 #-----------------------------------------------------------------------------
31 # Exportable symbols here.
33 Readonly::Array our @EXPORT_OK => qw(
47 $DEFAULT_VERBOSITY_WITH_FILE_NAME
74 is_included_module_name
78 is_package_declaration
81 is_perl_builtin_with_list_context
82 is_perl_builtin_with_multiple_arguments
83 is_perl_builtin_with_no_arguments
84 is_perl_builtin_with_one_argument
85 is_perl_builtin_with_optional_argument
86 is_perl_builtin_with_zero_and_or_one_arguments
93 is_valid_numeric_verbosity
106 # Note: this is deprecated.
107 Readonly::Array our @EXPORT => @EXPORT_OK; ## no critic (ProhibitAutomaticExport)
110 Readonly::Hash our %EXPORT_TAGS => (
111 all => [ @EXPORT_OK ],
112 booleans => [ qw{ $TRUE $FALSE } ],
147 is_included_module_name
151 is_package_declaration
156 is_perl_builtin_with_list_context
157 is_perl_builtin_with_multiple_arguments
158 is_perl_builtin_with_no_arguments
159 is_perl_builtin_with_one_argument
160 is_perl_builtin_with_optional_argument
161 is_perl_builtin_with_zero_and_or_one_arguments
166 is_valid_numeric_verbosity
169 data_conversion => [ qw{ hashify words_from_string interpolate } ],
170 ppi => [ qw{ first_arg parse_arg_list } ],
171 internal_lookup => [ qw{ severity_to_number verbosity_to_format } ],
172 language => [ qw{ precedence_of } ],
173 deprecated => [ qw{ find_keywords } ],
176 #-----------------------------------------------------------------------------
178 Readonly::Scalar our $POLICY_NAMESPACE => 'Perl::Critic::Policy';
180 #-----------------------------------------------------------------------------
182 Readonly::Scalar our $SEVERITY_HIGHEST => 5;
183 Readonly::Scalar our $SEVERITY_HIGH => 4;
184 Readonly::Scalar our $SEVERITY_MEDIUM => 3;
185 Readonly::Scalar our $SEVERITY_LOW => 2;
186 Readonly::Scalar our $SEVERITY_LOWEST => 1;
188 #-----------------------------------------------------------------------------
190 Readonly::Scalar our $COMMA => q{,};
191 Readonly::Scalar our $FATCOMMA => q{=>};
192 Readonly::Scalar our $COLON => q{:};
193 Readonly::Scalar our $SCOLON => q{;};
194 Readonly::Scalar our $QUOTE => q{'};
195 Readonly::Scalar our $DQUOTE => q{"};
196 Readonly::Scalar our $BACKTICK => q{`};
197 Readonly::Scalar our $PERIOD => q{.};
198 Readonly::Scalar our $PIPE => q{|};
199 Readonly::Scalar our $SPACE => q{ };
200 Readonly::Scalar our $SLASH => q{/};
201 Readonly::Scalar our $BSLASH => q{\\};
202 Readonly::Scalar our $LEFT_PAREN => q{(};
203 Readonly::Scalar our $RIGHT_PAREN => q{)};
204 Readonly::Scalar our $EMPTY => q{};
205 Readonly::Scalar our $TRUE => 1;
206 Readonly::Scalar our $FALSE => 0;
208 #-----------------------------------------------------------------------------
210 #TODO: Should this include punctuations vars?
214 #-----------------------------------------------------------------------------
215 ## no critic (ProhibitNoisyQuotes);
217 Readonly::Hash my %PRECEDENCE_OF => (
218 '->' => 1, '<' => 10, '//' => 15, '.=' => 19,
219 '++' => 2, '>' => 10, '||' => 15, '^=' => 19,
220 '--' => 2, '<=' => 10, '..' => 16, '<<=' => 19,
221 '**' => 3, '>=' => 10, '...' => 17, '>>=' => 19,
222 '!' => 4, 'lt' => 10, '?' => 18, ',' => 20,
223 '~' => 4, 'gt' => 10, ':' => 18, '=>' => 20,
224 '\\' => 4, 'le' => 10, '=' => 19, 'not' => 22,
225 '=~' => 5, 'ge' => 10, '+=' => 19, 'and' => 23,
226 '!~' => 5, '==' => 11, '-=' => 19, 'or' => 24,
227 '*' => 6, '!=' => 11, '*=' => 19, 'xor' => 24,
228 '/' => 6, '<=>' => 11, '/=' => 19,
229 '%' => 6, 'eq' => 11, '%=' => 19,
230 'x' => 6, 'ne' => 11, '||=' => 19,
231 '+' => 7, 'cmp' => 11, '&&=' => 19,
232 '-' => 7, '&' => 12, '|=' => 19,
233 '.' => 7, '|' => 13, '&=' => 19,
234 '<<' => 8, '^' => 13, '**=' => 19,
235 '>>' => 8, '&&' => 14, 'x=' => 19,
239 #-----------------------------------------------------------------------------
241 sub hashify { ##no critic(ArgUnpacking)
242 return map { $_ => 1 } @_;
245 #-----------------------------------------------------------------------------
248 my ( $literal ) = @_;
249 return eval "\"$literal\""; ## no critic 'StringyEval';
252 #-----------------------------------------------------------------------------
255 my ( $doc, $keyword ) = @_;
256 my $nodes_ref = $doc->find('PPI::Token::Word');
257 return if !$nodes_ref;
258 my @matches = grep { $_ eq $keyword } @{$nodes_ref};
259 return @matches ? \@matches : undef;
262 #-----------------------------------------------------------------------------
264 sub _name_for_sub_or_stringified_element {
267 if ( blessed $elem and $elem->isa('PPI::Statement::Sub') ) {
268 return $elem->name();
274 #-----------------------------------------------------------------------------
275 ## no critic (ProhibitPackageVars)
277 Readonly::Hash my %BUILTINS => hashify( @B::Keywords::Functions );
279 sub is_perl_builtin {
283 return exists $BUILTINS{ _name_for_sub_or_stringified_element($elem) };
286 #-----------------------------------------------------------------------------
288 Readonly::Hash my %BAREWORDS => hashify( @B::Keywords::Barewords );
290 sub is_perl_bareword {
294 return exists $BAREWORDS{ _name_for_sub_or_stringified_element($elem) };
297 #-----------------------------------------------------------------------------
299 sub _build_globals_without_sigils {
300 my @globals = map { substr $_, 1 } @B::Keywords::Arrays,
301 @B::Keywords::Hashes,
302 @B::Keywords::Scalars;
304 # Not all of these have sigils
305 foreach my $filehandle (@B::Keywords::Filehandles) {
306 (my $stripped = $filehandle) =~ s< \A [*] ><>xms;
307 push @globals, $stripped;
313 Readonly::Array my @GLOBALS_WITHOUT_SIGILS => _build_globals_without_sigils();
315 Readonly::Hash my %GLOBALS => hashify( @GLOBALS_WITHOUT_SIGILS );
320 my $var_name = "$elem"; #Convert Token::Symbol to string
321 $var_name =~ s{\A [\$@%*] }{}mx; #Chop off the sigil
322 return exists $GLOBALS{ $var_name };
325 #-----------------------------------------------------------------------------
327 Readonly::Hash my %FILEHANDLES => hashify( @B::Keywords::Filehandles );
329 sub is_perl_filehandle {
333 return exists $FILEHANDLES{ _name_for_sub_or_stringified_element($elem) };
337 #-----------------------------------------------------------------------------
339 # egrep '=item.*LIST' perlfunc.pod
340 Readonly::Hash my %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT =>
375 sub is_perl_builtin_with_list_context {
380 $BUILTINS_WHICH_PROVIDE_LIST_CONTEXT{
381 _name_for_sub_or_stringified_element($elem)
385 #-----------------------------------------------------------------------------
387 # egrep '=item.*[A-Z],' perlfunc.pod
388 Readonly::Hash my %BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS =>
453 keys %BUILTINS_WHICH_PROVIDE_LIST_CONTEXT
456 sub is_perl_builtin_with_multiple_arguments {
461 $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{
462 _name_for_sub_or_stringified_element($elem)
466 #-----------------------------------------------------------------------------
468 Readonly::Hash my %BUILTINS_WHICH_TAKE_NO_ARGUMENTS =>
497 sub is_perl_builtin_with_no_arguments {
502 $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{
503 _name_for_sub_or_stringified_element($elem)
507 #-----------------------------------------------------------------------------
509 Readonly::Hash my %BUILTINS_WHICH_TAKE_ONE_ARGUMENT =>
549 sub is_perl_builtin_with_one_argument {
554 $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{
555 _name_for_sub_or_stringified_element($elem)
559 #-----------------------------------------------------------------------------
561 ## no critic (ProhibitPackageVars)
562 Readonly::Hash my %BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT =>
564 grep { not exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $_ } }
565 grep { not exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $_ } }
566 grep { not exists $BUILTINS_WHICH_TAKE_MULTIPLE_ARGUMENTS{ $_ } }
567 @B::Keywords::Functions
571 sub is_perl_builtin_with_optional_argument {
576 $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{
577 _name_for_sub_or_stringified_element($elem)
581 #-----------------------------------------------------------------------------
583 sub is_perl_builtin_with_zero_and_or_one_arguments {
588 my $name = _name_for_sub_or_stringified_element($elem);
591 exists $BUILTINS_WHICH_TAKE_ONE_ARGUMENT{ $name }
592 or exists $BUILTINS_WHICH_TAKE_NO_ARGUMENTS{ $name }
593 or exists $BUILTINS_WHICH_TAKE_OPTIONAL_ARGUMENT{ $name }
597 #-----------------------------------------------------------------------------
599 sub is_qualified_name {
604 return index ( $name, q{::} ) >= 0;
607 #-----------------------------------------------------------------------------
612 return $PRECEDENCE_OF{ ref $elem ? "$elem" : $elem };
615 #-----------------------------------------------------------------------------
621 #If followed by an argument list, then its a function call, not a literal
622 return if _is_followed_by_parens($elem);
624 #Check curly-brace style: $hash{foo} = bar;
625 my $parent = $elem->parent();
627 my $grandparent = $parent->parent();
628 return if !$grandparent;
629 return 1 if $grandparent->isa('PPI::Structure::Subscript');
632 #Check declarative style: %hash = (foo => bar);
633 my $sib = $elem->snext_sibling();
635 return 1 if $sib->isa('PPI::Token::Operator') && $sib eq '=>';
640 #-----------------------------------------------------------------------------
642 sub _is_followed_by_parens {
646 my $sibling = $elem->snext_sibling() || return;
647 return $sibling->isa('PPI::Structure::List');
650 #-----------------------------------------------------------------------------
652 sub is_included_module_name {
655 my $stmnt = $elem->statement();
657 return if !$stmnt->isa('PPI::Statement::Include');
658 return $stmnt->schild(1) == $elem;
661 #-----------------------------------------------------------------------------
665 return 0 if not defined $value;
667 return $value =~ m{ \A [+-]? \d+ \z }mx;
670 #-----------------------------------------------------------------------------
672 sub is_label_pointer {
676 my $statement = $elem->statement();
677 return if !$statement;
679 my $psib = $elem->sprevious_sibling();
682 return $statement->isa('PPI::Statement::Break')
683 && $psib =~ m/(?:redo|goto|next|last)/mxo;
686 #-----------------------------------------------------------------------------
692 return _is_dereference_operator( $elem->sprevious_sibling() );
695 #-----------------------------------------------------------------------------
701 return _is_dereference_operator( $elem->snext_sibling() )
702 && !_is_dereference_operator( $elem->sprevious_sibling() );
705 #-----------------------------------------------------------------------------
707 sub _is_dereference_operator {
711 return $elem->isa('PPI::Token::Operator') && $elem eq q{->};
714 #-----------------------------------------------------------------------------
716 sub is_package_declaration {
719 my $stmnt = $elem->statement();
721 return if !$stmnt->isa('PPI::Statement::Package');
722 return $stmnt->schild(1) == $elem;
725 #-----------------------------------------------------------------------------
727 sub is_subroutine_name {
730 my $sib = $elem->sprevious_sibling();
732 my $stmnt = $elem->statement();
734 return $stmnt->isa('PPI::Statement::Sub') && $sib eq 'sub';
737 #-----------------------------------------------------------------------------
739 sub is_function_call {
743 return if is_hash_key($elem);
744 return if is_method_call($elem);
745 return if is_class_name($elem);
746 return if is_subroutine_name($elem);
747 return if is_included_module_name($elem);
748 return if is_package_declaration($elem);
749 return if is_perl_bareword($elem);
750 return if is_perl_filehandle($elem);
751 return if is_label_pointer($elem);
756 #-----------------------------------------------------------------------------
761 return shebang_line($doc) ? 1 : 0;
764 #-----------------------------------------------------------------------------
766 sub is_in_void_context {
769 # If part of a collective, can't be void.
770 return if $token->sprevious_sibling();
772 my $parent = $token->statement()->parent();
774 return if $parent->isa('PPI::Structure::List');
775 return if $parent->isa('PPI::Structure::ForLoop');
776 return if $parent->isa('PPI::Structure::Condition');
777 return if $parent->isa('PPI::Structure::Constructor');
779 my $grand_parent = $parent->parent();
782 $parent->isa('PPI::Structure::Block')
783 and not $grand_parent->isa('PPI::Statement::Compound');
790 #-----------------------------------------------------------------------------
792 sub policy_long_name {
793 my ( $policy_name ) = @_;
794 if ( $policy_name !~ m{ \A $POLICY_NAMESPACE }mx ) {
795 $policy_name = $POLICY_NAMESPACE . q{::} . $policy_name;
800 #-----------------------------------------------------------------------------
802 sub policy_short_name {
803 my ( $policy_name ) = @_;
804 $policy_name =~ s{\A $POLICY_NAMESPACE ::}{}mx;
808 #-----------------------------------------------------------------------------
812 my $sib = $elem->snext_sibling();
815 if ( $sib->isa('PPI::Structure::List') ) {
817 my $expr = $sib->schild(0);
819 return $expr->isa('PPI::Statement') ? $expr->schild(0) : $expr;
825 #-----------------------------------------------------------------------------
829 my $sib = $elem->snext_sibling();
832 if ( $sib->isa('PPI::Structure::List') ) {
834 #Pull siblings from list
835 my @list_contents = $sib->schildren();
836 return if not @list_contents;
838 my @list_expressions;
839 foreach my $item (@list_contents) {
841 is_ppi_expression_or_generic_statement($item)
845 split_nodes_on_comma( $item->schildren() );
848 push @list_expressions, $item;
852 return @list_expressions;
856 #Gather up remaining nodes in the statement
860 while ($iter = $iter->snext_sibling() ) {
861 last if $iter->isa('PPI::Token::Structure') and $iter eq $SCOLON;
862 push @arg_list, $iter;
864 return split_nodes_on_comma( @arg_list );
868 #---------------------------------
870 sub split_nodes_on_comma {
875 for my $node (@nodes) {
877 $node->isa('PPI::Token::Operator')
878 and ($node eq $COMMA or $node eq $FATCOMMA)
881 $i++; #Move forward to next 'node stack'
884 } elsif ( $node->isa('PPI::Token::QuoteLike::Words' )) {
885 my $section = $node->{sections}->[0];
886 my @words = words_from_string(substr $node->content, $section->{position}, $section->{size});
887 my $loc = $node->location;
888 for my $word (@words) {
889 my $token = PPI::Token::Quote::Single->new(q{'} . $word . q{'});
890 $token->{_location} = $loc;
891 push @{ $node_stacks[$i++] }, $token;
895 push @{ $node_stacks[$i] }, $node;
900 #-----------------------------------------------------------------------------
902 # XXX: You must keep the regular expressions in extras/perlcritic.el in sync
903 # if you change these.
904 Readonly::Hash my %FORMAT_OF => (
905 1 => "%f:%l:%c:%m\n",
906 2 => "%f: (%l:%c) %m\n",
907 3 => "%m at %f line %l\n",
908 4 => "%m at line %l, column %c. %e. (Severity: %s)\n",
909 5 => "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
910 6 => "%m at line %l, near '%r'. (Severity: %s)\n",
911 7 => "%f: %m at line %l near '%r'. (Severity: %s)\n",
912 8 => "[%p] %m at line %l, column %c. (Severity: %s)\n",
913 9 => "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
914 10 => "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
915 11 => "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n",
918 Readonly::Scalar our $DEFAULT_VERBOSITY => 4;
919 Readonly::Scalar our $DEFAULT_VERBOSITY_WITH_FILE_NAME => 5;
920 Readonly::Scalar my $DEFAULT_FORMAT => $FORMAT_OF{$DEFAULT_VERBOSITY};
922 sub is_valid_numeric_verbosity {
923 my ($verbosity) = @_;
925 return exists $FORMAT_OF{$verbosity};
928 sub verbosity_to_format {
929 my ($verbosity) = @_;
930 return $DEFAULT_FORMAT if not defined $verbosity;
931 return $FORMAT_OF{abs int $verbosity} || $DEFAULT_FORMAT if is_integer($verbosity);
932 return interpolate( $verbosity ); #Otherwise, treat as a format spec
935 #-----------------------------------------------------------------------------
937 Readonly::Hash my %SEVERITY_NUMBER_OF => (
945 Readonly::Array our @SEVERITY_NAMES => #This is exported!
947 { $SEVERITY_NUMBER_OF{$a} <=> $SEVERITY_NUMBER_OF{$b} }
948 keys %SEVERITY_NUMBER_OF;
950 sub severity_to_number {
952 return _normalize_severity( $severity ) if is_integer( $severity );
953 my $severity_number = $SEVERITY_NUMBER_OF{lc $severity};
955 if ( not defined $severity_number ) {
956 throw_generic qq{Invalid severity: "$severity"};
959 return $severity_number;
962 sub _normalize_severity {
963 my $s = shift || return $SEVERITY_HIGHEST;
964 $s = $s > $SEVERITY_HIGHEST ? $SEVERITY_HIGHEST : $s;
965 $s = $s < $SEVERITY_LOWEST ? $SEVERITY_LOWEST : $s;
969 #-----------------------------------------------------------------------------
971 Readonly::Array my @skip_dir => qw( CVS RCS .svn _darcs {arch} .bzr _build blib );
972 Readonly::Hash my %skip_dir => hashify( @skip_dir );
976 # Recursively searches a list of directories and returns the paths
977 # to files that seem to be Perl source code. This subroutine was
978 # poached from Test::Perl::Critic.
984 my $file = shift @queue;
986 opendir my ($dh), $file or next;
987 my @newfiles = sort readdir $dh;
990 @newfiles = File::Spec->no_upwards(@newfiles);
991 @newfiles = grep { !$skip_dir{$_} } @newfiles;
992 push @queue, map { File::Spec->catfile($file, $_) } @newfiles;
995 if ( (-f $file) && ! _is_backup($file) && _is_perl($file) ) {
996 push @code_files, $file;
1003 #-----------------------------------------------------------------------------
1004 # Decide if it's some sort of backup file
1008 return 1 if $file =~ m{ [.] swp \z}mx;
1009 return 1 if $file =~ m{ [.] bak \z}mx;
1010 return 1 if $file =~ m{ ~ \z}mx;
1011 return 1 if $file =~ m{ \A [#] .+ [#] \z}mx;
1015 #-----------------------------------------------------------------------------
1016 # Returns true if the argument ends with a perl-ish file
1017 # extension, or if it has a shebang-line containing 'perl' This
1018 # subroutine was also poached from Test::Perl::Critic
1023 #Check filename extensions
1024 return 1 if $file =~ m{ [.] PL \z}mx;
1025 return 1 if $file =~ m{ [.] p[lm] \z}mx;
1026 return 1 if $file =~ m{ [.] t \z}mx;
1029 open my $fh, '<', $file or return;
1031 close $fh or throw_generic "unable to close $file: $!";
1033 return 1 if defined $first && ( $first =~ m{ \A [#]!.*perl }mx );
1037 #-----------------------------------------------------------------------------
1041 my $first_element = $doc->first_element();
1042 return if not $first_element;
1043 return if not $first_element->isa('PPI::Token::Comment');
1044 my $location = $first_element->location();
1045 return if !$location;
1046 # The shebang must be the first two characters in the file, according to
1047 # http://en.wikipedia.org/wiki/Shebang_(Unix)
1048 return if $location->[0] != 1; # line number
1049 return if $location->[1] != 1; # column number
1050 my $shebang = $first_element->content;
1051 return if $shebang !~ m{ \A [#]! }mx;
1055 #-----------------------------------------------------------------------------
1057 sub words_from_string {
1060 return split q{ }, $str; # This must be a literal space, not $SPACE
1063 #-----------------------------------------------------------------------------
1065 sub is_unchecked_call {
1068 return if not is_function_call( $elem );
1070 # check to see if there's an '=' or 'unless' or something before this.
1071 if( my $sib = $elem->sprevious_sibling() ){
1076 if( my $statement = $elem->statement() ){
1078 # "open or die" is OK.
1079 # We can't check snext_sibling for 'or' since the next siblings are an
1080 # unknown number of arguments to the system call. Instead, check all of
1081 # the elements to this statement to see if we find 'or' or '||'.
1083 my $or_operators = sub {
1084 my (undef, $elem) = @_;
1085 return if not $elem->isa('PPI::Token::Operator');
1086 return if $elem ne q{or} && $elem ne q{||};
1090 return if $statement->find( $or_operators );
1093 if( my $parent = $elem->statement()->parent() ){
1095 # Check if we're in an if( open ) {good} else {bad} condition
1096 return if $parent->isa('PPI::Structure::Condition');
1098 # Return val could be captured in data structure and checked later
1099 return if $parent->isa('PPI::Structure::Constructor');
1101 # "die if not ( open() )" - It's in list context.
1102 if ( $parent->isa('PPI::Structure::List') ) {
1103 if( my $uncle = $parent->sprevious_sibling() ){
1110 return if _is_fatal($elem);
1112 # Otherwise, return. this system call is unchecked.
1119 my $top = $elem->top;
1120 return if !$top->isa('PPI::Document');
1121 my $includes = $top->find('PPI::Statement::Include');
1122 return if !$includes;
1123 for my $include (@{$includes}) {
1124 next if 'use' ne $include->type;
1125 if ('Fatal' eq $include->module) {
1126 my @args = parse_arg_list($include->schild(1));
1127 for my $arg (@args) {
1128 return 1 if $arg->[0]->isa('PPI::Token::Quote') && $elem eq $arg->[0]->string;
1130 } elsif ('Fatal::Exception' eq $include->module) {
1131 my @args = parse_arg_list($include->schild(1));
1132 shift @args; # skip exception class name
1133 for my $arg (@args) {
1134 return 1 if $arg->[0]->isa('PPI::Token::Quote') && $elem eq $arg->[0]->string;
1149 Perl::Critic::Utils - General utility subroutines and constants for Perl::Critic and derivative distributions.
1153 This module provides several static subs and variables that are useful for
1154 developing L<Perl::Critic::Policy> subclasses. Unless you are writing Policy
1155 modules, you probably don't care about this package.
1157 =head1 IMPORTABLE SUBS
1161 =item C<find_keywords( $doc, $keyword )>
1163 B<DEPRECATED:> Since version 0.11, every Policy is evaluated at each element
1164 of the document. So you shouldn't need to go looking for a particular
1165 keyword. If you I<do> want to use this, please import it via the
1166 C<:deprecated> tag, rather than directly, to mark the module as needing
1169 Given a L<PPI::Document> as C<$doc>, returns a reference to an array
1170 containing all the L<PPI::Token::Word> elements that match C<$keyword>. This
1171 can be used to find any built-in function, method call, bareword, or reserved
1172 keyword. It will not match variables, subroutine names, literal strings,
1173 numbers, or symbols. If the document doesn't contain any matches, returns
1176 =item C<is_perl_global( $element )>
1178 Given a L<PPI::Token::Symbol> or a string, returns true if that token
1179 represents one of the global variables provided by the L<English> module, or
1180 one of the builtin global variables like C<%SIG>, C<%ENV>, or C<@ARGV>. The
1181 sigil on the symbol is ignored, so things like C<$ARGV> or C<$ENV> will still
1184 =item C<is_perl_builtin( $element )>
1186 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1187 if that token represents a call to any of the builtin functions defined in
1190 =item C<is_perl_bareword( $element )>
1192 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1193 if that token represents a bareword (e.g. "if", "else", "sub", "package")
1194 defined in Perl 5.8.8.
1196 =item C<is_perl_filehandle( $element )>
1198 Given a L<PPI::Token::Word>, or string, returns true if that token represents
1199 one of the global filehandles (e.g. C<STDIN>, C<STDERR>, C<STDOUT>, C<ARGV>)
1200 that are defined in Perl 5.8.8. Note that this function will return false if
1201 given a filehandle that is represented as a typeglob (e.g. C<*STDIN>)
1203 =item C<is_perl_builtin_with_list_context( $element )>
1205 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1206 if that token represents a call to any of the builtin functions defined in
1207 Perl 5.8.8 that provide a list context to the following tokens.
1209 =item C<is_perl_builtin_with_multiple_arguments( $element )>
1211 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1212 if that token represents a call to any of the builtin functions defined in
1213 Perl 5.8.8 that B<can> take multiple arguments.
1215 =item C<is_perl_builtin_with_no_arguments( $element )>
1217 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1218 if that token represents a call to any of the builtin functions defined in
1219 Perl 5.8.8 that B<cannot> take any arguments.
1221 =item C<is_perl_builtin_with_one_argument( $element )>
1223 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1224 if that token represents a call to any of the builtin functions defined in
1225 Perl 5.8.8 that takes B<one and only one> argument.
1227 =item C<is_perl_builtin_with_optional_argument( $element )>
1229 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1230 if that token represents a call to any of the builtin functions defined in
1231 Perl 5.8.8 that takes B<no more than one> argument.
1233 The sets of values for which C<is_perl_builtin_with_multiple_arguments()>,
1234 C<is_perl_builtin_with_no_arguments()>,
1235 C<is_perl_builtin_with_one_argument()>, and
1236 C<is_perl_builtin_with_optional_argument()> return true are disjoint and
1237 their union is precisely the set of values that C<is_perl_builtin()> will
1240 =item C<is_perl_builtin_with_zero_and_or_one_arguments( $element )>
1242 Given a L<PPI::Token::Word>, L<PPI::Statement::Sub>, or string, returns true
1243 if that token represents a call to any of the builtin functions defined in
1244 Perl 5.8.8 that takes no and/or one argument.
1246 Returns true if any of C<is_perl_builtin_with_no_arguments()>,
1247 C<is_perl_builtin_with_one_argument()>, and
1248 C<is_perl_builtin_with_optional_argument()> returns true.
1250 =item C<is_qualified_name( $name )>
1252 Given a string, L<PPI::Token::Word>, or L<PPI::Token::Symbol>, answers
1253 whether it has a module component, i.e. contains "::".
1255 =item C<precedence_of( $element )>
1257 Given a L<PPI::Token::Operator> or a string, returns the precedence of the
1258 operator, where 1 is the highest precedence. Returns undef if the precedence
1259 can't be determined (which is usually because it is not an operator).
1261 =item C<is_hash_key( $element )>
1263 Given a L<PPI::Element>, returns true if the element is a literal hash key.
1264 PPI doesn't distinguish between regular barewords (like keywords or subroutine
1265 calls) and barewords in hash subscripts (which are considered literal). So
1266 this subroutine is useful if your Policy is searching for L<PPI::Token::Word>
1267 elements and you want to filter out the hash subscript variety. In both of
1268 the following examples, "foo" is considered a hash key:
1271 %hash2 = (foo => 1);
1273 But if the bareword is followed by an argument list, then perl treats it as a
1274 function call. So in these examples, "foo" is B<not> considered a hash key:
1276 $hash1{ foo() } = 1;
1277 &hash2 = (foo() => 1);
1279 =item C<is_included_module_name( $element )>
1281 Given a L<PPI::Token::Word>, returns true if the element is the name of a
1282 module that is being included via C<use>, C<require>, or C<no>.
1284 =item C<is_integer( $value )>
1286 Answers whether the parameter, as a string, looks like an integral value.
1288 =item C<is_class_name( $element )>
1290 Given a L<PPI::Token::Word>, returns true if the element that immediately
1291 follows this element is the dereference operator "->". When a bareword has a
1292 "->" on the B<right> side, it usually means that it is the name of the class
1293 (from which a method is being called).
1295 =item C<is_label_pointer( $element )>
1297 Given a L<PPI::Token::Word>, returns true if the element is the label
1298 in a C<next>, C<last>, C<redo>, or C<goto> statement. Note this is not the
1299 same thing as the label declaration.
1301 =item C<is_method_call( $element )>
1303 Given a L<PPI::Token::Word>, returns true if the element that immediately
1304 precedes this element is the dereference operator "->". When a bareword has a
1305 "->" on the B<left> side, it usually means that it is the name of a method
1306 (that is being called from a class).
1308 =item C<is_package_declaration( $element )>
1310 Given a L<PPI::Token::Word>, returns true if the element is the name of a
1311 package that is being declared.
1313 =item C<is_subroutine_name( $element )>
1315 Given a L<PPI::Token::Word>, returns true if the element is the name of a
1316 subroutine declaration. This is useful for distinguishing barewords and from
1317 function calls from subroutine declarations.
1319 =item C<is_function_call( $element )>
1321 Given a L<PPI::Token::Word> returns true if the element appears to be call to
1322 a static function. Specifically, this function returns true if
1323 C<is_hash_key>, C<is_method_call>, C<is_subroutine_name>,
1324 C<is_included_module_anme>, C<is_package_declaration>, C<is_perl_bareword>,
1325 C<is_perl_filehandle>, C<is_label_pointer> and C<is_subroutine_name> all
1326 return false for the given element.
1328 =item C<first_arg( $element )>
1330 Given a L<PPI::Element> that is presumed to be a function call (which is
1331 usually a L<PPI::Token::Word>), return the first argument. This is similar of
1332 C<parse_arg_list()> and follows the same logic. Note that for the code:
1336 this function will return just the C<$x>, not the whole expression. This is
1337 different from the behavior of C<parse_arg_list()>. Another caveat is:
1339 int(($x + $y) + 0.5)
1341 which returns C<($x + $y)> as a L<PPI::Structure::List> instance.
1343 =item C<parse_arg_list( $element )>
1345 Given a L<PPI::Element> that is presumed to be a function call (which is
1346 usually a L<PPI::Token::Word>), splits the argument expressions into arrays of
1347 tokens. Returns a list containing references to each of those arrays. This
1348 is useful because parentheses are optional when calling a function, and PPI
1349 parses them very differently. So this method is a poor-man's parse tree of
1350 PPI nodes. It's not bullet-proof because it doesn't respect precedence. In
1351 general, I don't like the way this function works, so don't count on it to be
1352 stable (or even present).
1354 =item C<split_nodes_on_comma( @nodes )>
1356 This has the same return type as C<parse_arg_list()> but expects to be passed
1357 the nodes that represent the interior of a list, like:
1361 =item C<is_script( $document )>
1363 Given a L<PPI::Document>, test if it starts with C</#!.*/>. If so, it is
1364 judged to be a script instead of a module. See C<shebang_line()>.
1366 =item C<is_in_void_context( $token )>
1368 Given a L<PPI::Token>, answer whether it appears to be in a void context.
1370 =item C<policy_long_name( $policy_name )>
1372 Given a policy class name in long or short form, return the long form.
1374 =item C<policy_short_name( $policy_name )>
1376 Given a policy class name in long or short form, return the short form.
1378 =item C<all_perl_files( @directories )>
1380 Given a list of directories, recursively searches through all the directories
1381 (depth first) and returns a list of paths for all the files that are Perl code
1382 files. Any administrative files for CVS or Subversion are skipped, as are
1383 things that look like temporary or backup files.
1385 A Perl code file is:
1389 =item * Any file that ends in F<.PL>, F<.pl>, F<.pm>, or F<.t>
1391 =item * Any file that has a first line with a shebang containing 'perl'
1395 =item C<severity_to_number( $severity )>
1397 If C<$severity> is given as an integer, this function returns C<$severity> but
1398 normalized to lie between C<$SEVERITY_LOWEST> and C<$SEVERITY_HIGHEST>. If
1399 C<$severity> is given as a string, this function returns the corresponding
1400 severity number. If the string doesn't have a corresponding number, this
1401 function will throw an exception.
1403 =item C<is_valid_numeric_verbosity( $severity )>
1405 Answers whether the argument has a translation to a Violation format.
1407 =item C<verbosity_to_format( $verbosity_level )>
1409 Given a verbosity level between 1 and 10, returns the corresponding predefined
1410 format string. These formats are suitable for passing to the C<set_format>
1411 method in L<Perl::Critic::Violation>. See the L<perlcritic> documentation for
1412 a listing of the predefined formats.
1414 =item C<hashify( @list )>
1416 Given C<@list>, return a hash where C<@list> is in the keys and each value is
1417 1. Duplicate values in C<@list> are silently squished.
1419 =item C<interpolate( $literal )>
1421 Given a C<$literal> string that may contain control characters (e.g.. '\t'
1422 '\n'), this function does a double interpolation on the string and returns it
1423 as if it had been declared in double quotes. For example:
1425 'foo \t bar \n' ...becomes... "foo \t bar \n"
1427 =item C<shebang_line( $document )>
1429 Given a L<PPI::Document>, test if it starts with C<#!>. If so, return that
1430 line. Otherwise return undef.
1432 =item C<words_from_string( $str )>
1434 Given config string I<$str>, return all the words from the string. This is
1435 safer than splitting on whitespace.
1437 =item C<is_unchecked_call( $element )>
1439 Given a L<PPI::Element>, test to see if it contains a function call whose
1440 return value is not checked.
1444 =head1 IMPORTABLE VARIABLES
1474 =item C<$LEFT_PAREN>
1476 =item C<$RIGHT_PAREN>
1478 These character constants give clear names to commonly-used strings that can
1479 be hard to read when surrounded by quotes and other punctuation. Can be
1480 imported in one go via the C<:characters> tag.
1482 =item C<$SEVERITY_HIGHEST>
1484 =item C<$SEVERITY_HIGH>
1486 =item C<$SEVERITY_MEDIUM>
1488 =item C<$SEVERITY_LOW>
1490 =item C<$SEVERITY_LOWEST>
1492 These numeric constants define the relative severity of violating each
1493 L<Perl::Critic::Policy>. The C<get_severity> and C<default_severity> methods
1494 of every Policy subclass must return one of these values. Can be imported via
1495 the C<:severities> tag.
1497 =item C<$DEFAULT_VERBOSITY>
1499 The default numeric verbosity.
1501 =item C<$DEFAULT_VERBOSITY_WITH_FILE_NAME>
1503 The numeric verbosity that corresponds to the format indicated by
1504 C<$DEFAULT_VERBOSITY>, but with the file name prefixed to it.
1510 These are simple booleans. 1 and 0 respectively. Be mindful of using these
1511 with string equality. C<$FALSE ne $EMPTY>. Can be imported via the
1518 The following groups of functions and constants are available as parameters to
1519 a C<use Perl::Critic::Util> statement.
1532 =item C<:severities>
1535 C<$SEVERITY_HIGHEST>,
1537 C<$SEVERITY_MEDIUM>,
1539 C<$SEVERITY_LOWEST>,
1542 =item C<:characters>
1561 =item C<:classification>
1564 C<is_function_call>,
1566 C<is_included_module_name>,
1569 C<is_package_declaration>,
1572 C<is_perl_builtin_with_list_context>
1573 C<is_perl_builtin_with_multiple_arguments>
1574 C<is_perl_builtin_with_no_arguments>
1575 C<is_perl_builtin_with_one_argument>
1576 C<is_perl_builtin_with_optional_argument>
1577 C<is_perl_builtin_with_zero_and_or_one_arguments>
1579 C<is_subroutine_name>,
1580 C<is_unchecked_call>
1581 C<is_valid_numeric_verbosity>
1583 See also L<Perl::Critic::Utils::PPI>.
1585 =item C<:data_conversion>
1587 Generic manipulation, not having anything specific to do with Perl::Critic.
1591 C<words_from_string>,
1596 Things for dealing with L<PPI>, other than classification.
1602 See also L<Perl::Critic::Utils::PPI>.
1604 =item C<:internal_lookup>
1606 Translations between internal representations.
1609 C<severity_to_number>,
1610 C<verbosity_to_format>
1614 Information about Perl not programmatically available elsewhere.
1619 =item C<:deprecated>
1621 Not surprisingly, things that are deprecated. It is preferred to use this tag
1622 to get to these functions, rather than the function names themselves, so as to
1623 mark any module using them as needing cleanup.
1632 L<Perl::Critic::Utils::Constants>,
1633 L<Perl::Critic::Utils::McCabe>,
1634 L<Perl::Critic::Utils::PPI>,
1638 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1642 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
1644 This program is free software; you can redistribute it and/or modify
1645 it under the same terms as Perl itself. The full text of this license
1646 can be found in the LICENSE file included with this module.
1652 # cperl-indent-level: 4
1654 # indent-tabs-mode: nil
1655 # c-indentation-style: bsd
1657 # ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :