Skip to main content

blyte_cli/
map_rust.rs

1use std::collections::{HashMap, HashSet};
2use std::ffi::OsStr;
3use std::path::{Component, Path, PathBuf};
4
5use quote::ToTokens;
6use syn::punctuated::Punctuated;
7use syn::visit::Visit;
8use syn::{
9    Attribute, GenericArgument, ImplItem, Item, Meta, PathArguments, ReturnType, Token, TraitItem,
10    Type, TypeParamBound, UseTree, Visibility,
11};
12
13use crate::map::{Edge, Field, Group, Part, Structure, Unit, Unparsed, Unresolved};
14
15struct CrateInfo {
16    pkg_name: String,
17    dir_rel: PathBuf,
18    manifest: toml::Value,
19}
20
21struct ParsedUnit {
22    id: String,
23    root_id: String,
24    is_lib_root: bool,
25    file_rel: String,
26    ast: syn::File,
27}
28
29struct ReexportTarget {
30    unit: String,
31    extra: Vec<String>,
32}
33
34struct StructEntry {
35    structure: Structure,
36    rel_path: Vec<String>,
37}
38
39struct UnitWalkCtx<'a> {
40    root: &'a Path,
41    group: &'a str,
42    root_id: &'a str,
43    units: &'a mut Vec<Unit>,
44    unparsed: &'a mut Vec<Unparsed>,
45    unresolved: &'a mut Vec<Unresolved>,
46    parsed: &'a mut Vec<ParsedUnit>,
47    visited: &'a mut HashSet<(String, PathBuf)>,
48}
49
50pub fn extract(root: &Path) -> Result<Part, String> {
51    let root_manifest_path = root.join("Cargo.toml");
52    let root_manifest = read_manifest(&root_manifest_path)?;
53
54    let crate_dirs = discover_crate_dirs(root, &root_manifest)?;
55    let mut crates = Vec::with_capacity(crate_dirs.len());
56    let mut dir_to_pkg: HashMap<PathBuf, String> = HashMap::new();
57    let mut groups = Vec::with_capacity(crate_dirs.len());
58
59    for dir_rel in crate_dirs {
60        let manifest_path = if dir_rel.as_os_str().is_empty() {
61            root_manifest_path.clone()
62        } else {
63            root.join(&dir_rel).join("Cargo.toml")
64        };
65        let manifest = if dir_rel.as_os_str().is_empty() {
66            root_manifest.clone()
67        } else {
68            read_manifest(&manifest_path)?
69        };
70        let pkg_name = manifest
71            .get("package")
72            .and_then(|p| p.get("name"))
73            .and_then(|n| n.as_str())
74            .ok_or_else(|| format!("missing [package].name in {}", manifest_path.display()))?
75            .to_string();
76        let path_str = rel_to_string(&dir_rel);
77        groups.push(Group {
78            id: pkg_name.clone(),
79            kind: "crate".to_string(),
80            path: path_str,
81            lang: "rust".to_string(),
82        });
83        dir_to_pkg.insert(dir_rel.clone(), pkg_name.clone());
84        crates.push(CrateInfo {
85            pkg_name,
86            dir_rel,
87            manifest,
88        });
89    }
90
91    let workspace_deps = root_manifest
92        .get("workspace")
93        .and_then(|w| w.get("dependencies"))
94        .and_then(|d| d.as_table());
95
96    let mut edges = Vec::new();
97    for info in &crates {
98        collect_group_edges(info, workspace_deps, &dir_to_pkg, &mut edges);
99    }
100
101    let mut units = Vec::new();
102    let mut unparsed = Vec::new();
103    let mut unresolved = Vec::new();
104    let mut parsed_units = Vec::new();
105    let mut lib_roots: HashSet<String> = HashSet::new();
106    let mut visited: HashSet<(String, PathBuf)> = HashSet::new();
107
108    for info in &crates {
109        let targets = crate_targets(root, info)?;
110        for (unit_id, is_lib_root, target_rel) in targets {
111            if is_lib_root {
112                lib_roots.insert(unit_id.clone());
113            }
114            let mut ctx = UnitWalkCtx {
115                root,
116                group: &info.pkg_name,
117                root_id: &unit_id,
118                units: &mut units,
119                unparsed: &mut unparsed,
120                unresolved: &mut unresolved,
121                parsed: &mut parsed_units,
122                visited: &mut visited,
123            };
124            visit_unit_file(&mut ctx, &unit_id, is_lib_root, true, &target_rel)?;
125        }
126    }
127
128    let unit_set: HashSet<String> = units.iter().map(|u| u.id.clone()).collect();
129    let reexports = collect_reexports(&parsed_units, &unit_set, &lib_roots);
130
131    let mut struct_entries: Vec<StructEntry> = Vec::new();
132    let mut structs_by_unit: HashMap<String, Vec<usize>> = HashMap::new();
133    for pu in &parsed_units {
134        let mut inline_mods = Vec::new();
135        collect_structures(
136            &pu.ast.items,
137            &pu.id,
138            &pu.file_rel,
139            &mut inline_mods,
140            &mut struct_entries,
141            &mut structs_by_unit,
142        );
143    }
144
145    for pu in &parsed_units {
146        let mut collector = PathCollector::default();
147        collector.visit_file(&pu.ast);
148        let unit_segs: Vec<String> = pu.id.split("::").map(|s| s.to_string()).collect();
149
150        for (raw_segs, inline_mods) in collector.paths {
151            let Some(resolved) =
152                resolve_counted_path(&raw_segs, &unit_segs, &inline_mods, &pu.root_id, &lib_roots)
153            else {
154                continue;
155            };
156            let Some((mut target_unit, mut remaining)) = longest_unit_prefix(&resolved, &unit_set)
157            else {
158                continue;
159            };
160
161            if lib_roots.contains(&target_unit) {
162                if let Some(first_rem) = remaining.first() {
163                    if let Some(reexp) = reexports.get(&(target_unit.clone(), first_rem.clone())) {
164                        target_unit = reexp.unit.clone();
165                        let mut new_rem = reexp.extra.clone();
166                        new_rem.extend_from_slice(&remaining[1..]);
167                        remaining = new_rem;
168                    }
169                }
170            }
171
172            if target_unit != pu.id {
173                edges.push(Edge {
174                    from: pu.id.clone(),
175                    to: target_unit.clone(),
176                    level: "unit".to_string(),
177                });
178                if let Some(indices) = structs_by_unit.get(&target_unit) {
179                    for &idx in indices {
180                        if remaining.starts_with(&struct_entries[idx].rel_path) {
181                            struct_entries[idx]
182                                .structure
183                                .referenced_by
184                                .push(pu.id.clone());
185                        }
186                    }
187                }
188            }
189        }
190    }
191
192    let structures = struct_entries.into_iter().map(|e| e.structure).collect();
193
194    Ok(Part {
195        groups,
196        units,
197        edges,
198        structures,
199        unparsed,
200        unresolved,
201    })
202}
203
204fn read_manifest(path: &Path) -> Result<toml::Value, String> {
205    let raw = std::fs::read_to_string(path)
206        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
207    toml::from_str::<toml::Value>(&raw).map_err(|e| format!("cannot parse {}: {e}", path.display()))
208}
209
210fn has_glob_chars(pattern: &str) -> bool {
211    pattern.contains('*') || pattern.contains('?') || pattern.contains('[') || pattern.contains(']')
212}
213
214fn discover_crate_dirs(root: &Path, root_manifest: &toml::Value) -> Result<Vec<PathBuf>, String> {
215    let mut dirs: Vec<PathBuf> = Vec::new();
216    let mut seen: HashSet<PathBuf> = HashSet::new();
217
218    if let Some(workspace) = root_manifest.get("workspace") {
219        let mut excluded: HashSet<PathBuf> = HashSet::new();
220        if let Some(arr) = workspace.get("exclude").and_then(|v| v.as_array()) {
221            for item in arr {
222                if let Some(s) = item.as_str() {
223                    excluded.insert(normalize_rel(Path::new(s)));
224                }
225            }
226        }
227
228        if let Some(arr) = workspace.get("members").and_then(|v| v.as_array()) {
229            for item in arr {
230                let Some(pattern) = item.as_str() else {
231                    continue;
232                };
233                if has_glob_chars(pattern) {
234                    let Some(prefix) = pattern.strip_suffix("/*") else {
235                        return Err(format!("unsupported workspace member pattern: {pattern}"));
236                    };
237                    if prefix.is_empty() || has_glob_chars(prefix) {
238                        return Err(format!("unsupported workspace member pattern: {pattern}"));
239                    }
240                    let prefix_rel = normalize_rel(Path::new(prefix));
241                    let parent_dir = root.join(&prefix_rel);
242                    let entries = std::fs::read_dir(&parent_dir).map_err(|e| {
243                        format!(
244                            "cannot read workspace member directory {}: {e}",
245                            parent_dir.display()
246                        )
247                    })?;
248                    let mut children = Vec::new();
249                    for entry in entries {
250                        let entry = entry.map_err(|e| {
251                            format!(
252                                "cannot read workspace member directory {}: {e}",
253                                parent_dir.display()
254                            )
255                        })?;
256                        let path = entry.path();
257                        if path.is_dir() && path.join("Cargo.toml").is_file() {
258                            let child_rel = normalize_rel(&prefix_rel.join(entry.file_name()));
259                            if !excluded.contains(&child_rel) {
260                                children.push(child_rel);
261                            }
262                        }
263                    }
264                    children.sort();
265                    for child in children {
266                        if seen.insert(child.clone()) {
267                            dirs.push(child);
268                        }
269                    }
270                } else {
271                    let rel = normalize_rel(Path::new(pattern));
272                    if !excluded.contains(&rel) && seen.insert(rel.clone()) {
273                        dirs.push(rel);
274                    }
275                }
276            }
277        }
278    }
279
280    if root_manifest.get("package").is_some() {
281        let root_rel = PathBuf::new();
282        if seen.insert(root_rel.clone()) {
283            dirs.push(root_rel);
284        }
285    }
286
287    if dirs.is_empty() {
288        return Err(format!(
289            "no crates found in {}",
290            root.join("Cargo.toml").display()
291        ));
292    }
293
294    Ok(dirs)
295}
296
297fn collect_group_edges(
298    info: &CrateInfo,
299    workspace_deps: Option<&toml::map::Map<String, toml::Value>>,
300    dir_to_pkg: &HashMap<PathBuf, String>,
301    edges: &mut Vec<Edge>,
302) {
303    let Some(deps) = info.manifest.get("dependencies").and_then(|d| d.as_table()) else {
304        return;
305    };
306    for (dep_name, spec) in deps {
307        let Some(table) = spec.as_table() else {
308            continue;
309        };
310        let target_dir = if let Some(path_str) = table.get("path").and_then(|p| p.as_str()) {
311            normalize_rel_checked(&info.dir_rel.join(path_str))
312        } else if table.get("workspace").and_then(|w| w.as_bool()) == Some(true) {
313            workspace_deps
314                .and_then(|ws| ws.get(dep_name))
315                .and_then(|v| v.as_table())
316                .and_then(|t| t.get("path"))
317                .and_then(|p| p.as_str())
318                .and_then(|p| normalize_rel_checked(Path::new(p)))
319        } else {
320            None
321        };
322
323        if let Some(dir) = target_dir {
324            if let Some(target_pkg) = dir_to_pkg.get(&dir) {
325                if target_pkg != &info.pkg_name {
326                    edges.push(Edge {
327                        from: info.pkg_name.clone(),
328                        to: target_pkg.clone(),
329                        level: "group".to_string(),
330                    });
331                }
332            }
333        }
334    }
335}
336
337fn crate_targets(root: &Path, info: &CrateInfo) -> Result<Vec<(String, bool, PathBuf)>, String> {
338    let mut targets = Vec::new();
339    let crate_abs = if info.dir_rel.as_os_str().is_empty() {
340        root.to_path_buf()
341    } else {
342        root.join(&info.dir_rel)
343    };
344    let manifest_path = crate_abs.join("Cargo.toml");
345
346    let lib_table = info.manifest.get("lib").and_then(|v| v.as_table());
347    let lib_name = lib_table
348        .and_then(|t| t.get("name"))
349        .and_then(|n| n.as_str())
350        .map(|s| s.to_string())
351        .unwrap_or_else(|| info.pkg_name.replace('-', "_"));
352    let lib_path_rel = if let Some(p) = lib_table
353        .and_then(|t| t.get("path"))
354        .and_then(|p| p.as_str())
355    {
356        let rel = normalize_rel(&info.dir_rel.join(p));
357        if !root.join(&rel).is_file() {
358            return Err(format!(
359                "missing [lib] path {} referenced by {}",
360                root.join(&rel).display(),
361                manifest_path.display()
362            ));
363        }
364        Some(rel)
365    } else {
366        let default_rel = normalize_rel(&info.dir_rel.join("src/lib.rs"));
367        if root.join(&default_rel).is_file() {
368            Some(default_rel)
369        } else {
370            None
371        }
372    };
373    if let Some(rel) = lib_path_rel {
374        targets.push((lib_name, true, rel));
375    }
376
377    if let Some(bins) = info.manifest.get("bin").and_then(|v| v.as_array()) {
378        for bin in bins {
379            let Some(table) = bin.as_table() else {
380                continue;
381            };
382            let bin_name = table
383                .get("name")
384                .and_then(|n| n.as_str())
385                .ok_or_else(|| format!("missing [[bin]].name in {}", manifest_path.display()))?;
386            let bin_rel = if let Some(p) = table.get("path").and_then(|p| p.as_str()) {
387                let rel = normalize_rel(&info.dir_rel.join(p));
388                if !root.join(&rel).is_file() {
389                    return Err(format!(
390                        "missing [[bin]] path {} referenced by {}",
391                        root.join(&rel).display(),
392                        manifest_path.display()
393                    ));
394                }
395                Some(rel)
396            } else {
397                let candidates = [
398                    info.dir_rel.join(format!("src/bin/{bin_name}.rs")),
399                    info.dir_rel.join(format!("src/bin/{bin_name}/main.rs")),
400                    info.dir_rel.join("src/main.rs"),
401                ];
402                candidates
403                    .into_iter()
404                    .map(|c| normalize_rel(&c))
405                    .find(|c| root.join(c).is_file())
406            };
407            if let Some(rel) = bin_rel {
408                targets.push((format!("bin:{bin_name}"), false, rel));
409            }
410        }
411    } else {
412        let default_main = normalize_rel(&info.dir_rel.join("src/main.rs"));
413        if root.join(&default_main).is_file() {
414            targets.push((format!("bin:{}", info.pkg_name), false, default_main));
415        }
416    }
417
418    Ok(targets)
419}
420
421fn visit_unit_file(
422    ctx: &mut UnitWalkCtx<'_>,
423    unit_id: &str,
424    is_lib_root: bool,
425    is_root: bool,
426    file_rel: &Path,
427) -> Result<(), String> {
428    let key = (unit_id.to_string(), file_rel.to_path_buf());
429    if !ctx.visited.insert(key) {
430        return Ok(());
431    }
432
433    let file_rel_str = rel_to_string(file_rel);
434    ctx.units.push(Unit {
435        id: unit_id.to_string(),
436        group: ctx.group.to_string(),
437        file: file_rel_str.clone(),
438        lang: "rust".to_string(),
439    });
440
441    let abs_path = ctx.root.join(file_rel);
442    let src = std::fs::read_to_string(&abs_path)
443        .map_err(|e| format!("cannot read {}: {e}", abs_path.display()))?;
444
445    let ast = match syn::parse_file(&src) {
446        Ok(f) => f,
447        Err(e) => {
448            ctx.unparsed.push(Unparsed {
449                file: file_rel_str,
450                reason: e.to_string(),
451            });
452            return Ok(());
453        }
454    };
455
456    let mut child_mods = Vec::new();
457    let mut inline_mods = Vec::new();
458    collect_mod_decls(&ast.items, &mut inline_mods, &mut child_mods);
459
460    ctx.parsed.push(ParsedUnit {
461        id: unit_id.to_string(),
462        root_id: ctx.root_id.to_string(),
463        is_lib_root,
464        file_rel: file_rel_str.clone(),
465        ast,
466    });
467
468    for (enclosing, mod_name, path_attr, line) in child_mods {
469        let child_unit_id = if enclosing.is_empty() {
470            format!("{unit_id}::{mod_name}")
471        } else {
472            format!("{unit_id}::{}::{mod_name}", enclosing.join("::"))
473        };
474        if let Some(child_rel) = resolve_mod_file(
475            ctx.root,
476            file_rel,
477            is_root,
478            &enclosing,
479            &mod_name,
480            path_attr.as_deref(),
481        ) {
482            visit_unit_file(ctx, &child_unit_id, false, false, &child_rel)?;
483        } else {
484            ctx.unresolved.push(Unresolved {
485                file: file_rel_str.clone(),
486                line,
487                reference: format!("mod {mod_name}"),
488            });
489        }
490    }
491
492    Ok(())
493}
494
495type ModDecl = (Vec<String>, String, Option<String>, u32);
496
497fn collect_mod_decls(items: &[Item], inline_mods: &mut Vec<String>, out: &mut Vec<ModDecl>) {
498    for item in items {
499        if is_cfg_test(item_attrs(item)) {
500            continue;
501        }
502        if let Item::Mod(m) = item {
503            if let Some((_, sub_items)) = &m.content {
504                inline_mods.push(m.ident.to_string());
505                collect_mod_decls(sub_items, inline_mods, out);
506                inline_mods.pop();
507            } else {
508                let path_attr = extract_path_attr(&m.attrs);
509                let line = m.ident.span().start().line as u32;
510                out.push((inline_mods.clone(), m.ident.to_string(), path_attr, line));
511            }
512        }
513    }
514}
515
516fn resolve_mod_file(
517    root: &Path,
518    decl_rel: &Path,
519    is_root: bool,
520    enclosing_inline: &[String],
521    mod_name: &str,
522    path_attr: Option<&str>,
523) -> Option<PathBuf> {
524    let decl_dir = decl_rel.parent().unwrap_or_else(|| Path::new(""));
525    if let Some(p) = path_attr {
526        let candidate = normalize_rel(&decl_dir.join(p));
527        return root.join(&candidate).is_file().then_some(candidate);
528    }
529
530    let mut base_dir = if is_root || decl_rel.file_name() == Some(OsStr::new("mod.rs")) {
531        decl_dir.to_path_buf()
532    } else {
533        let stem = decl_rel.file_stem()?;
534        decl_dir.join(stem)
535    };
536    for im in enclosing_inline {
537        base_dir = base_dir.join(im);
538    }
539
540    let file_candidate = normalize_rel(&base_dir.join(format!("{mod_name}.rs")));
541    if root.join(&file_candidate).is_file() {
542        return Some(file_candidate);
543    }
544    let dir_candidate = normalize_rel(&base_dir.join(mod_name).join("mod.rs"));
545    if root.join(&dir_candidate).is_file() {
546        return Some(dir_candidate);
547    }
548    None
549}
550
551fn collect_reexports(
552    parsed_units: &[ParsedUnit],
553    unit_set: &HashSet<String>,
554    lib_roots: &HashSet<String>,
555) -> HashMap<(String, String), ReexportTarget> {
556    let mut map = HashMap::new();
557    for pu in parsed_units {
558        if !pu.is_lib_root {
559            continue;
560        }
561        let inline_mod_names: HashSet<String> = pu
562            .ast
563            .items
564            .iter()
565            .filter_map(|item| {
566                if is_cfg_test(item_attrs(item)) {
567                    return None;
568                }
569                if let Item::Mod(m) = item {
570                    if m.content.is_some() {
571                        return Some(m.ident.to_string());
572                    }
573                }
574                None
575            })
576            .collect();
577
578        for item in &pu.ast.items {
579            if is_cfg_test(item_attrs(item)) {
580                continue;
581            }
582            let Item::Use(u) = item else {
583                continue;
584            };
585            if !matches!(u.vis, Visibility::Public(_)) {
586                continue;
587            }
588            let mut entries = Vec::new();
589            let mut prefix = Vec::new();
590            expand_use_tree_for_reexport(&u.tree, &mut prefix, &mut entries);
591            for (raw_segs, exported_name) in entries {
592                if raw_segs.is_empty() {
593                    continue;
594                }
595                let resolved = match raw_segs[0].as_str() {
596                    "crate" | "self" => {
597                        let mut v = Vec::with_capacity(raw_segs.len());
598                        v.push(pu.id.clone());
599                        v.extend_from_slice(&raw_segs[1..]);
600                        v
601                    }
602                    first if lib_roots.contains(first) => raw_segs,
603                    first => {
604                        let candidate_child = format!("{}::{first}", pu.id);
605                        if unit_set.contains(&candidate_child) || inline_mod_names.contains(first) {
606                            let mut v = Vec::with_capacity(raw_segs.len() + 1);
607                            v.push(pu.id.clone());
608                            v.extend(raw_segs);
609                            v
610                        } else {
611                            continue;
612                        }
613                    }
614                };
615                if let Some((target_unit, extra)) = longest_unit_prefix(&resolved, unit_set) {
616                    if target_unit != pu.id || !extra.is_empty() {
617                        map.insert(
618                            (pu.id.clone(), exported_name),
619                            ReexportTarget {
620                                unit: target_unit,
621                                extra,
622                            },
623                        );
624                    }
625                }
626            }
627        }
628    }
629    map
630}
631
632fn expand_use_tree_for_reexport(
633    tree: &UseTree,
634    prefix: &mut Vec<String>,
635    out: &mut Vec<(Vec<String>, String)>,
636) {
637    match tree {
638        UseTree::Path(p) => {
639            prefix.push(p.ident.to_string());
640            expand_use_tree_for_reexport(&p.tree, prefix, out);
641            prefix.pop();
642        }
643        UseTree::Name(n) => {
644            let name = n.ident.to_string();
645            if name == "self" {
646                if let Some(last) = prefix.last().cloned() {
647                    out.push((prefix.clone(), last));
648                }
649            } else {
650                prefix.push(name.clone());
651                out.push((prefix.clone(), name));
652                prefix.pop();
653            }
654        }
655        UseTree::Rename(r) => {
656            let orig = r.ident.to_string();
657            let alias = r.rename.to_string();
658            if orig == "self" {
659                if !prefix.is_empty() {
660                    out.push((prefix.clone(), alias));
661                }
662            } else {
663                prefix.push(orig);
664                out.push((prefix.clone(), alias));
665                prefix.pop();
666            }
667        }
668        UseTree::Glob(_) => {}
669        UseTree::Group(g) => {
670            for item in &g.items {
671                expand_use_tree_for_reexport(item, prefix, out);
672            }
673        }
674    }
675}
676
677fn expand_use_tree_paths(tree: &UseTree, prefix: &mut Vec<String>, out: &mut Vec<Vec<String>>) {
678    match tree {
679        UseTree::Path(p) => {
680            prefix.push(p.ident.to_string());
681            expand_use_tree_paths(&p.tree, prefix, out);
682            prefix.pop();
683        }
684        UseTree::Name(n) => {
685            let name = n.ident.to_string();
686            if name == "self" {
687                if !prefix.is_empty() {
688                    out.push(prefix.clone());
689                }
690            } else {
691                prefix.push(name);
692                out.push(prefix.clone());
693                prefix.pop();
694            }
695        }
696        UseTree::Rename(r) => {
697            let orig = r.ident.to_string();
698            if orig == "self" {
699                if !prefix.is_empty() {
700                    out.push(prefix.clone());
701                }
702            } else {
703                prefix.push(orig);
704                out.push(prefix.clone());
705                prefix.pop();
706            }
707        }
708        UseTree::Glob(_) => {
709            if !prefix.is_empty() {
710                out.push(prefix.clone());
711            }
712        }
713        UseTree::Group(g) => {
714            for item in &g.items {
715                expand_use_tree_paths(item, prefix, out);
716            }
717        }
718    }
719}
720
721#[derive(Default)]
722struct PathCollector {
723    inline_mods: Vec<String>,
724    paths: Vec<(Vec<String>, Vec<String>)>,
725}
726
727impl<'ast> Visit<'ast> for PathCollector {
728    fn visit_attribute(&mut self, _attr: &'ast Attribute) {}
729
730    fn visit_item(&mut self, item: &'ast Item) {
731        if is_cfg_test(item_attrs(item)) {
732            return;
733        }
734        match item {
735            Item::Mod(m) => {
736                if let Some((_, sub_items)) = &m.content {
737                    self.inline_mods.push(m.ident.to_string());
738                    for sub in sub_items {
739                        self.visit_item(sub);
740                    }
741                    self.inline_mods.pop();
742                }
743            }
744            Item::Use(u) => {
745                let mut prefix = Vec::new();
746                let mut expanded = Vec::new();
747                expand_use_tree_paths(&u.tree, &mut prefix, &mut expanded);
748                for segs in expanded {
749                    self.paths.push((segs, self.inline_mods.clone()));
750                }
751            }
752            other => syn::visit::visit_item(self, other),
753        }
754    }
755
756    fn visit_impl_item(&mut self, i: &'ast ImplItem) {
757        if is_cfg_test(impl_item_attrs(i)) {
758            return;
759        }
760        syn::visit::visit_impl_item(self, i);
761    }
762
763    fn visit_trait_item(&mut self, i: &'ast TraitItem) {
764        if is_cfg_test(trait_item_attrs(i)) {
765            return;
766        }
767        syn::visit::visit_trait_item(self, i);
768    }
769
770    fn visit_path(&mut self, path: &'ast syn::Path) {
771        let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
772        if !segs.is_empty() {
773            self.paths.push((segs, self.inline_mods.clone()));
774        }
775        syn::visit::visit_path(self, path);
776    }
777}
778
779fn resolve_counted_path(
780    raw_segs: &[String],
781    unit_segs: &[String],
782    inline_mods: &[String],
783    root_id: &str,
784    lib_roots: &HashSet<String>,
785) -> Option<Vec<String>> {
786    let first = raw_segs.first()?;
787    match first.as_str() {
788        "crate" => {
789            let mut v = Vec::with_capacity(raw_segs.len());
790            v.push(root_id.to_string());
791            v.extend_from_slice(&raw_segs[1..]);
792            Some(v)
793        }
794        "self" | "super" => {
795            if first == "self" && raw_segs.len() == 1 {
796                return None;
797            }
798            let mut base = Vec::with_capacity(unit_segs.len() + inline_mods.len());
799            base.extend_from_slice(unit_segs);
800            base.extend_from_slice(inline_mods);
801            let mut idx = 0;
802            while idx < raw_segs.len() {
803                match raw_segs[idx].as_str() {
804                    "self" => idx += 1,
805                    "super" => {
806                        if base.len() <= 1 {
807                            return None;
808                        }
809                        base.pop();
810                        idx += 1;
811                    }
812                    _ => break,
813                }
814            }
815            base.extend_from_slice(&raw_segs[idx..]);
816            Some(base)
817        }
818        name if lib_roots.contains(name) => Some(raw_segs.to_vec()),
819        _ => None,
820    }
821}
822
823fn longest_unit_prefix(
824    resolved: &[String],
825    unit_set: &HashSet<String>,
826) -> Option<(String, Vec<String>)> {
827    for len in (1..=resolved.len()).rev() {
828        let candidate = resolved[..len].join("::");
829        if unit_set.contains(&candidate) {
830            return Some((candidate, resolved[len..].to_vec()));
831        }
832    }
833    None
834}
835
836fn collect_structures(
837    items: &[Item],
838    unit_id: &str,
839    file_rel: &str,
840    inline_mods: &mut Vec<String>,
841    out: &mut Vec<StructEntry>,
842    by_unit: &mut HashMap<String, Vec<usize>>,
843) {
844    for item in items {
845        if is_cfg_test(item_attrs(item)) {
846            continue;
847        }
848        match item {
849            Item::Mod(m) => {
850                if let Some((_, sub_items)) = &m.content {
851                    inline_mods.push(m.ident.to_string());
852                    collect_structures(sub_items, unit_id, file_rel, inline_mods, out, by_unit);
853                    inline_mods.pop();
854                }
855            }
856            Item::Struct(s) => {
857                let name = s.ident.to_string();
858                let id = structure_id(unit_id, inline_mods, &name);
859                let line = s.ident.span().start().line as u32;
860                let serialisable = has_serde_derive(&s.attrs);
861                let fields = extract_struct_fields(&s.fields);
862                let mut rel_path = inline_mods.clone();
863                rel_path.push(name.clone());
864                let idx = out.len();
865                out.push(StructEntry {
866                    structure: Structure {
867                        id,
868                        name,
869                        kind: "struct".to_string(),
870                        unit: unit_id.to_string(),
871                        file: file_rel.to_string(),
872                        line,
873                        serialisable,
874                        fields,
875                        referenced_by: Vec::new(),
876                    },
877                    rel_path,
878                });
879                by_unit.entry(unit_id.to_string()).or_default().push(idx);
880            }
881            Item::Enum(e) => {
882                let name = e.ident.to_string();
883                let id = structure_id(unit_id, inline_mods, &name);
884                let line = e.ident.span().start().line as u32;
885                let serialisable = has_serde_derive(&e.attrs);
886                let fields = e
887                    .variants
888                    .iter()
889                    .filter(|v| !is_cfg_test(&v.attrs))
890                    .map(|v| Field {
891                        name: v.ident.to_string(),
892                        ty: format_variant_fields(&v.fields),
893                    })
894                    .collect();
895                let mut rel_path = inline_mods.clone();
896                rel_path.push(name.clone());
897                let idx = out.len();
898                out.push(StructEntry {
899                    structure: Structure {
900                        id,
901                        name,
902                        kind: "enum".to_string(),
903                        unit: unit_id.to_string(),
904                        file: file_rel.to_string(),
905                        line,
906                        serialisable,
907                        fields,
908                        referenced_by: Vec::new(),
909                    },
910                    rel_path,
911                });
912                by_unit.entry(unit_id.to_string()).or_default().push(idx);
913            }
914            _ => {}
915        }
916    }
917}
918
919fn structure_id(unit_id: &str, inline_mods: &[String], name: &str) -> String {
920    if inline_mods.is_empty() {
921        format!("{unit_id}::{name}")
922    } else {
923        format!("{unit_id}::{}::{name}", inline_mods.join("::"))
924    }
925}
926
927fn has_serde_derive(attrs: &[Attribute]) -> bool {
928    for attr in attrs {
929        if !attr.path().is_ident("derive") {
930            continue;
931        }
932        let Ok(paths) = attr.parse_args_with(Punctuated::<syn::Path, Token![,]>::parse_terminated)
933        else {
934            continue;
935        };
936        for path in paths {
937            if let Some(last) = path.segments.last() {
938                if last.ident == "Serialize" || last.ident == "Deserialize" {
939                    return true;
940                }
941            }
942        }
943    }
944    false
945}
946
947fn extract_struct_fields(fields: &syn::Fields) -> Vec<Field> {
948    match fields {
949        syn::Fields::Named(named) => named
950            .named
951            .iter()
952            .filter(|f| !is_cfg_test(&f.attrs))
953            .map(|f| Field {
954                name: f.ident.as_ref().map(|i| i.to_string()).unwrap_or_default(),
955                ty: format_type(&f.ty),
956            })
957            .collect(),
958        syn::Fields::Unnamed(unnamed) => unnamed
959            .unnamed
960            .iter()
961            .filter(|f| !is_cfg_test(&f.attrs))
962            .enumerate()
963            .map(|(i, f)| Field {
964                name: i.to_string(),
965                ty: format_type(&f.ty),
966            })
967            .collect(),
968        syn::Fields::Unit => Vec::new(),
969    }
970}
971
972fn format_variant_fields(fields: &syn::Fields) -> String {
973    match fields {
974        syn::Fields::Unit => String::new(),
975        syn::Fields::Unnamed(u) => {
976            let parts: Vec<String> = u.unnamed.iter().map(|f| format_type(&f.ty)).collect();
977            format!("({})", parts.join(", "))
978        }
979        syn::Fields::Named(n) => {
980            let parts: Vec<String> = n
981                .named
982                .iter()
983                .map(|f| {
984                    let name = f.ident.as_ref().map(|i| i.to_string()).unwrap_or_default();
985                    format!("{name}: {}", format_type(&f.ty))
986                })
987                .collect();
988            format!("{{{}}}", parts.join(", "))
989        }
990    }
991}
992
993fn format_type(ty: &Type) -> String {
994    match ty {
995        Type::Path(tp) => {
996            if let Some(qself) = &tp.qself {
997                let self_ty = format_type(&qself.ty);
998                if qself.position == 0 {
999                    format!("<{self_ty}>::{}", format_path(&tp.path))
1000                } else {
1001                    let segs: Vec<String> = tp.path.segments.iter().map(format_segment).collect();
1002                    let prefix = if tp.path.leading_colon.is_some() {
1003                        "::"
1004                    } else {
1005                        ""
1006                    };
1007                    let trait_part = segs[..qself.position].join("::");
1008                    let rest = segs[qself.position..].join("::");
1009                    format!("<{self_ty} as {prefix}{trait_part}>::{rest}")
1010                }
1011            } else {
1012                format_path(&tp.path)
1013            }
1014        }
1015        Type::Reference(tr) => {
1016            let mut s = String::from("&");
1017            if let Some(lt) = &tr.lifetime {
1018                s.push('\'');
1019                s.push_str(&lt.ident.to_string());
1020                s.push(' ');
1021            }
1022            if tr.mutability.is_some() {
1023                s.push_str("mut ");
1024            }
1025            s.push_str(&format_type(&tr.elem));
1026            s
1027        }
1028        Type::Slice(ts) => format!("[{}]", format_type(&ts.elem)),
1029        Type::Array(ta) => format!("[{}; {}]", format_type(&ta.elem), format_tokens(&ta.len)),
1030        Type::Tuple(tt) => {
1031            if tt.elems.is_empty() {
1032                "()".to_string()
1033            } else if tt.elems.len() == 1 {
1034                format!("({},)", format_type(&tt.elems[0]))
1035            } else {
1036                let parts: Vec<String> = tt.elems.iter().map(format_type).collect();
1037                format!("({})", parts.join(", "))
1038            }
1039        }
1040        Type::Ptr(tp) => {
1041            let qual = if tp.const_token.is_some() {
1042                "const"
1043            } else {
1044                "mut"
1045            };
1046            format!("*{qual} {}", format_type(&tp.elem))
1047        }
1048        Type::BareFn(bf) => {
1049            let mut s = String::new();
1050            if let Some(lt) = &bf.lifetimes {
1051                s.push_str(&format_bound_lifetimes(lt));
1052                s.push(' ');
1053            }
1054            if bf.unsafety.is_some() {
1055                s.push_str("unsafe ");
1056            }
1057            if let Some(abi) = &bf.abi {
1058                s.push_str("extern ");
1059                if let Some(name) = &abi.name {
1060                    s.push_str(&format_tokens(name));
1061                    s.push(' ');
1062                }
1063            }
1064            s.push_str("fn(");
1065            let mut inputs: Vec<String> = bf
1066                .inputs
1067                .iter()
1068                .map(|arg| {
1069                    if let Some((name, _)) = &arg.name {
1070                        format!("{name}: {}", format_type(&arg.ty))
1071                    } else {
1072                        format_type(&arg.ty)
1073                    }
1074                })
1075                .collect();
1076            if bf.variadic.is_some() {
1077                inputs.push("...".to_string());
1078            }
1079            s.push_str(&inputs.join(", "));
1080            s.push(')');
1081            if let ReturnType::Type(_, ret) = &bf.output {
1082                s.push_str(" -> ");
1083                s.push_str(&format_type(ret));
1084            }
1085            s
1086        }
1087        Type::Never(_) => "!".to_string(),
1088        Type::Infer(_) => "_".to_string(),
1089        Type::Paren(tp) => format!("({})", format_type(&tp.elem)),
1090        Type::Group(tg) => format_type(&tg.elem),
1091        Type::TraitObject(to) => {
1092            let prefix = if to.dyn_token.is_some() { "dyn " } else { "" };
1093            format!("{prefix}{}", format_bounds(&to.bounds))
1094        }
1095        Type::ImplTrait(it) => format!("impl {}", format_bounds(&it.bounds)),
1096        other => format_tokens(other),
1097    }
1098}
1099
1100fn format_path(path: &syn::Path) -> String {
1101    let prefix = if path.leading_colon.is_some() {
1102        "::"
1103    } else {
1104        ""
1105    };
1106    let segs: Vec<String> = path.segments.iter().map(format_segment).collect();
1107    format!("{prefix}{}", segs.join("::"))
1108}
1109
1110fn format_segment(seg: &syn::PathSegment) -> String {
1111    let mut s = seg.ident.to_string();
1112    match &seg.arguments {
1113        PathArguments::None => {}
1114        PathArguments::AngleBracketed(ab) => {
1115            let args: Vec<String> = ab.args.iter().map(format_generic_arg).collect();
1116            s.push('<');
1117            s.push_str(&args.join(", "));
1118            s.push('>');
1119        }
1120        PathArguments::Parenthesized(p) => {
1121            let inputs: Vec<String> = p.inputs.iter().map(format_type).collect();
1122            s.push('(');
1123            s.push_str(&inputs.join(", "));
1124            s.push(')');
1125            if let ReturnType::Type(_, ret) = &p.output {
1126                s.push_str(" -> ");
1127                s.push_str(&format_type(ret));
1128            }
1129        }
1130    }
1131    s
1132}
1133
1134fn format_generic_arg(arg: &GenericArgument) -> String {
1135    match arg {
1136        GenericArgument::Lifetime(lt) => format!("'{}", lt.ident),
1137        GenericArgument::Type(ty) => format_type(ty),
1138        GenericArgument::Const(expr) => format_tokens(expr),
1139        GenericArgument::AssocType(at) => {
1140            let generics = at
1141                .generics
1142                .as_ref()
1143                .map(|g| {
1144                    let args: Vec<String> = g.args.iter().map(format_generic_arg).collect();
1145                    format!("<{}>", args.join(", "))
1146                })
1147                .unwrap_or_default();
1148            format!("{}{generics} = {}", at.ident, format_type(&at.ty))
1149        }
1150        GenericArgument::AssocConst(ac) => {
1151            let generics = ac
1152                .generics
1153                .as_ref()
1154                .map(|g| {
1155                    let args: Vec<String> = g.args.iter().map(format_generic_arg).collect();
1156                    format!("<{}>", args.join(", "))
1157                })
1158                .unwrap_or_default();
1159            format!("{}{generics} = {}", ac.ident, format_tokens(&ac.value))
1160        }
1161        GenericArgument::Constraint(c) => {
1162            let generics = c
1163                .generics
1164                .as_ref()
1165                .map(|g| {
1166                    let args: Vec<String> = g.args.iter().map(format_generic_arg).collect();
1167                    format!("<{}>", args.join(", "))
1168                })
1169                .unwrap_or_default();
1170            format!("{}{generics}: {}", c.ident, format_bounds(&c.bounds))
1171        }
1172        other => format_tokens(other),
1173    }
1174}
1175
1176fn format_bounds(bounds: &Punctuated<TypeParamBound, Token![+]>) -> String {
1177    let parts: Vec<String> = bounds
1178        .iter()
1179        .map(|b| match b {
1180            TypeParamBound::Trait(tb) => {
1181                let mut s = String::new();
1182                if matches!(tb.modifier, syn::TraitBoundModifier::Maybe(_)) {
1183                    s.push('?');
1184                }
1185                if let Some(lt) = &tb.lifetimes {
1186                    s.push_str(&format_bound_lifetimes(lt));
1187                    s.push(' ');
1188                }
1189                s.push_str(&format_path(&tb.path));
1190                if tb.paren_token.is_some() {
1191                    format!("({s})")
1192                } else {
1193                    s
1194                }
1195            }
1196            TypeParamBound::Lifetime(lt) => format!("'{}", lt.ident),
1197            other => format_tokens(other),
1198        })
1199        .collect();
1200    parts.join(" + ")
1201}
1202
1203fn format_bound_lifetimes(lt: &syn::BoundLifetimes) -> String {
1204    let params: Vec<String> = lt
1205        .lifetimes
1206        .iter()
1207        .map(|p| match p {
1208            syn::GenericParam::Lifetime(l) => format!("'{}", l.lifetime.ident),
1209            other => format_tokens(other),
1210        })
1211        .collect();
1212    format!("for<{}>", params.join(", "))
1213}
1214
1215fn format_tokens<T: ToTokens>(t: &T) -> String {
1216    t.to_token_stream().to_string()
1217}
1218
1219fn consume_nested_value(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
1220    if meta.input.peek(Token![=]) {
1221        let _: syn::Expr = meta.value()?.parse()?;
1222    } else if meta.input.peek(syn::token::Paren) {
1223        let content;
1224        syn::parenthesized!(content in meta.input);
1225        let _: proc_macro2::TokenStream = content.parse()?;
1226    }
1227    Ok(())
1228}
1229
1230fn is_cfg_test(attrs: &[Attribute]) -> bool {
1231    for attr in attrs {
1232        if !attr.path().is_ident("cfg") {
1233            continue;
1234        }
1235        let mut found = false;
1236        let _ = attr.parse_nested_meta(|meta| {
1237            if meta.path.is_ident("test")
1238                && !meta.input.peek(Token![=])
1239                && !meta.input.peek(syn::token::Paren)
1240            {
1241                found = true;
1242                return Ok(());
1243            }
1244            if meta.path.is_ident("all") && meta.input.peek(syn::token::Paren) {
1245                let _ = meta.parse_nested_meta(|inner| {
1246                    if inner.path.is_ident("test")
1247                        && !inner.input.peek(Token![=])
1248                        && !inner.input.peek(syn::token::Paren)
1249                    {
1250                        found = true;
1251                        return Ok(());
1252                    }
1253                    consume_nested_value(&inner)
1254                });
1255                return Ok(());
1256            }
1257            consume_nested_value(&meta)
1258        });
1259        if found {
1260            return true;
1261        }
1262    }
1263    false
1264}
1265
1266fn extract_path_attr(attrs: &[Attribute]) -> Option<String> {
1267    for attr in attrs {
1268        if !attr.path().is_ident("path") {
1269            continue;
1270        }
1271        if let Meta::NameValue(nv) = &attr.meta {
1272            if let syn::Expr::Lit(expr_lit) = &nv.value {
1273                if let syn::Lit::Str(lit_str) = &expr_lit.lit {
1274                    return Some(lit_str.value());
1275                }
1276            }
1277        }
1278    }
1279    None
1280}
1281
1282fn item_attrs(item: &Item) -> &[Attribute] {
1283    match item {
1284        Item::Const(i) => &i.attrs,
1285        Item::Enum(i) => &i.attrs,
1286        Item::ExternCrate(i) => &i.attrs,
1287        Item::Fn(i) => &i.attrs,
1288        Item::ForeignMod(i) => &i.attrs,
1289        Item::Impl(i) => &i.attrs,
1290        Item::Macro(i) => &i.attrs,
1291        Item::Mod(i) => &i.attrs,
1292        Item::Static(i) => &i.attrs,
1293        Item::Struct(i) => &i.attrs,
1294        Item::Trait(i) => &i.attrs,
1295        Item::TraitAlias(i) => &i.attrs,
1296        Item::Type(i) => &i.attrs,
1297        Item::Union(i) => &i.attrs,
1298        Item::Use(i) => &i.attrs,
1299        _ => &[],
1300    }
1301}
1302
1303fn impl_item_attrs(item: &ImplItem) -> &[Attribute] {
1304    match item {
1305        ImplItem::Const(i) => &i.attrs,
1306        ImplItem::Fn(i) => &i.attrs,
1307        ImplItem::Type(i) => &i.attrs,
1308        ImplItem::Macro(i) => &i.attrs,
1309        _ => &[],
1310    }
1311}
1312
1313fn trait_item_attrs(item: &TraitItem) -> &[Attribute] {
1314    match item {
1315        TraitItem::Const(i) => &i.attrs,
1316        TraitItem::Fn(i) => &i.attrs,
1317        TraitItem::Type(i) => &i.attrs,
1318        TraitItem::Macro(i) => &i.attrs,
1319        _ => &[],
1320    }
1321}
1322
1323fn normalize_rel_checked(path: &Path) -> Option<PathBuf> {
1324    let mut parts: Vec<std::ffi::OsString> = Vec::new();
1325    for comp in path.components() {
1326        match comp {
1327            Component::CurDir => {}
1328            Component::ParentDir => {
1329                parts.pop()?;
1330            }
1331            Component::Normal(s) => parts.push(s.to_os_string()),
1332            Component::RootDir | Component::Prefix(_) => return None,
1333        }
1334    }
1335    let mut out = PathBuf::new();
1336    for p in parts {
1337        out.push(p);
1338    }
1339    Some(out)
1340}
1341
1342fn normalize_rel(path: &Path) -> PathBuf {
1343    let mut parts: Vec<std::ffi::OsString> = Vec::new();
1344    for comp in path.components() {
1345        match comp {
1346            Component::CurDir => {}
1347            Component::ParentDir => {
1348                parts.pop();
1349            }
1350            Component::Normal(s) => parts.push(s.to_os_string()),
1351            Component::RootDir | Component::Prefix(_) => {}
1352        }
1353    }
1354    let mut out = PathBuf::new();
1355    for p in parts {
1356        out.push(p);
1357    }
1358    out
1359}
1360
1361fn rel_to_string(rel: &Path) -> String {
1362    let parts: Vec<String> = rel
1363        .components()
1364        .filter_map(|c| match c {
1365            Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
1366            _ => None,
1367        })
1368        .collect();
1369    if parts.is_empty() {
1370        ".".to_string()
1371    } else {
1372        parts.join("/")
1373    }
1374}