fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
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
//! Duplication result types exposed through the engine boundary.

use std::path::{Path, PathBuf};

use fallow_config::DuplicatesConfig;
use fallow_types::discover::DiscoveredFile;
use rustc_hash::{FxHashMap, FxHashSet};

pub use crate::results::DuplicationAnalysis;
use crate::workspace_scope::WorkspaceScope;

#[path = "duplication_detector/mod.rs"]
mod detector;

#[cfg(test)]
pub(crate) use detector::token_types;
pub(crate) use detector::types;

pub use detector::DUPES_DEFAULT_IGNORES;

/// Detector internals re-exported for the engine's own benches and
/// integration tests; not part of the supported engine API surface.
#[doc(hidden)]
pub use detector::{detect, normalize, tokenize};

/// Engine alias for [`fallow_types::duplicates::CloneGroup`].
pub type CloneGroup = fallow_types::duplicates::CloneGroup;
/// Engine alias for [`fallow_types::duplicates::CloneGroupKind`].
pub type CloneGroupKind = fallow_types::duplicates::CloneGroupKind;
/// Engine alias for [`fallow_types::duplicates::CloneInstance`].
pub type CloneInstance = fallow_types::duplicates::CloneInstance;
/// Engine alias for [`fallow_types::duplicates::DefaultIgnoreSkips`].
pub type DefaultIgnoreSkips = fallow_types::duplicates::DefaultIgnoreSkips;
/// Engine alias for [`fallow_types::duplicates::DuplicationReport`].
pub type DuplicationReport = fallow_types::duplicates::DuplicationReport;
/// Engine alias for [`fallow_types::duplicates::DuplicationStats`].
pub type DuplicationStats = fallow_types::duplicates::DuplicationStats;
/// A clone group that a `duplicates.ignoredClones` entry hid from the report.
///
/// The audit reads these groups, so an accepted clone stays accepted when a
/// change edits it or pastes it again.
#[derive(Debug, Clone)]
pub struct IgnoredCloneGroup {
    /// The `ignoredClones` entry that matched the group.
    pub key: String,
    /// The hidden group.
    pub group: CloneGroup,
}

/// Engine alias for [`fallow_types::duplicates::RefactoringSuggestion`].
pub type RefactoringSuggestion = fallow_types::duplicates::RefactoringSuggestion;

pub use detector::{
    CloneFingerprintKey, CloneFingerprintSet, FINGERPRINT_PREFIX, clone_fingerprint,
    dominant_identifier,
};
pub(crate) use detector::{group_refactoring_suggestion, is_unparsed_collision_key};

/// Refresh clone-family and mirrored-directory fields after clone groups change.
pub fn refresh_clone_families(report: &mut DuplicationReport, root: &Path) {
    report.clone_families = detector::families::group_into_families(&report.clone_groups, root);
    report.mirrored_directories =
        detector::families::detect_mirrored_directories(&report.clone_families, root);
}

/// Rebuild the fields that a scope filter invalidates: clone families,
/// mirrored directories, statistics and the report order.
///
/// A scope filter (`--changed-since`, `--workspace`, a diff) narrows the corpus,
/// so `stats` describes the narrowed corpus after this call. A presentation cap
/// such as `--top` must not call this.
pub(crate) fn refresh_scoped_report(report: &mut DuplicationReport, root: &Path) {
    refresh_clone_families(report, root);
    report.stats = recompute_stats(report);
    report.sort();
}

/// Size of the corpus that a duplication run measured.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CorpusTotals {
    /// Number of files in the corpus.
    pub files: usize,
    /// Number of source lines in the corpus.
    pub lines: usize,
    /// Number of tokens in the corpus.
    pub tokens: usize,
}

impl CorpusTotals {
    /// The totals that `stats` records.
    #[must_use]
    pub const fn of(stats: &DuplicationStats) -> Self {
        Self {
            files: stats.total_files,
            lines: stats.total_lines,
            tokens: stats.total_tokens,
        }
    }
}

/// Counters that a statistics computation copies and does not derive from
/// the clone groups.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CarriedCounters {
    /// Number of clone families of the report.
    pub clone_families: usize,
    /// Number of clone groups that the `minOccurrences` filter hid.
    pub clone_groups_below_min_occurrences: usize,
    /// Number of clone groups that `ignoredClones` hid.
    pub clone_groups_ignored: usize,
    /// Number of near-clone candidates that the work bound skipped.
    pub near_candidates_skipped: usize,
}

/// Accumulates the clone groups of one scope into duplication statistics.
///
/// Covered lines are the union of the line ranges of each file, so
/// overlapping clone instances do not count a line two times.
#[derive(Debug, Default)]
pub struct CloneCoverage<'a> {
    ranges_by_file: FxHashMap<&'a Path, Vec<(usize, usize)>>,
    duplicated_tokens: usize,
    clone_groups: usize,
    clone_instances: usize,
}

impl<'a> CloneCoverage<'a> {
    /// Add one clone group.
    ///
    /// `instances` are the instances that this scope counts. Each instance
    /// after the first adds `token_count` redundant tokens.
    pub fn add_group(
        &mut self,
        instances: impl IntoIterator<Item = &'a CloneInstance>,
        token_count: usize,
    ) {
        self.clone_groups += 1;
        let mut count = 0usize;
        for instance in instances {
            count += 1;
            let ranges = self
                .ranges_by_file
                .entry(instance.file.as_path())
                .or_default();
            if instance.start_line <= instance.end_line {
                ranges.push((instance.start_line, instance.end_line));
            }
        }
        self.clone_instances += count;
        self.duplicated_tokens = self
            .duplicated_tokens
            .saturating_add(token_count.saturating_mul(count.saturating_sub(1)));
    }

    /// Build the statistics against `totals`.
    ///
    /// `duplication_percentage` divides by `totals.lines`, and
    /// `duplicated_tokens` does not exceed `totals.tokens`.
    #[must_use]
    pub fn into_stats(
        mut self,
        totals: CorpusTotals,
        carried: CarriedCounters,
    ) -> DuplicationStats {
        let duplicated_lines: usize = self
            .ranges_by_file
            .values_mut()
            .map(|ranges| count_covered_lines(ranges))
            .sum();
        DuplicationStats {
            total_files: totals.files,
            files_with_clones: self.ranges_by_file.len(),
            total_lines: totals.lines,
            duplicated_lines,
            total_tokens: totals.tokens,
            duplicated_tokens: self.duplicated_tokens.min(totals.tokens),
            clone_groups: self.clone_groups,
            clone_families: carried.clone_families,
            clone_instances: self.clone_instances,
            duplication_percentage: if totals.lines > 0 {
                (duplicated_lines as f64 / totals.lines as f64) * 100.0
            } else {
                0.0
            },
            clone_groups_below_min_occurrences: carried.clone_groups_below_min_occurrences,
            clone_groups_ignored: carried.clone_groups_ignored,
            near_candidates_skipped: carried.near_candidates_skipped,
        }
    }
}

/// Statistics of `groups`, with every instance of each group, against
/// `totals`.
#[must_use]
fn duplication_stats(
    groups: &[CloneGroup],
    totals: CorpusTotals,
    carried: CarriedCounters,
) -> DuplicationStats {
    let mut coverage = CloneCoverage::default();
    for group in groups {
        coverage.add_group(&group.instances, group.token_count);
    }
    coverage.into_stats(totals, carried)
}

/// Number of lines that the inclusive ranges cover. Sorts `ranges`.
fn count_covered_lines(ranges: &mut [(usize, usize)]) -> usize {
    ranges.sort_unstable();
    let Some(&(mut current_start, mut current_end)) = ranges.first() else {
        return 0;
    };

    let mut covered = 0usize;
    for &(start, end) in &ranges[1..] {
        if start <= current_end.saturating_add(1) {
            current_end = current_end.max(end);
            continue;
        }

        covered += current_end - current_start + 1;
        (current_start, current_end) = (start, end);
    }

    covered + current_end - current_start + 1
}

/// The scope of one duplication run, as the surface resolved it.
///
/// Every field is optional. A field that is `None` does not narrow the run.
#[derive(Debug, Clone, Copy)]
pub struct DuplicationScope<'a> {
    /// The resolved change scope: a global changed-file set or the
    /// configured package baselines.
    pub changes: Option<&'a crate::change_scope::ChangeScope>,
    /// A unified diff. Finding paths resolve against the report root.
    pub diff: Option<&'a fallow_output::DiffIndex>,
    /// `--workspace`, `--changed-workspaces` and a positional path.
    pub workspace_roots: Option<&'a WorkspaceScope>,
}

/// Narrow a duplication report to the scope of the run.
///
/// The CLI, the programmatic API and the MCP typed path call this one function,
/// so a scope narrows the same way on every surface. Each filter keeps a clone
/// group when at least one instance is in scope, and keeps every instance of
/// that group: a reviewer sees the full clone family. The filters run in this
/// order: changed files, the diff, the workspace roots.
pub fn apply_scope(report: &mut DuplicationReport, scope: &DuplicationScope<'_>, root: &Path) {
    if let Some(changes) = scope.changes {
        changes.retain_duplication(report, root);
    }
    if let Some(diff) = scope.diff {
        crate::diff_scope::filter_duplication_by_diff(report, diff, root);
    }
    if let Some(roots) = scope.workspace_roots {
        filter_to_workspaces(report, roots, root);
    }
}

/// Keep only the clone groups with at least one instance in the workspace
/// scope.
///
/// The full cross-workspace index is still built, so a group can hold an
/// instance in the selected workspace and one in another workspace. The group
/// stays whole: the documented rule is that a group is in scope when one of
/// its instances is. Clone families, statistics and the order are rebuilt from
/// the groups that stay.
pub fn filter_to_workspaces(report: &mut DuplicationReport, scope: &WorkspaceScope, root: &Path) {
    report.clone_groups.retain(|group| {
        group
            .instances
            .iter()
            .any(|instance| scope.contains(&instance.file))
    });
    report
        .range_marker_problems
        .retain(|finding| scope.contains(&finding.path));
    refresh_scoped_report(report, root);
}

/// Keep only the `n` highest-ranked clone groups (`--top`).
///
/// `stats` keeps describing the corpus the run measured. Truncation is a
/// presentation choice, so rewriting `clone_groups` or `clone_instances` from
/// the truncated array would put two scopes in one object next to the
/// untouched `files_with_clones` and `duplication_percentage`. Consumers read
/// the shown and omitted split from `DuplicationReport::clone_groups_shown`
/// and `clone_groups_omitted`.
pub fn apply_top(report: &mut DuplicationReport, n: usize, root: &Path) {
    report.sort();
    report.clone_groups.truncate(n);
    refresh_clone_families(report, root);
    report.sort();
}

/// Recompute duplication statistics after clone groups have been filtered.
///
/// Uses [`CloneCoverage`], as the detector does, so overlapping clone
/// instances do not inflate the duplicated line count.
///
/// `clone_families` is read from `report.clone_families`, so a scope filter
/// must call [`refresh_clone_families`] before this. A presentation cap such
/// as `--top` must not call this at all: it truncates the arrays while `stats`
/// keeps describing the corpus the run measured.
#[must_use]
pub(crate) fn recompute_stats(report: &DuplicationReport) -> DuplicationStats {
    duplication_stats(
        &report.clone_groups,
        CorpusTotals::of(&report.stats),
        CarriedCounters {
            clone_families: report.clone_families.len(),
            clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
            clone_groups_ignored: report.stats.clone_groups_ignored,
            near_candidates_skipped: report.stats.near_candidates_skipped,
        },
    )
}

/// Compare JS/TS sources for audit-safe reuse of the current analysis at base.
///
/// Token kinds retain identifiers, ordinary literal values and the cooked
/// static text of templates. Regex token kinds omit content, and template
/// token kinds omit the raw spelling of their text, so the raw source spans
/// of both must also match.
/// Whole-template comparison conservatively rejects formatting changes inside
/// interpolation expressions. The boolean is forwarded as tokenizer `skip_imports`.
#[must_use]
pub fn source_token_kinds_equivalent(
    path: &Path,
    current: &str,
    base: &str,
    cross_language: bool,
) -> bool {
    let current_tokens = detector::tokenize::tokenize_file(path, current, cross_language);
    let base_tokens = detector::tokenize::tokenize_file(path, base, cross_language);
    if current_tokens.tokens.len() != base_tokens.tokens.len() {
        return false;
    }
    current_tokens
        .tokens
        .iter()
        .zip(&base_tokens.tokens)
        .all(|(current_token, base_token)| {
            if current_token.kind != base_token.kind {
                return false;
            }
            if matches!(
                current_token.kind,
                detector::token_types::TokenKind::TemplateLiteral(_)
                    | detector::token_types::TokenKind::RegExpLiteral
            ) {
                return match (
                    current.get(current_token.span.start as usize..current_token.span.end as usize),
                    base.get(base_token.span.start as usize..base_token.span.end as usize),
                ) {
                    (Some(current_literal), Some(base_literal)) => current_literal == base_literal,
                    _ => false,
                };
            }
            true
        })
}

/// Run duplication detection on a discovered file set.
#[must_use]
pub fn find_duplicates(
    root: &Path,
    files: &[DiscoveredFile],
    config: &DuplicatesConfig,
) -> DuplicationReport {
    detector::find_duplicates(root, files, config)
}

/// Run duplication detection and include metadata about built-in ignored files.
#[must_use]
pub fn find_duplicates_with_defaults(
    root: &Path,
    files: &[DiscoveredFile],
    config: &DuplicatesConfig,
    cache_dir: Option<&Path>,
) -> DuplicationAnalysis {
    detector::detect_duplicates(root, files, config, None, cache_dir)
}

/// Run focused duplication detection and include metadata about built-in ignored files.
#[must_use]
pub fn find_duplicates_touching_files_with_defaults(
    root: &Path,
    files: &[DiscoveredFile],
    config: &DuplicatesConfig,
    changed_files: &[PathBuf],
    cache_dir: Option<&Path>,
) -> DuplicationAnalysis {
    let changed_files = changed_files.iter().cloned().collect::<FxHashSet<_>>();
    detector::detect_duplicates(root, files, config, Some(&changed_files), cache_dir)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    fn instance(file: &str, start_line: usize, end_line: usize) -> CloneInstance {
        CloneInstance {
            is_symlink: false,
            file: PathBuf::from(file),
            start_line,
            end_line,
            start_col: 0,
            end_col: 0,
            fragment: String::new(),
        }
    }

    fn report(clone_groups: Vec<CloneGroup>) -> DuplicationReport {
        DuplicationReport {
            clone_groups,
            clone_families: Vec::new(),
            mirrored_directories: Vec::new(),
            range_marker_problems: Vec::new(),
            stats: DuplicationStats {
                total_files: 3,
                total_lines: 100,
                total_tokens: 1_000,
                clone_groups_below_min_occurrences: 4,
                ..DuplicationStats::default()
            },
        }
    }

    #[test]
    fn recompute_stats_deduplicates_overlapping_lines_per_file() {
        let report = report(vec![
            CloneGroup {
                instances: vec![instance("src/a.ts", 1, 10), instance("src/b.ts", 20, 24)],
                token_count: 30,
                line_count: 10,
                similarity: None,
            },
            CloneGroup {
                instances: vec![instance("src/a.ts", 5, 12), instance("src/c.ts", 40, 44)],
                token_count: 20,
                line_count: 8,
                similarity: None,
            },
        ]);

        let stats = recompute_stats(&report);

        assert_eq!(stats.total_files, 3);
        assert_eq!(stats.files_with_clones, 3);
        assert_eq!(stats.total_lines, 100);
        assert_eq!(stats.duplicated_lines, 22);
        assert_eq!(stats.total_tokens, 1_000);
        assert_eq!(stats.duplicated_tokens, 50);
        assert_eq!(stats.clone_groups, 2);
        assert_eq!(stats.clone_instances, 4);
        assert!((stats.duplication_percentage - 22.0).abs() < f64::EPSILON);
        assert_eq!(stats.clone_groups_below_min_occurrences, 4);
    }

    #[test]
    fn recompute_stats_handles_zero_total_lines() {
        let mut report = report(vec![CloneGroup {
            instances: vec![instance("src/a.ts", 1, 1)],
            token_count: 5,
            line_count: 1,
            similarity: None,
        }]);
        report.stats.total_lines = 0;

        let stats = recompute_stats(&report);

        assert_eq!(stats.duplicated_lines, 1);
        assert!(stats.duplication_percentage.abs() < f64::EPSILON);
    }

    #[test]
    fn clone_fingerprint_set_delegates_without_leaking_core_type() {
        let groups = vec![CloneGroup {
            instances: vec![
                CloneInstance {
                    fragment: "const value = 1;".to_string(),
                    ..instance("src/a.ts", 1, 1)
                },
                CloneInstance {
                    fragment: "const value = 1;".to_string(),
                    ..instance("src/b.ts", 2, 2)
                },
            ],
            token_count: 5,
            line_count: 1,
            similarity: None,
        }];
        let fingerprints = CloneFingerprintSet::from_groups(&groups);
        let fingerprint = fingerprints.fingerprint_for_group(&groups[0]);

        assert!(fingerprint.starts_with(FINGERPRINT_PREFIX));
        assert!(fingerprints.find_group(&groups, &fingerprint).is_some());
    }

    fn group(instances: Vec<CloneInstance>, token_count: usize) -> CloneGroup {
        CloneGroup {
            instances,
            token_count,
            line_count: 0,
            similarity: None,
        }
    }

    const fn totals(files: usize, lines: usize, tokens: usize) -> CorpusTotals {
        CorpusTotals {
            files,
            lines,
            tokens,
        }
    }

    #[test]
    fn duplication_stats_matches_a_line_set_reference() {
        let groups = vec![
            group(
                vec![instance("src/a.ts", 1, 10), instance("src/a.ts", 5, 12)],
                10,
            ),
            group(
                vec![instance("src/a.ts", 20, 24), instance("src/a.ts", 25, 30)],
                10,
            ),
            group(
                vec![instance("src/a.ts", 40, 60), instance("src/a.ts", 45, 50)],
                10,
            ),
            group(
                vec![instance("src/a.ts", 9, 3), instance("src/d.ts", 9, 3)],
                10,
            ),
            group(
                vec![instance("src/a.ts", 70, 75), instance("src/a.ts", 70, 75)],
                10,
            ),
            group(
                vec![instance("src/b.ts", 1, 4), instance("src/c.ts", 3, 9)],
                10,
            ),
        ];

        let mut covered: FxHashSet<(&Path, usize)> = FxHashSet::default();
        let mut files: FxHashSet<&Path> = FxHashSet::default();
        for group in &groups {
            for instance in &group.instances {
                files.insert(&instance.file);
                for line in instance.start_line..=instance.end_line {
                    covered.insert((&instance.file, line));
                }
            }
        }

        let stats = duplication_stats(
            &groups,
            totals(4, 1_000, 10_000),
            CarriedCounters::default(),
        );

        assert_eq!(stats.duplicated_lines, covered.len());
        assert_eq!(stats.files_with_clones, files.len());
    }

    #[test]
    fn duplication_stats_clamps_tokens_and_guards_zero_lines() {
        let groups = vec![group(
            vec![
                instance("src/a.ts", 1, 5),
                instance("src/b.ts", 1, 5),
                instance("src/c.ts", 1, 5),
            ],
            1_000,
        )];

        let stats = duplication_stats(&groups, totals(3, 0, 500), CarriedCounters::default());

        assert!(stats.duplication_percentage.abs() < f64::EPSILON);
        assert_eq!(stats.duplicated_tokens, 500);
    }

    #[test]
    fn duplication_stats_copies_carried_counters() {
        let carried = CarriedCounters {
            clone_families: 1,
            clone_groups_below_min_occurrences: 2,
            clone_groups_ignored: 3,
            near_candidates_skipped: 4,
        };

        let stats = duplication_stats(&[], totals(1, 10, 100), carried);

        assert_eq!(stats.clone_families, 1);
        assert_eq!(stats.clone_groups_below_min_occurrences, 2);
        assert_eq!(stats.clone_groups_ignored, 3);
        assert_eq!(stats.near_candidates_skipped, 4);
    }

    #[test]
    fn clone_coverage_counts_only_the_instances_it_receives() {
        let clone_group = group(
            vec![instance("src/a.ts", 1, 10), instance("src/b.ts", 20, 40)],
            50,
        );
        let mut coverage = CloneCoverage::default();
        coverage.add_group(
            clone_group.instances.iter().take(1),
            clone_group.token_count,
        );

        let stats = coverage.into_stats(totals(2, 100, 1_000), CarriedCounters::default());

        assert_eq!(stats.clone_groups, 1);
        assert_eq!(stats.clone_instances, 1);
        assert_eq!(stats.duplicated_tokens, 0);
        assert_eq!(stats.duplicated_lines, 10);
    }
}