cargo-brief 0.9.2

Visibility-aware Rust API extractor — pseudo-Rust output for AI agent consumption
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
//! Pre-crafted tree-sitter code lookup by item kind and name.
//!
//! Bridges the gap between `search` (API shape, no source locations) and `ts`
//! (raw S-expressions). Provides `cargo brief code <target> [kind] <name>`.

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

use anyhow::{Result, bail};
use streaming_iterator::StreamingIterator;
use tree_sitter::{Parser, Query, QueryCursor};

use crate::cli::CodeArgs;
use crate::examples;

// ── Item kinds ───────────────────────────────────────────────────────

/// Supported item kinds for code lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemKind {
    Fn,
    Struct,
    Enum,
    Trait,
    Field,
    Type,
    Impl,
    Macro,
    Const,
    Use,
}

impl ItemKind {
    /// Parse a kind keyword. Returns `None` for unrecognized strings.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "fn" => Some(Self::Fn),
            "struct" => Some(Self::Struct),
            "enum" => Some(Self::Enum),
            "trait" => Some(Self::Trait),
            "field" => Some(Self::Field),
            "type" => Some(Self::Type),
            "impl" => Some(Self::Impl),
            "macro" => Some(Self::Macro),
            "const" => Some(Self::Const),
            "use" => Some(Self::Use),
            _ => None,
        }
    }

    /// Display keyword (lowercase, not Debug format).
    pub fn keyword(self) -> &'static str {
        match self {
            Self::Fn => "fn",
            Self::Struct => "struct",
            Self::Enum => "enum",
            Self::Trait => "trait",
            Self::Field => "field",
            Self::Type => "type",
            Self::Impl => "impl",
            Self::Macro => "macro",
            Self::Const => "const",
            Self::Use => "use",
        }
    }
}

// ── Argument resolution ──────────────────────────────────────────────

/// Resolved positional arguments for the `code` subcommand.
pub struct ResolvedCodeArgs {
    /// `"self"` or a crate name / spec.
    pub target: String,
    pub kind: Option<ItemKind>,
    pub name: String,
}

/// Parse the variadic positional args (`1..=3`) into target, kind, and name.
///
/// - **1 arg:** `code NAME` → target=`"self"`, catch-all. Errors if the single
///   arg is a kind keyword (ambiguous).
/// - **2 args:** `code KIND NAME` if arg[0] is a kind keyword, else
///   `code TARGET NAME` (catch-all).
/// - **3 args:** `code TARGET KIND NAME` — arg[1] must be a valid kind.
/// - **0 or 4+ args:** error with usage.
pub fn resolve_code_args(args: &CodeArgs) -> Result<ResolvedCodeArgs> {
    match args.args.len() {
        1 => {
            let a = &args.args[0];
            if ItemKind::parse(a).is_some() {
                bail!(
                    "'{}' is an item kind. Usage: cargo brief code [TARGET] {} <name>",
                    a,
                    a
                );
            }
            Ok(ResolvedCodeArgs {
                target: "self".to_string(),
                kind: None,
                name: a.clone(),
            })
        }
        2 => {
            let a0 = &args.args[0];
            let a1 = &args.args[1];
            if let Some(kind) = ItemKind::parse(a0) {
                Ok(ResolvedCodeArgs {
                    target: "self".to_string(),
                    kind: Some(kind),
                    name: a1.clone(),
                })
            } else {
                Ok(ResolvedCodeArgs {
                    target: a0.clone(),
                    kind: None,
                    name: a1.clone(),
                })
            }
        }
        3 => {
            let target = &args.args[0];
            let kind_str = &args.args[1];
            let name = &args.args[2];
            match ItemKind::parse(kind_str) {
                Some(kind) => Ok(ResolvedCodeArgs {
                    target: target.clone(),
                    kind: Some(kind),
                    name: name.clone(),
                }),
                None => bail!(
                    "Unknown item kind '{}'. Valid kinds: fn, struct, enum, trait, field, type, impl, macro, const, use",
                    kind_str
                ),
            }
        }
        _ => bail!(
            "Expected 1–3 positional arguments: [TARGET] [KIND] NAME\n\
             Usage: cargo brief code [TARGET] [KIND] NAME"
        ),
    }
}

// ── Tree-sitter queries ──────────────────────────────────────────────

/// Build a tree-sitter query string for the given item kind (or all kinds).
/// Each pattern has `@name` (the identifier to match) and `@item` (the full node).
fn build_query(kind: Option<ItemKind>) -> String {
    let mut parts = Vec::new();

    let add = |parts: &mut Vec<&str>, k: ItemKind| match k {
        ItemKind::Fn => {
            parts.push("(function_item name: (identifier) @name) @item");
            parts.push("(function_signature_item name: (identifier) @name) @item");
        }
        ItemKind::Struct => {
            parts.push("(struct_item name: (type_identifier) @name) @item");
        }
        ItemKind::Enum => {
            parts.push("(enum_item name: (type_identifier) @name) @item");
        }
        ItemKind::Trait => {
            parts.push("(trait_item name: (type_identifier) @name) @item");
        }
        ItemKind::Field => {
            parts.push("(field_declaration name: (field_identifier) @name) @item");
        }
        ItemKind::Type => {
            parts.push("(type_item name: (type_identifier) @name) @item");
        }
        ItemKind::Impl => {
            parts.push("(impl_item type: (type_identifier) @name) @item");
            parts.push("(impl_item type: (generic_type type: (type_identifier) @name)) @item");
            parts.push(
                "(impl_item type: (scoped_type_identifier name: (type_identifier) @name)) @item",
            );
        }
        ItemKind::Macro => {
            parts.push("(macro_definition name: (identifier) @name) @item");
        }
        ItemKind::Const => {
            parts.push("(const_item name: (identifier) @name) @item");
            parts.push("(static_item name: (identifier) @name) @item");
        }
        ItemKind::Use => {
            parts.push(
                "(use_declaration argument: (use_as_clause alias: (identifier) @name)) @item",
            );
            parts.push(
                "(use_declaration argument: (scoped_identifier name: (identifier) @name)) @item",
            );
            parts.push("(use_declaration argument: (identifier) @name) @item");
        }
    };

    if let Some(k) = kind {
        add(&mut parts, k);
    } else {
        // Catch-all: all kinds except Use (reduces noise)
        for k in [
            ItemKind::Fn,
            ItemKind::Struct,
            ItemKind::Enum,
            ItemKind::Trait,
            ItemKind::Field,
            ItemKind::Type,
            ItemKind::Impl,
            ItemKind::Macro,
            ItemKind::Const,
        ] {
            add(&mut parts, k);
        }
    }

    parts.join("\n")
}

// ── Name matching ────────────────────────────────────────────────────

/// Smart-case: all-lowercase pattern → case-insensitive.
fn is_case_sensitive(pattern: &str) -> bool {
    pattern.chars().any(|c| c.is_uppercase())
}

fn name_matches(captured: &str, pattern: &str, case_sensitive: bool) -> bool {
    if case_sensitive {
        captured == pattern
    } else {
        captured.eq_ignore_ascii_case(pattern)
    }
}

// ── File collection ──────────────────────────────────────────────────

fn collect_source_files(source_root: &Path, src_only: bool) -> Vec<PathBuf> {
    let mut files = Vec::new();
    let dirs: &[&str] = if src_only {
        &["src"]
    } else {
        &["src", "examples", "tests", "benches"]
    };
    for dir_name in dirs {
        let dir = source_root.join(dir_name);
        if dir.is_dir() {
            files.extend(examples::collect_rs_files(&dir, 999));
        }
    }
    files.sort();
    files
}

// ── Module context derivation ────────────────────────────────────────

/// Derive module path from file path relative to source root.
/// `lib.rs`/`main.rs` → empty. `src/foo/bar.rs` → `foo::bar`.
/// `src/foo/mod.rs` → `foo`.
fn derive_module_path(file_path: &Path, source_root: &Path) -> String {
    let rel = file_path.strip_prefix(source_root).unwrap_or(file_path);

    // Strip leading src/ if present
    let rel = rel.strip_prefix("src").unwrap_or(rel);

    let s = rel.to_string_lossy();
    let s = s.strip_suffix(".rs").unwrap_or(&s);

    // mod.rs → use parent dir
    let s = s
        .strip_suffix("/mod")
        .or_else(|| s.strip_suffix("\\mod"))
        .unwrap_or(s);

    // lib / main at root → empty
    if s == "lib" || s == "main" || s == "/lib" || s == "/main" || s == "\\lib" || s == "\\main" {
        return String::new();
    }

    // Strip leading separator
    let s = s
        .strip_prefix('/')
        .or_else(|| s.strip_prefix('\\'))
        .unwrap_or(s);

    s.replace(['/', '\\'], "::")
}

/// Walk up from a node collecting inline `mod_item` ancestor names (reversed for top-down order).
fn collect_inline_module_names(node: tree_sitter::Node, source: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "mod_item"
            && let Some(name_node) = parent.child_by_field_name("name")
        {
            names.push(source[name_node.start_byte()..name_node.end_byte()].to_string());
        }
        current = parent.parent();
    }
    names.reverse();
    names
}

/// Build full module context: `crate_name::file_module::inline_modules`.
fn build_module_context(
    crate_name: &str,
    file_path: &Path,
    source_root: &Path,
    node: tree_sitter::Node,
    source: &str,
) -> String {
    let file_mod = derive_module_path(file_path, source_root);
    let inline_mods = collect_inline_module_names(node, source);

    let mut path = String::from(crate_name);
    if !file_mod.is_empty() {
        path.push_str("::");
        path.push_str(&file_mod);
    }
    if !inline_mods.is_empty() {
        path.push_str("::");
        path.push_str(&inline_mods.join("::"));
    }
    path
}

// ── Parent context ───────────────────────────────────────────────────

/// Walk up from node to find nearest impl/trait/struct/enum parent.
/// Returns a display string like `impl Commands<'w, 's'>` or `trait Plugin`.
fn find_parent_context(node: tree_sitter::Node, source: &str) -> Option<String> {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "impl_item" => {
                // Extract: `impl [Trait for] Type`
                let trait_part = parent
                    .child_by_field_name("trait")
                    .map(|t| &source[t.start_byte()..t.end_byte()]);
                let type_part = parent
                    .child_by_field_name("type")
                    .map(|t| &source[t.start_byte()..t.end_byte()]);
                return match (trait_part, type_part) {
                    (Some(tr), Some(ty)) => Some(format!("impl {tr} for {ty}")),
                    (None, Some(ty)) => Some(format!("impl {ty}")),
                    _ => None,
                };
            }
            "trait_item" => {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    let name = &source[name_node.start_byte()..name_node.end_byte()];
                    return Some(format!("trait {name}"));
                }
            }
            "struct_item" => {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    let name = &source[name_node.start_byte()..name_node.end_byte()];
                    return Some(format!("struct {name}"));
                }
            }
            "enum_item" => {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    let name = &source[name_node.start_byte()..name_node.end_byte()];
                    return Some(format!("enum {name}"));
                }
            }
            // Skip intermediate nodes (declaration_list, etc.) and keep walking up
            "mod_item" => return None, // stop at module boundary
            _ => {}
        }
        current = parent.parent();
    }
    None
}

// ── Parent type extraction ────────────────────────────────────────────

/// Extract the type name from the nearest parent impl/trait/struct/enum.
/// Returns the bare type identifier (e.g., "Commands" from "impl Commands<'w>").
fn parent_type_name(node: tree_sitter::Node, source: &str) -> Option<String> {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "impl_item" => {
                let type_node = parent.child_by_field_name("type")?;
                return extract_type_identifier(type_node, source);
            }
            "trait_item" | "struct_item" | "enum_item" => {
                let name_node = parent.child_by_field_name("name")?;
                return Some(source[name_node.start_byte()..name_node.end_byte()].to_string());
            }
            "mod_item" => return None,
            _ => {}
        }
        current = parent.parent();
    }
    None
}

/// Extract the type_identifier from a type node, handling generic_type
/// and scoped_type_identifier wrappers.
fn extract_type_identifier(node: tree_sitter::Node, source: &str) -> Option<String> {
    match node.kind() {
        "type_identifier" => Some(source[node.start_byte()..node.end_byte()].to_string()),
        "generic_type" => {
            let type_node = node.child_by_field_name("type")?;
            extract_type_identifier(type_node, source)
        }
        "scoped_type_identifier" => {
            let name_node = node.child_by_field_name("name")?;
            Some(source[name_node.start_byte()..name_node.end_byte()].to_string())
        }
        _ => None,
    }
}

// ── Limit parsing ────────────────────────────────────────────────────

fn parse_limit(raw: Option<&str>) -> (usize, Option<usize>) {
    let Some(raw) = raw else {
        return (0, None);
    };
    if let Some((offset_str, limit_str)) = raw.split_once(':') {
        (
            offset_str.parse().unwrap_or(0),
            Some(limit_str.parse().unwrap_or(0)),
        )
    } else {
        (0, Some(raw.parse().unwrap_or(0)))
    }
}

// ── Main search function ─────────────────────────────────────────────

/// Search source files for code definitions matching kind and name.
///
/// `sources`: list of `(crate_name, source_root)` pairs to scan.
pub fn search_code(
    sources: &[(String, PathBuf)],
    name: &str,
    kind: Option<ItemKind>,
    args: &CodeArgs,
    in_type: Option<&str>,
) -> Result<String> {
    let language: tree_sitter::Language = tree_sitter_rust::LANGUAGE.into();
    let query_src = build_query(kind);
    let query = Query::new(&language, &query_src)
        .map_err(|e| anyhow::anyhow!("Failed to compile tree-sitter query: {e}"))?;

    let mut parser = Parser::new();
    parser
        .set_language(&language)
        .map_err(|e| anyhow::anyhow!("Failed to set tree-sitter language: {e}"))?;

    let capture_names = query.capture_names().to_vec();
    let name_idx = capture_names
        .iter()
        .position(|n| *n == "name")
        .expect("query must have @name capture") as u32;
    let item_idx = capture_names
        .iter()
        .position(|n| *n == "item")
        .expect("query must have @item capture") as u32;

    let case_sensitive = is_case_sensitive(name);
    let (offset, limit) = parse_limit(args.limit.as_deref());

    let mut output = String::new();
    let mut match_count = 0usize;
    let mut emitted = 0usize;

    // Pre-compute lowercase name for insensitive grep pre-filter
    let name_lower = name.to_ascii_lowercase();

    'outer: for (crate_name, source_root) in sources {
        let files = collect_source_files(source_root, args.src_only);

        for file_path in &files {
            let source = match std::fs::read_to_string(file_path) {
                Ok(s) => s,
                Err(_) => continue,
            };

            // Grep pre-filter: skip files that don't contain the name
            let contains = if case_sensitive {
                source.contains(name)
            } else {
                source.to_ascii_lowercase().contains(&name_lower)
            };
            if !contains {
                continue;
            }

            let Some(tree) = parser.parse(&source, None) else {
                continue;
            };

            let root = tree.root_node();
            let mut cursor = QueryCursor::new();
            let mut matches = cursor.matches(&query, root, source.as_bytes());

            while let Some(query_match) = matches.next() {
                // Find @name and @item captures
                let name_node = query_match.captures.iter().find(|c| c.index == name_idx);
                let item_node = query_match.captures.iter().find(|c| c.index == item_idx);

                let (Some(name_cap), Some(item_cap)) = (name_node, item_node) else {
                    continue;
                };

                let captured_name = &source[name_cap.node.start_byte()..name_cap.node.end_byte()];
                if !name_matches(captured_name, name, case_sensitive) {
                    continue;
                }

                // --in filter: only items inside matching parent type
                if let Some(filter_type) = in_type {
                    let filter_case_sensitive = is_case_sensitive(filter_type);
                    match parent_type_name(item_cap.node, &source) {
                        Some(ref parent_name) => {
                            if !name_matches(parent_name, filter_type, filter_case_sensitive) {
                                continue;
                            }
                        }
                        None => continue,
                    }
                }

                match_count += 1;
                if match_count <= offset {
                    continue;
                }
                if let Some(n) = limit
                    && emitted >= n
                {
                    break 'outer;
                }
                emitted += 1;

                let item_node = item_cap.node;
                let start_line = item_node.start_position().row + 1;
                let rel = file_path.strip_prefix(source_root).unwrap_or(file_path);

                // Module context
                let mod_ctx =
                    build_module_context(crate_name, file_path, source_root, item_node, &source);

                // Parent context
                let parent_ctx = find_parent_context(item_node, &source);

                // Format output
                if !output.is_empty() {
                    output.push('\n');
                }

                output.push_str(&format!("@{}:{}\n", rel.display(), start_line));

                // Context line: `  in module[, parent]`
                output.push_str("  in ");
                output.push_str(&mod_ctx);
                if let Some(ref ctx) = parent_ctx {
                    output.push_str(", ");
                    output.push_str(ctx);
                }
                output.push('\n');

                if !args.quiet {
                    output.push('\n');
                    let text = &source[item_node.start_byte()..item_node.end_byte()];
                    output.push_str(text);
                    if !text.ends_with('\n') {
                        output.push('\n');
                    }
                }
            }
        }
    }

    if match_count == 0 {
        let kind_str = kind.map_or("", |k| k.keyword());
        if kind_str.is_empty() {
            output.push_str(&format!("// no definitions found for '{name}'\n"));
        } else {
            output.push_str(&format!(
                "// no {kind_str} definitions found for '{name}'\n"
            ));
        }
    }

    Ok(output)
}

// ── Reference (grep) search ──────────────────────────────────────────

fn digit_count(mut n: usize) -> usize {
    if n == 0 {
        return 1;
    }
    let mut count = 0;
    while n > 0 {
        count += 1;
        n /= 10;
    }
    count
}

/// Grep source files for literal occurrences of `name`.
pub fn search_references(
    sources: &[(String, PathBuf)],
    name: &str,
    src_only: bool,
    quiet: bool,
    limit: Option<&str>,
) -> String {
    let case_sensitive = is_case_sensitive(name);
    let name_lower = name.to_ascii_lowercase();
    let (offset, limit_n) = parse_limit(limit);

    let ctx_lines: usize = 2;
    let mut output = String::new();
    let mut total_matches = 0usize;
    let mut emitted = 0usize;

    'outer: for (_crate_name, source_root) in sources {
        let files = collect_source_files(source_root, src_only);

        for file_path in &files {
            let content = match std::fs::read_to_string(file_path) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let lines: Vec<&str> = content.lines().collect();
            let total = lines.len();

            // Find matching line indices (0-based)
            let matches: Vec<usize> = lines
                .iter()
                .enumerate()
                .filter(|(_, line)| {
                    if case_sensitive {
                        line.contains(name)
                    } else {
                        line.to_ascii_lowercase().contains(&name_lower)
                    }
                })
                .map(|(i, _)| i)
                .collect();

            if matches.is_empty() {
                continue;
            }

            let rel = file_path
                .strip_prefix(source_root)
                .unwrap_or(file_path)
                .to_string_lossy()
                .replace('\\', "/");

            if quiet {
                for &m in &matches {
                    total_matches += 1;
                    if total_matches <= offset {
                        continue;
                    }
                    if let Some(n) = limit_n
                        && emitted >= n
                    {
                        break 'outer;
                    }
                    emitted += 1;
                    output.push_str(&format!("@{}:{}\n", rel, m + 1));
                }
            } else {
                // Determine which matches survive offset/limit
                let mut file_match_indices: Vec<usize> = Vec::new();
                for &m in &matches {
                    total_matches += 1;
                    if total_matches <= offset {
                        continue;
                    }
                    if let Some(n) = limit_n
                        && emitted >= n
                    {
                        break;
                    }
                    emitted += 1;
                    file_match_indices.push(m);
                }

                if file_match_indices.is_empty() {
                    if let Some(n) = limit_n
                        && emitted >= n
                    {
                        break 'outer;
                    }
                    continue;
                }

                // Compute context ranges and merge overlapping
                let mut ranges: Vec<(usize, usize)> = Vec::new();
                for &m in &file_match_indices {
                    let start = m.saturating_sub(ctx_lines);
                    let end = (m + ctx_lines).min(total.saturating_sub(1));
                    if let Some(last) = ranges.last_mut()
                        && start <= last.1 + 1
                    {
                        last.1 = last.1.max(end);
                        continue;
                    }
                    ranges.push((start, end));
                }

                // Line number column width
                let max_line_no = ranges.last().map_or(1, |r| r.1 + 1);
                let width = digit_count(max_line_no).max(4);

                output.push_str(&format!("@{rel}\n"));

                let match_set: std::collections::HashSet<usize> =
                    file_match_indices.iter().copied().collect();

                for (range_idx, &(start, end)) in ranges.iter().enumerate() {
                    if range_idx > 0 {
                        output.push_str("  ...\n");
                    }
                    for (i, line) in lines.iter().enumerate().take(end + 1).skip(start) {
                        let line_no = i + 1;
                        let marker = if match_set.contains(&i) { '*' } else { ' ' };
                        output.push_str(&format!(
                            "{marker}{line_no:>width$}:  {line}\n",
                            width = width,
                        ));
                    }
                }

                output.push('\n');

                if let Some(n) = limit_n
                    && emitted >= n
                {
                    break 'outer;
                }
            }
        }
    }

    if total_matches == 0 {
        output.push_str(&format!("// no references found for '{name}'\n"));
    }

    output
}