| 1 | # You may distribute under the terms of either the GNU General Public License | ||
| 2 | # or the Artistic License (the same terms as Perl itself) | ||
| 3 | # | ||
| 4 | # (C) Paul Evans, 2023 -- leonerd@leonerd.org.uk | ||
| 5 | |||
| 6 | use v5.36; | ||
| 7 | use Object::Pad 0.807; | ||
| 8 | |||
| 9 | class App::perl::distrolint::Check::NoStrictRefs 0.09; | ||
| 10 | |||
| 11 | apply App::perl::distrolint::CheckRole::EachFile; | ||
| 12 | apply App::perl::distrolint::CheckRole::TreeSitterPerl; | ||
| 13 | |||
| 14 | use Text::Treesitter 0.07; # child_by_field_name | ||
| 15 | |||
| 16 | use constant DESC => "forbid the use of no strict 'refs'"; | ||
| 17 | use constant SORT => 12; | ||
| 18 | |||
| 19 | use List::Util qw( any ); | ||
| 20 | |||
| 21 | =head1 NAME | ||
| 22 | |||
| 23 | C<App::perl::distrolint::Check::NoStrictRefs> - forbid the use of C<no strict 'refs'> | ||
| 24 | |||
| 25 | =head1 DESCRIPTION | ||
| 26 | |||
| 27 | This checks that no Perl source code file contains a C<no strict> declaration | ||
| 28 | that turns off the C<refs> stricture. | ||
| 29 | |||
| 30 | This is generally considered an anti-pattern that should be replaced by uses | ||
| 31 | of the L<meta> metaprogramming module, or more specialised things such as | ||
| 32 | L<Object::Pad::MOP>. | ||
| 33 | |||
| 34 | =cut | ||
| 35 | |||
| 36 | method run ( $app ) | ||
| 37 | { | ||
| 38 | return $self->run_for_each_perl_file( check_file => ); | ||
| 39 | } | ||
| 40 | |||
| 41 | my $QUERY = <<'EOF'; | ||
| 42 | (use_statement | ||
| 43 | "no" | ||
| 44 | module: _ @module (#eq? @module "strict")) | ||
| 45 | @statement | ||
| 46 | EOF | ||
| 47 | |||
| 48 | method check_file ( $file ) | ||
| 49 | { | ||
| 50 | my $tree = $self->parse_perl_file( $file ); | ||
| 51 | |||
| 52 | return 0 unless $self->walk_each_query_match( $QUERY, $tree->root_node, method ( $captures ) { | ||
| 53 | my $node = $captures->{statement}; | ||
| 54 | my @imports = $self->extract_use_module_imports( $node ); | ||
| 55 | |||
| 56 | my $has_refs = !@imports || any { $_ eq "refs" } @imports; | ||
| 57 | $has_refs or return 1; | ||
| 58 | |||
| 59 | App->diag( App->format_file( $file, $node->start_row + 1 ), " has " . App->format_literal( $node->text ) ); | ||
| 60 | |||
| 61 | return 0; | ||
| 62 | } ); | ||
| 63 | } | ||
| 64 | |||
| 65 | =head1 AUTHOR | ||
| 66 | |||
| 67 | Paul Evans <leonerd@leonerd.org.uk> | ||
| 68 | |||
| 69 | =cut | ||
| 70 | |||
| 71 | 0x55AA; |