Policy/ValuesAndExpressions/ProhibitUnknownBackslash.pm

filter: Statementstmt 96.7% 151 / 156 Branchbran 84.0% 79 / 94 Conditioncond 81.8% 45 / 55 MC/DCmcdc 60.7% 17 / 28 Subroutinesub 94.7% 18 / 19 Podpod 100% 2 / 2 totaltotal 88.1% 312 / 354 SCAR 42.8
CC
68
Cov
90%
violates
48.1
_pos_after_interpolate_variable
11.1
applies_to
7.0
CRAP 72.4
« Policy/CodeLayout/RequireFinalSemicolon.pm ↑ Summary Policy/ValuesAndExpressions/ProhibitDuplicateHashKeys.pm »
1 # Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde
2  
3 # Perl-Critic-Pulp is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 3, or (at your option) any later
6 # version.
7 #
8 # Perl-Critic-Pulp is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with Perl-Critic-Pulp. If not, see <http://www.gnu.org/licenses/>.
15  
16  
17 package Perl::Critic::Policy::ValuesAndExpressions::ProhibitUnknownBackslash;
18 40 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 40 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 40 ▶use version (); # but don't import qv()
Subroutine BEGIN: called CC=1 SCAR=0.0
21 40 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # 1.084 for Perl::Critic::Document highest_explicit_perl_version()
24 40 ▶use Perl::Critic::Policy 1.084;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 40 ▶use base 'Perl::Critic::Policy';
Subroutine BEGIN: called CC=1 SCAR=0.0
26 40 ▶use Perl::Critic::Utils;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 40 ▶use Perl::Critic::Pulp;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 # uncomment this to run the ### lines
31 # use Smart::Comments;
32  
33 40 our $VERSION = 99;
34  
35 40 use constant supported_parameters =>
36 ({ name => 'single',
37 description => 'Checking of single-quote strings.',
38 behavior => 'string',
39 default_string => 'none',
40 },
41 { name => 'double',
42 description => 'Checking of double-quote strings.',
43 behavior => 'string',
44 default_string => 'all',
45 },
46 { name => 'heredoc',
47 description => 'Checking of interpolated here-documents.',
48 behavior => 'string',
49 default_string => 'all',
50 },
51 { name => 'charnames',
52 description => 'Checking of character names \\N{}.',
53 behavior => 'string',
54 default_string => 'version',
55 40 ▶ });
Subroutine BEGIN: called CC=1 SCAR=0.0
56 40 ▶use constant default_severity => $Perl::Critic::Utils::SEVERITY_MEDIUM;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 40 ▶use constant default_themes => qw(pulp cosmetic);
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 sub applies_to {
60 290 ▶ my ($policy) = @_;
Subroutine applies_to: called CC=6 SCAR=19.5
Pod documented
61 return (($policy->{'_single'} ne 'none'
62 ? ('PPI::Token::Quote::Single', # ''
63 'PPI::Token::Quote::Literal') # q{}
64 : ()),
65  
66 ($policy->{'_single'} ne 'none'
67 || $policy->{'_double'} ne 'none'
68 ? ('PPI::Token::QuoteLike::Command') # qx{} or qx''
69 : ()),
70  
71 ($policy->{'_double'} ne 'none'
72 ? ('PPI::Token::Quote::Double', # ""
73 'PPI::Token::Quote::Interpolate', # qq{}
74 'PPI::Token::QuoteLike::Backtick') # ``
75 : ()),
76  
77 290 ▶ ($policy->{'_heredoc'} ne 'none'
Branch: 4 branches
BranchTrueFalseTotal
$policy->{'_single'} ne 'none' ? : 38 252 290
$policy->{'_single'} ne 'none' || $policy->{'_double'} ne 'none' ? : 290 0 290
$policy->{'_double'} ne 'none' ? : 290 0 290
$policy->{'_heredoc'} ne 'none' ? : 290 0 290
Condition66%2/3
$policy->{"_single"} ne "none" or $policy->{"_double"} ne "none"
l!l&&r!l&&!r
382520
MC/DC0%0/2
$policy->{"_single"} ne "none" or $policy->{"_double"} ne "none"
$policy->{"_single"} ne "none" $policy->{"_double"} ne "none"
Truth table66%2/3
A or B
A= $policy->{"_single"} ne "none"B= $policy->{"_double"} ne "none"
ABresult
1X1
011
000
78 ? ('PPI::Token::HereDoc')
79 : ()));
80 }
81  
82 # for violation messages
83 40 my %charname = ("\n" => '{newline}',
84 "\r" => '{cr}',
85 "\t" => '{tab}',
86 " " => '{space}');
87  
88 40 use constant _KNOWN => (
89 't' # \t tab
90 . 'n' # \n newline
91 . 'r' # \r carriage return
92 . 'f' # \f form feed
93 . 'b' # \b backspace
94 . 'a' # \a bell
95 . 'e' # \e esc
96 . '0123' # \377 octal
97 . 'x' # \xFF \x{FF} hex
98 . 'c' # \cX control char
99  
100 . 'l' # \l lowercase one char
101 . 'u' # \u uppercase one char
102 . 'L' # \L lowercase string
103 . 'U' # \U uppercase string
104 . 'E' # \E end case or quote
105 . 'Q' # \Q quotemeta
106 . '$' # non-interpolation
107 . '@' # non-interpolation
108 40 ▶ );
Subroutine BEGIN: called CC=1 SCAR=0.0
109  
110 40 use constant _CONTROL_KNOWN =>
111 40 ▶ '?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz'; ## no critic (RequireInterpolationOfMetachars)
Subroutine BEGIN: called CC=1 SCAR=0.0
112  
113 40 my $quotelike_re = qr/^(?:(q[qrwx]?) # $1 "q" if present
114 (?:(?:\s(?:\s*\#[^\n]*\n)*)\s*)? # possible comments
115 )? # possible "q"
116 (.) # $2 opening quote
117 (.*) # $3 guts
118 (.)$ # $4 closing quote
119 /xs;
120  
121 # extra explanation for double-quote interpolations
122 40 my %explain = ('%' => ' (hashes are not interpolated)',
123 '&' => ' (function calls are not interpolated)',
124 '4' => ' (until Perl 5.6 octal wide chars)',
125 '5' => ' (until Perl 5.6 octal wide chars)',
126 '6' => ' (until Perl 5.6 octal wide chars)',
127 '7' => ' (until Perl 5.6 octal wide chars)',
128 'N' => ' (without "use charnames" in scope)',
129 );
130  
131 40 my $v5016 = version->new('5.016');
132 40 my $v5006 = version->new('5.006');
133  
134 sub violates {
135 278 ▶ my ($self, $elem, $document) = @_;
Subroutine violates: called CC=47 SCAR=38.7
Pod documented
136  
137 278 my $have_perl_516;
138 278 ▶ if (defined (my $doc_version = $document->highest_explicit_perl_version)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $doc_version = $document->highest_explicit_perl_version)) 36 242 278
139 36 $have_perl_516 = ($doc_version >= $v5016);
140 }
141  
142 278 my $content = $elem->content;
143 278 my $close = substr ($content, -1, 1);
144 278 my $single = 0;
145 278 my ($param, $str);
146  
147 278 ▶ if ($elem->isa('PPI::Token::HereDoc')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elem->isa('PPI::Token::HereDoc')) { } 6 272 278
148 6 ▶ return if ($close eq "'"); # uninterpolated
Branch: 1 branch
BranchTrueFalseTotal
if $close eq "'" 2 4 6
149 4 $param = $self->{_heredoc};
150 4 $str = join ('', $elem->heredoc);
151  
152 } else {
153 272 ▶ if ($elem->can('string')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elem->can('string')) { } 258 14 272
154 258 $str = $elem->string;
155 } else {
156 14 ▶ $elem =~ $quotelike_re or die "Oops, didn't match quotelike_re";
Branch: 1 branch
BranchTrueFalseTotal
$elem =~ /$quotelike_re/ or die "Oops, didn't match quotelike_re" 0 14 14
157 14 $str = $3;
158 }
159 272 $str =~ s{((^|\G|[^\\])(\\\\)*)\\\Q$close}{$close}sg;
160  
161 272 ▶ if ($elem->isa('PPI::Token::Quote::Single')
Branch: 1 branch
BranchTrueFalseTotal
if ($elem->isa('PPI::Token::Quote::Single') or $elem->isa('PPI::Token::Quote::Literal') or $elem->isa('PPI::Token::QuoteLike::Command') and $close eq q[']) { } 42 230 272
Condition100%9/9
$elem->isa("PPI::Token::Quote::Single") or $elem->isa("PPI::Token::Quote::Literal") or $elem->isa("PPI::Token::QuoteLike::Command") and $close eq "'"
l!l&&r!l&&!r
348230
$elem->isa("PPI::Token::Quote::Single") or $elem->isa("PPI::Token::Quote::Literal")
l!l&&r!l&&!r
1618238
$elem->isa("PPI::Token::QuoteLike::Command") and $close eq "'"
!ll&&!rl&&r
22648
MC/DC100%4/4
$elem->isa("PPI::Token::Quote::Single") or $elem->isa("PPI::Token::Quote::Literal") or $elem->isa("PPI::Token::QuoteLike::Command") and $close eq "'"
$elem->isa("PPI::Token::Quote::Single") $elem->isa("PPI::Token::Quote::Literal") $elem->isa("PPI::Token::QuoteLike::Command") $close eq "'"
Truth table100%5/5
A or B or C and D
A= $elem->isa("PPI::Token::Quote::Single")B= $elem->isa("PPI::Token::Quote::Literal")C= $elem->isa("PPI::Token::QuoteLike::Command")D= $close eq "'"
ABCDresult
1XXX1
01XX1
00111
000X0
00100
162 || $elem->isa('PPI::Token::Quote::Literal')
163 || ($elem->isa('PPI::Token::QuoteLike::Command')
164 && $close eq "'")) {
165 42 $single = 1;
166 42 $param = $self->{_single};
167  
168 } else {
169 230 $param = $self->{_double};
170 }
171 }
172 276 ▶ return if ($param eq 'none');
Branch: 1 branch
BranchTrueFalseTotal
if $param eq "none" 4 272 276
173  
174 272 my $known = $close;
175  
176 272 ▶ if (! $single) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($single) 234 38 272
177 234 $known .= _KNOWN;
178  
179 # Octal chars above \377 are in 5.6 up.
180 # Consider known if no "use 5.x" at all, or if present and 5.6 up,
181 # so only under explicit "use 5.005" or lower are they not allowed.
182 234 my $perlver = $document->highest_explicit_perl_version;
183 234 ▶ if (! defined $perlver || $perlver >= $v5006) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $perlver or $perlver >= $v5006) 210 24 234
Condition100%3/3
not defined $perlver or $perlver >= $v5006
l!l&&r!l&&!r
1981224
MC/DC100%2/2
not defined $perlver or $perlver >= $v5006
not defined $perlver $perlver >= $v5006
Truth table100%3/3
not(A) or B
A= not defined $perlverB= $perlver >= $v5006
ABresult
1X1
011
000
184 210 $known .= '4567';
185 }
186 }
187  
188 ### elem: ref $elem
189 ### $content
190 ### $str
191 ### close char: $close
192 ### $known
193 ### perlver: $document->highest_explicit_perl_version
194  
195 272 my $have_use_charnames;
196 272 my $interpolate_var_end = -1;
197 272 my $interpolate_var_colon;
198 my @violations;
199  
200 272 ▶ while ($str =~ /(\$. # $ not at end-of-string
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /(\$. # $ not at end-of-string |\@[[:alnum:]:'\{\$+-]) # @ forms per toke.c S_scan_const() |(\\+) # $2 run of backslashes /gsx) 374 272 646
201 |\@[[:alnum:]:'\{\$+-]) # @ forms per toke.c S_scan_const()
202 |(\\+) # $2 run of backslashes
203 /sgx) {
204 374 ▶ if (defined $1) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) 54 320 374
205 # $ or @
206 54 ▶ unless ($single) { # no variables in single-quote
Branch: 1 branch
BranchTrueFalseTotal
unless ($single) 54 0 54
207 ### interpolation at: pos($str)
208 54 ▶ my $new_pos = _pos_after_interpolate_variable
Condition50%1/2
_pos_after_interpolate_variable($str, pos($str) - length($1)) || (last)
l!l
540
MC/DC0%0/1
_pos_after_interpolate_variable($str, pos($str) - length($1)) || (last)
_pos_after_interpolate_variable($str, pos($str) - length($1))
Truth table50%1/2
A
A= _pos_after_interpolate_variable($str, pos($str) - length($1))
Aresult
11
00
209 ($str, pos($str) - length($1))
210 || last;
211 54 pos($str) = $new_pos;
212 ### ends at: pos($str)
213 54 ▶ if (substr($str,pos($str)-1,1) =~ /(\w)|[]}]/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($str, pos($str) - 1, 1) =~ /(\w)|[]}]/) 54 0 54
214 54 $interpolate_var_colon = $1;
215 54 $interpolate_var_end = pos($str);
216 ### interpolate_var_end set to: $interpolate_var_end
217 }
218 }
219 54 next;
220 }
221  
222 320 ▶ if ((length($2) & 1) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ((length $2 & 1) == 0) 14 306 320
223 # even number of backslashes, not an escape
224 14 next;
225 }
226  
227 # shouldn't have \ as the last char in $str, but if that happends then
228 # $c is empty string ''
229  
230 306 my $c = substr($str,pos($str),1);
231 306 pos($str)++;
232  
233 306 ▶ if (! $single) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($single) 274 32 306
234 274 ▶ if ($c eq 'N') {
Branch: 5 branches
BranchTrueFalseTotal
if ($c eq 'N') { } 28 246 274
elsif ($c eq 'c') { } 32 214 246
elsif ($c eq ':') { } 34 180 214
elsif ($c eq '[' or $c eq '{') { } 26 154 180
elsif ($c eq '-') { } 10 144 154
235 28 ▶ if ($self->{_charnames} eq 'disallow') {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_charnames'} eq 'disallow') { } 6 22 28
elsif ($self->{'_charnames'} eq 'allow') { } 6 16 22
236 6 push @violations,
237 $self->violation ('charnames \\N disallowed by config',
238 '', $elem);
239 6 next;
240  
241 } elsif ($self->{_charnames} eq 'allow') {
242 6 next; # ok, allow by config
243  
244 } else { # $self->{_charnames} eq 'version'
245 16 ▶ if (! defined $have_use_charnames) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $have_use_charnames) 16 0 16
246 16 $have_use_charnames = _have_use_charnames_in_scope($elem);
247 }
248 16 ▶ if ($have_use_charnames || $have_perl_516) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have_use_charnames or $have_perl_516) 8 8 16
Condition100%3/3
$have_use_charnames or $have_perl_516
l!l&&r!l&&!r
448
MC/DC100%2/2
$have_use_charnames or $have_perl_516
$have_use_charnames $have_perl_516
Truth table100%3/3
A or B
A= $have_use_charnamesB= $have_perl_516
ABresult
1X1
011
000
249 8 next; # ok if "use charnames" or perl 5.16 up (which autoloads that)
250 }
251 }
252  
253 } elsif ($c eq 'c') {
254 # \cX control char.
255 # If \c is at end-of-string then new $c is '' and pos() will goes past
256 # length($str). That pos() is ok, the loop regexp gives no-match and
257 # terminates.
258 32 $c = substr ($str, pos($str)++, 1);
259 32 ▶ if ($c eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "") 4 28 32
260 4 push @violations,
261 $self->violation ('Control char \\c at end of string', '', $elem);
262 4 next;
263 }
264 28 ▶ if (index (_CONTROL_KNOWN, $c) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index("?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz", $c) != -1) 22 6 28
265 22 next; # a known escape
266 }
267 6 push @violations,
268 $self->violation ('Unknown control char \\c' . _printable($c),
269 '', $elem);
270 6 next;
271  
272 } elsif ($c eq ':') {
273 34 ▶ if ($interpolate_var_colon) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interpolate_var_colon) 20 14 34
274 ### backslash colon, pos: pos($str)
275 ### $interpolate_var_end
276 ### substr: substr ($str, $interpolate_var_end, 2)
277 20 ▶ if (pos($str) == $interpolate_var_end+2
Branch: 1 branch
BranchTrueFalseTotal
if (pos $str == $interpolate_var_end + 2 or pos $str == $interpolate_var_end + 4 and substr($str, $interpolate_var_end, 2) eq "\\:") 20 0 20
Condition50%3/6
pos $str == $interpolate_var_end + 2 or pos $str == $interpolate_var_end + 4 and substr($str, $interpolate_var_end, 2) eq "\\:"
l!l&&r!l&&!r
1280
pos $str == $interpolate_var_end + 4 and substr($str, $interpolate_var_end, 2) eq "\\:"
!ll&&!rl&&r
008
MC/DC0%0/3
pos $str == $interpolate_var_end + 2 or pos $str == $interpolate_var_end + 4 and substr($str, $interpolate_var_end, 2) eq "\\:"
pos $str == $interpolate_var_end + 2 pos $str == $interpolate_var_end + 4 substr($str, $interpolate_var_end, 2) eq "\\:"
Truth table50%2/4
A or B and C
A= pos $str == $interpolate_var_end + 2B= pos $str == $interpolate_var_end + 4C= substr($str, $interpolate_var_end, 2) eq "\\:"
ABCresult
1XX1
0111
00X0
0100
278 || (pos($str) == $interpolate_var_end+4
279 && substr ($str, $interpolate_var_end, 2) eq '\\:')) {
280 20 next;
281 }
282 }
283  
284 ▶ } elsif ($c eq '[' || $c eq '{') {
Condition100%3/3
$c eq "[" or $c eq "{"
l!l&&r!l&&!r
1412154
MC/DC100%2/2
$c eq "[" or $c eq "{"
$c eq "[" $c eq "{"
Truth table100%3/3
A or B
A= $c eq "["B= $c eq "{"
ABresult
1X1
011
000
285 ### backslash bracket, pos: pos($str)
286 ### $interpolate_var_end
287 26 ▶ if (pos($str) == $interpolate_var_end+2) {
Branch: 1 branch
BranchTrueFalseTotal
if (pos $str == $interpolate_var_end + 2) 18 8 26
288 18 next;
289 }
290  
291 } elsif ($c eq '-') {
292 ### backslash dash: pos($str)
293 10 ▶ if ($str =~ /\G>[[{]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\G>[[{]/) 4 6 10
294 ### is for bracket or brace, pos now: pos($str)
295 4 next;
296 }
297 }
298 }
299  
300 212 ▶ if ($param eq 'quotemeta') {
Branch: 2 branches
BranchTrueFalseTotal
if ($param eq 'quotemeta') { } 2 210 212
elsif ($param eq 'alnum') { } 0 210 210
301 # only report on chars quotemeta leaves unchanged
302 2 ▶ next if $c ne quotemeta($c);
Branch: 1 branch
BranchTrueFalseTotal
if $c ne quotemeta $c 2 0 2
303 } elsif ($param eq 'alnum') {
304 # only report unknown alphanumerics, like perl does
305 # believe perl only reports ascii alnums as bad, wide char alphas ok
306 0 ▶ next if $c !~ /[a-zA-Z0-9]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /[a-zA-Z0-9]/ 0 0 0
307 }
308  
309 # if $c eq '' for end-of-string then index() returns 0, for no violation
310 210 ▶ if (index ($known, $c) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($known, $c) != -1) 86 124 210
311 # a known escape
312 86 next;
313 }
314  
315 124 ▶ my $explain = !$single && ($explain{$c} || '');
Condition100%5/5
!$single && ($explain{$c} || '')
!ll&&!rl&&r
327220
$explain{$c} or ""
l!l
2072
MC/DC100%2/2
!$single && ($explain{$c} || '')
!$single $explain{$c}
Truth table100%3/3
not(A) && B
A= !$singleB= $explain{$c}
ABresult
0X0
100
111
316 124 my $message = ('Unknown or unnecessary backslash \\'._printable($c)
317 . $explain);
318 124 push @violations, $self->violation ($message, '', $elem);
319  
320 # would have to take into account HereDoc begins on next line ...
321 # _violation_elem_offset ($violation, $elem, pos($str)-2);
322 }
323 272 return @violations;
324 }
325  
326 # $pos is a position within $str of a "$" or "@" interpolation.
327 # Return the position within $str after that variable or expression.
328 #
329 # FIXME: Would like PPI to do this. Its PPI::Token::Quote::Double version
330 # 1.236 interpolations() has a comment that returning the expressions would
331 # be good.
332 #
333 sub _pos_after_interpolate_variable {
334 72 ▶ my ($str, $pos) = @_;
Subroutine _pos_after_interpolate_variable: called CC=10 SCAR=24.1
335 72 $str = substr ($str, $pos);
336 ### _pos_after_interpolate_variable() ...
337 ### $str
338  
339 # PPI circa 1.236 doesn't like to parse non-ascii as program code
340 # identifiers etc, try changing to spaces for measuring.
341 #
342 # Might be happy for it to parse the interpolate expression and ignore
343 # anything bad after, but PPI::Tokenizer crunches a whole line at a time
344 # or something like that.
345 #
346 72 $str =~ s/[^[:print:]\t\r\n]/ /g;
347  
348 72 require PPI::Document;
349 72 my $doc = PPI::Document->new(\$str);
350 72 ▶ my $elem = $doc && $doc->child(0);
Condition33%1/3
$doc && $doc->child(0)
!ll&&!rl&&r
0072
MC/DC0%0/2
$doc && $doc->child(0)
$doc $doc->child(0)
Truth table33%1/3
A && B
A= $docB= $doc->child(0)
ABresult
0X0
100
111
351 72 ▶ $elem = $elem && $elem->child(0);
Condition33%1/3
$elem && $elem->child(0)
!ll&&!rl&&r
0072
MC/DC0%0/2
$elem && $elem->child(0)
$elem $elem->child(0)
Truth table33%1/3
A && B
A= $elemB= $elem->child(0)
ABresult
0X0
100
111
352 72 ▶ if (! $elem) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($elem) 0 72 72
353 0 warn "ProhibitUnknownBackslash: oops, cannot parse interpolation, skipping string";
354 0 return undef;
355 }
356 ### elem: ref $elem
357 ### length: length($elem->content)
358 72 $pos += length($elem->content);
359  
360 72 ▶ if ($elem->isa('PPI::Token::Cast')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($elem->isa('PPI::Token::Cast')) { } 10 62 72
elsif ($elem->isa('PPI::Token::Symbol')) { } 58 4 62
361 # get the PPI::Structure::Block following "$" or "@", can have
362 # whitespace before it too
363 10 ▶ while ($elem = $elem->next_sibling) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elem = $elem->next_sibling) 10 0 10
364 ### and: "$elem"
365 ### length: length($elem->content)
366 10 $pos += length($elem->content);
367 10 ▶ last if $elem->isa('PPI::Structure::Block');
Branch: 1 branch
BranchTrueFalseTotal
if $elem->isa("PPI::Structure::Block") 10 0 10
368 }
369  
370 } elsif ($elem->isa('PPI::Token::Symbol')) {
371 # any subscripts 'PPI::Structure::Subscript' following, like "$hash{...}"
372 # whitespace stops the subscripts, so that Struct alone
373 58 for (;;) {
374 92 ▶ $elem = $elem->next_sibling || last;
Condition100%2/2
$elem->next_sibling || (last)
l!l
875
MC/DC100%1/1
$elem->next_sibling || (last)
$elem->next_sibling
Truth table100%2/2
A
A= $elem->next_sibling
Aresult
11
00
375 87 ▶ $elem->isa('PPI::Structure::Subscript') || last;
Branch: 1 branch
BranchTrueFalseTotal
$elem->isa("PPI::Structure::Subscript") or last 53 34 87
376 ### and: "$elem"
377 ### length: length($elem->content)
378 34 $pos += length($elem->content);
379 }
380 }
381  
382 72 return $pos;
383 }
384  
385 # use Perl::Critic::Policy::Compatibility::PodMinimumVersion;
386 sub _violation_elem_offset {
387 0 ▶ my ($violation, $elem, $offset) = @_;
Subroutine _violation_elem_offset: not called CC=1 SCAR=6.9
388 0 return $violation;
389  
390 #
391 # my $pre = substr ($elem->content, 0, $offset);
392 # my $newlines = ($pre =~ tr/\n//);
393 #
394 # my $document = $elem->document;
395 # my $doc_str = $document->content;
396 #
397 # return Perl::Critic::Pulp::Utils::_violation_override_linenum ($violation, $doc_str, $newlines - 1);
398 }
399  
400 sub _printable {
401 130 ▶ my ($c) = @_;
Subroutine _printable: called CC=2 SCAR=6.9
402 130 $c =~ s{([^[:graph:]]|[^[:ascii:]])}
403 12 ▶ { $charname{$1} || sprintf('{0x%X}',ord($1)) }e;
Branch: 1 branch
BranchTrueFalseTotal
$charname{$1} or sprintf "{0x%X}", ord $1 6 6 12
404 130 return $c;
405 }
406  
407 # return true if $elem has a 'use charnames' in its lexical scope
408 sub _have_use_charnames_in_scope {
409 16 ▶ my ($elem) = @_;
Subroutine _have_use_charnames_in_scope: called CC=7 SCAR=19.5
410 16 for (;;) {
411 48 ▶ $elem = $elem->sprevious_sibling || $elem->parent
Condition100%5/5
$elem->sprevious_sibling || $elem->parent || (return 0)
l!l
3612
$elem->sprevious_sibling or $elem->parent
l!l&&r!l&&!r
82812
MC/DC100%2/2
$elem->sprevious_sibling || $elem->parent || (return 0)
$elem->sprevious_sibling $elem->parent
Truth table100%3/3
A or B
A= $elem->sprevious_siblingB= $elem->parent
ABresult
1X1
011
000
412 || return 0;
413 36 ▶ if ($elem->isa ('PPI::Statement::Include')
Branch: 1 branch
BranchTrueFalseTotal
if ($elem->isa("PPI::Statement::Include") and $elem->type eq "use" and ($elem->module || "") eq "charnames") 4 32 36
Condition87%7/8
$elem->isa("PPI::Statement::Include") and $elem->type eq "use" and ($elem->module || "") eq "charnames"
!ll&&!rl&&r
3024
$elem->isa("PPI::Statement::Include") and $elem->type eq "use"
!ll&&!rl&&r
3006
$elem->module || ''
l!l
42
MC/DC66%2/3
$elem->isa("PPI::Statement::Include") and $elem->type eq "use" and ($elem->module || "") eq "charnames"
$elem->isa("PPI::Statement::Include") $elem->type eq "use" $elem->module
Truth table75%3/4
A and B and C
A= $elem->isa("PPI::Statement::Include")B= $elem->type eq "use"C= $elem->module
ABCresult
0XX0
10X0
1100
1111
414 && $elem->type eq 'use'
415 && ($elem->module || '') eq 'charnames') {
416 4 return 1;
417 }
418 }
419 }
420  
421  
422 #-----------------------------------------------------------------------------
423 # unused bits
424  
425 # # $elem is a PPI::Token::Quote, PPI::Token::QuoteLike or PPI::Token::HereDoc
426 # sub _string {
427 # my ($elem) = @_;
428 # if ($elem->can('heredoc')) {
429 # return join ('', $elem->heredoc);
430 # }
431 # if ($elem->can('string')) {
432 # return $elem->string;
433 # }
434 # $elem =~ $quotelike_re
435 # or die "Oops, didn't match quote_re";
436 # return $3;
437 # }
438  
439 # # $elem is a PPI::Token::Quote or PPI::Token::QuoteLike
440 # # return ($q, $open, $close) where $q is the "q" intro or empty string if
441 # # none, and $open and $close are the quote chars
442 # sub _quote_delims {
443 # my ($elem) = @_;
444 # if ($elem->can('heredoc')) {
445 # return '"', '"';
446 # }
447 # $elem =~ $quotelike_re
448 # or die "Oops, didn't match quote_re";
449 # return ($1||'', $2, $4);
450 # }
451  
452 # perlop "Quote and Quote-like Operators"
453 # my $known = '';
454 # if ($elem->isa ('PPI::Token::Quote::Double')
455 # || $elem->isa ('PPI::Token::Quote::Interpolate')
456 # || $elem->isa ('PPI::Token::QuoteLike::Backtick')
457 # || ($elem->isa ('PPI::Token::QuoteLike::Command')
458 # && $close ne '\'') # no interpolation in qx'echo hi'
459 # ) {
460 # $known = 'tnrfbae0123xcluLUQE$@';
461 #
462 # # \N and octals bigger than 8-bits are in 5.6 up, and allow them if no
463 # # "use 5.x" at all too
464 # my $perlver = $document->highest_explicit_perl_version;
465 # if (! defined $perlver || $perlver >= 5.006) {
466 # $known .= 'N456789';
467 # }
468 # }
469 # $known .= $close;
470 #
471 # my $re = qr/\\+[^\\$known$close]/;
472 # my $unknown = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
473 # $unknown =~ s{(.)}
474 # {index($known,$1) >= 0 ? '' : $1}eg;
475  
476 40 1;
477 __END__
478  
479 =for stopwords backslashed upcase FS unicode ascii non-ascii ok alnum quotemeta backslashing backticks Ryde coderef alphanumerics arrowed
480  
481 =head1 NAME
482  
483 Perl::Critic::Policy::ValuesAndExpressions::ProhibitUnknownBackslash - don't use undefined backslash forms
484  
485 =head1 DESCRIPTION
486  
487 This policy is part of the L<C<Perl::Critic::Pulp>|Perl::Critic::Pulp>
488 add-on. It checks for unknown backslash escapes like
489  
490 print "\*.c"; # bad
491  
492 This is harmless, assuming the intention is a literal "*" (which it gives),
493 but unnecessary, and on that basis this policy is under the C<cosmetic>
494 theme (see L<Perl::Critic/POLICY THEMES>). Sometimes it can be a
495 misunderstanding or a typo though, for instance a backslashed newline is a
496 newline, but perhaps you thought it meant a continuation.
497  
498 print "this\ # bad
499 is a newline";
500  
501 Perl already warns about unknown escaped alphanumerics like C<\v> under
502 C<perl -w> or C<use warnings> (see L<perldiag/Unrecognized escape \%c passed
503 through>).
504  
505 print "\v"; # bad, and provokes Perl warning
506  
507 This policy extends to report on any unknown escape, with options below to
508 vary the strictness and to check single-quote strings too if desired.
509  
510 =head2 Control Characters \c
511  
512 Control characters C<\cX> are checked and only the conventional A-Z a-z @ [
513 \ ] ^ _ ? are considered known.
514  
515 print "\c*"; # bad
516  
517 Perl accepts any C<\c> and does an upcase xor 0x40, so C<\c*> is letter "j",
518 at least on an ASCII system. But that's obscure and likely to be a typo or
519 error.
520  
521 For reference, C<\c\> is the ASCII FS "file separator" and the second
522 backslash is not an escape, except for a closing quote character, which it
523 does escape (basically because Perl scans for a closing quote before
524 considering interpolations). Thus,
525  
526 print " \c\ "; # ok, control-\ FS
527 print " \c\" "; # bad, control-" is unknown
528 print qq[ \c\] ]; # ok, control-] GS
529  
530 =head2 Ending Interpolation
531  
532 A backslashed colon, bracket, brace or dash is allowed after an interpolated
533 variable or element, since this stops interpolation at that point.
534  
535 print "$foo\::bar"; # ok, $foo
536 print "@foo\::"; # ok, @foo
537  
538 print "$foo[0]\[1]"; # ok, is $foo[0]
539 print "$esc\[1m"; # ok
540  
541 print "$foo\{k}"; # ok
542 print "$foo\{k}"; # ok
543 print "$foo{k}\[0]"; # ok, is $foo{k}
544 print "@foo\{1,2}"; # ok, is @foo
545  
546 print "$foo\->[0]"; # ok, is $foo
547 print "$foo\->{zz}"; # ok
548  
549 A single backslash like C<"\::"> is enough for the colon case, but
550 backslashing the second too as C<"\:\:"> is quite common and is allowed.
551  
552 print "$#foo\:\:bar"; # ok
553  
554 Only an array or hash C<-E<gt>[]> or C<-E<gt>{}> need C<\-> to stop
555 interpolation. Other cases such as an apparent method call or arrowed
556 coderef call don't interpolate and the backslash is treated as unknown since
557 unnecessary.
558  
559 print "$coderef\->(123)"; # bad, unnecessary
560 print "Usage: $class\->foo()"; # bad, unnecessary
561  
562 For reference, the alternative in all the above is to write C<{}> braces
563 around the variable or element to delimit from anything following. Doing so
564 may be clearer than backslashing,
565  
566 print "${foo}::bar"; # alternatives
567 print "@{foo}::bar";
568 print "$#{foo}th";
569 print "${foo[0]}[1]"; # array element $foo[0]
570  
571 The full horror story of backslashing interpolations can be found in
572 L<perlop/Gory details of parsing quoted constructs>.
573  
574 =head2 Octal Wide Chars
575  
576 Octal escapes C<\400> to C<\777> for wide chars 256 to 511 are new in Perl
577 5.6. They're considered unknown in 5.005 and earlier (where they end up
578 chopped to 8-bits 0 to 255). Currently if there's no C<use> etc Perl
579 version then it's presumed a high octal is intentional and is allowed.
580  
581 print "\400"; # ok
582  
583 use 5.006;
584 print "\777"; # ok
585  
586 use 5.005;
587 print "\777"; # bad in 5.005 and earlier
588  
589  
590 =head2 Named Chars
591  
592 Named chars C<\N{SOME THING}> are added by L<charnames>, new in Perl 5.6.
593 In Perl 5.16 up, that module is automatically loaded when C<\N> is used.
594 C<\N> is considered known when C<use 5.016> or higher,
595  
596 use 5.016;
597 print "\N{EQUALS SIGN}"; # ok with 5.16 automatic charnames
598  
599 or if C<use charnames> is in the lexical scope,
600  
601 { use charnames ':full';
602 print "\N{APOSTROPHE}"; # ok
603 }
604 print "\N{COLON}"; # bad, no charnames in lexical scope
605  
606 In Perl 5.6 through 5.14, a C<\N> without C<charnames> is a compile error so
607 would be seen in those versions immediately anyway. There's no check of the
608 character name appearing in the C<\N>. C<charnames> gives an error for
609 unknown names.
610  
611 The C<charnames> option (L</CONFIGURATION> below) can be allow to always
612 allow named characters. This can be used for instance if you always have
613 Perl 5.16 up but without declaring that in a C<use> statement.
614  
615 The C<charnames> option can be disallow to always disallow named characters.
616 This is a blanket prohibition rather than an UnknownBackslash as such, but
617 matches the allow option. Disallowing can be matter of personal preference
618 or perhaps aim to save a little memory or startup time.
619  
620 =head2 Other Notes
621  
622 In the violation messages, a non-ascii or non-graphical escaped char is
623 shown as hex like C<\{0x263A}>, to ensure the message is printable and
624 unambiguous.
625  
626 Interpolated C<$foo> or C<@{expr}> variables and expressions are parsed like
627 Perl does, so backslashes for refs within are ok, in particular tricks like
628 C<${\scalar ...}> are fine (see L<perlfaq4/How do I expand function calls in
629 a string?>).
630  
631 print "this ${\(some()+thing())}"; # ok
632  
633 =head2 Disabling
634  
635 As always, if you're not interested in any of this then you can disable
636 C<ProhibitUnknownBackslash> from your F<.perlcriticrc> in the usual way (see
637 L<Perl::Critic/CONFIGURATION>),
638  
639 [-ValuesAndExpressions::ProhibitUnknownBackslash]
640  
641 =head1 CONFIGURATION
642  
643 =over 4
644  
645 =item C<double> (string, default "all")
646  
647 =item C<heredoc> (string, default "all")
648  
649 C<double> applies to double-quote strings C<"">, C<qq{}>, C<qx{}>, etc.
650 C<heredoc> applies to interpolated here-documents C<E<lt>E<lt>HERE> etc.
651 The possible values are
652  
653 none don't report anything
654 alnum report unknown alphanumerics, like Perl's warning
655 quotemeta report anything quotemeta() doesn't escape
656 all report all unknowns
657  
658 "alnum" does no more than compiling with C<perl -w>, but might be good for
659 checking code you don't want to run.
660  
661 "quotemeta" reports escapes not produced by C<quotemeta()>. For example
662 C<quotemeta> escapes a C<*>, so C<\*> is not reported, but it doesn't escape
663 an underscore C<_>, so C<\_> is reported. The effect is to prohibit a few
664 more escapes than "alnum". One use is to check code generated by other code
665 where you've used C<quotemeta> to produce double-quoted strings and thus may
666 have escaping which is unnecessary but works fine.
667  
668 =item C<single> (string, default "none")
669  
670 C<single> applies to single-quote strings C<''>, C<q{}>, C<qx''>, etc. The
671 possible values are as above, though only "all" or "none" make much sense.
672  
673 none don't report anything
674 all report all unknowns
675  
676 The default is "none" because literal backslashes in single-quotes are
677 usually both what you want and quite convenient. Setting "all" effectively
678 means you must write backslashes as C<\\>.
679  
680 print 'c:\my\msdos\filename'; # bad under "single=all"
681 print 'c:\\my\\msdos\\filename'; # ok
682  
683 Doubled backslashing like this is correct, and can emphasize that you really
684 did want a backslash, but it's tedious and not easy on the eye and so left
685 only as an option.
686  
687 For reference, single-quote here-documents C<E<lt>E<lt>'HERE'> don't have
688 any backslash escapes and so are not considered by this policy. C<qx{}>
689 command backticks are double-quote but C<qx''> is single-quote. They are
690 treated per the corresponding C<single> or C<double> option.
691  
692 =item C<charnames> (string, default "version")
693  
694 Whether to treat named characters C<\N{}> in double-quote strings as known
695 or unknown,
696  
697 version known if use charnames or use 5.016
698 allow always allow
699 disallow always disallow
700  
701 =back
702  
703 =head1 BUGS
704  
705 Interpolations in double-quote strings are found by some code here in
706 C<ProhibitUnknownBackslash> (re-parse the string content as Perl code
707 starting from the C<$> or C<@>). If this fails for some reason then a
708 warning is given and the rest of the string is unchecked. In the future
709 would like PPI to parse interpolations, for the benefit of string chopping
710 like here or checking of code in an interpolation.
711  
712 =head1 SEE ALSO
713  
714 L<Perl::Critic::Pulp>,
715 L<Perl::Critic>
716  
717 L<perlop/Quote and Quote-like Operators>
718  
719 =head1 HOME PAGE
720  
721 http://user42.tuxfamily.org/perl-critic-pulp/index.html
722  
723 =head1 COPYRIGHT
724  
725 Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde
726  
727 Perl-Critic-Pulp is free software; you can redistribute it and/or modify it
728 under the terms of the GNU General Public License as published by the Free
729 Software Foundation; either version 3, or (at your option) any later
730 version.
731  
732 Perl-Critic-Pulp is distributed in the hope that it will be useful, but
733 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
734 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
735 more details.
736  
737 You should have received a copy of the GNU General Public License along with
738 Perl-Critic-Pulp. If not, see <http://www.gnu.org/licenses>.
739  
740 =cut
« Policy/CodeLayout/RequireFinalSemicolon.pm ↑ Summary Policy/ValuesAndExpressions/ProhibitDuplicateHashKeys.pm »