Skip to main content

ridx_syntax/ty_infer/
db.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-dependency trait boundary ([`TyDefDb`]), `#[repr(u16)]`-aligned [`TyLangItem`] catalog
12//! (matching `ridx-format::LangItemKind`), constructor shapes, and arena type cloner (`clone_ty_into`).
13
14pub use super::arena::clone_ty_into;
15use super::arena::InferTyArena;
16use super::ty::{InferTyId, TySliceRange};
17use super::uf_table::UnionFindTable;
18use crate::name_res::{GlobalDefId, ImplTargetKey};
19
20/// Compiler `#[lang = "..."]` items and associated trait items used during local type inference.
21/// Discriminants match `ridx_format::LangItemKind` 1-to-1 for zero-cost bridging.
22#[repr(u16)]
23#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub enum TyLangItem {
25    Sized = 0,
26    Copy = 1,
27    Clone = 2,
28    Sync = 3,
29    Freeze = 4,
30    Unpin = 5,
31    Drop = 6,
32    Tuple = 7,
33    FnPtrTrait = 8,
34    Option = 9,
35    OptionSome = 10,
36    OptionNone = 11,
37    Result = 12,
38    ResultOk = 13,
39    ResultErr = 14,
40    ControlFlow = 15,
41    ControlFlowContinue = 16,
42    ControlFlowBreak = 17,
43    Poll = 18,
44    PollReady = 19,
45    PollPending = 20,
46    Pin = 21,
47    OwnedBox = 22,
48    String = 23,
49    RangeFull = 28,
50    Range = 29,
51    RangeFrom = 30,
52    RangeTo = 31,
53    RangeInclusive = 32,
54    RangeToInclusive = 33,
55    Try = 34,
56    TryOutput = 35,
57    Fn = 43,
58    FnMut = 45,
59    FnOnce = 47,
60    FnOnceOutput = 49,
61    AsyncFn = 50,
62    AsyncFnMut = 52,
63    AsyncFnOnce = 54,
64    AsyncFnOnceOutput = 56,
65    Deref = 59,
66    DerefTarget = 60,
67    DerefMut = 62,
68    Index = 66,
69    IndexOutput = 67,
70    IndexMut = 69,
71    Iterator = 71,
72    IteratorItem = 72,
73    IntoIterator = 74,
74    IntoIteratorItem = 75,
75    Future = 78,
76    FutureOutput = 79,
77    IntoFuture = 81,
78    IntoFutureOutput = 82,
79    Add = 87,
80    Sub = 88,
81    Mul = 89,
82    Div = 90,
83    Rem = 91,
84    Neg = 92,
85    Not = 93,
86    BitXor = 94,
87    BitAnd = 95,
88    BitOr = 96,
89    Shl = 97,
90    Shr = 98,
91    Other = u16::MAX,
92}
93
94impl TyLangItem {
95    #[inline]
96    pub const fn is_fn_trait(self) -> bool {
97        matches!(self, Self::Fn | Self::FnMut | Self::FnOnce | Self::AsyncFn | Self::AsyncFnMut | Self::AsyncFnOnce)
98    }
99
100    #[inline]
101    pub const fn is_async_fn_trait(self) -> bool {
102        matches!(self, Self::AsyncFn | Self::AsyncFnMut | Self::AsyncFnOnce)
103    }
104
105    #[inline]
106    pub const fn is_range_adt(self) -> bool {
107        matches!(self, Self::Range | Self::RangeFrom | Self::RangeTo | Self::RangeInclusive | Self::RangeToInclusive | Self::RangeFull)
108    }
109}
110
111/// Value/record constructor shape of a `struct`, `union`, or `enum` variant.
112#[repr(u8)]
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
114pub enum CtorShapeKind {
115    #[default]
116    None = 0,
117    Unit = 1,
118    Tuple = 2,
119    Record = 3,
120}
121
122/// Candidate method produced during `3.3` inherent / trait / bound method resolution (`Copy`, `0` heap allocs).
123#[derive(Clone, Copy, Debug)]
124pub struct MethodCand {
125    /// Resolved `AssocFn` `GlobalDefId` (`impl`'s `AssocFn` when defined/overridden, else `trait`'s `AssocFn`).
126    pub method_def: GlobalDefId,
127    /// Enclosing `Trait` `GlobalDefId` (`GlobalDefId::NONE` for inherent methods).
128    pub trait_def: GlobalDefId,
129    /// Callable `GlobalDefId` holding generic `Fn*` parameter bounds (`trait` `AssocFn` when default or fallback).
130    pub bound_owner_def: GlobalDefId,
131    /// Number of non-lifetime generic parameters on the `impl` (`0` for direct `Param`/`Dyn`/`Opaque` bounds).
132    pub container_generics: u16,
133    /// Number of non-lifetime generic parameters declared on the method itself.
134    pub method_generics: u16,
135    /// `true` when `method_sig` uses `Trait` parameter indexing (`Param(0) = Self`, `1..1+N = trait_args`).
136    pub has_fixed_trait_subst: bool,
137    pub fixed_self_ty: InferTyId,
138    pub fixed_trait_args: TySliceRange,
139    pub is_blanket_impl: bool,
140    /// Enclosing `impl` identifier (`CrateId::LOCAL_OVERLAY` + `NodeId` for local CST, `(r_idx, impl_idx)` for `.ridx`).
141    pub impl_owner: GlobalDefId,
142    /// CST `NodeId` when backed by `LocalCstDefs` (`u32::MAX` when backed by `TyDefDb`).
143    pub cst_fn_node: u32,
144}
145
146/// Trait associated-function canonical metadata (`Checkbox 3.4`, `Copy`, `0` heap allocs).
147/// Lifts both `Trait::fn` and `Type::trait_fn` to `(trait_fn_def, [Self, TraitArgs.., MethodArgs..])`.
148#[derive(Clone, Copy, Debug)]
149pub struct TraitAssocFnMeta {
150    pub trait_def: GlobalDefId,
151    pub trait_fn_def: GlobalDefId,
152    pub trait_generics: u16,
153    pub method_generics: u16,
154}
155
156/// Parameterized `where`-clause or inline generic obligation (`Checkbox 3.4`, `Copy`, `0` heap allocs).
157#[derive(Clone, Copy, Debug)]
158pub enum WhereObligation {
159    TraitBound { lhs_ty: InferTyId, trait_def: GlobalDefId, trait_args: TySliceRange },
160    ProjectionEq { lhs_ty: InferTyId, trait_def: GlobalDefId, assoc_def: GlobalDefId, trait_args: TySliceRange, rhs_ty: InferTyId },
161}
162
163/// Result type shapes produced by built-in / stdlib declarative macro families (`Checkbox 3.6.2`).
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum StdMacroTy {
166    /// `vec![...]` -> `alloc::vec::Vec<elem, alloc::alloc::Global>`.
167    Vec(InferTyId),
168    /// `format!(...)` -> `alloc::string::String`.
169    String,
170    /// `format_args!(...)` / `format_args_nl!(...)` -> `core::fmt::Arguments<'_>`.
171    FmtArguments,
172    /// `core::fmt::Result` (`Result<(), core::fmt::Error>`).
173    FmtResult,
174    /// `option_env!(...)` -> `core::option::Option<&'static str>`.
175    OptionStr,
176    /// `thread_local! { static NAME: T = ...; }` -> `std::thread::LocalKey<T>`.
177    ThreadLocalKey(InferTyId),
178}
179
180/// External/indexed type & signature provider decoupling `ridx-syntax::ty_infer` from `ridx-format`.
181/// All methods materialize types directly into the caller's reusable [`InferTyArena`] (`0` heap allocs).
182pub trait TyDefDb {
183    /// Function or associated function signature: appends parameter types to `inputs_out` and returns
184    /// `(generic_type_or_const_param_count, output_ty)`.
185    fn fn_sig(&self, def: GlobalDefId, arena: &mut InferTyArena, inputs_out: &mut Vec<InferTyId>) -> Option<(u16, InferTyId)>;
186
187    /// Definition type for an ADT (`Struct`/`Enum`/`Union`), `Variant` (returns owning `Enum` ADT type),
188    /// `TypeAlias` (returns aliased target type), `Const`, or `Static`, along with `(generic_count, ctor_shape)`.
189    fn def_ty(&self, def: GlobalDefId, arena: &mut InferTyArena) -> Option<(u16, CtorShapeKind, InferTyId)>;
190
191    /// Tuple constructor field types for a tuple `Struct` or tuple `Variant`; returns `generic_count`.
192    fn ctor_tuple_fields(&self, def: GlobalDefId, arena: &mut InferTyArena, fields_out: &mut Vec<InferTyId>) -> Option<u16>;
193
194    /// Field type by name (or `"0"`, `"1"` for tuple fields) on a `Struct`, `Union`, or `Variant`,
195    /// returning `(generic_count, field_ty)` parameterized by `Param { idx, .. }`.
196    fn field_ty(&self, owner_def: GlobalDefId, name: &str, arena: &mut InferTyArena) -> Option<(u16, InferTyId)>;
197
198    /// Field type + field `GlobalDefId` by name (or `"0"`, `"1"` for tuple fields).
199    fn field_ty_and_def(&self, owner_def: GlobalDefId, name: &str, arena: &mut InferTyArena) -> Option<(u16, InferTyId, GlobalDefId)> {
200        self.field_ty(owner_def, name, arena).map(|(gc, ty)| (gc, ty, GlobalDefId::NONE))
201    }
202
203    /// Resolves a known compiler [`TyLangItem`] to its [`GlobalDefId`].
204    fn lang_item(&self, item: TyLangItem) -> Option<GlobalDefId>;
205
206    /// Reverse lookup: returns the [`TyLangItem`] tag of `def`, if `def` is a lang item.
207    fn lang_item_of_def(&self, def: GlobalDefId) -> Option<TyLangItem>;
208
209    /// Projects an associated type (`TryOutput`, `FutureOutput`, `IntoFutureOutput`, `DerefTarget`,
210    /// `IndexOutput`, `IntoIteratorItem`, `IteratorItem`, or operator `Output`) for `self_ty` and `trait_args`.
211    fn project_assoc_ty(&self, assoc_item: TyLangItem, self_ty: InferTyId, trait_args: &[InferTyId], arena: &mut InferTyArena, vars: &mut UnionFindTable) -> Option<InferTyId>;
212
213    /// Projects an arbitrary trait associated type `<self_ty as trait_def<trait_args>>::assoc_def`.
214    fn project_trait_assoc(
215        &self,
216        _trait_def: GlobalDefId,
217        _assoc_def: GlobalDefId,
218        _self_ty: InferTyId,
219        _trait_args: &[InferTyId],
220        _arena: &mut InferTyArena,
221        _vars: &mut UnionFindTable,
222    ) -> Option<InferTyId> {
223        None
224    }
225
226    /// Queries an `Fn*` / `AsyncFn*` trait bound on generic parameter `param_idx` of `owner_def`,
227    /// appending expected closure parameter types (containing `Param { idx, .. }`) to `inputs_out`
228    /// and returning `(fn_trait_item, ret_ty)`.
229    fn param_fn_bound(&self, owner_def: GlobalDefId, param_idx: u16, arena: &mut InferTyArena, inputs_out: &mut Vec<InferTyId>) -> Option<(TyLangItem, InferTyId)>;
230
231    /// Appends inherent `impl` method candidates (`has_self == true`) matching `(target, method_name)`.
232    fn inherent_method_cands(&self, _target: ImplTargetKey, _method_name: &str, _arena: &mut InferTyArena, _out: &mut Vec<MethodCand>) {}
233
234    /// Appends concrete and blanket `impl Trait for ...` method candidates (`has_self == true`) for `trait_def`
235    /// (including supertraits of `trait_def`) matching `(target, method_name)` and compatible with `step_ty`.
236    #[allow(clippy::too_many_arguments)]
237    fn trait_impl_method_cands(
238        &self,
239        _target: ImplTargetKey,
240        _trait_def: GlobalDefId,
241        _method_name: &str,
242        _step_ty: InferTyId,
243        _arena: &mut InferTyArena,
244        _vars: &mut UnionFindTable,
245        _out: &mut Vec<MethodCand>,
246    ) {
247    }
248
249    /// Looks up `method_name` (`has_self == true`) directly on `trait_def` (or its supertraits) for `Param`/`Dyn`/`Opaque` receivers.
250    fn trait_decl_method_cand(&self, _trait_def: GlobalDefId, _trait_args: &[InferTyId], _self_ty: InferTyId, _method_name: &str, _arena: &mut InferTyArena) -> Option<MethodCand> {
251        None
252    }
253
254    /// Materializes `cand.method_def`'s formal parameter types (`inputs_out[0]` = `self_param_ty`) and return type.
255    fn method_sig(&self, cand: &MethodCand, arena: &mut InferTyArena, inputs_out: &mut Vec<InferTyId>) -> Option<InferTyId> {
256        self.fn_sig(cand.method_def, arena, inputs_out).map(|(_, out)| out)
257    }
258
259    /// Appends direct supertraits (and optional instantiated trait args) of `trait_def`.
260    fn trait_supertraits(&self, _trait_def: GlobalDefId, _out: &mut Vec<GlobalDefId>) {}
261
262    /// Appends trait bounds `Param(param_idx): BoundTrait` declared on `owner_def` (`Fn` or `AssocFn` or `Impl`).
263    fn param_trait_bounds(&self, _owner_def: GlobalDefId, _param_idx: u16, _out: &mut Vec<GlobalDefId>) {}
264
265    /// Returns the parent `Trait` `GlobalDefId` of a trait associated type `assoc_def`.
266    fn assoc_ty_parent_trait(&self, _assoc_def: GlobalDefId) -> Option<GlobalDefId> {
267        None
268    }
269
270    /// Appends trait bounds `type Assoc: BoundTrait` declared on trait associated type `assoc_def`.
271    fn assoc_ty_trait_bounds(&self, _assoc_def: GlobalDefId, _out: &mut Vec<GlobalDefId>) {}
272
273    /// Verifies blanket-impl `where` bounds after binding `impl_subst` against a method receiver.
274    fn check_blanket_method_bounds(&self, _cand: &MethodCand, _impl_subst: &[InferTyId], _arena: &mut InferTyArena, _vars: &mut UnionFindTable) -> bool {
275        true
276    }
277
278    /// Returns canonical trait `AssocFn` metadata if `assoc_fn` is a trait declaration method or a trait-`impl` override.
279    fn trait_of_assoc_fn(&self, _assoc_fn: GlobalDefId) -> Option<TraitAssocFnMeta> {
280        None
281    }
282
283    /// Refines an inherent `AssocFn` when multiple specialized inherent `impl` blocks exist for `qself_ty` (e.g. `AtomicUsize::new`).
284    fn refine_inherent_assoc_fn(&self, assoc_fn: GlobalDefId, _qself_ty: InferTyId, _arena: &mut InferTyArena, _vars: &mut UnionFindTable) -> GlobalDefId {
285        assoc_fn
286    }
287
288    /// Looks up canonical trait `AssocFn` metadata by `(trait_def, fn_name)` (including static methods without `self`).
289    fn trait_assoc_fn_by_name(&self, _trait_def: GlobalDefId, _fn_name: &str) -> Option<TraitAssocFnMeta> {
290        None
291    }
292
293    /// Appends parameterized `TraitBound` and `ProjectionEq` `where` obligations declared on `owner_def` (and enclosing `impl`/`trait`).
294    fn owner_where_obligations(&self, _owner_def: GlobalDefId, _arena: &mut InferTyArena, _out: &mut Vec<WhereObligation>) {}
295    /// The trait bounds of the indexed `impl` that `cand` belongs to, with the impl's generic parameters as
296    /// `Param { idx }` in the order `check_blanket_method_bounds` substitutes them.
297    fn impl_trait_bounds(&self, _cand: &MethodCand, _arena: &mut InferTyArena, _out: &mut Vec<WhereObligation>) {}
298
299    /// Solves `<self_ty as trait_def<trait_args>>` against concrete and bound-checked blanket impls (`Checkbox 3.4`),
300    /// committing variable bindings into `vars` when a unique candidate impl matches.
301    fn solve_trait_obligation(&self, _trait_def: GlobalDefId, _self_ty: InferTyId, _trait_args: &[InferTyId], _arena: &mut InferTyArena, _vars: &mut UnionFindTable) -> bool {
302        false
303    }
304
305    /// Projects `<Param(param_idx) as trait_def<trait_args>>::assoc_def` from `owner_def`'s `ProjectionEq` bounds.
306    fn project_param_assoc(
307        &self,
308        _owner_def: GlobalDefId,
309        _param_idx: u16,
310        _trait_def: GlobalDefId,
311        _assoc_def: GlobalDefId,
312        _trait_args: &[InferTyId],
313        _arena: &mut InferTyArena,
314    ) -> Option<InferTyId> {
315        None
316    }
317
318    /// Optional `core::ffi::CStr` definition for `c"..."` literals (`&CStr`).
319    fn cstr_def(&self) -> Option<GlobalDefId> {
320        None
321    }
322
323    /// Returns the parameterized default type (`Param { idx: 0..param_idx }`) declared on non-lifetime
324    /// generic parameter `param_idx` of `def` (e.g. `Global` on `Vec<T, A = Global>`).
325    fn generic_param_default_ty(&self, _def: GlobalDefId, _param_idx: u16, _arena: &mut InferTyArena) -> Option<InferTyId> {
326        None
327    }
328
329    /// Constructs a well-known stdlib macro result type (`Vec<T, Global>`, `String`, `fmt::Arguments`, `fmt::Result`, `Option<&str>`).
330    fn std_macro_ty(&self, kind: StdMacroTy, arena: &mut InferTyArena) -> Option<InferTyId> {
331        match kind {
332            StdMacroTy::String => self.lang_item(TyLangItem::String).map(|d| arena.mk_adt(d, &[])),
333            StdMacroTy::OptionStr => self.lang_item(TyLangItem::Option).map(|d| arena.mk_adt(d, &[InferTyId::STR_REF])),
334            _ => None,
335        }
336    }
337}
338
339/// Zero-state [`TyDefDb`] when running pure local CST inference without an external `.ridx` index.
340#[derive(Clone, Copy, Debug, Default)]
341pub struct EmptyTyDefDb;
342
343impl TyDefDb for EmptyTyDefDb {
344    fn fn_sig(&self, _: GlobalDefId, _: &mut InferTyArena, _: &mut Vec<InferTyId>) -> Option<(u16, InferTyId)> {
345        None
346    }
347    fn def_ty(&self, _: GlobalDefId, _: &mut InferTyArena) -> Option<(u16, CtorShapeKind, InferTyId)> {
348        None
349    }
350    fn ctor_tuple_fields(&self, _: GlobalDefId, _: &mut InferTyArena, _: &mut Vec<InferTyId>) -> Option<u16> {
351        None
352    }
353    fn field_ty(&self, _: GlobalDefId, _: &str, _: &mut InferTyArena) -> Option<(u16, InferTyId)> {
354        None
355    }
356    fn lang_item(&self, _: TyLangItem) -> Option<GlobalDefId> {
357        None
358    }
359    fn lang_item_of_def(&self, _: GlobalDefId) -> Option<TyLangItem> {
360        None
361    }
362    fn project_assoc_ty(&self, _: TyLangItem, _: InferTyId, _: &[InferTyId], _: &mut InferTyArena, _: &mut UnionFindTable) -> Option<InferTyId> {
363        None
364    }
365    fn param_fn_bound(&self, _: GlobalDefId, _: u16, _: &mut InferTyArena, _: &mut Vec<InferTyId>) -> Option<(TyLangItem, InferTyId)> {
366        None
367    }
368}