1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
|
# Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde
# Perl-Critic-Pulp is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# Perl-Critic-Pulp is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with Perl-Critic-Pulp. If not, see <http://www.gnu.org/licenses/>.
package Perl::Critic::Policy::CodeLayout::RequireFinalSemicolon;
use 5.006;
use strict;
use warnings;
use List::Util;
use base 'Perl::Critic::Policy';
use Perl::Critic::Utils;
use Perl::Critic::Pulp;
use Perl::Critic::Pulp::Utils;
# uncomment this to run the ### lines
# use Smart::Comments;
our $VERSION = 99;
use constant supported_parameters =>
({ name => 'except_same_line',
description => 'Whether to allow no semicolon at the end of blocks with the } closing brace on the same line as the last statement.',
behavior => 'boolean',
default_string => '1',
},
{ name => 'except_expression_blocks',
description => 'Whether to allow no semicolon at the end of do{} expression blocks.',
behavior => 'boolean',
default_string => '1',
});
use constant default_severity => $Perl::Critic::Utils::SEVERITY_LOW;
use constant default_themes => qw(pulp cosmetic);
use constant applies_to => 'PPI::Structure::Block';
sub violates {
my ($self, $elem, $document) = @_;
### RequireFinalSemicolon elem: $elem->content
if (_block_is_hash_constructor($elem) != 0) {
### hash constructor, or likely so, stop ...
return;
}
my $block_last = $elem->schild(-1)
|| return; # empty block doesn't need a semi
### block_last: ref($block_last),$block_last->content
$block_last->isa('PPI::Statement') || do {
### last in block is not a PPI-Statement ...
return;
};
if (_elem_statement_no_need_semicolon($block_last)) {
return;
}
{
my $bstat_last = $block_last->schild(-1)
|| return; # statement shouldn't be empty, should it?
### bstat_last in statement: ref($bstat_last),$bstat_last->content
if (_elem_is_semicolon($bstat_last)) {
### has final semicolon, ok ...
return;
}
}
if ($self->{'_except_expression_blocks'}) {
if (_block_is_expression($elem)) {
### do expression, ok
return;
}
### not a do{} expression
}
# if don't have final brace then this option doesn't apply as there's no
# final brace to be on the same line
if ($self->{'_except_same_line'} && $elem->complete) {
if (! _newline_in_following_sibling($block_last)) {
### no newline before close, ok
return;
}
}
my $report_at = $block_last->next_sibling || $block_last;
return $self->violation
('Put semicolon ; on last statement in a block',
'',
$report_at);
}
# return true if $elem is a PPI::Statement subclass which doesn't require a
# terminating ";"
sub _elem_statement_no_need_semicolon {
my ($elem) = @_;
return ($elem->isa('PPI::Statement::Compound') # for(){} etc
|| $elem->isa('PPI::Statement::Sub') # nested named sub
|| $elem->isa('PPI::Statement::Given')
|| $elem->isa('PPI::Statement::When')
|| $elem->isa('PPI::Statement::End') # __END__
|| $elem->isa('PPI::Statement::Null') # ;
|| $elem->isa('PPI::Statement::UnmatchedBrace') # stray }
|| _elem_is_try_block($elem)
);
}
my %postfix_loops = (while => 1, until => 1);
my %prefix_expressions = (do => 1,
map => 1,
grep => 1,
sort => 1,
map { $_ => 1, "List::Util::$_" => 1 }
qw(
reduce any all none notall first
pairfirst pairgrep pairmap
),
map { $_ => 1, "List::Pairwise::$_" => 1 }
qw(
mapp map_pairwise grepp grep_pairwise
firstp first_pairwise lastp last_pairwise
),
);
# $elem is a PPI::Structure::Block.
# return 1 definitely a hash
# 0 definitely a block
# -1 not certain
#
# PPI 1.212 tends to be give PPI::Structure::Block for various things which
# are actually anon hash constructors and ought to be
# PPI::Structure::Constructor. For example,
#
# return bless { x => 123 };
# return \ { x => 123 };
#
# _block_is_hash_constructor() tries to recognise some of those blocks which
# are actually hash constructors, so as not to apply the final semicolon
# rule to hash constructors.
#
my %word_is_block = (sub => 1,
do => 1,
map => 1,
grep => 1,
sort => 1,
# from Try.pm, TryCatch.pm, Try::Tiny prototypes, etc
try => 1,
catch => 1,
finally => 1,
# List::Util first() etc are not of interest to
# RequireFinalSemicolon but ProhibitDuplicateHashKeys
# shares this code so recognise them for it.
%prefix_expressions,
);
sub _block_is_hash_constructor {
my ($elem) = @_;
### _block_is_hash_constructor(): ref($elem), "$elem"
# if (_block_starts_semi($elem)) {
# ### begins with ";", block is correct ...
# return 0;
# }
if (_block_has_multiple_statements($elem)) {
### contains one or more ";", block is correct ...
return 0;
}
if (my $prev = $elem->sprevious_sibling) {
### prev: ref($prev), "$prev"
if ($prev->isa('PPI::Structure::Condition')) {
### prev condition, block is correct ...
return 0;
}
if ($prev->isa('PPI::Token::Cast')) {
if ($prev eq '\\') {
### ref cast, is a hash ...
return 1;
} else {
### other cast, block is correct (or a variable name) ...
return 0;
}
}
if ($prev->isa('PPI::Token::Operator')) {
### prev operator, is a hash ...
return 1;
}
if (! $prev->isa('PPI::Token::Word')) {
### prev not a word, not sure ...
return -1;
}
if ($word_is_block{$prev}) {
# "sub { ... }"
# "do { ... }"
### do/sub/map/grep/sort, block is correct ...
return 0;
}
if (! ($prev = $prev->sprevious_sibling)) {
# "bless { ... }"
# "return { ... }" etc
# ENHANCE-ME: notice List::Util first{} and other prototyped things
### nothing else preceding, likely a hash ...
return -1;
}
### prev prev: "$prev"
if ($prev eq 'sub') {
# "sub foo {}"
### named sub, block is correct ...
return 0;
}
# "word bless { ... }"
# "word return { ... }" etc
### other word preceding, likely a hash ...
return -1;
}
my $parent = $elem->parent || do {
### umm, at toplevel, is a block ...
return 0;
};
if ($parent->isa('PPI::Statement::Compound')
&& ($parent = $parent->parent)
&& (
$parent->isa('PPI::Structure::List')
||
$parent->isa('PPI::Structure::Constructor'))) {
### in a list or arrayref, is a hashref ...
# This catches
# ppidump "[{%args}]"
# which comes out (from PPI 1.270) as
#
# PPI::Structure::Constructor [ ... ]
# PPI::Statement::Compound
# PPI::Structure::Block { ... }
# PPI::Statement
# PPI::Token::Symbol '%args'
#
# It should be like
#
# PPI::Structure::Constructor [ ... ]
# PPI::Statement
# PPI::Structure::Constructor { ... }
# PPI::Statement::Expression
#
# which is what ppidump "[{x=>1}]" gives.
#
# The PPI::Structure::List is for something like
# ppidump "func({ %args })"
# which in for example PPI 1.220 was PPI::Structure::Block too.
# That one is ok in PPI 1.270 (when ready to demand that version).
#
# The plan would be to remove the whole of this check for
# PPI::Statement::Compound if PPI can do the right thing on arrayrefs
# too ...
return 1;
}
return 0;
}
# $elem is a PPI::Structure::Block
# return true if it contains two or more PPI::Statement
#
sub _block_has_multiple_statements {
my ($elem) = @_;
my $count = 0;
foreach my $child ($elem->schildren) {
$count++;
if ($count >= 2) { return 1; }
}
return 0;
}
# $elem is a PPI::Structure::Block
# return true if it starts with a ";"
#
sub _block_starts_semi {
my ($elem) = @_;
# note child() not schild() since an initial ";" is not "significant"
$elem = $elem->child(0);
### first child: $elem && (ref $elem)." $elem"
$elem = _elem_skip_whitespace_and_comments($elem);
return ($elem && $elem->isa('PPI::Statement::Null'));
}
# $elem is a PPI::Element or undef
# return the next non-whitespace and non-comment after it
sub _elem_skip_whitespace_and_comments {
my ($elem) = @_;
while ($elem
&& ($elem->isa('PPI::Token::Whitespace')
|| $elem->isa ('PPI::Token::Comment'))) {
$elem = $elem->next_sibling;
### next elem: $elem && (ref $elem)." $elem"
}
return $elem;
}
sub _elem_is_semicolon {
my ($elem) = @_;
return ($elem->isa('PPI::Token::Structure') && $elem eq ';');
}
# $elem is a PPI::Node
# return true if any following sibling (not $elem itself) contains a newline
sub _newline_in_following_sibling {
my ($elem) = @_;
while ($elem = $elem->next_sibling) {
if ($elem =~ /\n/) {
return 1;
}
}
return 0;
}
# $block is a PPI::Structure::Block
# return true if it's "do{}" expression, and not a "do{}while" or "do{}until"
# loop
sub _block_is_expression {
my ($elem) = @_;
### _block_is_expression(): "$elem"
if (my $next = $elem->snext_sibling) {
if ($next->isa('PPI::Token::Word')
&& $postfix_loops{$next}) {
### {}while or {}until, not an expression
return 0;
}
}
### do, map, grep, sort, etc are expressions ..
my $prev = $elem->sprevious_sibling;
return ($prev
&& $prev->isa('PPI::Token::Word')
&& $prefix_expressions{$prev});
}
# Return true if $elem is a "try" block like
# Try.pm try { } catch {}
# TryCatch.pm try { } catch ($err) {} ... catch {}
# Syntax::Feature::Try try { } catch ($err) {} ... catch {} finally {}
# The return is true only for the block type "try"s of these three modules.
# "try" forms from Try::Tiny and its friends are plain subroutine calls
# rather than blocks.
#
sub _elem_is_try_block {
my ($elem) = @_;
return ($elem->isa('PPI::Statement')
&& ($elem = $elem->schild(0))
&& $elem->isa('PPI::Token::Word')
&& $elem->content eq 'try'
&& _elem_has_preceding_use_trycatch($elem));
}
# return true if $elem is preceded by any of
# use Try
# use TryCatch
# use syntax 'try'
sub _elem_has_preceding_use_trycatch {
my ($elem) = @_;
my $ret = 0;
my $document = $elem->top; # PPI::Document, not Perl::Critic::Document
$document->find_first (sub {
my ($doc, $e) = @_;
# ### comment: (ref $e)." ".$e->content
if ($e == $elem) {
### not found before target elem, stop ...
return undef;
}
if (_elem_is_use_try($e)) {
### found "use Try" etc, stop ...
$ret = 1;
return undef;
}
return 0; # continue
});
return $ret;
}
sub _elem_is_use_try {
my ($elem) = @_;
($elem->isa('PPI::Statement::Include') && $elem->type eq 'use')
or return 0;
my $module = $elem->module;
return ($module eq 'Try'
|| $module eq 'TryCatch'
|| ($module eq 'syntax'
&& _syntax_has_feature($elem,'try')));
}
# $elem is a PPI::Statement::Include of "use syntax".
# Return true if $feature (a string) is among the feature names it imports.
sub _syntax_has_feature {
my ($elem, $feature) = @_;
return ((grep {$_ eq $feature} _syntax_feature_list($elem)) > 0);
}
# $elem is a PPI::Statement::Include of "use syntax".
# Return a list of the feature names it imports.
sub _syntax_feature_list {
my ($elem) = @_;
### _syntax_feature_list(): $elem && ref $elem
my @ret;
for ($elem = $elem->schild(2); $elem; $elem = $elem->snext_sibling) {
if ($elem->isa('PPI::Token::Word')) {
push @ret, $elem->content;
} elsif ($elem->isa('PPI::Token::QuoteLike::Words')) {
push @ret, $elem->literal;
} elsif ($elem->isa('PPI::Token::Quote')) {
push @ret, $elem->string;
}
}
return @ret;
}
1;
__END__
=for stopwords boolean hashref eg Ryde
=head1 NAME
Perl::Critic::Policy::CodeLayout::RequireFinalSemicolon - require a semicolon at the end of code blocks
=head1 DESCRIPTION
This policy is part of the L<C<Perl::Critic::Pulp>|Perl::Critic::Pulp>
add-on. It asks you to put a semicolon C<;> on the final statement of a
subroutine or block.
sub foo {
do_something(); # ok
}
sub bar {
do_something() # bad
}
The idea is that if you add more code you don't have to notice the previous
line needs a terminator. It's also more like the C language, if you
consider that a virtue.
This is only a matter of style since the code runs the same either way, and
on that basis this policy is low severity and under the "cosmetic" theme
(see L<Perl::Critic/POLICY THEMES>).
=head2 Same Line Closing Brace
By default (see L</CONFIGURATION> below), a semicolon is not required when
the closing brace is on the same line as the last statement. This is good
for constants and one-liners.
sub foo { 'my-constant-value' } # ok
sub square { return $_[0] ** 2 } # ok
=head2 Final Value Expression
A semicolon is not required in places where the last statement is an
expression giving a value.
map { some_thing();
$_+123 # ok
} @values;
do {
foo();
1+2+3 # ok
}
This currently means
do grep map sort # builtins
reduce any all none notall first # List::Util
pairfirst pairgrep pairmap
mapp map_pairwise grepp grep_pairwise # List::Pairwise
firstp first_pairwise lastp last_pairwise
These module function names are always treated as expressions. There's no
check for whether the respective module is actually in use. Fully qualified
names like C<List::Util::first> are recognised too.
C<do {} while> or C<do {} until> loops are ordinary blocks, not expression
blocks, so still require a semicolon on the last statement inside.
do {
foo() # bad
} until ($condition);
=head2 Try/Catch Blocks
The C<Try>, C<TryCatch> and C<Syntax::Feature::Try> modules all add C<try>
block forms. These are blocks not requiring a terminating semicolon, the
same as an C<if> etc doesn't.
use TryCatch;
sub foo {
try {
attempt_something();
} catch {
error_recovery();
} # ok, no semi required here for TryCatch
}
The insides of the C<try> and C<catch> are the same as other blocks, but the
C<try> statement itself doesn't require a semicolon. (See policy
C<ValuesAndExpressions::ProhibitNullStatements> to notice one added
unnecessarily.)
For reference, C<PPI> doesn't know C<try>/C<catch> specifically, so when
they don't have a final semicolon the next statement runs together and the
nature of those parts might be lost. This could upset things like
recognition of C<for> loops and could potentially make some perlcritic
reports go wrong.
The C<try>/C<catch> block exemption here is only for the modules with this
block syntax. There are other try modules such as C<Try::Tiny> and friends
where a final semicolon is normal and necessary if more code follows
(because their C<try> and C<catch> are ordinary function calls prototyped to
take code blocks).
use Try::Tiny;
sub foo {
try {
attempt_something();
} catch {
error_recovery();
} # bad, semi required here for Try::Tiny
}
=head2 Disabling
If you don't care about this you can always disable from your
F<.perlcriticrc> file in the usual way (see L<Perl::Critic/CONFIGURATION>),
[-CodeLayout::RequireFinalSemicolon]
=head1 CONFIGURATION
=over 4
=item C<except_same_line> (boolean, default true)
If true (the default) then don't demand a semicolon if the closing brace is
on the same line as the final statement.
sub foo { return 123 } # ok if "except_same_line=yes"
# bad if "except_same_line=no"
=item C<except_expression_blocks> (boolean, default true)
If true (the default) then don't demand a semicolon at the end of an
expression block, as described under L</Final Value Expression> above.
# ok under "except_expression_blocks=yes"
# bad under "except_expression_blocks=no"
do { 1+2+3 }
map { $_+1 } @array
grep {defined} @x
The statements and functions for this exception are currently hard coded.
Maybe in the future they could be configurable, though multi-line
expressions in this sort of thing tends to be unusual anyway. (See policy
C<BuiltinFunctions::RequireSimpleSortBlock> for example to demand C<sort> is
only one line.)
=back
=head1 BUGS
It's very difficult to distinguish a code block from an anonymous hashref
constructor if there might be a function prototype in force, eg.
foo { abc => 123 }; # hash ref normally
# code block if foo() has prototype
C<PPI> tends to assume code. C<RequireFinalSemicolon> currently assumes
hashref so as to avoid false violations. Any C<try>, C<catch> or C<finally>
are presumed to be code blocks (the various Try modules). Perhaps other
common or particular functions or syntax with code blocks could be
recognised. In general this sort of ambiguity is another good reason to
avoid function prototypes.
PPI as of its version 1.270 sometimes takes hashrefs in lists and arrarefs
to be code blocks, eg.
ppidump 'foo({%y,x=>1})'
ppidump '[{%y,x=>1}]'
ppidump '[{x=>1,%y}]' # ok, hash
=head1 SEE ALSO
L<Perl::Critic::Pulp>,
L<Perl::Critic>,
L<Perl::Critic::Policy::CodeLayout::RequireTrailingCommas>,
L<Perl::Critic::Policy::CodeLayout::RequireTrailingCommaAtNewline>,
L<Perl::Critic::Policy::Subroutines::RequireFinalReturn>,
L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitNullStatements>,
L<Perl::Critic::Policy::BuiltinFunctions::RequireSimpleSortBlock>
L<List::Util>, L<List::Pairwise>,
L<Try>, L<TryCatch>, L<Syntax::Feature::Try>
=head1 HOME PAGE
L<http://user42.tuxfamily.org/perl-critic-pulp/index.html>
=head1 COPYRIGHT
Copyright 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2021 Kevin Ryde
Perl-Critic-Pulp is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
Perl-Critic-Pulp is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
Perl-Critic-Pulp. If not, see <http://www.gnu.org/licenses>.
=cut
|