Skip to main content

ridx_format/ty_arena/
mod.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 reader views, structural interner, and formatter for `TyArena`.
12
13mod display;
14mod field_view;
15mod fn_sig;
16mod generic_view;
17mod impl_view;
18mod intern;
19mod iter;
20mod lang_view;
21mod use_view;
22
23pub use self::field_view::{DefTyView, FieldIter, FieldView, RawDefTy, RawField};
24pub use self::fn_sig::{FnSigView, RawFnSig};
25pub use self::generic_view::{GenericParamIter, GenericParamView, RawGenericParam, RawWherePred, WherePredIter, WherePredView};
26pub use self::impl_view::{AssocTyIter, AssocTyView, ImplIter, ImplView, RawAssocTy, RawImpl};
27pub use self::intern::{RawGenericArg, RawTy, RawTyBound, RawTyDef, TyInterner};
28pub use self::iter::{AssocBindingIter, AssocBindingView, GenericArgIter, GenericArgView, TyBoundIter, TyBoundView, TyListIter, U32ListIter};
29pub use self::lang_view::{LangItemIter, LangItemView, RawLangItem};
30pub use self::use_view::{RawUse, UseIter, UseView};
31
32use crate::format::{
33    ConstArg, FloatTyWidth, FnAbiKind, GenericArgWord, IntTyWidth, TyBoundEntry, TyDefEntry, TyDefId, TyEntry, TyId, TyMutability, TyTag, UintTyWidth, BOUND_FLAG_MAYBE,
34    FN_FLAG_UNSAFE, FN_FLAG_VARIADIC,
35};
36
37/// Resolved zero-copy view of a `TyDefEntry`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct TyDefView<'a> {
40    pub path_hash: u64,
41    pub path: &'a str,
42    pub local_def_idx: Option<u32>,
43    pub extern_unit: Option<&'a str>,
44}
45
46/// Structured, `Infer`-free zero-copy decoded view of a `TyEntry`.
47#[derive(Debug, Clone, Copy)]
48pub enum TyKindView<'a> {
49    Unit,
50    Bool,
51    Char,
52    Int(IntTyWidth),
53    Uint(UintTyWidth),
54    Float(FloatTyWidth),
55    Str,
56    Never,
57    Adt { def: TyDefId, args: GenericArgIter<'a> },
58    Ref { mutability: TyMutability, inner: TyId, lifetime: u32 },
59    Ptr { mutability: TyMutability, inner: TyId },
60    Slice(TyId),
61    Array { elem: TyId, len: ConstArg },
62    Tuple(TyListIter<'a>),
63    FnPtr { inputs: TyListIter<'a>, output: TyId, abi: FnAbiKind, is_unsafe: bool, is_variadic: bool },
64    FnDef { def: TyDefId, args: GenericArgIter<'a> },
65    Param { index: u32, name: &'a str },
66    Assoc { trait_def: TyDefId, name: &'a str, self_ty: TyId, trait_args: GenericArgIter<'a> },
67    Dyn { bounds: TyBoundIter<'a>, lifetime: u32 },
68    ImplTrait { bounds: TyBoundIter<'a> },
69    Unknown,
70}
71
72/// Zero-copy view over a shard's `TyArena` sections and string pool.
73#[derive(Debug, Clone, Copy)]
74pub struct TyArenaView<'a> {
75    string_pool: &'a [u8],
76    defs: &'a [TyDefEntry],
77    entries: &'a [TyEntry],
78    bounds: &'a [TyBoundEntry],
79    args: &'a [u32],
80}
81
82impl<'a> TyArenaView<'a> {
83    #[inline]
84    pub const fn new(string_pool: &'a [u8], defs: &'a [TyDefEntry], entries: &'a [TyEntry], bounds: &'a [TyBoundEntry], args: &'a [u32]) -> Self {
85        Self { string_pool, defs, entries, bounds, args }
86    }
87
88    #[inline]
89    pub const fn is_empty(&self) -> bool {
90        self.entries.is_empty()
91    }
92
93    #[inline]
94    pub const fn ty_count(&self) -> usize {
95        self.entries.len()
96    }
97
98    #[inline]
99    pub const fn def_count(&self) -> usize {
100        self.defs.len()
101    }
102
103    #[inline]
104    pub const fn bound_count(&self) -> usize {
105        self.bounds.len()
106    }
107
108    #[inline]
109    pub const fn arg_count(&self) -> usize {
110        self.args.len()
111    }
112
113    #[inline]
114    pub fn str_at(&self, offset: u32) -> &'a str {
115        let start = offset as usize;
116        if start >= self.string_pool.len() {
117            return "";
118        }
119        let end = self.string_pool[start..].iter().position(|&b| b == 0).map_or(self.string_pool.len(), |p| start + p);
120        std::str::from_utf8(&self.string_pool[start..end]).unwrap_or("")
121    }
122
123    #[inline]
124    pub fn def(&self, id: TyDefId) -> Option<TyDefView<'a>> {
125        let raw = self.defs.get(id.index())?;
126        let path = self.str_at(raw.path_offset());
127        let extern_unit = raw.extern_unit_offset().map(|off| self.str_at(off));
128        Some(TyDefView { path_hash: raw.path_hash(), path, local_def_idx: raw.local_def_idx(), extern_unit })
129    }
130
131    #[inline]
132    pub fn get(&self, id: TyId) -> Option<TyKindView<'a>> {
133        let e = self.entries.get(id.index())?.from_le();
134        Some(self.decode_entry(e))
135    }
136
137    #[inline]
138    pub fn kind(&self, id: TyId) -> TyKindView<'a> {
139        self.get(id).unwrap_or(TyKindView::Unknown)
140    }
141
142    #[inline]
143    pub(crate) fn words_slice(&self, start: u32, len: u32) -> &'a [u32] {
144        let s = start as usize;
145        let end = s.saturating_add(len as usize);
146        self.args.get(s..end).unwrap_or(&[])
147    }
148
149    #[inline]
150    fn bounds_slice(&self, start: u32, len: u32) -> &'a [TyBoundEntry] {
151        let s = start as usize;
152        let end = s.saturating_add(len as usize);
153        self.bounds.get(s..end).unwrap_or(&[])
154    }
155
156    #[inline]
157    pub(crate) fn decode_bound(&self, b: TyBoundEntry) -> TyBoundView<'a> {
158        let args_len = u32::from(b.args_len);
159        let assoc_words = u32::from(b.assoc_len).saturating_mul(2);
160        let args = GenericArgIter { words: self.words_slice(b.args_start, args_len) };
161        let assocs = AssocBindingIter { arena: *self, words: self.words_slice(b.args_start.saturating_add(args_len), assoc_words) };
162        TyBoundView { trait_def: TyDefId(b.trait_def), is_maybe: (b.flags & BOUND_FLAG_MAYBE) != 0, flags: b.flags, args, assocs }
163    }
164
165    fn decode_entry(&self, e: TyEntry) -> TyKindView<'a> {
166        match TyTag::from_u8(e.tag) {
167            TyTag::Unit => TyKindView::Unit,
168            TyTag::Bool => TyKindView::Bool,
169            TyTag::Char => TyKindView::Char,
170            TyTag::Int => TyKindView::Int(IntTyWidth::from_u8(e.flags)),
171            TyTag::Uint => TyKindView::Uint(UintTyWidth::from_u8(e.flags)),
172            TyTag::Float => TyKindView::Float(FloatTyWidth::from_u8(e.flags)),
173            TyTag::Str => TyKindView::Str,
174            TyTag::Never => TyKindView::Never,
175            TyTag::Adt => TyKindView::Adt { def: TyDefId(e.a), args: GenericArgIter { words: self.words_slice(e.b, e.c) } },
176            TyTag::Ref => TyKindView::Ref { mutability: TyMutability::from_u8(e.flags), inner: TyId(e.a), lifetime: e.b },
177            TyTag::Ptr => TyKindView::Ptr { mutability: TyMutability::from_u8(e.flags), inner: TyId(e.a) },
178            TyTag::Slice => TyKindView::Slice(TyId(e.a)),
179            TyTag::Array => TyKindView::Array { elem: TyId(e.a), len: GenericArgWord::decode_const(e.b) },
180            TyTag::Tuple => TyKindView::Tuple(TyListIter { words: self.words_slice(e.a, e.b) }),
181            TyTag::FnPtr => TyKindView::FnPtr {
182                inputs: TyListIter { words: self.words_slice(e.a, e.b) },
183                output: TyId(e.c),
184                abi: FnAbiKind::from_u16(e.extra),
185                is_unsafe: (e.flags & FN_FLAG_UNSAFE) != 0,
186                is_variadic: (e.flags & FN_FLAG_VARIADIC) != 0,
187            },
188            TyTag::FnDef => TyKindView::FnDef { def: TyDefId(e.a), args: GenericArgIter { words: self.words_slice(e.b, e.c) } },
189            TyTag::Param => TyKindView::Param { index: e.a, name: self.str_at(e.b) },
190            TyTag::Assoc => {
191                let (self_ty, trait_args) = if e.extra == 0 {
192                    (TyId(e.c), GenericArgIter::EMPTY)
193                } else {
194                    let s = self.words_slice(e.c, 1 + u32::from(e.extra));
195                    match s.split_first() {
196                        Some((&first, rest)) => (TyId(u32::from_le(first)), GenericArgIter { words: rest }),
197                        None => (TyId::NONE, GenericArgIter::EMPTY),
198                    }
199                };
200                TyKindView::Assoc { trait_def: TyDefId(e.a), name: self.str_at(e.b), self_ty, trait_args }
201            }
202            TyTag::Dyn => TyKindView::Dyn { bounds: TyBoundIter { arena: *self, bounds: self.bounds_slice(e.a, e.b) }, lifetime: e.c },
203            TyTag::ImplTrait => TyKindView::ImplTrait { bounds: TyBoundIter { arena: *self, bounds: self.bounds_slice(e.a, e.b) } },
204            TyTag::Unknown => TyKindView::Unknown,
205        }
206    }
207}