Skip to main content

ridx_format/ty_arena/
intern.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//! Bottom-up hash-consing interner for `TyArena`.
12
13use std::collections::HashMap;
14
15use crate::format::{
16    fnv1a_64, ConstArg, FloatTyWidth, FnAbiKind, GenericArgWord, IntTyWidth, TyBoundEntry, TyDefEntry, TyDefId, TyEntry, TyId, TyMutability, TyTag, UintTyWidth, BOUND_FLAG_MAYBE,
17    FN_FLAG_UNSAFE, FN_FLAG_VARIADIC,
18};
19
20/// Input definition reference for `TyInterner::intern_def`.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum RawTyDef<'a> {
23    Local { path: &'a str, local_def_idx: u32 },
24    External { path: &'a str, unit_key: Option<&'a str> },
25}
26
27/// Input generic argument for `Adt`, `FnDef`, `Assoc`, and `RawTyBound`.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum RawGenericArg<'a> {
30    Type(TyId),
31    ConstValue(u32),
32    ConstParam(u32),
33    ConstExpr(&'a str),
34    Lifetime(u32),
35}
36
37/// Input trait bound for `Dyn` and `ImplTrait`.
38#[derive(Debug, Clone)]
39pub struct RawTyBound<'a> {
40    pub trait_def: TyDefId,
41    pub args: &'a [RawGenericArg<'a>],
42    pub assocs: &'a [(&'a str, TyId)],
43    pub is_maybe: bool,
44}
45
46/// Input type node for `TyInterner::intern_ty` (`Infer`-free).
47#[derive(Debug, Clone)]
48pub enum RawTy<'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: &'a [RawGenericArg<'a>] },
58    Ref { mutability: TyMutability, inner: TyId, lifetime: u32 },
59    Ptr { mutability: TyMutability, inner: TyId },
60    Slice(TyId),
61    ArrayVal { elem: TyId, len: u32 },
62    ArrayConstParam { elem: TyId, param_idx: u32 },
63    ArrayConstExpr { elem: TyId, expr: &'a str },
64    Tuple(&'a [TyId]),
65    FnPtr { inputs: &'a [TyId], output: TyId, abi: FnAbiKind, is_unsafe: bool, is_variadic: bool },
66    FnDef { def: TyDefId, args: &'a [RawGenericArg<'a>] },
67    Param { index: u32, name: &'a str },
68    Assoc { trait_def: TyDefId, name: &'a str, self_ty: TyId, trait_args: &'a [RawGenericArg<'a>] },
69    Dyn { bounds: &'a [RawTyBound<'a>], lifetime: u32 },
70    ImplTrait { bounds: &'a [RawTyBound<'a>] },
71    Unknown,
72}
73
74/// Deduplicating builder for `TyArena` tables (`ty_defs`, `ty_entries`, `ty_bounds`, `ty_args`).
75#[derive(Debug, Default)]
76pub struct TyInterner {
77    defs: Vec<TyDefEntry>,
78    entries: Vec<TyEntry>,
79    bounds: Vec<TyBoundEntry>,
80    args: Vec<u32>,
81
82    def_map: HashMap<TyDefEntry, TyDefId>,
83    entry_map: HashMap<TyEntry, TyId>,
84    arg1_map: HashMap<u32, u32>,
85    arg_slice_map: HashMap<Box<[u32]>, u32>,
86    single_bound_map: HashMap<TyBoundEntry, u32>,
87    bound_list_map: HashMap<Box<[TyBoundEntry]>, u32>,
88    scratch_words: Vec<u32>,
89    scratch_bounds: Vec<TyBoundEntry>,
90}
91
92impl TyInterner {
93    pub fn new() -> Self {
94        Self::default()
95    }
96
97    #[inline]
98    pub fn defs(&self) -> &[TyDefEntry] {
99        &self.defs
100    }
101
102    #[inline]
103    pub fn entries(&self) -> &[TyEntry] {
104        &self.entries
105    }
106
107    #[inline]
108    pub fn bounds(&self) -> &[TyBoundEntry] {
109        &self.bounds
110    }
111
112    #[inline]
113    pub fn args(&self) -> &[u32] {
114        &self.args
115    }
116
117    pub fn intern_def<F>(&mut self, def: RawTyDef<'_>, mut intern_str: F) -> TyDefId
118    where
119        F: FnMut(&str) -> u32,
120    {
121        let entry = match def {
122            RawTyDef::Local { path, local_def_idx } => {
123                let path_hash = fnv1a_64(path.as_bytes());
124                let path_off = intern_str(path);
125                TyDefEntry::local(path_hash, path_off, local_def_idx)
126            }
127            RawTyDef::External { path, unit_key } => {
128                let path_hash = fnv1a_64(path.as_bytes());
129                let path_off = intern_str(path);
130                let unit_off = match unit_key {
131                    Some(u) if !u.is_empty() => intern_str(u),
132                    _ => 0,
133                };
134                TyDefEntry::external(path_hash, path_off, unit_off)
135            }
136        };
137        if let Some(&id) = self.def_map.get(&entry) {
138            return id;
139        }
140        let id = TyDefId(self.defs.len() as u32);
141        self.defs.push(entry);
142        self.def_map.insert(entry, id);
143        id
144    }
145
146    pub fn intern_ty<F>(&mut self, ty: RawTy<'_>, mut intern_str: F) -> TyId
147    where
148        F: FnMut(&str) -> u32,
149    {
150        let entry = self.encode_raw_ty(ty, &mut intern_str);
151        if let Some(&id) = self.entry_map.get(&entry) {
152            return id;
153        }
154        let id = TyId(self.entries.len() as u32);
155        self.entries.push(entry);
156        self.entry_map.insert(entry, id);
157        id
158    }
159
160    /// Interns and deduplicates a list of `TyId`s in `ty_args` (used by `FnSigEntry` parameter lists).
161    pub fn intern_ty_list(&mut self, tys: &[TyId]) -> (u32, u16) {
162        if tys.is_empty() {
163            return (0, 0);
164        }
165        let mut buf = std::mem::take(&mut self.scratch_words);
166        buf.clear();
167        buf.extend(tys.iter().map(|t| t.0));
168        let (start, len) = self.intern_words(&buf);
169        self.scratch_words = buf;
170        (start, u16::try_from(len).unwrap_or(u16::MAX))
171    }
172
173    /// Interns and deduplicates a list of raw `u32` indices in `ty_args` (used by `ImplEntry` assoc defs).
174    pub fn intern_u32_list(&mut self, items: &[u32]) -> (u32, u16) {
175        if items.is_empty() {
176            return (0, 0);
177        }
178        let (start, len) = self.intern_words(items);
179        (start, u16::try_from(len).unwrap_or(u16::MAX))
180    }
181
182    /// Interns and deduplicates a list of `RawGenericArg`s in `ty_args` (used by `ImplEntry` trait args).
183    pub fn intern_generic_args_list<F>(&mut self, args: &[RawGenericArg<'_>], mut intern_str: F) -> (u32, u16)
184    where
185        F: FnMut(&str) -> u32,
186    {
187        let (start, len) = self.intern_generic_args(args, &mut intern_str);
188        (start, u16::try_from(len).unwrap_or(u16::MAX))
189    }
190
191    fn intern_words(&mut self, words: &[u32]) -> (u32, u32) {
192        match words {
193            [] => (0, 0),
194            &[w0] => {
195                if let Some(&start) = self.arg1_map.get(&w0) {
196                    return (start, 1);
197                }
198                let start = self.args.len() as u32;
199                self.args.push(w0);
200                self.arg1_map.insert(w0, start);
201                (start, 1)
202            }
203            many => {
204                if let Some(&start) = self.arg_slice_map.get(many) {
205                    return (start, many.len() as u32);
206                }
207                let start = self.args.len() as u32;
208                self.args.extend_from_slice(many);
209                self.arg_slice_map.insert(many.into(), start);
210                (start, many.len() as u32)
211            }
212        }
213    }
214
215    fn encode_arg_word<F>(arg: RawGenericArg<'_>, intern_str: &mut F) -> u32
216    where
217        F: FnMut(&str) -> u32,
218    {
219        match arg {
220            RawGenericArg::Type(t) => GenericArgWord::from_type(t).0,
221            RawGenericArg::ConstValue(v) => GenericArgWord::from_const(ConstArg::Value(v)).0,
222            RawGenericArg::ConstParam(idx) => GenericArgWord::from_const(ConstArg::Param(idx)).0,
223            RawGenericArg::ConstExpr(s) => GenericArgWord::from_const(ConstArg::ExprOffset(intern_str(s))).0,
224            RawGenericArg::Lifetime(lt) => GenericArgWord::from_lifetime(lt).0,
225        }
226    }
227
228    fn intern_generic_args<F>(&mut self, args: &[RawGenericArg<'_>], intern_str: &mut F) -> (u32, u32)
229    where
230        F: FnMut(&str) -> u32,
231    {
232        if args.is_empty() {
233            return (0, 0);
234        }
235        let mut buf = std::mem::take(&mut self.scratch_words);
236        buf.clear();
237        buf.reserve(args.len());
238        for &a in args {
239            buf.push(Self::encode_arg_word(a, intern_str));
240        }
241        let res = self.intern_words(&buf);
242        self.scratch_words = buf;
243        res
244    }
245
246    fn encode_bound<F>(&mut self, b: &RawTyBound<'_>, intern_str: &mut F) -> TyBoundEntry
247    where
248        F: FnMut(&str) -> u32,
249    {
250        let (args_start, _) = if b.args.is_empty() && b.assocs.is_empty() {
251            (0, 0)
252        } else {
253            let mut buf = std::mem::take(&mut self.scratch_words);
254            buf.clear();
255            buf.reserve(b.args.len() + b.assocs.len() * 2);
256            for &a in b.args {
257                buf.push(Self::encode_arg_word(a, intern_str));
258            }
259            for &(name, ty) in b.assocs {
260                buf.push(intern_str(name));
261                buf.push(ty.0);
262            }
263            let res = self.intern_words(&buf);
264            self.scratch_words = buf;
265            res
266        };
267        TyBoundEntry { trait_def: b.trait_def.0, args_start, args_len: b.args.len() as u16, assoc_len: b.assocs.len() as u16, flags: if b.is_maybe { BOUND_FLAG_MAYBE } else { 0 } }
268    }
269
270    fn intern_bounds<F>(&mut self, raw_bounds: &[RawTyBound<'_>], intern_str: &mut F) -> (u32, u32)
271    where
272        F: FnMut(&str) -> u32,
273    {
274        match raw_bounds {
275            [] => (0, 0),
276            [only] => {
277                let b0 = self.encode_bound(only, intern_str);
278                if let Some(&idx) = self.single_bound_map.get(&b0) {
279                    return (idx, 1);
280                }
281                let idx = self.bounds.len() as u32;
282                self.bounds.push(b0);
283                self.single_bound_map.insert(b0, idx);
284                (idx, 1)
285            }
286            many => {
287                let mut bbuf = std::mem::take(&mut self.scratch_bounds);
288                bbuf.clear();
289                bbuf.reserve(many.len());
290                for rb in many {
291                    bbuf.push(self.encode_bound(rb, intern_str));
292                }
293                if let Some(&start) = self.bound_list_map.get(bbuf.as_slice()) {
294                    let len = bbuf.len() as u32;
295                    self.scratch_bounds = bbuf;
296                    return (start, len);
297                }
298                let start = self.bounds.len() as u32;
299                for (offset, &b) in bbuf.iter().enumerate() {
300                    self.single_bound_map.entry(b).or_insert(start + offset as u32);
301                }
302                self.bounds.extend_from_slice(&bbuf);
303                let len = bbuf.len() as u32;
304                self.bound_list_map.insert(bbuf.as_slice().into(), start);
305                self.scratch_bounds = bbuf;
306                (start, len)
307            }
308        }
309    }
310
311    fn encode_raw_ty<F>(&mut self, ty: RawTy<'_>, intern_str: &mut F) -> TyEntry
312    where
313        F: FnMut(&str) -> u32,
314    {
315        let mk = |tag: TyTag, flags: u8, extra: u16, a: u32, b: u32, c: u32| TyEntry { tag: tag as u8, flags, extra, a, b, c };
316        match ty {
317            RawTy::Unit | RawTy::Tuple(&[]) => mk(TyTag::Unit, 0, 0, 0, 0, 0),
318            RawTy::Bool => mk(TyTag::Bool, 0, 0, 0, 0, 0),
319            RawTy::Char => mk(TyTag::Char, 0, 0, 0, 0, 0),
320            RawTy::Int(w) => mk(TyTag::Int, w as u8, 0, 0, 0, 0),
321            RawTy::Uint(w) => mk(TyTag::Uint, w as u8, 0, 0, 0, 0),
322            RawTy::Float(w) => mk(TyTag::Float, w as u8, 0, 0, 0, 0),
323            RawTy::Str => mk(TyTag::Str, 0, 0, 0, 0, 0),
324            RawTy::Never => mk(TyTag::Never, 0, 0, 0, 0, 0),
325            RawTy::Unknown => mk(TyTag::Unknown, 0, 0, 0, 0, 0),
326            RawTy::Adt { def, args } => {
327                let (s, l) = self.intern_generic_args(args, intern_str);
328                mk(TyTag::Adt, 0, 0, def.0, s, l)
329            }
330            RawTy::Ref { mutability, inner, lifetime } => mk(TyTag::Ref, mutability as u8, 0, inner.0, lifetime, 0),
331            RawTy::Ptr { mutability, inner } => mk(TyTag::Ptr, mutability as u8, 0, inner.0, 0, 0),
332            RawTy::Slice(elem) => mk(TyTag::Slice, 0, 0, elem.0, 0, 0),
333            RawTy::ArrayVal { elem, len } => mk(TyTag::Array, 0, 0, elem.0, GenericArgWord::from_const(ConstArg::Value(len)).0, 0),
334            RawTy::ArrayConstParam { elem, param_idx } => mk(TyTag::Array, 0, 0, elem.0, GenericArgWord::from_const(ConstArg::Param(param_idx)).0, 0),
335            RawTy::ArrayConstExpr { elem, expr } => {
336                let off = intern_str(expr);
337                mk(TyTag::Array, 0, 0, elem.0, GenericArgWord::from_const(ConstArg::ExprOffset(off)).0, 0)
338            }
339            RawTy::Tuple(elems) => {
340                let mut buf = std::mem::take(&mut self.scratch_words);
341                buf.clear();
342                buf.extend(elems.iter().map(|t| t.0));
343                let (s, l) = self.intern_words(&buf);
344                self.scratch_words = buf;
345                mk(TyTag::Tuple, 0, 0, s, l, 0)
346            }
347            RawTy::FnPtr { inputs, output, abi, is_unsafe, is_variadic } => {
348                let mut buf = std::mem::take(&mut self.scratch_words);
349                buf.clear();
350                buf.extend(inputs.iter().map(|t| t.0));
351                let (s, l) = self.intern_words(&buf);
352                self.scratch_words = buf;
353                let flags = (if is_unsafe { FN_FLAG_UNSAFE } else { 0 }) | (if is_variadic { FN_FLAG_VARIADIC } else { 0 });
354                mk(TyTag::FnPtr, flags, abi as u16, s, l, output.0)
355            }
356            RawTy::FnDef { def, args } => {
357                let (s, l) = self.intern_generic_args(args, intern_str);
358                mk(TyTag::FnDef, 0, 0, def.0, s, l)
359            }
360            RawTy::Param { index, name } => {
361                let name_off = if name.is_empty() { 0 } else { intern_str(name) };
362                mk(TyTag::Param, 0, 0, index, name_off, 0)
363            }
364            RawTy::Assoc { trait_def, name, self_ty, trait_args } => {
365                let name_off = intern_str(name);
366                if trait_args.is_empty() {
367                    mk(TyTag::Assoc, 0, 0, trait_def.0, name_off, self_ty.0)
368                } else {
369                    let mut buf = std::mem::take(&mut self.scratch_words);
370                    buf.clear();
371                    buf.reserve(1 + trait_args.len());
372                    buf.push(self_ty.0);
373                    for &a in trait_args {
374                        buf.push(Self::encode_arg_word(a, intern_str));
375                    }
376                    let (s, _) = self.intern_words(&buf);
377                    self.scratch_words = buf;
378                    mk(TyTag::Assoc, 0, trait_args.len() as u16, trait_def.0, name_off, s)
379                }
380            }
381            RawTy::Dyn { bounds, lifetime } => {
382                let (s, l) = self.intern_bounds(bounds, intern_str);
383                mk(TyTag::Dyn, 0, 0, s, l, lifetime)
384            }
385            RawTy::ImplTrait { bounds } => {
386                let (s, l) = self.intern_bounds(bounds, intern_str);
387                mk(TyTag::ImplTrait, 0, 0, s, l, 0)
388            }
389        }
390    }
391}