Skip to main content

ridx_format/audit/
sysroot.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Targeted audit of sysroot index shards (`core`, `alloc`, `std`).
12
13use std::fs;
14
15use crate::format::{fnv1a_64, DefKind};
16use crate::reader::IndexReader;
17use crate::workspace::WorkspaceIndex;
18
19use super::{audit_workspace_items, def_kind_slot, is_primitive_owner, is_sysroot_shard, AuditScope, GlobalKindSets, ItemAuditReport};
20
21/// Per-shard statistics for a sysroot `.ridx` shard (`core`, `alloc`, `std`).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct SysrootShardSummary {
24    pub crate_name: String,
25    pub file_size: u64,
26    pub string_pool_bytes: u64,
27    pub defs_count: u32,
28    pub refs_count: u32,
29    pub types_count: u32,
30    pub notes_count: u32,
31    pub derefs_count: u32,
32    pub owners_count: u32,
33    pub fields_count: u64,
34    pub variants_count: u64,
35    pub ty_params_count: u64,
36    pub impls_count: u64,
37    pub reexports_count: u64,
38}
39
40/// Detailed probe of a canonical owner/type in the sysroot index.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub struct SysrootOwnerProbe {
43    pub target: String,
44    pub def_present: bool,
45    pub def_kind: Option<DefKind>,
46    pub def_has_sig: bool,
47    pub reexport_aliases: u32,
48    pub owned_assoc_fns: u32,
49    pub assoc_fns_with_self: u32,
50    pub assoc_fns_unqualified_ret: u32,
51    pub owned_fields: u32,
52    pub owned_variants: u32,
53    pub variants_with_sig: u32,
54    pub owned_assoc_tys: u32,
55    pub assoc_tys_with_sig: u32,
56    pub owned_ty_params: u32,
57    pub actual_deref_targets: Vec<String>,
58    pub trait_impl_targets: u32,
59    pub supertrait_targets: u32,
60    pub sample_sigs: Vec<(String, String)>,
61}
62
63/// Summary across `core::iter::adapters::*` structs in sysroot.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct IteratorAdaptersAudit {
66    pub adapter_structs: u32,
67    pub adapters_with_iterator_edge: u32,
68    pub adapters_with_item_assoc_ty: u32,
69    pub adapters_with_ty_params: u32,
70    pub total_inherent_assoc_fns: u32,
71    pub adapter_names: Vec<String>,
72}
73
74/// Full sysroot audit report.
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
76pub struct SysrootAuditReport {
77    pub shards: Vec<SysrootShardSummary>,
78    pub items: ItemAuditReport,
79    pub probes: Vec<SysrootOwnerProbe>,
80    pub iter_adapters: IteratorAdaptersAudit,
81}
82
83/// Default canonical targets audited for sysroot (`0.2`).
84pub const DEFAULT_SYSROOT_TARGETS: &[&str] = &[
85    "alloc::vec::Vec",
86    "core::option::Option",
87    "core::result::Result",
88    "std::io::error::Result",
89    "alloc::string::String",
90    "core::iter::traits::iterator::Iterator",
91    "slice",
92    "core::slice::iter::Iter",
93    "str",
94    "core::ops::range::Range",
95];
96
97fn has_unqualified_adt_return(sig: &str) -> bool {
98    let Some((_, ret)) = sig.split_once("->") else {
99        return false;
100    };
101    let ret = ret.trim().trim_start_matches('&').trim_start_matches("mut ").trim();
102    let head: String = ret.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ':').collect();
103    if head.is_empty() || head.contains("::") || head == "Self" || head.len() == 1 || is_primitive_owner(&head) {
104        return false;
105    }
106    head.as_bytes()[0].is_ascii_uppercase()
107}
108
109/// Audits attached sysroot shards in `ws` (or all shards if `ws` was opened directly on a sysroot directory).
110pub fn audit_sysroot(ws: &WorkspaceIndex, targets: &[&str]) -> SysrootAuditReport {
111    let any_marked_sys = (0..ws.readers().len()).any(|i| is_sysroot_shard(ws, i));
112    let scope = if any_marked_sys { AuditScope::SysrootOnly } else { AuditScope::All };
113    let items = audit_workspace_items(ws, scope);
114
115    let mut sets = GlobalKindSets::default();
116    let mut sys_indices = Vec::new();
117    for (idx, reader) in ws.readers().iter().enumerate() {
118        sets.record_reader(reader);
119        if !any_marked_sys || is_sysroot_shard(ws, idx) {
120            sys_indices.push(idx);
121        }
122    }
123
124    let mut shards = Vec::with_capacity(sys_indices.len());
125    for &idx in &sys_indices {
126        let reader = &ws.readers()[idx];
127        let h = reader.header();
128        let file_size = ws.paths().get(idx).and_then(|p| fs::metadata(p).ok()).map_or(0, |m| m.len());
129        let single = super::audit_reader_items(reader);
130        shards.push(SysrootShardSummary {
131            crate_name: reader.crate_name().to_string(),
132            file_size,
133            string_pool_bytes: h.string_pool_len,
134            defs_count: h.defs_count,
135            refs_count: h.refs_count,
136            types_count: h.types_count,
137            notes_count: h.notes_count,
138            derefs_count: h.derefs_count,
139            owners_count: h.defs_by_owner_count,
140            fields_count: single.by_kind[def_kind_slot(DefKind::Field)].total,
141            variants_count: single.by_kind[def_kind_slot(DefKind::Variant)].total,
142            ty_params_count: single.by_kind[def_kind_slot(DefKind::TyParam)].total,
143            impls_count: single.by_kind[def_kind_slot(DefKind::Impl)].total,
144            reexports_count: single.reexports.flag_reexport_defs,
145        });
146    }
147
148    let sys_readers: Vec<&IndexReader<_>> = sys_indices.iter().map(|&i| &ws.readers()[i]).collect();
149    let probes = targets.iter().map(|&t| probe_owner(&sys_readers, &sets, t)).collect();
150    let iter_adapters = audit_iterator_adapters(&sys_readers, &sets);
151
152    SysrootAuditReport { shards, items, probes, iter_adapters }
153}
154
155pub(crate) fn probe_owner<B: AsRef<[u8]>>(readers: &[&IndexReader<B>], sets: &GlobalKindSets, target: &str) -> SysrootOwnerProbe {
156    let mut p = SysrootOwnerProbe { target: target.to_string(), ..Default::default() };
157    let target_hash = fnv1a_64(target.as_bytes());
158    let src_is_trait = sets.traits.contains(&target_hash);
159    let mut methods: Vec<(String, String)> = Vec::new();
160
161    for reader in readers {
162        let defs = reader.definitions();
163        for raw in defs {
164            let d = raw.from_le();
165            let path = reader.get_str(d.path_offset);
166            if raw.is_reexport() {
167                if d.sig_offset != 0 && reader.get_str(d.sig_offset) == target {
168                    p.reexport_aliases += 1;
169                }
170                continue;
171            }
172            if path == target {
173                p.def_present = true;
174                p.def_kind = Some(DefKind::from(d.kind));
175                p.def_has_sig = d.sig_offset != 0;
176            }
177        }
178
179        let owners = reader.defs_by_owner();
180        let from = owners.partition_point(|o| o.hash() < target_hash);
181        for oe in owners[from..].iter().take_while(|o| o.hash() == target_hash) {
182            if reader.get_str(oe.owner_path_offset()) != target {
183                continue;
184            }
185            let Some(raw_def) = defs.get(oe.def_index() as usize) else {
186                continue;
187            };
188            if raw_def.is_reexport() {
189                continue;
190            }
191            let d = raw_def.from_le();
192            match DefKind::from(d.kind) {
193                DefKind::AssocFn => {
194                    p.owned_assoc_fns += 1;
195                    let sig = if d.sig_offset != 0 { reader.get_str(d.sig_offset) } else { "" };
196                    if sig.contains("(&self") || sig.contains("(&mut self") || sig.contains("(self") {
197                        p.assoc_fns_with_self += 1;
198                    }
199                    if has_unqualified_adt_return(sig) {
200                        p.assoc_fns_unqualified_ret += 1;
201                    }
202                    methods.push((reader.get_str(d.name_offset).to_string(), sig.to_string()));
203                }
204                DefKind::Field => p.owned_fields += 1,
205                DefKind::Variant => {
206                    p.owned_variants += 1;
207                    p.variants_with_sig += u32::from(d.sig_offset != 0);
208                }
209                DefKind::AssocTy => {
210                    p.owned_assoc_tys += 1;
211                    p.assoc_tys_with_sig += u32::from(d.sig_offset != 0);
212                }
213                DefKind::TyParam => p.owned_ty_params += 1,
214                _ => {}
215            }
216        }
217
218        let derefs = reader.deref_entries();
219        let d_from = derefs.partition_point(|e| e.source_type_hash() < target_hash);
220        for de in derefs[d_from..].iter().take_while(|e| e.source_type_hash() == target_hash) {
221            if reader.get_str(de.source_type_offset()) != target {
222                continue;
223            }
224            let tgt = reader.get_str(de.target_type_offset());
225            let tgt_h = fnv1a_64(tgt.as_bytes());
226            if sets.traits.contains(&tgt_h) {
227                if src_is_trait {
228                    p.supertrait_targets += 1;
229                } else {
230                    p.trait_impl_targets += 1;
231                }
232            } else if !p.actual_deref_targets.iter().any(|x| x == tgt) {
233                p.actual_deref_targets.push(tgt.to_string());
234            }
235        }
236    }
237
238    methods.sort_by(|a, b| a.0.cmp(&b.0));
239    methods.dedup_by(|a, b| a.0 == b.0);
240    p.sample_sigs = methods.into_iter().take(4).collect();
241    p
242}
243
244fn audit_iterator_adapters<B: AsRef<[u8]>>(readers: &[&IndexReader<B>], sets: &GlobalKindSets) -> IteratorAdaptersAudit {
245    const ITER_TRAIT: &str = "core::iter::traits::iterator::Iterator";
246    let mut adapter_paths: Vec<(String, String)> = Vec::new();
247    for reader in readers {
248        for raw in reader.definitions() {
249            if raw.is_reexport() {
250                continue;
251            }
252            let d = raw.from_le();
253            if DefKind::from(d.kind) != DefKind::Struct {
254                continue;
255            }
256            let path = reader.get_str(d.path_offset);
257            if path.starts_with("core::iter::adapters::") {
258                adapter_paths.push((reader.get_str(d.name_offset).to_string(), path.to_string()));
259            }
260        }
261    }
262    adapter_paths.sort_by(|a, b| a.1.cmp(&b.1));
263    adapter_paths.dedup_by(|a, b| a.1 == b.1);
264
265    let iter_hash = fnv1a_64(ITER_TRAIT.as_bytes());
266    let mut out = IteratorAdaptersAudit { adapter_structs: adapter_paths.len() as u32, ..Default::default() };
267
268    for (name, path) in adapter_paths {
269        let probe = probe_owner(readers, sets, &path);
270        out.total_inherent_assoc_fns += probe.owned_assoc_fns;
271        out.adapters_with_item_assoc_ty += u32::from(probe.owned_assoc_tys > 0);
272        out.adapters_with_ty_params += u32::from(probe.owned_ty_params > 0);
273
274        let path_h = fnv1a_64(path.as_bytes());
275        let mut impls_iter = false;
276        for reader in readers {
277            let derefs = reader.deref_entries();
278            let from = derefs.partition_point(|e| e.source_type_hash() < path_h);
279            for de in derefs[from..].iter().take_while(|e| e.source_type_hash() == path_h) {
280                let tgt = reader.get_str(de.target_type_offset());
281                if fnv1a_64(tgt.as_bytes()) == iter_hash && tgt == ITER_TRAIT {
282                    impls_iter = true;
283                    break;
284                }
285            }
286        }
287        out.adapters_with_iterator_edge += u32::from(impls_iter);
288        out.adapter_names.push(name);
289    }
290    out
291}