Skip to main content

ridx_syntax/name_res/
impl_collect.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//! Flat CST arena (`LocalImplArena`) for `impl` blocks, `trait` associated items, and `type`
12//! alias targets on dirty-file overlays and unindexed local crates.
13
14use super::db::{FileId, GlobalDefId, ItemKind, ModuleId, VisKind};
15use super::db_impls::{ImplTargetKey, LocalImplId};
16use super::per_ns::LocalItemId;
17use super::use_tree::PathAnchor;
18use crate::sema_fn::norm_ident;
19use crate::syntax_kind::SyntaxKind as K;
20use crate::token::TokenKind as T;
21use crate::tree::{NodeId, SyntaxTree};
22
23#[derive(Clone, Copy, Debug, Default)]
24pub(super) enum RawSelfHead {
25    #[default]
26    Unknown,
27    Path {
28        anchor: PathAnchor,
29        seg_start: u32,
30        seg_len: u16,
31    },
32    DynPath {
33        anchor: PathAnchor,
34        seg_start: u32,
35        seg_len: u16,
36    },
37    Slice,
38    Array,
39    Tuple(u16),
40    Ref {
41        is_mut: bool,
42    },
43    Ptr {
44        is_mut: bool,
45    },
46    FnPtr {
47        arity: u16,
48    },
49    Never,
50}
51
52/// Locally extracted `impl` block (resolved into [`ImplTargetKey`] + `trait_def` after import solving).
53#[derive(Clone, Copy, Debug)]
54pub struct LocalImplData {
55    pub id: LocalImplId,
56    pub module: ModuleId,
57    pub file: FileId,
58    pub index_def: GlobalDefId,
59    pub is_negative: bool,
60    pub has_trait: bool,
61    pub(super) raw_head: RawSelfHead,
62    pub(super) trait_anchor: PathAnchor,
63    pub(super) trait_seg_start: u32,
64    pub(super) trait_seg_len: u16,
65    pub(super) gp_start: u32,
66    pub(super) gp_len: u16,
67    pub assoc_start: u32,
68    pub assoc_len: u16,
69    pub target: ImplTargetKey,
70    pub trait_def: GlobalDefId,
71    pub span_start: u32,
72    pub span_end: u32,
73}
74
75/// Associated `fn`, `const`, or `type` inside a local `impl` or `trait` block.
76#[derive(Clone, Copy, Debug)]
77pub struct LocalAssocItem {
78    pub def: GlobalDefId,
79    pub module: ModuleId,
80    pub file: FileId,
81    pub owner_impl: LocalImplId,
82    pub owner_trait: LocalItemId,
83    pub(super) name_start: u32,
84    pub(super) name_end: u32,
85    pub kind: ItemKind,
86    pub vis: VisKind,
87    pub vis_mod: ModuleId,
88    pub has_self_receiver: bool,
89    pub span_start: u32,
90    pub span_end: u32,
91}
92
93#[derive(Clone, Copy, Debug)]
94pub(super) struct LocalTypeAlias {
95    pub item_id: LocalItemId,
96    pub module: ModuleId,
97    pub gp_start: u32,
98    pub gp_len: u16,
99    pub raw_head: RawSelfHead,
100}
101
102#[derive(Clone, Copy, Debug)]
103pub(super) struct RawTraitSuper {
104    pub trait_item: LocalItemId,
105    pub module: ModuleId,
106    pub anchor: PathAnchor,
107    pub seg_start: u32,
108    pub seg_len: u16,
109}
110
111/// Contiguous arena of locally parsed `impl` blocks, `trait` associated items, and `type` aliases.
112#[derive(Clone, Debug, Default)]
113pub struct LocalImplArena {
114    pub(super) strings: String,
115    pub(super) segs: Vec<(u32, u32)>,
116    pub(super) generic_params: Vec<(u32, u32)>,
117    pub impls: Vec<LocalImplData>,
118    pub assoc_items: Vec<LocalAssocItem>,
119    /// `(trait_local_id, assoc_start, assoc_len)` for locally scanned `trait` definitions.
120    pub(super) trait_assocs: Vec<(LocalItemId, u32, u16)>,
121    pub(super) raw_trait_supers: Vec<RawTraitSuper>,
122    pub(super) local_trait_supers: Vec<(LocalItemId, GlobalDefId)>,
123    pub(super) type_aliases: Vec<LocalTypeAlias>,
124}
125
126impl LocalImplArena {
127    #[inline]
128    pub fn assoc_name(&self, item: &LocalAssocItem) -> &str {
129        &self.strings[item.name_start as usize..item.name_end as usize]
130    }
131
132    #[inline]
133    pub fn impl_assocs(&self, imp: &LocalImplData) -> &[LocalAssocItem] {
134        let s = imp.assoc_start as usize;
135        &self.assoc_items[s..s + imp.assoc_len as usize]
136    }
137
138    pub(super) fn push_str(&mut self, s: &str) -> (u32, u32) {
139        let start = self.strings.len() as u32;
140        self.strings.push_str(s);
141        (start, self.strings.len() as u32)
142    }
143
144    pub(super) fn push_generic_type_params(&mut self, st: &SyntaxTree<'_>, owner: NodeId) -> (u32, u16) {
145        let start = self.generic_params.len() as u32;
146        if let Some(gpl) = st.child(owner, K::GenericParamList) {
147            for gp in st.children(gpl) {
148                if st.kind(gp) == K::TypeParam {
149                    if let Some(nn) = st.child(gp, K::Name) {
150                        let sp = self.push_str(norm_ident(st.text(nn)));
151                        self.generic_params.push(sp);
152                    }
153                }
154            }
155        }
156        let len = (self.generic_params.len() as u32 - start).min(u16::MAX as u32) as u16;
157        (start, len)
158    }
159
160    pub(super) fn extract_type_head(&mut self, st: &SyntaxTree<'_>, mut ty_node: NodeId) -> RawSelfHead {
161        while st.kind(ty_node) == K::ParenType {
162            let Some(inner) = st.children(ty_node).find(|&c| st.kind(c).is_type()) else {
163                return RawSelfHead::Unknown;
164            };
165            ty_node = inner;
166        }
167        match st.kind(ty_node) {
168            K::PathType => match st.child(ty_node, K::Path) {
169                Some(p) => {
170                    let (anchor, seg_start, seg_len) = self.push_cst_path(st, p);
171                    RawSelfHead::Path { anchor, seg_start, seg_len }
172                }
173                None => RawSelfHead::Unknown,
174            },
175            K::DynTraitType => match find_first_path_in_dyn(st, ty_node) {
176                Some(p) => {
177                    let (anchor, seg_start, seg_len) = self.push_cst_path(st, p);
178                    RawSelfHead::DynPath { anchor, seg_start, seg_len }
179                }
180                None => RawSelfHead::Unknown,
181            },
182            K::RefType => RawSelfHead::Ref { is_mut: head_has_mut_before_inner_ty(st, ty_node) },
183            K::PtrType => RawSelfHead::Ptr { is_mut: head_has_mut_before_inner_ty(st, ty_node) },
184            K::SliceType => RawSelfHead::Slice,
185            K::ArrayType => RawSelfHead::Array,
186            K::TupleType => {
187                let arity = st.children(ty_node).filter(|&c| st.kind(c).is_type()).count() as u16;
188                RawSelfHead::Tuple(arity)
189            }
190            K::FnPtrType => {
191                let arity = st.child(ty_node, K::ParamList).map_or(0, |pl| st.children(pl).filter(|&c| st.kind(c) == K::Param).count() as u16);
192                RawSelfHead::FnPtr { arity }
193            }
194            K::NeverType => RawSelfHead::Never,
195            _ => RawSelfHead::Unknown,
196        }
197    }
198
199    pub(super) fn push_cst_path(&mut self, st: &SyntaxTree<'_>, path_node: NodeId) -> (PathAnchor, u32, u16) {
200        let mut anchor = PathAnchor::Bare;
201        let toks = st.tokens_of(path_node);
202        let mut sig = toks.iter().filter(|t| !t.is_trivia());
203        if let (Some(t0), Some(t1)) = (sig.next(), sig.next()) {
204            if t0.kind == T::Colon && t1.kind == T::Colon {
205                anchor = PathAnchor::ExternRoot;
206            }
207        }
208        let seg_start = self.segs.len() as u32;
209        let mut idx = 0usize;
210        let mut super_cnt = 0u16;
211        for seg_node in st.children(path_node) {
212            if st.kind(seg_node) != K::PathSegment {
213                continue;
214            }
215            let Some(seg_tok) = st.tokens_of(seg_node).iter().find(|t| !t.is_trivia()) else { continue };
216            match seg_tok.kind {
217                T::Crate if idx == 0 && anchor == PathAnchor::Bare => {
218                    anchor = PathAnchor::CrateRoot;
219                }
220                T::SelfKw if idx == 0 && anchor == PathAnchor::Bare => {
221                    anchor = PathAnchor::SelfMod;
222                }
223                T::Super if (idx == 0 && anchor == PathAnchor::Bare) || matches!(anchor, PathAnchor::Super(_)) => {
224                    if self.segs.len() as u32 == seg_start {
225                        super_cnt += 1;
226                        anchor = PathAnchor::Super(super_cnt);
227                    }
228                }
229                T::Ident | T::RawIdent | T::SelfType => {
230                    let sp = self.push_str(norm_ident(seg_tok.text(st.src)));
231                    self.segs.push(sp);
232                }
233                _ => return (PathAnchor::Bare, seg_start, 0),
234            }
235            idx += 1;
236        }
237        let seg_len = (self.segs.len() as u32 - seg_start).min(u16::MAX as u32) as u16;
238        (anchor, seg_start, seg_len)
239    }
240}
241
242fn find_first_path_in_dyn(st: &SyntaxTree<'_>, dyn_node: NodeId) -> Option<NodeId> {
243    for ch in st.children(dyn_node) {
244        match st.kind(ch) {
245            K::PathType => return st.child(ch, K::Path),
246            K::TypeBoundList => {
247                for b in st.children(ch) {
248                    if st.kind(b) == K::TypeBound {
249                        if let Some(p) = st.child(b, K::Path) {
250                            return Some(p);
251                        }
252                    }
253                }
254            }
255            _ => {}
256        }
257    }
258    None
259}
260
261fn head_has_mut_before_inner_ty(st: &SyntaxTree<'_>, ty_node: NodeId) -> bool {
262    let first_inner_tok = st.children(ty_node).find(|&c| st.kind(c).is_type()).map_or(st.node(ty_node).end, |c| st.node(c).first);
263    let start_tok = st.node(ty_node).first;
264    st.tokens[start_tok as usize..first_inner_tok as usize].iter().any(|t| t.kind == T::Mut)
265}