Skip to main content

ridx_syntax/ty_infer/
uf_table.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//! Tarjan union-find table over [`TyVarId`] with union-by-rank, snapshot-safe path compression,
12//! occurs-check, shallow chasing, and deep structural resolution with Rust literal fallbacks.
13
14use super::arena::InferTyArena;
15use super::ty::{InferTyId, InferTyKind, TySliceRange, TyVarId, TyVarKind};
16
17#[derive(Clone, Copy, Debug)]
18pub(super) enum VarSlot {
19    /// Root when `parent == own_id`; redirected child when `parent != own_id`.
20    Unbound { parent: TyVarId, rank: u8, kind: TyVarKind, self_ty: InferTyId },
21    /// Root bound to a concrete or composite `InferTyId`.
22    Bound { ty: InferTyId },
23}
24
25#[derive(Clone, Copy, Debug)]
26struct UndoEntry {
27    var: TyVarId,
28    prev: VarSlot,
29}
30
31/// Token representing a speculative unification checkpoint (`start_snapshot` -> `commit` / `rollback_to`).
32#[derive(Debug)]
33pub struct InferSnapshot {
34    var_len: usize,
35    undo_len: usize,
36}
37
38/// Flat union-find inference variable table reusable across functions via [`Self::clear`].
39#[derive(Debug, Default)]
40pub struct UnionFindTable {
41    slots: Vec<VarSlot>,
42    undo_log: Vec<UndoEntry>,
43    active_snapshots: u32,
44}
45
46impl UnionFindTable {
47    pub fn with_capacity(cap: usize) -> Self {
48        Self { slots: Vec::with_capacity(cap), undo_log: Vec::with_capacity(cap / 2), active_snapshots: 0 }
49    }
50
51    #[inline]
52    pub fn clear(&mut self) {
53        self.slots.clear();
54        self.undo_log.clear();
55        self.active_snapshots = 0;
56    }
57
58    #[inline]
59    pub fn var_count(&self) -> usize {
60        self.slots.len()
61    }
62
63    /// Allocates a fresh inference variable and its [`InferTyId`] wrapper inside `arena`.
64    #[inline]
65    pub fn new_var(&mut self, arena: &mut InferTyArena, kind: TyVarKind) -> (TyVarId, InferTyId) {
66        let vid = TyVarId(self.slots.len() as u32);
67        let ty = arena.mk_infer(vid);
68        self.slots.push(VarSlot::Unbound { parent: vid, rank: 0, kind, self_ty: ty });
69        (vid, ty)
70    }
71
72    #[inline]
73    pub fn start_snapshot(&mut self) -> InferSnapshot {
74        self.active_snapshots += 1;
75        InferSnapshot { var_len: self.slots.len(), undo_len: self.undo_log.len() }
76    }
77
78    #[inline]
79    pub fn commit(&mut self, snap: InferSnapshot) {
80        debug_assert!(self.active_snapshots > 0);
81        self.active_snapshots -= 1;
82        if self.active_snapshots == 0 {
83            self.undo_log.clear();
84        } else {
85            let _ = snap;
86        }
87    }
88
89    pub fn rollback_to(&mut self, snap: InferSnapshot) {
90        debug_assert!(self.active_snapshots > 0);
91        while self.undo_log.len() > snap.undo_len {
92            let entry = self.undo_log.pop().unwrap();
93            if (entry.var.0 as usize) < snap.var_len {
94                self.slots[entry.var.0 as usize] = entry.prev;
95            }
96        }
97        self.slots.truncate(snap.var_len);
98        self.active_snapshots -= 1;
99        if self.active_snapshots == 0 {
100            self.undo_log.clear();
101        }
102    }
103
104    #[inline]
105    fn set_slot(&mut self, var: TyVarId, next: VarSlot) {
106        let idx = var.0 as usize;
107        if self.active_snapshots > 0 {
108            self.undo_log.push(UndoEntry { var, prev: self.slots[idx] });
109        }
110        self.slots[idx] = next;
111    }
112
113    /// Finds the current representative of `var` with snapshot-aware path halving/compression.
114    pub fn probe_var(&mut self, mut var: TyVarId) -> Result<InferTyId, (TyVarId, TyVarKind, u8, InferTyId)> {
115        let start = var;
116        let root_res = loop {
117            match self.slots[var.0 as usize] {
118                VarSlot::Bound { ty } => break Ok(ty),
119                VarSlot::Unbound { parent, rank, kind, self_ty } => {
120                    if parent == var {
121                        break Err((var, kind, rank, self_ty));
122                    }
123                    var = parent;
124                }
125            }
126        };
127        let target_parent = match root_res {
128            Ok(_) => var,
129            Err((root, ..)) => root,
130        };
131        let mut cur = start;
132        while let VarSlot::Unbound { parent, rank, kind, self_ty } = self.slots[cur.0 as usize] {
133            if parent == cur {
134                break;
135            }
136            if parent != target_parent {
137                self.set_slot(cur, VarSlot::Unbound { parent: target_parent, rank, kind, self_ty });
138            }
139            cur = parent;
140        }
141        root_res
142    }
143
144    /// Immutable read without path compression (safe for diagnostics and assertions).
145    pub fn probe_var_imm(&self, mut var: TyVarId) -> Result<InferTyId, (TyVarId, TyVarKind)> {
146        loop {
147            match self.slots[var.0 as usize] {
148                VarSlot::Bound { ty } => return Ok(ty),
149                VarSlot::Unbound { parent, kind, .. } => {
150                    if parent == var {
151                        return Err((var, kind));
152                    }
153                    var = parent;
154                }
155            }
156        }
157    }
158
159    /// Peels chained `Infer(v)` indirections until reaching a concrete type or an unbound root `Infer(root)`.
160    #[inline]
161    pub fn shallow_resolve(&mut self, arena: &InferTyArena, mut ty: InferTyId) -> InferTyId {
162        while let InferTyKind::Infer(vid) = arena.kind(ty) {
163            match self.probe_var(vid) {
164                Ok(bound) => ty = bound,
165                Err((_root, _kind, _rank, root_ty)) => return root_ty,
166            }
167        }
168        ty
169    }
170
171    #[inline]
172    pub(super) fn bind_root(&mut self, root: TyVarId, ty: InferTyId) {
173        self.set_slot(root, VarSlot::Bound { ty });
174    }
175
176    pub(super) fn union_roots(&mut self, a: (TyVarId, u8, InferTyId), b: (TyVarId, u8, InferTyId), merged_kind: TyVarKind) {
177        let (ra, rank_a, ty_a) = a;
178        let (rb, rank_b, ty_b) = b;
179        if ra == rb {
180            self.set_slot(ra, VarSlot::Unbound { parent: ra, rank: rank_a, kind: merged_kind, self_ty: ty_a });
181            return;
182        }
183        if rank_a < rank_b {
184            self.set_slot(ra, VarSlot::Unbound { parent: rb, rank: rank_a, kind: merged_kind, self_ty: ty_a });
185            self.set_slot(rb, VarSlot::Unbound { parent: rb, rank: rank_b, kind: merged_kind, self_ty: ty_b });
186        } else if rank_a > rank_b {
187            self.set_slot(rb, VarSlot::Unbound { parent: ra, rank: rank_b, kind: merged_kind, self_ty: ty_b });
188            self.set_slot(ra, VarSlot::Unbound { parent: ra, rank: rank_a, kind: merged_kind, self_ty: ty_a });
189        } else {
190            self.set_slot(rb, VarSlot::Unbound { parent: ra, rank: rank_b, kind: merged_kind, self_ty: ty_b });
191            self.set_slot(ra, VarSlot::Unbound { parent: ra, rank: rank_a.saturating_add(1), kind: merged_kind, self_ty: ty_a });
192        }
193    }
194
195    /// Checks whether `needle_root` appears anywhere inside `ty` (`O(1)` fast path when `!has_infer()`).
196    pub fn occurs_in(&mut self, arena: &InferTyArena, needle_root: TyVarId, ty: InferTyId) -> bool {
197        self.occurs_rec(arena, needle_root, ty, 0)
198    }
199
200    fn occurs_rec(&mut self, arena: &InferTyArena, needle_root: TyVarId, ty: InferTyId, depth: u8) -> bool {
201        if depth > 64 || !arena.flags(ty).has_infer() {
202            return false;
203        }
204        let resolved = self.shallow_resolve(arena, ty);
205        if !arena.flags(resolved).has_infer() {
206            return false;
207        }
208        let check_slice = |this: &mut Self, r: TySliceRange| -> bool {
209            for idx in 0..r.len as usize {
210                let elem = arena.slice(r)[idx];
211                if this.occurs_rec(arena, needle_root, elem, depth + 1) {
212                    return true;
213                }
214            }
215            false
216        };
217        match arena.kind(resolved) {
218            InferTyKind::Infer(v) => v == needle_root,
219            InferTyKind::Ref { inner, .. } | InferTyKind::Ptr { inner, .. } | InferTyKind::Slice(inner) | InferTyKind::Array { elem: inner, .. } => {
220                self.occurs_rec(arena, needle_root, inner, depth + 1)
221            }
222            InferTyKind::Tuple(r)
223            | InferTyKind::Adt { args: r, .. }
224            | InferTyKind::FnPtr { sig: r }
225            | InferTyKind::FnDef { args: r, .. }
226            | InferTyKind::Closure { sig: r, .. }
227            | InferTyKind::Dyn { args: r, .. }
228            | InferTyKind::Opaque { args: r, .. } => check_slice(self, r),
229            InferTyKind::Alias { self_ty, args, .. } => self.occurs_rec(arena, needle_root, self_ty, depth + 1) || check_slice(self, args),
230            InferTyKind::Unknown | InferTyKind::Never | InferTyKind::Prim(_) | InferTyKind::Param { .. } => false,
231        }
232    }
233
234    /// Recursively substitutes solved inference variables (`O(1)` when `!has_infer()`).
235    /// When `fallback_unbound` is true, maps `{integer} -> i32`, `{float} -> f64`, `_ -> {unknown}`.
236    pub fn deep_resolve(&mut self, arena: &mut InferTyArena, ty: InferTyId, fallback_unbound: bool) -> InferTyId {
237        self.deep_resolve_rec(arena, ty, fallback_unbound, 0)
238    }
239
240    fn deep_resolve_rec(&mut self, arena: &mut InferTyArena, ty: InferTyId, fallback: bool, depth: u8) -> InferTyId {
241        if depth > 64 {
242            return InferTyId::UNKNOWN;
243        }
244        if !arena.flags(ty).has_infer() {
245            return ty;
246        }
247        let resolved = self.shallow_resolve(arena, ty);
248        if !arena.flags(resolved).has_infer() {
249            return resolved;
250        }
251        match arena.kind(resolved) {
252            InferTyKind::Infer(vid) => {
253                if !fallback {
254                    return resolved;
255                }
256                match self.probe_var(vid) {
257                    Ok(b) => self.deep_resolve_rec(arena, b, true, depth + 1),
258                    Err((_, TyVarKind::IntVar, ..)) => InferTyId::I32,
259                    Err((_, TyVarKind::FloatVar, ..)) => InferTyId::F64,
260                    Err((_, TyVarKind::General, ..)) => InferTyId::UNKNOWN,
261                }
262            }
263            InferTyKind::Ref { is_mut, inner } => {
264                let sub = self.deep_resolve_rec(arena, inner, fallback, depth + 1);
265                arena.mk_ref(is_mut, sub)
266            }
267            InferTyKind::Ptr { is_mut, inner } => {
268                let sub = self.deep_resolve_rec(arena, inner, fallback, depth + 1);
269                arena.mk_ptr(is_mut, sub)
270            }
271            InferTyKind::Slice(elem) => {
272                let sub = self.deep_resolve_rec(arena, elem, fallback, depth + 1);
273                arena.mk_slice(sub)
274            }
275            InferTyKind::Array { elem, len } => {
276                let sub = self.deep_resolve_rec(arena, elem, fallback, depth + 1);
277                let r_len = if (len & 0xFFFF_FFFF_0000_0000) == super::arena::ARRAY_LEN_VAR_TAG {
278                    match self.probe_var(TyVarId((len & 0xFFFF_FFFF) as u32)) {
279                        Ok(b) => match arena.kind(self.shallow_resolve(arena, b)) {
280                            InferTyKind::Array { elem: e, len: c_len } if e == InferTyId::NEVER => c_len,
281                            _ => u64::MAX,
282                        },
283                        Err(_) => {
284                            if fallback {
285                                u64::MAX
286                            } else {
287                                len
288                            }
289                        }
290                    }
291                } else {
292                    len
293                };
294                arena.mk_array(sub, r_len)
295            }
296            InferTyKind::Tuple(r) => {
297                let sub = self.resolve_slice_buf(arena, r, fallback, depth + 1);
298                arena.mk_tuple(sub.as_slice())
299            }
300            InferTyKind::Adt { def, args } => {
301                let sub = self.resolve_slice_buf(arena, args, fallback, depth + 1);
302                arena.mk_adt(def, sub.as_slice())
303            }
304            InferTyKind::FnPtr { sig } => {
305                let sub = self.resolve_slice_buf(arena, sig, fallback, depth + 1);
306                let s = sub.as_slice();
307                arena.mk_fn_ptr(&s[..s.len() - 1], s[s.len() - 1])
308            }
309            InferTyKind::FnDef { def, args } => {
310                let sub = self.resolve_slice_buf(arena, args, fallback, depth + 1);
311                arena.mk_fn_def(def, sub.as_slice())
312            }
313            InferTyKind::Closure { def_start, def_end, sig } => {
314                let sub = self.resolve_slice_buf(arena, sig, fallback, depth + 1);
315                let s = sub.as_slice();
316                arena.mk_closure(def_start, def_end, &s[..s.len() - 1], s[s.len() - 1])
317            }
318            InferTyKind::Alias { trait_def, assoc_def, self_ty, args } => {
319                let ns = self.deep_resolve_rec(arena, self_ty, fallback, depth + 1);
320                let sub = self.resolve_slice_buf(arena, args, fallback, depth + 1);
321                arena.mk_alias(trait_def, assoc_def, ns, sub.as_slice())
322            }
323            InferTyKind::Dyn { principal, args } => {
324                let sub = self.resolve_slice_buf(arena, args, fallback, depth + 1);
325                arena.mk_dyn(principal, sub.as_slice())
326            }
327            InferTyKind::Opaque { def, args } => {
328                let sub = self.resolve_slice_buf(arena, args, fallback, depth + 1);
329                arena.mk_opaque(def, sub.as_slice())
330            }
331            InferTyKind::Unknown | InferTyKind::Never | InferTyKind::Prim(_) | InferTyKind::Param { .. } => resolved,
332        }
333    }
334
335    fn resolve_slice_buf(&mut self, arena: &mut InferTyArena, r: TySliceRange, fallback: bool, depth: u8) -> InlineTyBuf {
336        let mut buf = InlineTyBuf::new();
337        for idx in 0..r.len as usize {
338            let orig = arena.slice(r)[idx];
339            let next = self.deep_resolve_rec(arena, orig, fallback, depth);
340            buf.push(next);
341        }
342        buf
343    }
344}
345
346pub struct InlineTyBuf {
347    inline: [InferTyId; 32],
348    len: usize,
349    spill: Vec<InferTyId>,
350}
351
352impl Default for InlineTyBuf {
353    #[inline]
354    fn default() -> Self {
355        Self::new()
356    }
357}
358
359impl InlineTyBuf {
360    #[inline]
361    pub fn new() -> Self {
362        Self { inline: [InferTyId::UNKNOWN; 32], len: 0, spill: Vec::new() }
363    }
364
365    #[inline]
366    pub fn push(&mut self, ty: InferTyId) {
367        if self.len < 32 {
368            self.inline[self.len] = ty;
369            self.len += 1;
370        } else {
371            if self.spill.is_empty() {
372                self.spill.extend_from_slice(&self.inline);
373            }
374            self.spill.push(ty);
375        }
376    }
377
378    #[inline]
379    pub fn as_slice(&self) -> &[InferTyId] {
380        if self.spill.is_empty() {
381            &self.inline[..self.len]
382        } else {
383            &self.spill
384        }
385    }
386
387    #[inline]
388    pub fn set(&mut self, idx: usize, ty: InferTyId) {
389        if self.spill.is_empty() {
390            if idx < self.len {
391                self.inline[idx] = ty;
392            }
393        } else if idx < self.spill.len() {
394            self.spill[idx] = ty;
395        }
396    }
397}