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
use std::collections::{HashMap, HashSet};
use rustdoc_types::{Crate, Id, Item, ItemEnum, Visibility};
/// Extended reachability information for external-crate API rendering.
pub struct ReachableInfo {
/// All item IDs reachable through the public API.
pub reachable: HashSet<Id>,
/// Private module IDs reachable only via glob re-exports.
/// API render should NOT render these as `mod name { ... }`.
pub glob_private_modules: HashSet<Id>,
/// Maps glob Use item ID → source private module ID.
/// Render should inline these modules' items instead of `pub use source::*;`.
pub glob_inlined: HashMap<Id, Id>,
}
/// A processed view of a crate's items, organized by module hierarchy.
pub struct CrateModel {
pub krate: Crate,
/// Maps module paths (e.g., "outer::inner") to their item IDs.
pub module_index: HashMap<String, Id>,
/// Maps item IDs to their containing module path.
pub item_module_path: HashMap<Id, String>,
}
impl CrateModel {
/// Build a CrateModel from a parsed rustdoc JSON Crate.
pub fn from_crate(krate: Crate) -> Self {
let mut module_index = HashMap::new();
let mut item_module_path = HashMap::new();
// Walk the module tree starting from the crate root
let crate_name = krate
.index
.get(&krate.root)
.and_then(|item| item.name.as_deref())
.unwrap_or("unknown")
.to_string();
if let Some(root_item) = krate.index.get(&krate.root) {
Self::walk_modules(
&krate,
root_item,
&krate.root,
&crate_name,
&mut module_index,
&mut item_module_path,
);
}
Self {
krate,
module_index,
item_module_path,
}
}
fn walk_modules(
krate: &Crate,
item: &Item,
item_id: &Id,
current_path: &str,
module_index: &mut HashMap<String, Id>,
item_module_path: &mut HashMap<Id, String>,
) {
module_index.insert(current_path.to_string(), item_id.clone());
item_module_path.insert(item_id.clone(), current_path.to_string());
if let ItemEnum::Module(module) = &item.inner {
for child_id in &module.items {
if let Some(child_item) = krate.index.get(child_id) {
let child_path = if let Some(name) = &child_item.name {
format!("{current_path}::{name}")
} else {
continue;
};
item_module_path.insert(child_id.clone(), current_path.to_string());
if matches!(child_item.inner, ItemEnum::Module(_)) {
Self::walk_modules(
krate,
child_item,
child_id,
&child_path,
module_index,
item_module_path,
);
}
}
}
}
}
/// Get the crate name.
pub fn crate_name(&self) -> &str {
self.krate
.index
.get(&self.krate.root)
.and_then(|item| item.name.as_deref())
.unwrap_or("unknown")
}
/// Find a module by its path relative to the crate root.
/// Accepts paths like "outer::inner" (without crate name prefix).
pub fn find_module(&self, module_path: &str) -> Option<&Item> {
self.find_module_entry(module_path).map(|(_id, item)| item)
}
/// Find a module by path, returning both its Id and Item.
pub fn find_module_entry(&self, module_path: &str) -> Option<(&Id, &Item)> {
let full_path = format!("{}::{}", self.crate_name(), module_path);
let id = self
.module_index
.get(&full_path)
.or_else(|| self.module_index.get(module_path))?;
self.krate.index.get(id).map(|item| (id, item))
}
/// Find the root module of the crate.
pub fn root_module(&self) -> Option<&Item> {
self.krate.index.get(&self.krate.root)
}
/// Get children items of a module.
pub fn module_children<'a>(&'a self, module_item: &'a Item) -> Vec<(&'a Id, &'a Item)> {
match &module_item.inner {
ItemEnum::Module(module) => module
.items
.iter()
.filter_map(|id| self.krate.index.get(id).map(|item| (id, item)))
.collect(),
_ => vec![],
}
}
/// Resolve the full module path for a given item ID.
/// Returns the path of the module *containing* the item.
#[allow(dead_code)]
pub fn containing_module_path(&self, item_id: &Id) -> Option<&str> {
self.item_module_path.get(item_id).map(|s| s.as_str())
}
/// Get the full module path for a module ID.
pub fn module_path(&self, module_id: &Id) -> Option<&str> {
// Check module_index values
for (path, id) in &self.module_index {
if id == module_id {
return Some(path.as_str());
}
}
None
}
/// Find a non-module item by name within a parent module.
///
/// `parent_module_path` is relative to the crate root (e.g., "outer" or "outer::inner").
/// An empty string means the crate root module.
///
/// For `Use` items (re-exports), follows the chain to the actual definition (max 10 hops).
/// If the chain leads to a foreign item not in the index, returns the original Use item.
/// Skips `Module` items — those are resolved by the module path system.
pub fn find_item_in_module(
&self,
parent_module_path: &str,
item_name: &str,
) -> Option<(&Id, &Item)> {
let parent_item = if parent_module_path.is_empty() {
self.root_module()?
} else {
self.find_module_entry(parent_module_path)
.map(|(_, item)| item)?
};
let children = self.module_children(parent_item);
for (child_id, child) in children {
// Skip modules — module resolution takes priority
if matches!(child.inner, ItemEnum::Module(_)) {
continue;
}
// Extract item name using the item.name / use_item.name fallback pattern
let name = child
.name
.as_deref()
.or(if let ItemEnum::Use(u) = &child.inner {
Some(u.name.as_str())
} else {
None
});
let Some(name) = name else { continue };
if name != item_name {
continue;
}
// For Use items, follow the chain to the actual definition
if let ItemEnum::Use(use_item) = &child.inner {
if use_item.is_glob {
continue;
}
if let Some(target_id) = &use_item.id {
// Follow the chain (max 10 hops)
let mut current_id = target_id;
for _ in 0..10 {
match self.krate.index.get(current_id) {
Some(item) if matches!(item.inner, ItemEnum::Use(ref u) if !u.is_glob) =>
{
if let ItemEnum::Use(u) = &item.inner
&& let Some(next_id) = &u.id
{
current_id = next_id;
continue;
}
// Chain broken — return what we have
return Some((current_id, item));
}
Some(item) => return Some((current_id, item)),
None => {
// Foreign item — return the original Use item
return Some((child_id, child));
}
}
}
// Exceeded hop limit — return current resolution
if let Some(item) = self.krate.index.get(current_id) {
return Some((current_id, item));
}
}
// Use without target id — return it as-is
return Some((child_id, child));
}
return Some((child_id, child));
}
None
}
/// Check if `ancestor_path` is an ancestor of (or equal to) `descendant_path`.
pub fn is_ancestor_or_equal(ancestor_path: &str, descendant_path: &str) -> bool {
if ancestor_path == descendant_path {
return true;
}
descendant_path.starts_with(ancestor_path)
&& descendant_path.as_bytes().get(ancestor_path.len()) == Some(&b':')
}
}
/// Determine if an item is visible from a given observer module.
pub fn is_visible_from(
model: &CrateModel,
item: &Item,
_item_id: &Id,
observer_module_path: &str,
same_crate: bool,
) -> bool {
match &item.visibility {
Visibility::Public => true,
Visibility::Crate => same_crate,
Visibility::Restricted { parent, path: _ } => {
if !same_crate {
return false;
}
// The item is visible within the module identified by `parent`.
// Check if the observer is within that module.
if let Some(restricted_path) = model.module_path(parent) {
CrateModel::is_ancestor_or_equal(restricted_path, observer_module_path)
} else {
false
}
}
Visibility::Default => {
// `default` visibility is used for impl blocks and their items.
// These are visible if they're on a type that is visible.
// For simplicity, we treat default as "same module only" for non-impl items,
// and delegate impl visibility to the parent type.
false
}
}
}
/// Compute the set of item IDs reachable through the crate's public API.
///
/// Walks from the root module following only `Visibility::Public` children.
/// For `pub use` re-exports targeting local items, marks the target and its
/// ancestor modules as reachable (so private modules containing reachable
/// items are rendered). For reachable structs/enums/unions, marks their
/// impl blocks as reachable.
///
/// Also tracks glob-private modules (private modules reached only via
/// `pub use private::*`) and the Use items that inline them.
pub fn compute_reachable_set(model: &CrateModel) -> ReachableInfo {
let mut info = ReachableInfo {
reachable: HashSet::new(),
glob_private_modules: HashSet::new(),
glob_inlined: HashMap::new(),
};
let Some(root) = model.root_module() else {
return info;
};
// Root module is always reachable
info.reachable.insert(model.krate.root);
let crate_name = model.crate_name();
walk_public(model, root, crate_name, crate_name, &mut info);
info
}
fn walk_public(
model: &CrateModel,
module_item: &Item,
resolution_path: &str,
canonical_path: &str,
info: &mut ReachableInfo,
) {
let children = model.module_children(module_item);
for (child_id, child) in &children {
if !matches!(child.visibility, Visibility::Public) {
continue;
}
match &child.inner {
ItemEnum::Module(_) => {
info.reachable.insert(**child_id);
let name = match &child.name {
Some(name) => name,
None => continue,
};
let child_res = format!("{resolution_path}::{name}");
let child_can = format!("{canonical_path}::{name}");
walk_public(model, child, &child_res, &child_can, info);
}
ItemEnum::Use(use_item) if !use_item.is_glob => {
info.reachable.insert(**child_id);
if let Some(target_id) = &use_item.id {
mark_reachable_with_ancestors(model, target_id, &mut info.reachable);
}
}
ItemEnum::Use(use_item) => {
info.reachable.insert(**child_id);
// Follow intra-crate glob re-exports: resolve the source module
// and walk its public items into the reachable set.
// Cross-crate sources won't be in module_index → harmlessly skipped.
let source = use_item
.source
.strip_prefix("self::")
.unwrap_or(&use_item.source);
// Try relative to current module first (handles nested private modules
// like bevy's `mod bind_group; pub use bind_group::*;` inside render_resource)
let relative = format!("{resolution_path}::{source}");
if let Some((mod_id, mod_item)) = model.find_module_entry(&relative) {
let is_private = !matches!(mod_item.visibility, Visibility::Public);
if is_private {
info.glob_private_modules.insert(*mod_id);
info.glob_inlined.insert(**child_id, *mod_id);
}
if info.reachable.insert(*mod_id) {
let child_can = if is_private {
canonical_path.to_string()
} else {
format!("{canonical_path}::{source}")
};
walk_public(model, mod_item, &relative, &child_can, info);
}
} else if let Some((mod_id, mod_item)) = model.find_module_entry(source) {
let is_private = !matches!(mod_item.visibility, Visibility::Public);
if is_private {
info.glob_private_modules.insert(*mod_id);
info.glob_inlined.insert(**child_id, *mod_id);
}
if info.reachable.insert(*mod_id) {
let full = format!("{}::{source}", model.crate_name());
let child_can = if is_private {
canonical_path.to_string()
} else {
full.clone()
};
walk_public(model, mod_item, &full, &child_can, info);
}
}
}
_ => {
info.reachable.insert(**child_id);
mark_impls(model, child, &mut info.reachable);
}
}
}
}
/// Mark an item reachable, along with its ancestor modules and impl blocks.
fn mark_reachable_with_ancestors(model: &CrateModel, item_id: &Id, reachable: &mut HashSet<Id>) {
let Some(item) = model.krate.index.get(item_id) else {
return;
};
reachable.insert(*item_id);
mark_impls(model, item, reachable);
// Walk ancestor modules up to root
if let Some(parent_path) = model.item_module_path.get(item_id) {
let mut path = parent_path.as_str();
loop {
if let Some(mod_id) = model.module_index.get(path) {
reachable.insert(*mod_id);
}
match path.rsplit_once("::") {
Some((parent, _)) => path = parent,
None => break,
}
}
}
}
/// Mark impl blocks of a struct/enum/union as reachable.
fn mark_impls(model: &CrateModel, item: &Item, reachable: &mut HashSet<Id>) {
let impls = match &item.inner {
ItemEnum::Struct(s) => &s.impls,
ItemEnum::Enum(e) => &e.impls,
ItemEnum::Union(u) => &u.impls,
_ => return,
};
for impl_id in impls {
if model.krate.index.contains_key(impl_id) {
reachable.insert(*impl_id);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_ancestor_or_equal() {
assert!(CrateModel::is_ancestor_or_equal("foo", "foo"));
assert!(CrateModel::is_ancestor_or_equal("foo", "foo::bar"));
assert!(CrateModel::is_ancestor_or_equal("foo", "foo::bar::baz"));
assert!(!CrateModel::is_ancestor_or_equal("foo", "foobar"));
assert!(!CrateModel::is_ancestor_or_equal("foo::bar", "foo"));
assert!(!CrateModel::is_ancestor_or_equal("foo::bar", "foo::baz"));
}
}