targeted-mutation 0.12.0

Targeted mutation testing for Rust: find the wrong implementations your tests let through
Documentation
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Distinguishing inputs for bit masks, string lengths, and existing range mutants.

use std::collections::BTreeMap;

use syn::parse::Parser;
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::{BinOp, Expr, FnArg, Item, ItemFn, Pat, ReturnType, Stmt, Type};

use super::common::{
    ident_binding, is_integer_type_name as is_integer, is_plain_fn, type_name, unparen,
    unparen_path_ident as path,
};
use super::{Candidate, Edit, Scenario};

pub(super) fn discover(
    source: &str,
    file: &syn::File,
    out: &mut Vec<Candidate>,
    include_existing: bool,
) {
    let mut fixtures = RangeFixtures {
        source,
        tests: Vec::new(),
        seeds: BTreeMap::new(),
    };
    if include_existing {
        fixtures.visit_file(file);
    }
    for item in &file.items {
        let Item::Fn(function) = item else { continue };
        if !supports(function) {
            continue;
        }
        out.extend(bit_mask(source, function));
        out.extend(string_length(source, function));
        if include_existing && let Some(seeds) = fixtures.seeds.get(&function.sig.ident.to_string())
        {
            out.extend(range_mutation(source, function, seeds));
        }
    }
}

pub(super) fn supports(function: &ItemFn) -> bool {
    is_plain_fn(function, true)
}

fn parameter(item: &FnArg) -> Option<(&syn::Ident, &Type)> {
    let FnArg::Typed(typed) = item else {
        return None;
    };
    Some((ident_binding(&typed.pat)?, &typed.ty))
}

fn returns(function: &ItemFn, name: &str) -> bool {
    matches!(&function.sig.output, ReturnType::Type(_, ty) if type_name(ty).is_some_and(|id| id == name))
}

fn tail(function: &ItemFn) -> Option<&Expr> {
    let [Stmt::Expr(expr, None)] = function.block.stmts.as_slice() else {
        return None;
    };
    Some(expr)
}

fn integer_literal(expr: &Expr) -> Option<&syn::LitInt> {
    let Expr::Lit(lit) = unparen(expr) else {
        return None;
    };
    let syn::Lit::Int(value) = &lit.lit else {
        return None;
    };
    Some(value)
}

fn decimal_value(expr: &Expr) -> Option<String> {
    let expr = unparen(expr);
    let (negative, value) = match expr {
        Expr::Unary(unary) if matches!(unary.op, syn::UnOp::Neg(_)) => (true, unary.expr.as_ref()),
        _ => (false, expr),
    };
    let value = integer_literal(value)?.base10_parse::<u128>().ok()?;
    Some(if negative && value != 0 {
        format!("-{value}")
    } else {
        value.to_string()
    })
}

fn bit_mask(source: &str, function: &ItemFn) -> Option<Candidate> {
    let mut arguments = function.sig.inputs.iter();
    let (bits, bits_type) = parameter(arguments.next()?)?;
    let (mask, mask_type) = parameter(arguments.next()?)?;
    if arguments.next().is_some() || !returns(function, "bool") {
        return None;
    }
    let integer = type_name(bits_type)?;
    if !is_integer(integer) || type_name(mask_type) != Some(integer) {
        return None;
    }
    let expr = tail(function)?;
    let Expr::Binary(comparison) = unparen(expr) else {
        return None;
    };
    if !matches!(comparison.op, BinOp::Ne(_)) {
        return None;
    }
    let zero = |expr: &Expr| {
        integer_literal(expr).and_then(|int| int.base10_parse::<u128>().ok()) == Some(0)
    };
    let operation = if zero(&comparison.right) {
        unparen(&comparison.left)
    } else if zero(&comparison.left) {
        unparen(&comparison.right)
    } else {
        return None;
    };
    let Expr::Binary(and) = operation else {
        return None;
    };
    if !matches!(and.op, BinOp::BitAnd(_)) {
        return None;
    }
    let lhs = path(&and.left)?;
    let rhs = path(&and.right)?;
    if !((lhs == bits && rhs == mask) || (lhs == mask && rhs == bits)) {
        return None;
    }
    let original = source.get(expr.span().byte_range())?;
    let replacement = format!("{lhs} & {rhs} == {mask}");
    let description =
        format!("replace any-bit test `{original}` with all-bit test `{replacement}`");
    Some(candidate(
        function,
        expr.span(),
        replacement,
        description,
        false,
        vec![Scenario {
            expression: format!("{}(0b01, 0b11)", function.sig.ident),
            guidance: Some(
                "Use this input if the API accepts masks with multiple bits set.".into(),
            ),
            ..Scenario::default()
        }],
    ))
}

fn string_length(source: &str, function: &ItemFn) -> Option<Candidate> {
    let mut arguments = function.sig.inputs.iter();
    let (text, ty) = parameter(arguments.next()?)?;
    if arguments.next().is_some() || !returns(function, "usize") {
        return None;
    }
    let Type::Reference(reference) = ty else {
        return None;
    };
    if reference.mutability.is_some() || type_name(&reference.elem)? != "str" {
        return None;
    }
    let expr = tail(function)?;
    let Expr::MethodCall(method) = unparen(expr) else {
        return None;
    };
    if !plain_method(method) {
        return None;
    }
    let replacement = if method.method == "len" && path(&method.receiver) == Some(text) {
        format!("{text}.chars().count()")
    } else if method.method == "count"
        && let Expr::MethodCall(chars) = unparen(&method.receiver)
        && chars.method == "chars"
        && plain_method(chars)
        && path(&chars.receiver) == Some(text)
    {
        format!("{text}.len()")
    } else {
        return None;
    };
    let original = source.get(expr.span().byte_range())?;
    let description = format!("replace `{original}` with `{replacement}`");
    Some(candidate(
        function,
        expr.span(),
        replacement,
        description,
        false,
        vec![Scenario {
            expression: format!("{}(\"é\")", function.sig.ident),
            // The input is this tool's, not one the tests gave: it may be outside of
            // what the function is for.
            guidance: Some("Use this input if the API accepts text outside ASCII.".into()),
            ..Scenario::default()
        }],
    ))
}

fn plain_method(method: &syn::ExprMethodCall) -> bool {
    method.args.is_empty() && method.turbofish.is_none()
}

fn range_mutation(source: &str, function: &ItemFn, seeds: &[RangeSeed]) -> Option<Candidate> {
    let mut arguments = function.sig.inputs.iter();
    let (slice_name, ty) = parameter(arguments.next()?)?;
    let (bound, bound_type) = parameter(arguments.next()?)?;
    if arguments.next().is_some() || type_name(bound_type)? != "usize" {
        return None;
    }
    let Type::Reference(reference) = ty else {
        return None;
    };
    let Type::Slice(slice) = reference.elem.as_ref() else {
        return None;
    };
    let element = type_name(&slice.elem)?;
    if reference.mutability.is_some()
        || !is_integer(element)
        || !returns(function, &element.to_string())
    {
        return None;
    }
    let range = function.block.stmts.iter().find_map(|stmt| {
        let Stmt::Expr(Expr::ForLoop(iteration), _) = stmt else {
            return None;
        };
        let Pat::Ident(index) = iteration.pat.as_ref() else {
            return None;
        };
        let Expr::Range(range) = unparen(&iteration.expr) else {
            return None;
        };
        let first = integer_literal(range.start.as_deref()?)?;
        if first.base10_parse::<u128>().ok()? != 0
            || !matches!(range.limits, syn::RangeLimits::HalfOpen(_))
            || path(range.end.as_deref()?)? != bound
        {
            return None;
        }
        let [Stmt::Expr(Expr::Binary(accumulation), _)] = iteration.body.stmts.as_slice() else {
            return None;
        };
        let Expr::Index(value) = unparen(&accumulation.right) else {
            return None;
        };
        (matches!(accumulation.op, BinOp::AddAssign(_))
            && path(&accumulation.left).is_some()
            && path(&value.expr) == Some(slice_name)
            && path(&value.index) == Some(&index.ident))
        .then_some(range)
    })?;
    let first = source.get(range.start.as_deref()?.span().byte_range())?;
    let end = source.get(range.end.as_deref()?.span().byte_range())?;
    let replacement = format!("{first}..={end}");
    let description = format!(
        "`{}..={}`",
        crate::report::one_line(first),
        crate::report::one_line(end)
    );
    Some(candidate(
        function,
        range.span(),
        replacement,
        description,
        true,
        seeds
            .iter()
            .map(|seed| Scenario {
                expression: seed.expression.clone(),
                guidance: seed.expected.as_ref().map(|_| seed.guidance.clone()),
                fixture_expectation: seed.expected.clone(),
                source_test: Some(seed.test.clone()),
                ..Scenario::default()
            })
            .collect(),
    ))
}

struct RangeSeed {
    expression: String,
    guidance: String,
    test: String,
    expected: Option<String>,
}

struct RangeFixtures<'src> {
    source: &'src str,
    tests: Vec<String>,
    seeds: BTreeMap<String, Vec<RangeSeed>>,
}

impl RangeFixtures<'_> {
    fn seed(&mut self, expr: &Expr, expected: &Expr) -> Option<()> {
        let Expr::Call(call) = unparen(expr) else {
            return None;
        };
        let Expr::Path(callee) = unparen(&call.func) else {
            return None;
        };
        let name = callee.path.segments.last()?.ident.to_string();
        if callee.qself.is_some()
            || !(callee.path.get_ident().is_some()
                || (callee.path.segments.len() == 2
                    && (callee.path.segments[0].ident == "crate"
                        || (self.tests.len() == 2 && callee.path.segments[0].ident == "super"))))
        {
            return None;
        }
        let mut arguments = call.args.iter();
        let slice = arguments.next()?;
        let bound = integer_literal(arguments.next()?)?;
        if arguments.next().is_some() {
            return None;
        }
        let Expr::Reference(reference) = unparen(slice) else {
            return None;
        };
        let Expr::Array(array) = unparen(&reference.expr) else {
            return None;
        };
        if reference.mutability.is_some()
            || !array.elems.iter().all(|item| {
                integer_literal(item).is_some()
                    || matches!(unparen(item), Expr::Unary(negative) if matches!(negative.op, syn::UnOp::Neg(_)) && integer_literal(&negative.expr).is_some())
            })
        {
            return None;
        }
        let zero = integer_literal(
            array
                .elems
                .iter()
                .nth(bound.base10_parse::<usize>().ok()?)?,
        )?;
        if zero.base10_parse::<u128>().ok()? != 0 {
            return None;
        }
        let span = slice.span().byte_range();
        let original = self.source.get(span.clone())?;
        let zero_span = zero.span().byte_range();
        let token = self.source.get(zero_span.clone())?;
        // Keep the original radix, separators, and type suffix. Only the last zero digit changes.
        let digit = token.strip_suffix(zero.suffix())?.rfind('0')?;
        let index = zero_span.start.checked_sub(span.start)? + digit;
        let mut changed = original.to_owned();
        changed.replace_range(index..index + 1, "1");
        let test = self.tests.join("::");
        let expression = format!("{name}({changed}, {bound})");
        let scenarios = self.seeds.entry(name).or_default();
        if scenarios.iter().filter(|seed| seed.test == test).count() < 4
            && !scenarios
                .iter()
                .any(|seed| seed.expression == expression && seed.test == test)
        {
            scenarios.push(RangeSeed {
                expression,
                guidance: format!("In `{test}`, change `{original}` to `{changed}`."),
                test,
                expected: decimal_value(expected),
            });
        }
        Some(())
    }
}

impl<'ast> Visit<'ast> for RangeFixtures<'_> {
    fn visit_item_mod(&mut self, module: &'ast syn::ItemMod) {
        self.tests.push(module.ident.to_string());
        syn::visit::visit_item_mod(self, module);
        self.tests.pop();
    }

    fn visit_item_fn(&mut self, function: &'ast ItemFn) {
        if function
            .attrs
            .iter()
            .any(|attr| attr.path().is_ident("test"))
        {
            self.tests.push(function.sig.ident.to_string());
            self.visit_block(&function.block);
            self.tests.pop();
        }
    }

    fn visit_macro(&mut self, mac: &'ast syn::Macro) {
        if mac.path.is_ident("assert_eq")
            && let Ok(args) = syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated
                .parse2(mac.tokens.clone())
            && let Some((left, right)) = args.first().zip(args.iter().nth(1))
        {
            self.seed(left, right);
            self.seed(right, left);
        }
    }
}

fn candidate(
    function: &ItemFn,
    span: proc_macro2::Span,
    replacement: String,
    description: String,
    existing: bool,
    scenarios: Vec<Scenario>,
) -> Candidate {
    Candidate {
        edits: vec![Edit {
            span: span.byte_range(),
            replacement,
        }],
        scope: span.start().line..=span.end().line,
        signature_lines: vec![function.sig.span().start().line],
        description,
        existing,
        advice: None,
        file: Default::default(),
        finding_at: None,
        scenarios,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn candidates(source: &str) -> Vec<Candidate> {
        let file = syn::parse_file(source).unwrap();
        let mut found = Vec::new();
        discover(source, &file, &mut found, true);
        found
    }

    #[test]
    fn a_partial_mask_distinguishes_any_bit_from_all_bits() {
        let source = "fn enabled(bits: u64, active: u64) -> bool { bits & active != 0 }";
        let found = candidates(source);
        assert_eq!(found.len(), 1);
        let candidate = &found[0];
        assert!(!candidate.existing);
        assert_eq!(
            &source[candidate.edits[0].span.clone()],
            "bits & active != 0"
        );
        assert_eq!(candidate.edits[0].replacement, "bits & active == active");
        assert_eq!(candidate.scenarios[0].expression, "enabled(0b01, 0b11)");
        assert!(
            candidate.scenarios[0]
                .guidance
                .as_ref()
                .unwrap()
                .contains("multiple bits")
        );
    }

    #[test]
    fn a_non_ascii_scalar_distinguishes_char_and_byte_counts() {
        let source = r#"
fn chars(label: &str) -> usize { label.chars().count() }
fn bytes(label: &str) -> usize { label.len() }
fn unrelated(values: &[u8]) -> usize { values.len() }
"#;
        let found = candidates(source);
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].edits[0].replacement, "label.len()");
        assert_eq!(found[0].scenarios[0].expression, r#"chars("é")"#);
        assert_eq!(found[1].edits[0].replacement, "label.chars().count()");
        assert_eq!(found[1].scenarios[0].expression, r#"bytes("é")"#);
    }

    #[test]
    fn a_range_witness_changes_only_the_unused_zero_in_an_existing_test() {
        let source = r#"
fn total_of(items: &[u32], bound: usize) -> u32 {
    let mut total = 0;
    for i in 0 .. bound { total += items[i]; }
    total
}
#[cfg(test)]
mod checks {
    use super::*;
    #[test]
    fn preserves_sum() {
        assert_eq!((0x9_u32), total_of(&[4, 5, 0], 2));
        assert_eq!(total_of(&[4], 1), 4);
    }
}
"#;
        let found = candidates(source);
        assert_eq!(found.len(), 1);
        let candidate = &found[0];
        assert!(candidate.existing);
        assert_eq!(candidate.description, "`0..=bound`");
        assert_eq!(&source[candidate.edits[0].span.clone()], "0 .. bound");
        assert_eq!(candidate.edits[0].replacement, "0..=bound");
        assert_eq!(candidate.scenarios.len(), 1);
        let scenario = &candidate.scenarios[0];
        assert_eq!(scenario.expression, "total_of(&[4, 5, 1], 2)");
        assert_eq!(scenario.fixture_expectation.as_deref(), Some("9"));
        assert_eq!(
            scenario.source_test.as_deref(),
            Some("checks::preserves_sum")
        );
        assert_eq!(
            scenario.guidance.as_deref(),
            Some("In `checks::preserves_sum`, change `&[4, 5, 0]` to `&[4, 5, 1]`."),
        );
    }

    #[test]
    fn only_plain_functions_with_harmless_attributes_get_a_witness() {
        let body = "(bits: u64, active: u64) -> bool { bits & active != 0 }";
        for prefix in [
            "fn enabled",
            "pub fn enabled",
            "/// Any bit.\nfn enabled",
            "#[inline]\nfn enabled",
            "#[must_use]\nfn enabled",
            "/// Any bit.\n#[inline]\n#[must_use]\nfn enabled",
        ] {
            let source = format!("{prefix}{body}");
            assert_eq!(candidates(&source).len(), 1, "{source}");
        }
        // The witness calls the function as `enabled(0b01, 0b11)` from a plain test.
        for prefix in [
            "fn enabled<T>",
            "async fn enabled",
            "unsafe fn enabled",
            "extern \"C\" fn enabled",
            "#[cfg(feature = \"masks\")]\nfn enabled",
            "#[inline]\n#[test]\nfn enabled",
        ] {
            let source = format!("{prefix}{body}");
            assert!(candidates(&source).is_empty(), "{source}");
        }
    }

    #[test]
    fn parameters_have_to_be_plain_bindings() {
        for parameters in [
            "ref bits: u64, active: u64",
            "bits @ _: u64, active: u64",
            "bits: u64, ref active: u64",
        ] {
            let source = format!("fn enabled({parameters}) -> bool {{ bits & active != 0 }}");
            assert!(candidates(&source).is_empty(), "{source}");
        }
    }

    #[test]
    fn a_bit_mask_needs_two_integers_of_one_type_and_a_bool() {
        for signature in [
            "(bits: u64, active: u64) -> u64",
            "(bits: u64, active: u64)",
            "(bits: u64, active: u64, extra: u64) -> bool",
            "(bits: u64, active: u64, extra: u64) -> u64",
            "(bits: u64, active: u32) -> bool",
            "(bits: Flags, active: Flags) -> bool",
            "(bits: Flags, active: u64) -> bool",
            "(bits: bool, active: bool) -> bool",
        ] {
            let source = format!("fn enabled{signature} {{ bits & active != 0 }}");
            assert!(candidates(&source).is_empty(), "{source}");
        }
        for integer in [
            "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
        ] {
            let source = format!(
                "fn enabled(bits: {integer}, active: {integer}) -> bool {{ bits & active != 0 }}"
            );
            assert_eq!(candidates(&source).len(), 1, "{source}");
        }
    }

    #[test]
    fn a_bit_mask_compares_the_two_parameters_with_zero() {
        // The all-bit test keeps the operands in their order and compares with the mask.
        for (body, replacement) in [
            ("active & bits != 0", "active & bits == active"),
            ("0 != bits & active", "bits & active == active"),
            ("(bits & (active)) != (0)", "bits & active == active"),
        ] {
            let source = format!("fn enabled(bits: u64, active: u64) -> bool {{ {body} }}");
            let found = candidates(&source);
            assert_eq!(found.len(), 1, "{source}");
            assert_eq!(&source[found[0].edits[0].span.clone()], body);
            assert_eq!(found[0].edits[0].replacement, replacement);
            assert_eq!(
                found[0].description,
                format!("replace any-bit test `{body}` with all-bit test `{replacement}`")
            );
        }
        for body in [
            "bits & active != 1",
            "1 != bits & active",
            "bits & active == 0",
            "bits | active != 0",
            "bits & bits != 0",
            "active & active != 0",
            "bits & OTHER != 0",
            "OTHER & active != 0",
        ] {
            let source = format!("fn enabled(bits: u64, active: u64) -> bool {{ {body} }}");
            assert!(candidates(&source).is_empty(), "{source}");
        }
    }

    #[test]
    fn a_string_length_is_a_plain_count_of_the_one_shared_str() {
        let found = candidates("fn bytes(label: &str) -> usize { label.len() }");
        assert_eq!(found.len(), 1);
        assert_eq!(
            found[0].description,
            "replace `label.len()` with `label.chars().count()`"
        );
        assert!(!found[0].existing);
        // The input is the tool's own, so the report says when it applies.
        assert_eq!(
            found[0].scenarios[0].guidance.as_deref(),
            Some("Use this input if the API accepts text outside ASCII.")
        );
        for function in [
            "fn bytes(label: &str) -> u64 { label.len() }",
            "fn bytes(label: &str) { label.len() }",
            "fn bytes(label: &str, extra: u8) -> usize { label.len() }",
            "fn bytes(label: &str, extra: u8) -> u64 { label.len() }",
            "fn bytes(label: &mut str) -> usize { label.len() }",
            "fn bytes(label: &String) -> usize { label.len() }",
            "fn bytes(label: &str) -> usize { OTHER.len() }",
            "fn bytes(label: &str) -> usize { label.count() }",
            "fn bytes(label: &str) -> usize { label.len(1) }",
            "fn bytes(label: &str) -> usize { label.len::<u8>() }",
            "fn chars(label: &str) -> usize { label.chars().last() }",
            "fn chars(label: &str) -> usize { label.bytes().count() }",
            "fn chars(label: &str) -> usize { OTHER.chars().count() }",
            "fn chars(label: &str) -> usize { label.chars(1).count() }",
            "fn chars(label: &str) -> usize { label.chars::<u8>().count() }",
            "fn chars(label: &str) -> usize { label.chars().count(1) }",
            "fn chars(label: &str) -> usize { label.chars().count::<u8>() }",
        ] {
            assert!(candidates(function).is_empty(), "{function}");
        }
    }

    const TOTAL: &str = "fn total_of(items: &[u32], bound: usize) -> u32 { let mut total = 0; for i in 0..bound { total += items[i]; } total }";

    /// The range rule only speaks when an existing test gives it an input to change.
    fn with_range_test(function: &str, assertion: &str) -> String {
        format!("{function}\n#[test]\nfn sums() {{ {assertion} }}\n")
    }

    fn range_inputs(source: &str) -> Vec<(String, String)> {
        candidates(source)
            .iter()
            .flat_map(|candidate| &candidate.scenarios)
            .map(|scenario| {
                (
                    scenario.source_test.clone().unwrap(),
                    scenario.expression.clone(),
                )
            })
            .collect()
    }

    fn pairs(inputs: &[(String, String)]) -> Vec<(&str, &str)> {
        inputs
            .iter()
            .map(|(test, expression)| (test.as_str(), expression.as_str()))
            .collect()
    }

    #[test]
    fn a_range_mutation_needs_a_counted_sum_over_a_shared_integer_slice() {
        let assertion = "assert_eq!(total_of(&[4, 5, 0], 2), 9);";
        let found = candidates(&with_range_test(TOTAL, assertion));
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].scenarios.len(), 1);
        let scenario = &found[0].scenarios[0];
        assert_eq!(scenario.expression, "total_of(&[4, 5, 1], 2)");
        assert_eq!(scenario.fixture_expectation.as_deref(), Some("9"));
        assert_eq!(scenario.source_test.as_deref(), Some("sums"));

        for (from, to) in [
            ("bound: usize)", "bound: usize, extra: u8)"),
            ("bound: usize", "bound: u32"),
            ("&[u32]", "&mut [u32]"),
            (
                "items: &[u32], bound: usize) -> u32",
                "items: &[f32], bound: usize) -> f32",
            ),
            ("-> u32", "-> u64"),
            ("-> u32", ""),
            ("0..bound", "1..bound"),
            ("0..bound", "0..=bound"),
            ("0..bound", "0..OTHER"),
            ("total += items[i]", "total -= items[i]"),
            ("total += items[i]", "totals[0] += items[i]"),
            ("total += items[i]", "total += OTHER[i]"),
            ("total += items[i]", "total += items[j]"),
        ] {
            assert!(TOTAL.contains(from), "{from}");
            let source = with_range_test(&TOTAL.replacen(from, to, 1), assertion);
            assert!(candidates(&source).is_empty(), "{source}");
        }
    }

    #[test]
    fn a_range_input_comes_from_a_direct_call_with_a_literal_shared_array() {
        for (assertion, expression) in [
            (
                "assert_eq!(crate::total_of(&[4, 5, 0], 2), 9);",
                "total_of(&[4, 5, 1], 2)",
            ),
            (
                "assert_eq!(total_of(&[-4, 5, 0], 2), 1);",
                "total_of(&[-4, 5, 1], 2)",
            ),
            // Only the last zero digit changes: radix, separators and suffix stay.
            (
                "assert_eq!(total_of(&[4, 5, 0x0], 2), 9);",
                "total_of(&[4, 5, 0x1], 2)",
            ),
            (
                "assert_eq!(total_of(&[4, 5, 0x0_0u32], 2), 9);",
                "total_of(&[4, 5, 0x0_1u32], 2)",
            ),
        ] {
            let source = with_range_test(TOTAL, assertion);
            assert_eq!(
                pairs(&range_inputs(&source)),
                [("sums", expression)],
                "{source}"
            );
        }
        for assertion in [
            "assert_eq!(<Sums as crate>::total_of(&[4, 5, 0], 2), 9);",
            "assert_eq!(other::total_of(&[4, 5, 0], 2), 9);",
            "assert_eq!(crate::other::total_of(&[4, 5, 0], 2), 9);",
            // `super` of a test at the root of the file is not this file.
            "assert_eq!(super::total_of(&[4, 5, 0], 2), 9);",
            "assert_eq!(total_of(&mut [4, 5, 0], 2), 9);",
            "assert_eq!(total_of(&[4, FIVE, 0], 2), 9);",
            "assert_eq!(total_of(&[4, !5, 0], 2), 9);",
            // The element just past the bound has to be a zero the test does not use yet.
            "assert_eq!(total_of(&[4, 5, 10], 2), 9);",
            "assert_eq!(total_of(&[4, 5, 6], 2), 9);",
        ] {
            let source = with_range_test(TOTAL, assertion);
            assert!(candidates(&source).is_empty(), "{source}");
        }
    }

    #[test]
    fn range_inputs_are_named_after_the_test_that_holds_them() {
        let source = format!(
            r#"{TOTAL}
mod first {{
    #[test]
    fn one() {{ assert_eq!(super::total_of(&[1, 0], 1), 1); }}
    #[test]
    fn two() {{ assert_eq!(total_of(&[2, 0], 1), 2); }}
    #[test]
    fn elsewhere() {{ assert_eq!(other::total_of(&[7, 0], 1), 7); }}
    mod deeper {{
        #[test]
        fn far() {{ assert_eq!(super::total_of(&[9, 0], 1), 9); }}
    }}
}}
mod second {{
    #[test]
    fn three() {{ assert_eq!(total_of(&[3, 0], 1), 3); }}
}}
#[test]
fn four() {{ assert_eq!(total_of(&[4, 0], 1), 4); }}
"#
        );
        assert_eq!(
            pairs(&range_inputs(&source)),
            [
                ("first::one", "total_of(&[1, 1], 1)"),
                ("first::two", "total_of(&[2, 1], 1)"),
                ("second::three", "total_of(&[3, 1], 1)"),
                ("four", "total_of(&[4, 1], 1)"),
            ]
        );
    }

    #[test]
    fn one_test_gives_at_most_four_different_range_inputs() {
        let source = format!(
            r#"{TOTAL}
#[test]
fn many() {{
    assert_eq!(total_of(&[1, 0], 1), 1);
    assert_eq!(total_of(&[1, 0], 1), 1);
    assert_eq!(total_of(&[2, 0], 1), 2);
    assert_eq!(total_of(&[3, 0], 1), 3);
    assert_eq!(total_of(&[4, 0], 1), 4);
    assert_eq!(total_of(&[5, 0], 1), 5);
}}
#[test]
fn again() {{
    assert_eq!(total_of(&[1, 0], 1), 1);
}}
"#
        );
        assert_eq!(
            pairs(&range_inputs(&source)),
            [
                ("many", "total_of(&[1, 1], 1)"),
                ("many", "total_of(&[2, 1], 1)"),
                ("many", "total_of(&[3, 1], 1)"),
                ("many", "total_of(&[4, 1], 1)"),
                ("again", "total_of(&[1, 1], 1)"),
            ]
        );
    }

    #[test]
    fn fixture_expectations_use_the_same_integer_spelling_as_runtime_values() {
        for (input, expected) in [
            ("-0x9_i32", Some("-9")),
            ("-0", Some("0")),
            ("EXPECTED", None),
            ("!0", None),
        ] {
            let value = syn::parse_str(input).unwrap();
            assert_eq!(decimal_value(&value).as_deref(), expected, "{input}");
        }
    }
}