cargo-brief 0.12.0

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
use std::collections::{BTreeMap, HashSet};

use rustdoc_types::{Id, Item, ItemEnum, MacroKind, Visibility};

use crate::model::{CrateModel, ReachableInfo, is_visible_from};

/// Kind of item for summary counting.
/// Ord derives display order: traits first, unions last.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ItemKind {
    Trait,
    Struct,
    Enum,
    Function,
    TypeAlias,
    Constant,
    Macro,
    ProcMacro,
    ProcAttrMacro,
    ProcDeriveMacro,
    Union,
}

impl ItemKind {
    fn plural(self) -> &'static str {
        match self {
            ItemKind::Trait => "traits",
            ItemKind::Struct => "structs",
            ItemKind::Enum => "enums",
            ItemKind::Function => "fns",
            ItemKind::TypeAlias => "types",
            ItemKind::Constant => "consts",
            ItemKind::Macro => "macros",
            ItemKind::ProcMacro => "proc_macros",
            ItemKind::ProcAttrMacro => "attr_macros",
            ItemKind::ProcDeriveMacro => "derive_macros",
            ItemKind::Union => "unions",
        }
    }
}

/// Per-module item counts.
#[derive(Default)]
struct ModuleSummary {
    counts: BTreeMap<ItemKind, usize>,
}

impl ModuleSummary {
    fn increment(&mut self, kind: ItemKind) {
        *self.counts.entry(kind).or_insert(0) += 1;
    }

    fn is_empty(&self) -> bool {
        self.counts.values().all(|&c| c == 0)
    }

    fn format_counts(&self) -> String {
        self.counts
            .iter()
            .filter(|&(_, c)| *c > 0)
            .map(|(kind, count)| format!("{count} {}", kind.plural()))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

/// Classify an item into an ItemKind, following non-glob `Use` to its target.
fn classify_item(item: &Item, model: &CrateModel) -> Option<ItemKind> {
    match &item.inner {
        ItemEnum::Struct(_) => Some(ItemKind::Struct),
        ItemEnum::Enum(_) => Some(ItemKind::Enum),
        ItemEnum::Function(_) => Some(ItemKind::Function),
        ItemEnum::Trait(_) => Some(ItemKind::Trait),
        ItemEnum::TypeAlias(_) => Some(ItemKind::TypeAlias),
        ItemEnum::Constant { .. } | ItemEnum::Static(_) => Some(ItemKind::Constant),
        ItemEnum::Macro(_) => Some(ItemKind::Macro),
        ItemEnum::ProcMacro(pm) => Some(match pm.kind {
            MacroKind::Bang => ItemKind::ProcMacro,
            MacroKind::Attr => ItemKind::ProcAttrMacro,
            MacroKind::Derive => ItemKind::ProcDeriveMacro,
        }),
        ItemEnum::Union(_) => Some(ItemKind::Union),
        ItemEnum::Use(use_item) => {
            if use_item.is_glob {
                return None; // glob uses are not counted
            }
            // Follow the re-export to classify the target
            use_item
                .id
                .as_ref()
                .and_then(|target_id| model.krate.index.get(target_id))
                .and_then(|target| classify_item(target, model))
        }
        ItemEnum::Module(_) | ItemEnum::Impl(_) => None,
        _ => None,
    }
}

/// Check if an item passes visibility filtering.
fn is_item_visible(
    item: &Item,
    item_id: &Id,
    observer: Option<&str>,
    same_crate: bool,
    reachable: Option<&ReachableInfo>,
    model: &CrateModel,
) -> bool {
    if let Some(info) = reachable {
        info.reachable.contains(item_id)
    } else if same_crate {
        let obs = observer.unwrap_or("");
        is_visible_from(model, item, item_id, obs, true)
    } else {
        matches!(item.visibility, Visibility::Public)
    }
}

/// Recursively walk the module tree, collecting item counts per module.
#[allow(clippy::too_many_arguments)]
fn count_module_items(
    model: &CrateModel,
    module_item: &Item,
    current_path: &str,
    root_path: &str,
    observer: Option<&str>,
    same_crate: bool,
    reachable: Option<&ReachableInfo>,
    root_summary: &mut ModuleSummary,
    module_summaries: &mut BTreeMap<String, ModuleSummary>,
) {
    // Bind once — module_children allocates a Vec; all other call sites bind once
    // and reuse. The pre-pass borrows via .iter().copied(); the main loop consumes.
    let children = model.module_children(module_item);

    // Pre-collect module IDs reached via visible named pub use re-exports.
    // The Module arm below uses this to skip modules that were already processed,
    // preventing double-counting when the same module appears as both a direct
    // `pub mod` child and a named `pub use` re-export in the same parent scope.
    let use_module_ids: HashSet<&Id> = children
        .iter()
        .copied()
        .filter(|(child_id, child)| {
            is_item_visible(child, child_id, observer, same_crate, reachable, model)
        })
        .filter_map(|(_, child)| match &child.inner {
            ItemEnum::Use(u) if !u.is_glob => u.id.as_ref().filter(|target_id| {
                model
                    .krate
                    .index
                    .get(*target_id)
                    .is_some_and(|t| matches!(t.inner, ItemEnum::Module(_)))
            }),
            _ => None,
        })
        .collect();

    for (child_id, child) in children {
        if !is_item_visible(child, child_id, observer, same_crate, reachable, model) {
            continue;
        }

        // Named `pub use` of a module (e.g. `pub use private_mod::sub_pub;`):
        // treat as an inline module declaration under the alias and recurse into
        // the target's children so its items appear in the summary.
        if let ItemEnum::Use(use_item) = &child.inner
            && !use_item.is_glob
            && let Some(target_id) = use_item.id.as_ref()
            && let Some(target) = model.krate.index.get(target_id)
            && matches!(target.inner, ItemEnum::Module(_))
        {
            let alias = child.name.as_deref().unwrap_or(&use_item.name);
            let child_path = if current_path == root_path {
                alias.to_string()
            } else {
                let rel = current_path
                    .strip_prefix(root_path)
                    .and_then(|s| s.strip_prefix("::"))
                    .unwrap_or(current_path);
                format!("{rel}::{alias}")
            };

            module_summaries.entry(child_path).or_default();

            let full_child_path = format!("{current_path}::{alias}");
            count_module_items(
                model,
                target,
                &full_child_path,
                root_path,
                observer,
                same_crate,
                reachable,
                root_summary,
                module_summaries,
            );
            continue;
        }

        if let ItemEnum::Module(_) = &child.inner {
            // Skip modules already handled via the named pub use branch above.
            if use_module_ids.contains(child_id) {
                continue;
            }

            let is_glob_private =
                reachable.is_some_and(|info| info.glob_private_modules.contains(child_id));

            if is_glob_private {
                // Recurse but count items at PARENT level (same current_path)
                count_module_items(
                    model,
                    child,
                    current_path,
                    root_path,
                    observer,
                    same_crate,
                    reachable,
                    root_summary,
                    module_summaries,
                );
            } else {
                // For modules, check actual visibility — being in the reachable set
                // alone isn't enough (e.g., pub(crate) modules whose items are glob-reexported
                // are reachable but shouldn't appear as named module lines in external view).
                let module_visible = if !same_crate {
                    matches!(child.visibility, Visibility::Public)
                } else {
                    true // already passed is_item_visible above
                };
                if !module_visible {
                    continue;
                }

                let child_name = match &child.name {
                    Some(n) => n.as_str(),
                    None => continue,
                };
                let child_path = if current_path == root_path {
                    child_name.to_string()
                } else {
                    // Strip root_path prefix to get relative module path
                    let rel = current_path
                        .strip_prefix(root_path)
                        .and_then(|s| s.strip_prefix("::"))
                        .unwrap_or(current_path);
                    format!("{rel}::{child_name}")
                };

                // Ensure entry exists
                module_summaries.entry(child_path.clone()).or_default();

                // Build full path for recursive walk
                let full_child_path = format!("{current_path}::{child_name}");
                count_module_items(
                    model,
                    child,
                    &full_child_path,
                    root_path,
                    observer,
                    same_crate,
                    reachable,
                    root_summary,
                    module_summaries,
                );
            }
            continue;
        }

        if let Some(kind) = classify_item(child, model) {
            if current_path == root_path {
                root_summary.increment(kind);
            } else {
                let rel = current_path
                    .strip_prefix(root_path)
                    .and_then(|s| s.strip_prefix("::"))
                    .unwrap_or(current_path);
                module_summaries
                    .entry(rel.to_string())
                    .or_default()
                    .increment(kind);
            }
        }
    }
}

/// Render a compact summary of visible modules and their item counts.
///
/// If `module_path` is Some, scopes to that module. Otherwise uses the crate root.
pub fn render_summary(
    model: &CrateModel,
    module_path: Option<&str>,
    same_crate: bool,
    reachable: Option<&ReachableInfo>,
) -> String {
    let root_item = if let Some(path) = module_path {
        match model.find_module(path) {
            Some(item) => item,
            None => return format!("// module '{path}' not found\n"),
        }
    } else {
        match model.root_module() {
            Some(item) => item,
            None => return String::new(),
        }
    };

    let root_path = if let Some(path) = module_path {
        format!("{}::{path}", model.crate_name())
    } else {
        model.crate_name().to_string()
    };

    let observer = if same_crate {
        Some(root_path.as_str())
    } else {
        None
    };

    let mut root_summary = ModuleSummary::default();
    let mut module_summaries = BTreeMap::new();

    count_module_items(
        model,
        root_item,
        &root_path,
        &root_path,
        observer,
        same_crate,
        reachable,
        &mut root_summary,
        &mut module_summaries,
    );

    // Build output
    let mut output = String::new();

    // Header
    let display_name = if let Some(path) = module_path {
        format!("{}::{path}", model.crate_name())
    } else {
        model.crate_name().to_string()
    };
    output.push_str(&format!("// crate {display_name}\n"));

    // Collect non-empty module lines for column alignment
    let mut mod_lines: Vec<(String, String)> = Vec::new();
    for (path, summary) in &module_summaries {
        if summary.is_empty() {
            continue;
        }
        let decl = format!("mod {path};");
        let comment = summary.format_counts();
        mod_lines.push((decl, comment));
    }

    if !mod_lines.is_empty() {
        // Find max declaration width for column alignment
        let max_decl_width = mod_lines.iter().map(|(d, _)| d.len()).max().unwrap_or(0);

        for (decl, comment) in &mod_lines {
            let padding = max_decl_width - decl.len() + 1;
            output.push_str(decl);
            output.push_str(&" ".repeat(padding));
            output.push_str(&format!("// {comment}\n"));
        }
    }

    // Root items
    if !root_summary.is_empty() {
        let counts = root_summary.format_counts();
        output.push_str(&format!("// root: {counts}\n"));
    }

    output
}

/// Merge a sub-crate summary into the main output, prefixing module paths.
pub fn merge_sub_crate_summary(main_output: &mut String, sub_output: &str, display_name: &str) {
    for line in sub_output.lines() {
        if line.starts_with("// crate ") {
            // Skip the sub-crate header
            continue;
        }
        if let Some(rest) = line.strip_prefix("mod ") {
            main_output.push_str(&format!("mod {display_name}::{rest}\n"));
        } else if let Some(rest) = line.strip_prefix("// root: ") {
            main_output.push_str(&format!("mod {display_name};  // {rest}\n"));
        } else {
            main_output.push_str(line);
            main_output.push('\n');
        }
    }
}

use crate::cross_crate::{AccessibleItemKind, CrossCrateIndex};

/// Summarize a `CrossCrateIndex` by counting items per top-level accessible path segment.
///
/// Returns summary lines in the same format as `render_summary`, ready to
/// be appended to the main crate's summary output.
pub fn summarize_cross_crate_index(index: &CrossCrateIndex) -> String {
    let mut module_summaries: BTreeMap<String, ModuleSummary> = BTreeMap::new();
    let mut root_summary = ModuleSummary::default();

    for entry in &index.items {
        if entry.item_kind == AccessibleItemKind::Module {
            // Ensure the module path entry exists
            module_summaries
                .entry(entry.accessible_path.clone())
                .or_default();
            continue;
        }

        let kind = match entry.item_kind {
            AccessibleItemKind::Struct => ItemKind::Struct,
            AccessibleItemKind::Enum => ItemKind::Enum,
            AccessibleItemKind::Function => ItemKind::Function,
            AccessibleItemKind::Trait => ItemKind::Trait,
            AccessibleItemKind::TypeAlias => ItemKind::TypeAlias,
            AccessibleItemKind::Constant | AccessibleItemKind::Static => ItemKind::Constant,
            AccessibleItemKind::Macro => ItemKind::Macro,
            AccessibleItemKind::ProcMacro => ItemKind::ProcMacro,
            AccessibleItemKind::ProcAttrMacro => ItemKind::ProcAttrMacro,
            AccessibleItemKind::ProcDeriveMacro => ItemKind::ProcDeriveMacro,
            AccessibleItemKind::Union => ItemKind::Union,
            AccessibleItemKind::Module => continue,
        };

        // Determine which module this item belongs to
        if let Some(last_sep) = entry.accessible_path.rfind("::") {
            let module_path = &entry.accessible_path[..last_sep];
            module_summaries
                .entry(module_path.to_string())
                .or_default()
                .increment(kind);
        } else {
            // Root-level item
            root_summary.increment(kind);
        }
    }

    let mut output = String::new();

    // Collect non-empty module lines for column alignment
    let mut mod_lines: Vec<(String, String)> = Vec::new();
    for (path, summary) in &module_summaries {
        if summary.is_empty() {
            continue;
        }
        let decl = format!("mod {path};");
        let comment = summary.format_counts();
        mod_lines.push((decl, comment));
    }

    if !mod_lines.is_empty() {
        let max_decl_width = mod_lines.iter().map(|(d, _)| d.len()).max().unwrap_or(0);

        for (decl, comment) in &mod_lines {
            let padding = max_decl_width - decl.len() + 1;
            output.push_str(decl);
            output.push_str(&" ".repeat(padding));
            output.push_str(&format!("// {comment}\n"));
        }
    }

    // Root items (rare for cross-crate, but possible from glob flattening)
    if !root_summary.is_empty() {
        let counts = root_summary.format_counts();
        output.push_str(&format!("// root: {counts}\n"));
    }

    output
}

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

    #[test]
    fn test_item_kind_ordering() {
        assert!(ItemKind::Trait < ItemKind::Struct);
        assert!(ItemKind::Struct < ItemKind::Enum);
        assert!(ItemKind::Enum < ItemKind::Function);
        assert!(ItemKind::Function < ItemKind::TypeAlias);
        assert!(ItemKind::TypeAlias < ItemKind::Constant);
        assert!(ItemKind::Constant < ItemKind::Macro);
        assert!(ItemKind::Macro < ItemKind::Union);
    }

    #[test]
    fn test_module_summary_format() {
        let mut summary = ModuleSummary::default();
        summary.increment(ItemKind::Trait);
        summary.increment(ItemKind::Trait);
        summary.increment(ItemKind::Struct);
        summary.increment(ItemKind::Function);
        summary.increment(ItemKind::Function);
        summary.increment(ItemKind::Function);

        assert_eq!(summary.format_counts(), "2 traits, 1 structs, 3 fns");
        assert!(!summary.is_empty());
    }

    #[test]
    fn test_empty_summary() {
        let summary = ModuleSummary::default();
        assert!(summary.is_empty());
        assert_eq!(summary.format_counts(), "");
    }
}