File Coverage

File:blib/lib/App/Test/Generator/Mutation/ReturnUndef.pm
Coverage:93.1%

linestmtbrancondsubtimecode
1package App::Test::Generator::Mutation::ReturnUndef;
2
3
19
19
19
100902
11
140
use strict;
4
19
19
19
17
9
253
use warnings;
5
19
19
19
20
5
266
use Carp qw(carp);
6
19
19
19
19
25
32
use parent 'App::Test::Generator::Mutation::Base';
7
19
19
19
489
22
112
use App::Test::Generator::Mutant;
8
19
19
19
23
11
5100
use PPI;
9
10our $VERSION = '0.52';
11
12 - 61
=head1 NAME

App::Test::Generator::Mutation::ReturnUndef - Replace return expressions
with undef to expose missing undef-return checks in the test suite

=head1 VERSION

Version 0.52

=head1 METHODS

=head2 applies_to

Return true if the given document contains at least one return
statement this mutation strategy could mutate. Used by
L<App::Test::Generator::Mutator> to pre-filter strategies before
calling C<mutate>, so a document with nothing to mutate skips the
walk entirely.

    my $applies = $mutation->applies_to($doc);

=head3 Arguments

=over 4

=item * C<$doc>

A L<PPI::Document> object to inspect.

=back

=head3 Returns

True if the document contains a C<return> statement (PPI::Statement::Break
whose first token is C<return>), false otherwise.

=head3 API specification

=head4 input

    {
        self => { type => OBJECT, isa => 'App::Test::Generator::Mutation::ReturnUndef' },
        doc  => { type => OBJECT, isa => 'PPI::Document' },
    }

=head4 output

    { type => SCALAR }

=cut
62
63sub applies_to {
64
71
5971
        my ($self, $doc) = @_;
65
66        # PPI >= 1.270 classifies return as PPI::Statement::Break rather
67        # than the dedicated PPI::Statement::Return class -- scan the whole
68        # document for at least one qualifying return statement. This must
69        # match the document-level pre-filter contract used by
70        # Mutator::generate_mutants (and documented in Mutation::Base) rather
71        # than testing a single node, otherwise every call from
72        # generate_mutants would see $doc itself, which is never a
73        # PPI::Statement::Break, and mutate() would never run.
74        my $returns = $doc->find(sub {
75
8188
22905
                my $node = $_[1];
76
8188
7110
                return 0 unless $node->isa('PPI::Statement::Break');
77
198
140
                my $first = $node->schild(0) or return 0;
78
198
840
                return $first->content eq 'return';
79
71
191
        }) || [];
80
81
71
71
360
125
        return @{$returns} ? 1 : 0;
82}
83
84 - 167
=head2 mutate

Walk a PPI document and generate one mutant for each non-bare return
statement, replacing its expression with C<undef>. For example,
C<return $result> becomes C<return undef>.

Bare C<return;> statements are skipped because they already return
undef - mutating them would produce a redundant mutant that can never
be killed.

    my $mutation = App::Test::Generator::Mutation::ReturnUndef->new;
    my $doc      = PPI::Document->new(\$source);
    my @mutants  = $mutation->mutate($doc);

    for my $m (@mutants) {
        print $m->id, ': ', $m->description, "\n";
    }

=head3 Arguments

=over 4

=item * C<$self>

An instance of C<App::Test::Generator::Mutation::ReturnUndef>.

=item * C<$doc>

A L<PPI::Document> object representing the parsed source to mutate.
The document is not modified by this method.

=back

=head3 Returns

A list of L<App::Test::Generator::Mutant> objects, one per qualifying
return statement found in the document. Returns an empty list if no
non-bare return statements are found.

Each mutant carries a C<transform> closure that when called with a
fresh L<PPI::Document> copy will replace the targeted return expression
with the literal C<undef>.

=head3 Notes

Mutant IDs include both line and column number to ensure uniqueness
when multiple return statements appear in the same source file.

Only return statements with an expression child are mutated - bare
C<return;> statements are skipped as they already return undef.

Each mutant's optional C<context> field is set to C<conditional> if
the return statement sits inside (or is itself the keyword of) an
C<if>/C<unless>/C<while>/C<until> compound statement, or C<statement>
otherwise; its C<line_content> field holds the raw source text of the
mutated line. Both are consumed by
L<App::Test::Generator::Mutator>'s fast-mode dedup.

=head3 API specification

=head4 input

    {
        self => {
            type => OBJECT,
            isa  => 'App::Test::Generator::Mutation::ReturnUndef',
        },
        doc => {
            type => OBJECT,
            isa  => 'PPI::Document',
        },
    }

=head4 output

    {
        type     => ARRAYREF,
        elements => {
            type => OBJECT,
            isa  => 'App::Test::Generator::Mutant',
        },
    }

=cut
168
169sub mutate {
170
104
34572
        my ($self, $doc) = @_;
171
172        # PPI >= 1.270 classifies return statements as PPI::Statement::Break
173        # rather than PPI::Statement::Return -- use a custom predicate
174        my $returns = $doc->find(sub {
175
8868
24724
                my $node = $_[1];
176                # Match Break nodes that are specifically return statements
177
8868
7655
                return 0 unless $node->isa('PPI::Statement::Break');
178
240
167
                my $first = $node->schild(0) or return 0;
179
240
999
                return $first->content eq 'return';
180
104
207
        }) || [];
181
182
104
468
        my @mutants;
183
184
104
104
75
106
        for my $ret (@{$returns}) {
185                # Skip bare return statements — they already return undef
186                # so mutating them would produce a redundant mutant that
187                # can never be killed by any meaningful test. Also skips
188                # bare returns with only a postfix conditional/loop modifier.
189
240
196
                my @expr = _return_expr_span($ret);
190
240
185
                next unless @expr;
191
192                # Skip a lone structure node (e.g. return ($x, $y) gives a
193                # single PPI::Structure::List child) — nothing simple to splice
194
234
327
                next if @expr == 1 && !$expr[0]->isa('PPI::Token');
195
196                # Capture location so the transform closure targets the
197                # exact statement rather than the first match on that line
198
233
229
                my $line = $ret->location->[0];
199
233
7277
                my $col  = $ret->location->[1];
200
201                # Build a unique ID from line and column so multiple return
202                # statements in the same file never collide
203
233
1169
                my $id = "RETURN_UNDEF_${line}_${col}";
204
205
233
136
                my $mutant = eval {
206                        App::Test::Generator::Mutant->new(
207                                id           => $id,
208                                group        => "RETURN_UNDEF:$line",
209                                description  => 'Replace return expression with undef',
210                                original     => $ret->content(),
211                                line         => $line,
212                                type         => 'return',
213                                context      => $self->_in_conditional($ret) ? 'conditional' : 'statement',
214                                line_content => $self->_line_content($doc, $line),
215
216                                # The transform closure captures line and col so it
217                                # targets precisely the right return statement in the
218                                # document copy it receives at test time
219                                transform => sub {
220
12
14
                                        my $doc  = $_[0];
221                                        # PPI >= 1.270 uses PPI::Statement::Break for return
222                                        my $rets = $doc->find(sub {
223                                                my $node = $_[1];
224                                                return 0 unless $node->isa('PPI::Statement::Break');
225                                                my $first = $node->schild(0) or return 0;
226                                                return $first->content eq 'return';
227
12
24
                                                }) || [];
228
12
12
58
13
                                        for my $ret (@{$rets}) {
229
13
413
                                                next unless $ret->line_number   == $line;
230
12
1953
                                                next unless $ret->column_number == $col;
231
232
12
83
                                                my @expr = _return_expr_span($ret);
233
12
10
                                                last unless @expr;
234
12
30
                                                last if @expr == 1 && !$expr[0]->isa('PPI::Token');
235
236                                                # Replace the whole expression span with a single
237                                                # 'undef' token rather than just its first token --
238                                                # $self->{x} is three significant children (Symbol,
239                                                # Operator, Structure) and replacing only the
240                                                # leading $self produced the broken mutant
241                                                # 'return undef->{x};'
242
12
14
                                                $expr[0]->insert_before(PPI::Token::Word->new('undef'));
243
12
245
                                                $_->remove for @expr;
244
12
264
                                                last;
245                                        }
246                                },
247
233
262
                        );
248                };
249
250                # If the Mutant construction fails, report clearly rather than
251                # silently dropping the mutant from the results
252
233
343
                if($@ || !$mutant) {
253
1
12
                        carp "Failed to construct mutant $id: $@" if $@;
254
1
142
                        next;
255                }
256
257
232
196
                push @mutants, $mutant;
258        }
259
260
104
143
        return @mutants;
261}
262
263# --------------------------------------------------
264# Purpose: identify the PPI elements making up the expression
265#          being returned by a 'return' statement, excluding
266#          the leading 'return' keyword, the trailing statement
267#          terminator, and any postfix conditional/loop modifier
268#          (if/unless/while/until/for/foreach) and its condition.
269# Entry:   a PPI::Statement::Break node already confirmed to be
270#          a 'return' statement.
271# Exit:    a list of the significant child elements making up
272#          the return expression, or an empty list for a bare
273#          return (with or without a postfix modifier).
274# Side effects: none.
275# --------------------------------------------------
276sub _return_expr_span {
277
256
7064
        my ($ret) = @_;
278
279
256
226
        my @children = $ret->schildren;
280
256
1108
        shift @children;
281
282
256
518
        if(@children && $children[-1]->isa('PPI::Token::Structure') && $children[-1]->content eq ';') {
283
232
355
                pop @children;
284        }
285
286
256
240
        for my $i (0 .. $#children) {
287
448
283
                my $child = $children[$i];
288
448
490
                next unless $child->isa('PPI::Token::Word');
289
20
23
                next unless $child->content =~ /^(?:if|unless|while|until|for|foreach)$/;
290
11
30
                @children = @children[0 .. $i - 1];
291
11
7
                last;
292        }
293
294
256
221
        return @children;
295}
296
297 - 309
=head1 AUTHOR

Nigel Horne, C<< <njh at nigelhorne.com> >>

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the terms of GPL2.
If you use it,
please let me know.

=cut
310
3111;