Skip to main content

ridx_syntax/name_res/
db_impls.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//! Simplified `impl` target keys, indexed `impl` descriptors, and in-memory [`OverlaySourceDb`]
12//! for dirty-file overrides over an existing [`SourceDb`].
13
14use std::collections::HashMap;
15
16use super::db::{FileId, GlobalDefId, SourceDb};
17use super::mod_tree::join_norm_path;
18use super::per_ns::PrimTy;
19
20/// Arena index into [`super::def_map::CrateDefMap::local_impls`].
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct LocalImplId(pub u32);
23
24impl LocalImplId {
25    pub const NONE: Self = Self(u32::MAX);
26
27    #[inline]
28    pub const fn is_some(self) -> bool {
29        self.0 != u32::MAX
30    }
31}
32
33impl Default for LocalImplId {
34    #[inline]
35    fn default() -> Self {
36        Self::NONE
37    }
38}
39
40/// Canonical simplified self-type head of an `impl` block (matches `.ridx` `v5` `SimplifiedType` buckets).
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub enum ImplTargetKey {
43    #[default]
44    Unknown,
45    /// `struct`, `enum`, or `union` identified by compiler or `LOCAL_OVERLAY` [`GlobalDefId`].
46    Adt(GlobalDefId),
47    /// Builtin primitive (`u32`, `str`, `bool`, ...).
48    Prim(PrimTy),
49    /// `[T]` slice type.
50    Slice,
51    /// `[T; N]` fixed-size array type.
52    Array,
53    /// `(T0, T1, ...)` tuple of the given arity (`0` for unit `()`).
54    Tuple(u16),
55    /// `&T` (`is_mut = false`) or `&mut T` (`is_mut = true`).
56    Ref { is_mut: bool },
57    /// `*const T` (`is_mut = false`) or `*mut T` (`is_mut = true`).
58    Ptr { is_mut: bool },
59    /// `fn(A, B) -> R` function pointer of the given parameter count.
60    FnPtr { arity: u16 },
61    /// `dyn Trait + ...` trait object keyed by principal trait [`GlobalDefId`].
62    Dyn(GlobalDefId),
63    /// `!` never type.
64    Never,
65    /// Blanket generic parameter self type (`impl<T> Trait for T`).
66    Param,
67}
68
69/// One `impl` block entry in [`super::db::ItemDb`].
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub struct IndexedImpl {
72    pub id: GlobalDefId,
73    /// Defining workspace [`FileId`] (`FileId::NONE` for external dependency crates).
74    /// When `file` is in `dirty_files`, this indexed `impl` is suppressed in favor of the dirty CST.
75    pub file: FileId,
76    pub target: ImplTargetKey,
77    /// Implemented trait [`GlobalDefId`] (`GlobalDefId::NONE` for inherent `impl` blocks).
78    pub trait_def: GlobalDefId,
79    pub is_negative: bool,
80}
81
82impl IndexedImpl {
83    #[inline]
84    pub const fn is_inherent(&self) -> bool {
85        !self.trait_def.is_some()
86    }
87}
88
89/// Overlay [`SourceDb`] layering unsaved/edited file contents (and newly created unsaved files)
90/// on top of an immutable base [`SourceDb`] without copying clean files.
91pub struct OverlaySourceDb<'a> {
92    base: &'a dyn SourceDb,
93    base_file_count: u32,
94    overrides: HashMap<FileId, String>,
95    added_files: Vec<(String, String)>,
96    added_by_path: HashMap<String, FileId>,
97    dirty_list: Vec<FileId>,
98}
99
100impl<'a> OverlaySourceDb<'a> {
101    pub fn new(base: &'a dyn SourceDb, base_file_count: u32) -> Self {
102        Self { base, base_file_count, overrides: HashMap::new(), added_files: Vec::new(), added_by_path: HashMap::new(), dirty_list: Vec::new() }
103    }
104
105    /// Overrides the text of an existing `file` and marks `file` dirty.
106    pub fn set_file_override(&mut self, file: FileId, new_text: impl Into<String>) {
107        self.overrides.insert(file, new_text.into());
108        if !self.dirty_list.contains(&file) {
109            self.dirty_list.push(file);
110        }
111    }
112
113    /// Overrides an existing path in `base` or registers a brand-new unsaved virtual file at `rel_path`.
114    pub fn upsert_path(&mut self, rel_path: &str, new_text: impl Into<String>) -> FileId {
115        let norm = join_norm_path("", rel_path);
116        if let Some(existing) = self.base.resolve_path(&norm) {
117            self.set_file_override(existing, new_text);
118            return existing;
119        }
120        if let Some(&added_id) = self.added_by_path.get(&norm) {
121            let idx = (added_id.0 - self.base_file_count) as usize;
122            self.added_files[idx].1 = new_text.into();
123            return added_id;
124        }
125        let id = FileId(self.base_file_count + self.added_files.len() as u32);
126        self.added_files.push((norm.clone(), new_text.into()));
127        self.added_by_path.insert(norm, id);
128        self.dirty_list.push(id);
129        id
130    }
131
132    /// Slice of all dirty [`FileId`]s modified or added in this overlay.
133    #[inline]
134    pub fn dirty_files(&self) -> &[FileId] {
135        &self.dirty_list
136    }
137}
138
139impl SourceDb for OverlaySourceDb<'_> {
140    fn file_path(&self, file: FileId) -> &str {
141        if file.0 >= self.base_file_count {
142            if let Some((p, _)) = self.added_files.get((file.0 - self.base_file_count) as usize) {
143                return p.as_str();
144            }
145        }
146        self.base.file_path(file)
147    }
148
149    fn file_text(&self, file: FileId) -> &str {
150        if let Some(ov) = self.overrides.get(&file) {
151            return ov.as_str();
152        }
153        if file.0 >= self.base_file_count {
154            if let Some((_, t)) = self.added_files.get((file.0 - self.base_file_count) as usize) {
155                return t.as_str();
156            }
157        }
158        self.base.file_text(file)
159    }
160
161    fn resolve_path(&self, rel_path: &str) -> Option<FileId> {
162        let norm = join_norm_path("", rel_path);
163        self.added_by_path.get(&norm).copied().or_else(|| self.base.resolve_path(&norm))
164    }
165}