File Coverage

File:blib/lib/App/Test/Generator/Mutation/BooleanNegation.pm
Coverage:91.7%

linestmtbrancondsubtimecode
1package App::Test::Generator::Mutation::BooleanNegation;
2
3
19
19
19
152874
12
151
use strict;
4
19
19
19
25
12
303
use warnings;
5
6
19
19
19
26
13
268
use Carp qw(carp);
7
19
19
19
165
101
57
use parent 'App::Test::Generator::Mutation::Base';
8
19
19
19
1875
18
142
use App::Test::Generator::Mutant;
9
19
19
19
365
102185
5122
use PPI;
10
11our $VERSION = '0.52';
12
13 - 62
=head1 NAME

App::Test::Generator::Mutation::BooleanNegation - Negate boolean return
expressions to expose missing assertion coverage

=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::BooleanNegation' },
        doc  => { type => OBJECT, isa => 'PPI::Document' },
    }

=head4 output

    { type => SCALAR }

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

Walk a PPI document and generate one mutant for each return statement
whose expression can be negated. For example, C<return $ok> becomes
C<return !($ok)>.

    my $mutation = App::Test::Generator::Mutation::BooleanNegation->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::BooleanNegation>.

=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
return statements with expressions are found.

Each mutant carries a C<transform> closure that when called with a
fresh L<PPI::Document> copy will wrap the targeted return expression
in C<!( )>, negating its boolean value.

=head3 Notes

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

Only return statements that have an expression child (i.e. not bare
C<return;> statements) are mutated.

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::BooleanNegation',
        },
        doc => {
            type => OBJECT,
            isa  => 'PPI::Document',
        },
    }

=head4 output

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

=cut
165
166sub mutate {
167
107
40761
        my ($self, $doc) = @_;
168
169        # PPI >= 1.270 classifies return statements as PPI::Statement::Break
170        # (alongside last/next/redo) rather than PPI::Statement::Return.
171        # Use a custom predicate to match only 'return' Break nodes.
172        my $returns = $doc->find(sub {
173
8957
25307
                my $node = $_[1];
174                # Must be a Break statement -- the parent class for return in
175                # newer PPI versions
176
8957
7821
                return 0 unless $node->isa('PPI::Statement::Break');
177                # Distinguish return from last/next/redo by checking the
178                # first significant child token
179
245
202
                my $first = $node->schild(0) or return 0;
180
245
1013
                return $first->content eq 'return';
181
107
225
        }) || [];
182
183
107
520
        my @mutants;
184
185
107
107
73
107
        for my $ret (@{$returns}) {
186                # Skip bare return statements with no expression to negate,
187                # and bare returns with only a postfix conditional/loop
188                # modifier (return if $cond; has nothing to negate)
189
245
248
                my @expr = _return_expr_span($ret);
190
245
206
                next unless @expr;
191
192                # Skip a lone structure node (e.g. return ($x, $y) gives a
193                # single PPI::Structure::List child) — wrapping it is not
194                # useful and there is nothing simple to splice around
195
238
377
                next if @expr == 1 && !$expr[0]->isa('PPI::Token');
196
197                # Capture location so the transform closure targets the
198                # exact statement rather than the first match on that line
199
238
282
                my $line = $ret->location->[0];
200
238
73688
                my $col  = $ret->location->[1];
201
202                # Build a unique ID from line and column so multiple return
203                # statements in the same file never collide
204
238
1223
                my $id = "BOOL_NEGATE_${line}_${col}";
205
206
238
137
                my $mutant = eval {
207                        App::Test::Generator::Mutant->new(
208                                id           => $id,
209                                group        => "BOOL_NEGATE:$line",
210                                description  => 'Negate boolean return expression',
211                                original     => $ret->content,
212                                line         => $line,
213                                type         => 'boolean',
214                                context      => $self->_in_conditional($ret) ? 'conditional' : 'statement',
215                                line_content => $self->_line_content($doc, $line),
216
217                                # The transform closure captures line and col so it
218                                # targets precisely the right return statement in the
219                                # document copy it receives at test time
220                                transform => sub {
221
15
11
                                        my $doc  = $_[0];
222
223                                        # Locate all return statements in the fresh document copy using
224                                        # the same PPI::Statement::Break predicate as the outer find --
225                                        # PPI >= 1.270 no longer uses PPI::Statement::Return
226                                        my $rets = $doc->find(sub {
227                                                my $node = $_[1];
228                                                # Match Break nodes only -- covers return/last/next/redo
229                                                return 0 unless $node->isa('PPI::Statement::Break');
230                                                # Filter to return specifically by inspecting the first token
231                                                my $first = $node->schild(0) or return 0;
232                                                return $first->content eq 'return';
233
15
51
                                        }) || [];
234
235
15
15
72
12
                                        for my $ret (@{$rets}) {
236                                                # Match by line and column to avoid mutating
237                                                # the wrong return statement
238
17
866
                                                next unless $ret->line_number   == $line;
239
15
4730
                                                next unless $ret->column_number == $col;
240
241                                                # Skip bare returns with no expression
242
15
105
                                                my @expr = _return_expr_span($ret);
243
15
21
                                                last unless @expr;
244
245                                                # Skip a lone structure node
246
15
31
                                                last if @expr == 1 && !$expr[0]->isa('PPI::Token');
247
248                                                # Wrap the whole expression span in !(...) rather
249                                                # than just its first token -- $self->{x} is three
250                                                # significant children (Symbol, Operator, Structure)
251                                                # and wrapping only the leading $self produced the
252                                                # broken mutant 'return !($self)->{x};'
253
15
23
                                                $expr[0]->insert_before(PPI::Token::Operator->new('!'));
254
15
406
                                                $expr[0]->insert_before(PPI::Token::Structure->new('('));
255
15
236
                                                $expr[-1]->insert_after(PPI::Token::Structure->new(')'));
256
15
317
                                                last;
257                                        }
258                                },
259
238
271
                        );
260                };
261
262                # If the Mutant construction fails, report clearly rather than
263                # silently dropping the mutant from the results
264
238
394
                if($@ || !$mutant) {
265
1
11
                        carp "Failed to construct mutant $id: $@" if $@;
266
1
131
                        next;
267                }
268
269
237
226
                push @mutants, $mutant;
270        }
271
272
107
153
        return @mutants;
273}
274
275# --------------------------------------------------
276# Purpose: identify the PPI elements making up the expression
277#          being returned by a 'return' statement, excluding
278#          the leading 'return' keyword, the trailing statement
279#          terminator, and any postfix conditional/loop modifier
280#          (if/unless/while/until/for/foreach) and its condition.
281# Entry:   a PPI::Statement::Break node already confirmed to be
282#          a 'return' statement.
283# Exit:    a list of the significant child elements making up
284#          the return expression, or an empty list for a bare
285#          return (with or without a postfix modifier).
286# Side effects: none.
287# --------------------------------------------------
288sub _return_expr_span {
289
262
3639
        my ($ret) = @_;
290
291
262
263
        my @children = $ret->schildren;
292
262
1193
        shift @children;
293
294
262
595
        if(@children && $children[-1]->isa('PPI::Token::Structure') && $children[-1]->content eq ';') {
295
237
374
                pop @children;
296        }
297
298
262
273
        for my $i (0 .. $#children) {
299
463
323
                my $child = $children[$i];
300
463
526
                next unless $child->isa('PPI::Token::Word');
301
22
24
                next unless $child->content =~ /^(?:if|unless|while|until|for|foreach)$/;
302
11
33
                @children = @children[0 .. $i - 1];
303
11
8
                last;
304        }
305
306
262
236
        return @children;
307}
308
309 - 331
=head1 AUTHOR

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

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to licence terms.

The licence terms of this software are as follows:

=over 4

=item * Personal single user, single computer use: GPL2

=item * All other users (including Commercial, Charity, Educational,
Government) must apply in writing for a licence for use from Nigel Horne
at the above e-mail.

=back

=cut
332
3331;