Skip to main content

ridx_format/reader/
ty_access.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//! Zero-copy `IndexReader` accessors for `notes` (v4+) and `TyArena` (v5+) sections.
12
13use crate::format::{
14    AssocTyEntry, DefTyEntry, FieldEntry, FnSigEntry, GenericOwner, GenericParamEntry, ImplEntry, LangItemEntry, LangItemKind, NoteEntry, SimplifiedSelfKind, TyBoundEntry,
15    TyDefEntry, TyEntry, WherePredEntry,
16};
17use crate::ty_arena::{DefTyView, FieldIter, FieldView, FnSigView, GenericParamIter, ImplIter, ImplView, LangItemIter, LangItemView, TyArenaView, WherePredIter};
18
19use super::IndexReader;
20
21impl<B: AsRef<[u8]>> IndexReader<B> {
22    #[inline]
23    pub(super) fn typed_slice<T>(&self, offset: u64, count: u32) -> &[T] {
24        let count = count as usize;
25        if count == 0 {
26            return &[];
27        }
28        let start = offset as usize;
29        let len = count.saturating_mul(std::mem::size_of::<T>());
30        let bytes = self.bytes();
31        if start.saturating_add(len) > bytes.len() {
32            return &[];
33        }
34        unsafe { std::slice::from_raw_parts(bytes[start..].as_ptr() as *const T, count) }
35    }
36
37    /// Slice of all notes in the index (sorted by span); empty for indexes older than format version 4.
38    #[inline]
39    pub fn notes(&self) -> &[NoteEntry] {
40        let h = self.header();
41        self.typed_slice(h.notes_offset, h.notes_count)
42    }
43
44    /// The text of the `kind` note whose span starts at `(file_id, line, col)`.
45    pub fn note_at(&self, file_id: u32, line: u32, col: u32, kind: u32) -> Option<&str> {
46        let notes = self.notes();
47        let key = (file_id, line, col);
48        let from = notes.partition_point(|n| {
49            let s = n.span();
50            (s.file_id(), s.start_line(), s.start_col()) < key
51        });
52        notes[from..]
53            .iter()
54            .take_while(|n| {
55                let s = n.span();
56                (s.file_id(), s.start_line(), s.start_col()) == key
57            })
58            .find(|n| n.kind() == kind)
59            .map(|n| self.get_str(n.text_offset()))
60    }
61
62    /// Raw slice of `TyDefEntry` records in this shard's `TyArena` (empty for format < v5).
63    #[inline]
64    pub fn ty_defs(&self) -> &[TyDefEntry] {
65        let h = self.header();
66        self.typed_slice(h.ty_defs_offset, h.ty_defs_count)
67    }
68
69    /// Raw slice of `TyEntry` records in this shard's `TyArena` (empty for format < v5).
70    #[inline]
71    pub fn ty_entries(&self) -> &[TyEntry] {
72        let h = self.header();
73        self.typed_slice(h.ty_entries_offset, h.ty_entries_count)
74    }
75
76    /// Raw slice of `TyBoundEntry` records in this shard's `TyArena` (empty for format < v5).
77    #[inline]
78    pub fn ty_bounds(&self) -> &[TyBoundEntry] {
79        let h = self.header();
80        self.typed_slice(h.ty_bounds_offset, h.ty_bounds_count)
81    }
82
83    /// Raw slice of `u32` words in this shard's `TyArena` argument pool (empty for format < v5).
84    #[inline]
85    pub fn ty_args_raw(&self) -> &[u32] {
86        let h = self.header();
87        self.typed_slice(h.ty_args_offset, h.ty_args_count)
88    }
89
90    /// Zero-copy `TyArenaView` over this shard's interned types and string pool.
91    #[inline]
92    pub fn ty_arena(&self) -> TyArenaView<'_> {
93        let h = self.header();
94        let pool_start = h.string_pool_offset as usize;
95        let pool_end = pool_start.saturating_add(h.string_pool_len as usize).min(self.bytes().len());
96        let pool = self.bytes().get(pool_start..pool_end).unwrap_or(&[]);
97        TyArenaView::new(pool, self.ty_defs(), self.ty_entries(), self.ty_bounds(), self.ty_args_raw())
98    }
99
100    /// Raw slice of sorted `FnSigEntry` records in this shard (empty for format < v5).
101    #[inline]
102    pub fn fn_sigs(&self) -> &[FnSigEntry] {
103        let h = self.header();
104        self.typed_slice(h.fn_sigs_offset, h.fn_sigs_count)
105    }
106
107    /// Looks up the structured `FnSigView` for `def_index` in `O(log N)` via binary search.
108    #[inline]
109    pub fn fn_sig_for_def(&self, def_index: u32) -> Option<FnSigView<'_>> {
110        let sigs = self.fn_sigs();
111        let pos = sigs.binary_search_by_key(&def_index, FnSigEntry::def_index).ok()?;
112        Some(FnSigView::new(sigs[pos], self.ty_args_raw()))
113    }
114
115    /// Raw slice of sorted `ImplEntry` records in this shard (empty for format < v5).
116    #[inline]
117    pub fn impls(&self) -> &[ImplEntry] {
118        let h = self.header();
119        self.typed_slice(h.impls_offset, h.impls_count)
120    }
121
122    /// Raw slice of contiguous `AssocTyEntry` bindings in this shard (empty for format < v5).
123    #[inline]
124    pub fn assoc_tys(&self) -> &[AssocTyEntry] {
125        let h = self.header();
126        self.typed_slice(h.assoc_tys_offset, h.assoc_tys_count)
127    }
128
129    /// Decodes the `ImplView` at `impl_index` (`0..impls().len()`).
130    #[inline]
131    pub fn impl_view(&self, impl_index: u32) -> Option<ImplView<'_>> {
132        let raw = *self.impls().get(impl_index as usize)?;
133        Some(ImplView::new(impl_index, raw, self.ty_arena(), self.assoc_tys()))
134    }
135
136    /// Iterates over all `ImplView` headers in this shard.
137    #[inline]
138    pub fn impls_iter(&self) -> ImplIter<'_> {
139        ImplIter::new(0, self.impls(), self.ty_arena(), self.assoc_tys())
140    }
141
142    /// Binary-searches all `ImplEntry` records (both inherent and trait) whose `self_ty` matches `kind`.
143    #[inline]
144    pub fn impls_for_simplified(&self, kind: SimplifiedSelfKind) -> ImplIter<'_> {
145        let all = self.impls();
146        let k = kind as u8;
147        let start = all.partition_point(|e| e.simplified_self < k);
148        let end = start + all[start..].partition_point(|e| e.simplified_self == k);
149        ImplIter::new(start as u32, &all[start..end], self.ty_arena(), self.assoc_tys())
150    }
151
152    /// Binary-searches inherent `impl Self` blocks whose `self_ty` matches `kind`.
153    #[inline]
154    pub fn inherent_impls_for_simplified(&self, kind: SimplifiedSelfKind) -> ImplIter<'_> {
155        self.impls_for_bucket(kind, false)
156    }
157
158    /// Binary-searches `impl Trait for Self` blocks whose `self_ty` matches `kind`.
159    #[inline]
160    pub fn trait_impls_for_simplified(&self, kind: SimplifiedSelfKind) -> ImplIter<'_> {
161        self.impls_for_bucket(kind, true)
162    }
163
164    #[inline]
165    fn impls_for_bucket(&self, kind: SimplifiedSelfKind, want_trait: bool) -> ImplIter<'_> {
166        let all = self.impls();
167        let key = (kind as u8, u8::from(want_trait));
168        let start = all.partition_point(|e| (e.simplified_self, u8::from(e.is_trait())) < key);
169        let end = start + all[start..].partition_point(|e| (e.simplified_self, u8::from(e.is_trait())) == key);
170        ImplIter::new(start as u32, &all[start..end], self.ty_arena(), self.assoc_tys())
171    }
172
173    /// Raw slice of sorted `FieldEntry` records in this shard (empty for format < v5).
174    #[inline]
175    pub fn fields(&self) -> &[FieldEntry] {
176        let h = self.header();
177        self.typed_slice(h.fields_offset, h.fields_count)
178    }
179
180    /// Binary-searches all `FieldEntry` rows belonging to `owner_def_index` (`Struct`, `Union`, or `Variant`).
181    #[inline]
182    pub fn fields_for_owner(&self, owner_def_index: u32) -> FieldIter<'_> {
183        let all = self.fields();
184        let start = all.partition_point(|e| e.owner_def_index() < owner_def_index);
185        let end = start + all[start..].partition_point(|e| e.owner_def_index() == owner_def_index);
186        FieldIter::new(self.ty_arena(), &all[start..end])
187    }
188
189    /// Looks up a specific field `name` (or positional `"0"`, `"1"`) on `owner_def_index`.
190    #[inline]
191    pub fn find_field(&self, owner_def_index: u32, name: &str) -> Option<FieldView<'_>> {
192        self.fields_for_owner(owner_def_index).find(|f| f.name == name)
193    }
194
195    /// Raw slice of sorted `DefTyEntry` records in this shard (empty for format < v5).
196    #[inline]
197    pub fn def_tys(&self) -> &[DefTyEntry] {
198        let h = self.header();
199        self.typed_slice(h.def_tys_offset, h.def_tys_count)
200    }
201
202    /// Looks up the `DefTyView` (`TyAlias` RHS, `Const`/`Static`/`AssocConst` type, or ADT/variant ctor shape)
203    /// for `def_index` in `O(log N)` via binary search.
204    #[inline]
205    pub fn def_ty_for_def(&self, def_index: u32) -> Option<DefTyView> {
206        let all = self.def_tys();
207        let pos = all.binary_search_by_key(&def_index, DefTyEntry::def_index).ok()?;
208        Some(DefTyView::new(all[pos]))
209    }
210
211    /// Raw slice of sorted `GenericParamEntry` records in this shard (empty for format < v5).
212    #[inline]
213    pub fn generic_params(&self) -> &[GenericParamEntry] {
214        let h = self.header();
215        self.typed_slice(h.generic_params_offset, h.generic_params_count)
216    }
217
218    /// Binary-searches all `GenericParamEntry` declarations owned by `owner` (`Def` or `Impl`).
219    #[inline]
220    pub fn generic_params_for_owner(&self, owner: GenericOwner) -> GenericParamIter<'_> {
221        let all = self.generic_params();
222        let key = owner.to_raw();
223        let start = all.partition_point(|e| e.owner_key() < key);
224        let end = start + all[start..].partition_point(|e| e.owner_key() == key);
225        GenericParamIter::new(self.ty_arena(), &all[start..end])
226    }
227
228    /// Binary-searches all `GenericParamEntry` declarations owned by `DefEntry` `def_index`.
229    #[inline]
230    pub fn generic_params_for_def(&self, def_index: u32) -> GenericParamIter<'_> {
231        self.generic_params_for_owner(GenericOwner::Def(def_index))
232    }
233
234    /// Binary-searches all `GenericParamEntry` declarations owned by `ImplEntry` `impl_index`.
235    #[inline]
236    pub fn generic_params_for_impl(&self, impl_index: u32) -> GenericParamIter<'_> {
237        self.generic_params_for_owner(GenericOwner::Impl(impl_index))
238    }
239
240    /// Raw slice of sorted `WherePredEntry` records in this shard (empty for format < v5).
241    #[inline]
242    pub fn where_preds(&self) -> &[WherePredEntry] {
243        let h = self.header();
244        self.typed_slice(h.where_preds_offset, h.where_preds_count)
245    }
246
247    /// Binary-searches all `WherePredEntry` bounds/predicates owned by `owner` (`Def` or `Impl`).
248    #[inline]
249    pub fn where_preds_for_owner(&self, owner: GenericOwner) -> WherePredIter<'_> {
250        let all = self.where_preds();
251        let key = owner.to_raw();
252        let start = all.partition_point(|e| e.owner_key() < key);
253        let end = start + all[start..].partition_point(|e| e.owner_key() == key);
254        WherePredIter::new(self.ty_arena(), &all[start..end])
255    }
256
257    /// Binary-searches all `WherePredEntry` bounds/predicates owned by `DefEntry` `def_index`.
258    #[inline]
259    pub fn where_preds_for_def(&self, def_index: u32) -> WherePredIter<'_> {
260        self.where_preds_for_owner(GenericOwner::Def(def_index))
261    }
262
263    /// Binary-searches all `WherePredEntry` bounds/predicates owned by `ImplEntry` `impl_index`.
264    #[inline]
265    pub fn where_preds_for_impl(&self, impl_index: u32) -> WherePredIter<'_> {
266        self.where_preds_for_owner(GenericOwner::Impl(impl_index))
267    }
268
269    /// Raw slice of `LangItemEntry` records sorted by `kind` (empty for v3/v4 shards).
270    #[inline]
271    pub fn lang_items(&self) -> &[LangItemEntry] {
272        let h = self.header();
273        self.typed_slice(h.lang_items_offset, h.lang_items_count)
274    }
275
276    /// Zero-allocation iterator over all `LangItemEntry` records in this shard.
277    #[inline]
278    pub fn lang_items_iter(&self) -> LangItemIter<'_> {
279        LangItemIter::new(self.lang_items())
280    }
281
282    /// Binary-searches the `LangItemEntry` for `kind` in this shard.
283    #[inline]
284    pub fn lang_item(&self, kind: LangItemKind) -> Option<LangItemView> {
285        let all = self.lang_items();
286        let target = kind as u16;
287        let idx = all.binary_search_by(|e| e.kind_raw().cmp(&target)).ok()?;
288        Some(LangItemView::from_raw(all[idx]))
289    }
290}