ripr 0.10.0

Find static mutation-exposure gaps before expensive mutation testing
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
use super::super::diff::{ChangedFile, ChangedLine};
use super::super::rust_index::{
    RustIndex, SyntaxNodeFact, changed_nodes_for_lines, extract_identifier_tokens,
    find_owner_function,
};
use super::classify::{classify_changed_syntax, should_ignore_changed_line};
use super::expectations::{expected_sinks, required_oracles};
use super::family::delta_for_family;
use super::ids::{diff_probe_id, normalize_expression};
use super::lexical::classify_changed_line;
use crate::domain::{Probe, ProbeFamily, SourceLocation};
use std::path::Path;

pub fn probes_for_file(root: &Path, changed: &ChangedFile, index: &RustIndex) -> Vec<Probe> {
    let mut probes = Vec::new();
    // Use `new_side_line` for all lines: for added lines this equals `line`; for
    // removed lines `new_side_line` is the new-file coordinate, which is what
    // the RustIndex (built from the new file) expects (RANK-1 fix, #1222).
    let changed_lines = changed
        .added_lines
        .iter()
        .chain(changed.removed_lines.iter())
        .map(|line| line.new_side_line)
        .collect::<Vec<_>>();
    let changed_nodes = changed_nodes_for_lines(index, &changed.path, &changed_lines);
    let build_context = ProbeBuildContext {
        root,
        changed,
        index,
        changed_nodes: &changed_nodes,
    };

    for added in &changed.added_lines {
        let text = added.text.trim();
        if should_ignore_changed_line(text) {
            continue;
        }
        if changed_line_owned_by_test(index, &changed.path, added.new_side_line) {
            continue;
        }
        let families = classify_changed_syntax(index, &changed.path, added.new_side_line, text)
            .unwrap_or_else(|| classify_changed_line(text));
        for family in families {
            probes.push(build_probe(
                &build_context,
                added,
                family,
                nearby_removed_line(text, changed),
                Some(text.to_string()),
            ));
        }
    }

    for removed in &changed.removed_lines {
        let text = removed.text.trim();
        if should_ignore_changed_line(text) {
            continue;
        }
        // Use new_side_line so the owner lookup queries the new-file index at the
        // correct position (RANK-1 fix: `removed.line` is an old-side coordinate
        // and diverges from the new file when an earlier hunk shifted lines).
        if changed_line_owned_by_test(index, &changed.path, removed.new_side_line) {
            continue;
        }
        for family in classify_changed_line(text) {
            if has_matching_added_line(removed, &family, changed) {
                continue;
            }
            probes.push(build_probe(
                &build_context,
                removed,
                family,
                Some(text.to_string()),
                None,
            ));
        }
    }

    // Post-hoc collision de-dup: if two probes got the same id, append .2, .3, …
    // to the 2nd+ occurrences (the first keeps its id as-is, i.e. ordinal 1).
    dedup_probe_ids(&mut probes);

    probes
}

/// Scan `probes` in order; for any id that appears more than once, rewrite the
/// 2nd+ occurrences to append `.2`, `.3`, … (ordinal-based collision suffix).
fn dedup_probe_ids(probes: &mut [Probe]) {
    use std::collections::HashMap;
    let mut seen: HashMap<String, u32> = HashMap::new();
    for probe in probes.iter_mut() {
        let count = seen.entry(probe.id.0.clone()).or_insert(0);
        *count += 1;
        if *count > 1 {
            probe.id.0 = format!("{}.{}", probe.id.0, count);
        }
    }
}

/// Tests are the instrument, not the surface under test: a probe on a line
/// inside a `#[test]` function (e.g. the error path of a `?` in the test body)
/// is unactionable, because the test failing *is* the discrimination (#1055).
fn changed_line_owned_by_test(index: &RustIndex, path: &Path, line: usize) -> bool {
    find_owner_function(index, path, line).is_some_and(|function| function.is_test)
}

struct ProbeBuildContext<'a> {
    root: &'a Path,
    changed: &'a ChangedFile,
    index: &'a RustIndex,
    changed_nodes: &'a [SyntaxNodeFact],
}

fn build_probe(
    context: &ProbeBuildContext<'_>,
    changed_line: &ChangedLine,
    family: ProbeFamily,
    before: Option<String>,
    after: Option<String>,
) -> Probe {
    let text = changed_line.text.trim();
    let delta = delta_for_family(&family);
    // Use `new_side_line` for all index lookups and the SourceLocation: for
    // added lines this equals `line`; for removed lines it is the new-file
    // coordinate, which is what the RustIndex (built from the new file) and any
    // IDE navigation into the new file require (RANK-1 fix, #1222).
    let new_line = changed_line.new_side_line;
    let owner = context
        .changed_nodes
        .iter()
        .find(|node| node.start_line <= new_line && new_line <= node.end_line)
        .and_then(|node| node.owner.clone())
        .or_else(|| {
            find_owner_function(context.index, &context.changed.path, new_line)
                .map(|function| function.id.clone())
        });
    let norm_expr = normalize_expression(text);
    // Ordinal 1 here; post-hoc dedup in probes_for_file handles collisions.
    let id = diff_probe_id(
        &context.changed.path,
        &family,
        owner.as_ref(),
        &norm_expr,
        1,
    );
    let expected_sinks = expected_sinks(text, &family);
    let required_oracles = required_oracles(text, &family);

    Probe {
        id,
        location: SourceLocation::new(context.root.join(&context.changed.path), new_line, 1),
        owner,
        family,
        delta,
        before,
        after,
        expression: text.to_string(),
        expected_sinks,
        required_oracles,
    }
}

fn has_matching_added_line(
    removed_line: &ChangedLine,
    removed_family: &ProbeFamily,
    changed: &ChangedFile,
) -> bool {
    let removed_tokens = extract_identifier_tokens(&removed_line.text);
    !removed_tokens.is_empty()
        && changed.added_lines.iter().any(|line| {
            // Compare new-side positions: `removed_line.new_side_line` is the
            // new-file coordinate of the removed line; `line.new_side_line`
            // (== `line.line` for added lines) is the added line's new-file
            // coordinate.  Using old-side `removed_line.line` would give wrong
            // proximity when earlier hunks shifted the coordinate systems.
            if removed_line.new_side_line.abs_diff(line.new_side_line) > 1 {
                return false;
            }
            let added_families = classify_changed_line(line.text.trim());
            if !added_families.iter().any(|family| family == removed_family) {
                return false;
            }
            let added_tokens = extract_identifier_tokens(&line.text);
            added_tokens
                .iter()
                .any(|token| removed_tokens.iter().any(|other| other == token))
        })
}

fn nearby_removed_line(added: &str, changed: &ChangedFile) -> Option<String> {
    let added_tokens = extract_identifier_tokens(added);
    changed
        .removed_lines
        .iter()
        .find(|line| {
            let removed_tokens = extract_identifier_tokens(&line.text);
            !added_tokens.is_empty()
                && added_tokens
                    .iter()
                    .any(|token| removed_tokens.iter().any(|other| other == token))
        })
        .map(|line| line.text.trim().to_string())
        .or_else(|| {
            changed
                .removed_lines
                .first()
                .map(|line| line.text.trim().to_string())
        })
}

#[cfg(test)]
mod tests {
    use super::super::super::diff::ChangedLine;
    use super::super::super::rust_index::{
        FileFacts, FunctionFact, PROBE_SHAPE_PREDICATE, ProbeShapeFact, RustIndex,
    };
    use super::*;
    use crate::domain::SymbolId;
    use std::collections::BTreeMap;
    use std::path::{Path, PathBuf};

    #[test]
    fn probes_for_file_uses_syntax_shape_owner_and_removed_context() {
        let path = PathBuf::from("src/lib.rs");
        let changed = ChangedFile {
            path: path.clone(),
            added_lines: vec![ChangedLine {
                line: 3,
                new_side_line: 3,
                text: "if amount >= threshold {".to_string(),
            }],
            removed_lines: vec![ChangedLine {
                line: 3,
                new_side_line: 3,
                text: "if amount > threshold {".to_string(),
            }],
        };
        let index = RustIndex {
            files: BTreeMap::from([(
                path.clone(),
                FileFacts {
                    path: path.clone(),
                    functions: vec![FunctionFact {
                        id: SymbolId("pricing::discounted_total".to_string()),
                        name: "discounted_total".to_string(),
                        file: path.clone(),
                        start_line: 1,
                        end_line: 5,
                        body: "fn discounted_total() { if amount >= threshold {} }".to_string(),
                        calls: vec![],
                        returns: vec![],
                        literals: vec![],
                        is_test: false,
                        attrs: vec![],
                    }],
                    probe_shapes: vec![ProbeShapeFact {
                        start_line: 3,
                        end_line: 3,
                        start_byte: 20,
                        kind: PROBE_SHAPE_PREDICATE.to_string(),
                        text: "if amount >= threshold {".to_string(),
                    }],
                    ..FileFacts::default()
                },
            )]),
            ..RustIndex::default()
        };

        let probes = probes_for_file(Path::new("workspace"), &changed, &index);

        assert_eq!(probes.len(), 1);
        let probe = &probes[0];
        assert_eq!(probe.id.0, "probe:src_lib.rs:predicate:b6638ef3");
        assert_eq!(probe.family, ProbeFamily::Predicate);
        assert_eq!(
            probe.owner,
            Some(SymbolId("pricing::discounted_total".to_string()))
        );
        assert_eq!(probe.before, Some("if amount > threshold {".to_string()));
        assert_eq!(probe.after, Some("if amount >= threshold {".to_string()));
        assert!(
            probe
                .expected_sinks
                .iter()
                .any(|sink| sink == "branch result")
        );
    }

    #[test]
    fn probes_for_file_skips_lines_owned_by_test_functions() {
        let path = PathBuf::from("src/config.rs");
        let changed = ChangedFile {
            path: path.clone(),
            added_lines: vec![ChangedLine {
                line: 3,
                new_side_line: 3,
                text: "let config = toml::from_str(text)?;".to_string(),
            }],
            removed_lines: vec![],
        };
        let index_with = |is_test: bool| RustIndex {
            files: BTreeMap::from([(
                path.clone(),
                FileFacts {
                    path: path.clone(),
                    functions: vec![FunctionFact {
                        id: SymbolId("config::tests::parses".to_string()),
                        name: "parses".to_string(),
                        file: path.clone(),
                        start_line: 1,
                        end_line: 5,
                        body: "fn parses() { let config = toml::from_str(text)?; }".to_string(),
                        calls: vec![],
                        returns: vec![],
                        literals: vec![],
                        is_test,
                        attrs: vec![],
                    }],
                    ..FileFacts::default()
                },
            )]),
            ..RustIndex::default()
        };

        // Control: a production owner still probes the error path.
        let production = probes_for_file(Path::new("workspace"), &changed, &index_with(false));
        assert!(
            !production.is_empty(),
            "a non-test error path should still generate a probe"
        );

        // #1055: the same line owned by a `#[test]` function generates nothing —
        // the test is the instrument, not the surface under test.
        let in_test = probes_for_file(Path::new("workspace"), &changed, &index_with(true));
        assert!(
            in_test.is_empty(),
            "a line owned by a test function must not generate probes, got {in_test:?}"
        );
    }

    #[test]
    fn probes_for_file_falls_back_to_static_unknown_without_syntax_shape() {
        let changed = ChangedFile {
            path: PathBuf::from("src/lib.rs"),
            added_lines: vec![ChangedLine {
                line: 10,
                new_side_line: 10,
                text: "let total = discounted;".to_string(),
            }],
            removed_lines: vec![],
        };

        let probes = probes_for_file(Path::new("workspace"), &changed, &RustIndex::default());

        assert_eq!(probes.len(), 1);
        assert_eq!(probes[0].id.0, "probe:src_lib.rs:static_unknown:1e078e9a");
        assert_eq!(probes[0].family, ProbeFamily::StaticUnknown);
        assert_eq!(probes[0].before, None);
    }

    #[test]
    fn probes_for_file_keeps_removed_only_behavior_changes() {
        let path = PathBuf::from("src/lib.rs");
        let changed = ChangedFile {
            path: path.clone(),
            added_lines: vec![],
            removed_lines: vec![ChangedLine {
                line: 4,
                new_side_line: 4,
                text: "events.publish(invoice);".to_string(),
            }],
        };
        let index = RustIndex {
            files: BTreeMap::from([(
                path.clone(),
                FileFacts {
                    path: path.clone(),
                    functions: vec![FunctionFact {
                        id: SymbolId("billing::record_invoice".to_string()),
                        name: "record_invoice".to_string(),
                        file: path.clone(),
                        start_line: 1,
                        end_line: 6,
                        body: "fn record_invoice() { }".to_string(),
                        calls: vec![],
                        returns: vec![],
                        literals: vec![],
                        is_test: false,
                        attrs: vec![],
                    }],
                    ..FileFacts::default()
                },
            )]),
            ..RustIndex::default()
        };

        let probes = probes_for_file(Path::new("workspace"), &changed, &index);

        assert_eq!(probes.len(), 2);
        let side_effect_position = probes
            .iter()
            .position(|probe| probe.family == ProbeFamily::SideEffect);
        assert_ne!(
            side_effect_position, None,
            "removed side effect should stay visible as a probe"
        );
        let Some(side_effect_position) = side_effect_position else {
            return;
        };
        let side_effect = &probes[side_effect_position];
        assert_eq!(side_effect.id.0, "probe:src_lib.rs:side_effect:682b613e");
        assert_eq!(
            side_effect.before,
            Some("events.publish(invoice);".to_string())
        );
        assert_eq!(side_effect.after, None);
        assert_eq!(side_effect.expression, "events.publish(invoice);");
        assert_eq!(
            side_effect.owner,
            Some(SymbolId("billing::record_invoice".to_string()))
        );
    }

    #[test]
    fn probes_for_file_does_not_duplicate_replacements_as_removed_only_changes() {
        let changed = ChangedFile {
            path: PathBuf::from("src/lib.rs"),
            added_lines: vec![ChangedLine {
                line: 3,
                new_side_line: 3,
                text: "if amount >= threshold {".to_string(),
            }],
            removed_lines: vec![ChangedLine {
                line: 3,
                new_side_line: 3,
                text: "if amount > threshold {".to_string(),
            }],
        };

        let probes = probes_for_file(Path::new("workspace"), &changed, &RustIndex::default());

        assert_eq!(probes.len(), 1);
        assert_eq!(
            probes[0].before,
            Some("if amount > threshold {".to_string())
        );
        assert_eq!(
            probes[0].after,
            Some("if amount >= threshold {".to_string())
        );
    }

    #[test]
    fn probes_for_file_ignores_non_behavior_lines() {
        let changed = ChangedFile {
            path: PathBuf::from("src/lib.rs"),
            added_lines: vec![
                ChangedLine {
                    line: 1,
                    new_side_line: 1,
                    text: "use crate::pricing;".to_string(),
                },
                ChangedLine {
                    line: 2,
                    new_side_line: 2,
                    text: "// comment".to_string(),
                },
            ],
            removed_lines: vec![],
        };

        let probes = probes_for_file(Path::new("workspace"), &changed, &RustIndex::default());
        assert!(probes.is_empty());
    }
}