Skip to main content

ridx_format/workspace/navigation/
decl_lookup.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//! Trait-item declaration lookup for `textDocument/declaration` and macro-based trait rename expansion.
12
13use super::impl_parse::parse_impl_def_path;
14use super::qualified_path::{extract_impl_trait, extract_root_crate};
15use super::trait_impl_refs::{path_matches_trait, strip_generics};
16use super::*;
17use std::collections::HashSet;
18
19impl WorkspaceIndex {
20    /// Resolves the trait declaration for an associated item defined inside a trait `impl`.
21    pub fn find_trait_item_declaration<'a>(&'a self, def: &ResolvedDefinition<'a>) -> Option<ResolvedDefinition<'a>> {
22        if !matches!(def.kind, DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy) || def.name.is_empty() {
23            return None;
24        }
25        let trait_str = extract_impl_trait(def.path).or_else(|| self.find_enclosing_impl_trait_path(def))?;
26        let raw_trait = strip_generics(trait_str);
27        if raw_trait.is_empty() {
28            return None;
29        }
30
31        let mut cands = std_map::std_path_candidates(raw_trait);
32        if let Some(rest) = raw_trait.strip_prefix("core::") {
33            cands.extend([format!("std::{rest}"), format!("alloc::{rest}")]);
34        } else if let Some(rest) = raw_trait.strip_prefix("alloc::") {
35            cands.extend([format!("std::{rest}"), format!("core::{rest}")]);
36        }
37        if let Some(r_idx) = def.reader_idx {
38            let def_crate = self.readers[r_idx].crate_name();
39            if !def_crate.is_empty() && !raw_trait.starts_with(&format!("{def_crate}::")) {
40                cands.push(format!("{def_crate}::{raw_trait}"));
41            }
42        }
43
44        let mut checked = HashSet::new();
45        for idx in def.reader_idx.into_iter().chain(cands.iter().flat_map(|tp| self.readers_for_crate_fast(extract_root_crate(tp)).into_owned())).chain(0..self.readers.len()) {
46            if checked.insert(idx) {
47                if let Some(res) = self.search_trait_item_decl_in_reader(idx, def, raw_trait, &cands) {
48                    return Some(res);
49                }
50            }
51        }
52        None
53    }
54
55    pub(super) fn find_enclosing_impl_trait_path<'a>(&'a self, def: &ResolvedDefinition<'a>) -> Option<&'a str> {
56        let r = self.readers.get(def.reader_idx?)?;
57        find_enclosing_impl_trait_at(r, r.find_file_id(def.file)?, def.start_line)
58    }
59
60    fn search_trait_item_decl_in_reader<'a>(&'a self, reader_idx: usize, def: &ResolvedDefinition<'a>, raw_trait: &str, cands: &[String]) -> Option<ResolvedDefinition<'a>> {
61        let (r, cname) = (&self.readers[reader_idx], self.readers[reader_idx].crate_name());
62        let is_valid_item = |d: &DefEntry| -> bool {
63            DefKind::from(d.kind) == def.kind
64                && !d.is_reexport()
65                && r.get_str(d.name_offset()) == def.name
66                && r.get_file(d.span().file_id()) != "external"
67                && extract_impl_trait(r.get_str(d.path_offset())).is_none()
68        };
69        let mut matches: Vec<&DefEntry> = Vec::new();
70        let push_unique = |matches: &mut Vec<&'a DefEntry>, d: &'a DefEntry| {
71            if is_valid_item(d) && !matches.iter().any(|existing| std::ptr::eq(*existing, d)) {
72                matches.push(d);
73            }
74        };
75        for tp in cands {
76            let local_tp = tp.strip_prefix(&format!("{cname}::")).unwrap_or(tp);
77            let global_tp = format!("{cname}::{local_tp}");
78            for owner_q in [local_tp, global_tp.as_str(), tp.as_str()] {
79                r.find_definitions_by_owner(owner_q).into_iter().for_each(|d| push_unique(&mut matches, d));
80            }
81            for path_q in [format!("{local_tp}::{}", def.name), format!("{global_tp}::{}", def.name)] {
82                if let Some(d) = r.find_definition_by_path(&path_q) {
83                    push_unique(&mut matches, d);
84                }
85            }
86        }
87        if matches.is_empty() && (Some(reader_idx) == def.reader_idx || cands.iter().any(|tp| extract_root_crate(tp) == cname)) {
88            let (local_raw, global_raw) =
89                (raw_trait.strip_prefix(&format!("{cname}::")).unwrap_or(raw_trait), format!("{cname}::{}", raw_trait.strip_prefix(&format!("{cname}::")).unwrap_or(raw_trait)));
90            for td in r.definitions().iter().filter(|td| DefKind::from(td.kind) == DefKind::Trait) {
91                let dp = r.get_str(td.path_offset());
92                if path_matches_trait(dp, raw_trait, local_raw, &global_raw, cands) {
93                    for owner_q in [dp, dp.strip_prefix(&format!("{cname}::")).unwrap_or(dp)] {
94                        r.find_definitions_by_owner(owner_q).into_iter().for_each(|d| push_unique(&mut matches, d));
95                    }
96                }
97            }
98        }
99        let best = matches
100            .iter()
101            .copied()
102            .filter(|d| Some(reader_idx) == def.reader_idx && r.get_file(d.span().file_id()) == def.file && d.span().start_line() <= def.start_line)
103            .max_by_key(|d| d.span().start_line())
104            .or_else(|| matches.first().copied())?;
105        Some(self.make_resolved_definition(reader_idx, best))
106    }
107
108    pub fn external_trait_for_def(&self, def: &ResolvedDefinition<'_>) -> Option<String> {
109        self.external_trait_for_target(def.kind, def.path, def.reader_idx, def.file, def.start_line, &def.resolved_path())
110    }
111
112    pub fn external_trait_for_impl_item(&self, loc_refs: &LocationReferences<'_>) -> Option<String> {
113        self.external_trait_for_target(
114            loc_refs.target_kind,
115            loc_refs.target_path,
116            loc_refs.target_reader_idx,
117            loc_refs.target_file,
118            loc_refs.target_line,
119            &loc_refs.target_resolved_path(),
120        )
121    }
122
123    fn external_trait_for_target(&self, kind: DefKind, path: &str, reader_idx: Option<usize>, file: &str, line: u32, resolved_p: &Path) -> Option<String> {
124        if !matches!(kind, DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst | DefKind::Field) {
125            return None;
126        }
127        let check_trait_is_external = |tr: &str| -> Option<String> {
128            let base_tr = strip_generics(tr);
129            if base_tr.is_empty() {
130                return None;
131            }
132            if matches!(extract_root_crate(base_tr), "core" | "alloc" | "std" | "proc_macro") {
133                return Some(base_tr.to_string());
134            }
135            if self.resolve_workspace_trait_container(base_tr, reader_idx, true).is_some_and(|(t, _, _)| t.is_some_and(|i| !self.is_reader_external(i))) {
136                return None;
137            }
138            let trait_short = base_tr.rsplit("::").next().unwrap_or(base_tr);
139            (!self.rename_cache().ws_trait_short_names.contains(trait_short)).then(|| base_tr.to_string())
140        };
141        if kind != DefKind::Field {
142            if let Some(tr) = extract_impl_trait(path) {
143                return check_trait_is_external(tr);
144            }
145            if let Some((raw_parent, _)) = path.rsplit_once("::") {
146                if self.resolve_workspace_trait_container(raw_parent, reader_idx, false).is_some_and(|(t, _, _)| t.is_some_and(|i| !self.is_reader_external(i))) {
147                    return None;
148                }
149            }
150            if let Some(ri) = reader_idx {
151                if let Some(r) = self.readers.get(ri) {
152                    if let Some(fid) = r.find_file_id(file) {
153                        let defs = r.definitions();
154                        let mut found_impl = false;
155                        for &(_, _, d_idx) in self.unit_match.defs_in_file_up_to(ri, fid, line) {
156                            if let Some(d) = defs.get(d_idx as usize) {
157                                if DefKind::from(d.kind) == DefKind::Impl && d.span().start_line() <= line && line <= d.span().end_line() {
158                                    found_impl = true;
159                                    if let (Some(tr), _) = parse_impl_def_path(r.get_str(d.path_offset())) {
160                                        let base_tr = strip_generics(tr);
161                                        if !base_tr.contains("::") {
162                                            for &(_, _, td_idx) in self.unit_match.defs_in_file_up_to(ri, fid, u32::MAX) {
163                                                if let Some(td) =
164                                                    defs.get(td_idx as usize).filter(|td| DefKind::from(td.kind) == DefKind::Trait && r.get_str(td.name_offset()) == base_tr)
165                                                {
166                                                    return check_trait_is_external(r.get_str(td.path_offset()));
167                                                }
168                                            }
169                                        }
170                                        return check_trait_is_external(tr);
171                                    }
172                                }
173                            }
174                        }
175                        if found_impl {
176                            return None;
177                        }
178                    }
179                }
180            }
181        }
182        let content = self.read_source_file(file).or_else(|| std::fs::read_to_string(resolved_p).ok())?;
183        if !content.contains(" for ") {
184            return None;
185        }
186        let (lines, idx) = (content.lines().collect::<Vec<&str>>(), line.saturating_sub(1) as usize);
187        if kind == DefKind::Field && !lines.get(idx).is_some_and(|l| l.trim_start().starts_with("fn ")) {
188            return None;
189        }
190        lines.get(idx).and_then(|_| find_enclosing_trait_in_impl_for(&lines, idx)).and_then(&check_trait_is_external)
191    }
192}
193
194pub(super) fn pm_declares_derive_for_trait(content: &str, trait_short: &str) -> bool {
195    use crate::workspace::cursor_path::is_ident_byte;
196    !trait_short.is_empty()
197        && content.contains("proc_macro_derive")
198        && content.match_indices(&format!("proc_macro_derive({trait_short}")).any(|(pos, m)| pos + m.len() >= content.len() || !is_ident_byte(content.as_bytes()[pos + m.len()]))
199}
200
201pub(super) fn collect_enum_variant_idents_from_source(content: &str, enum_name: &str, start_line_1based: u32, out: &mut HashSet<String>) {
202    use crate::workspace::cursor_path::is_ident_byte;
203    let (mut depth, mut entered) = (0i32, false);
204    for raw_ln in content.lines().skip(start_line_1based.saturating_sub(1) as usize) {
205        let code = crate::workspace::rename_parse::strip_line_comment(raw_ln);
206        for (i, ch) in code.char_indices() {
207            match ch {
208                '{' => {
209                    depth += 1;
210                    entered = true;
211                }
212                '}' => {
213                    depth -= 1;
214                    if entered && depth <= 0 {
215                        return;
216                    }
217                }
218                _ if entered && depth == 1 && (ch.is_ascii_alphabetic() || ch == '_') && (i == 0 || !is_ident_byte(code.as_bytes()[i - 1])) => {
219                    let prev = code[..i].trim_end();
220                    if prev.is_empty() || prev.ends_with('{') || prev.ends_with(',') || prev.ends_with(']') {
221                        let len = code[i..].bytes().take_while(|&b| is_ident_byte(b)).count();
222                        let ident = &code[i..i + len];
223                        if ident != enum_name && !matches!(ident, "pub" | "crate" | "super") {
224                            out.insert(ident.to_string());
225                        }
226                    }
227                }
228                _ => {}
229            }
230        }
231    }
232}
233
234pub(crate) fn reader_has_def_kind_at_path(r: &IndexReader<memmap2::Mmap>, path: &str, kind: DefKind) -> bool {
235    let hash = crate::format::fnv1a_64(path.as_bytes());
236    let defs_hash = r.defs_by_hash();
237    let Ok(idx) = defs_hash.binary_search_by_key(&hash, |e| e.hash()) else { return false };
238    let defs = r.definitions();
239    let mut i = idx;
240    while i > 0 && defs_hash[i - 1].hash() == hash {
241        i -= 1;
242    }
243    while i < defs_hash.len() && defs_hash[i].hash() == hash {
244        let d = &defs[defs_hash[i].index() as usize];
245        if DefKind::from(d.kind) == kind && r.get_str(d.path_offset()) == path {
246            return true;
247        }
248        i += 1;
249    }
250    false
251}
252
253pub(crate) fn reader_has_non_trait_type_at_path(r: &IndexReader<memmap2::Mmap>, path: &str) -> bool {
254    let hash = crate::format::fnv1a_64(path.as_bytes());
255    let defs_hash = r.defs_by_hash();
256    let Ok(idx) = defs_hash.binary_search_by_key(&hash, |e| e.hash()) else { return false };
257    let defs = r.definitions();
258    let mut i = idx;
259    while i > 0 && defs_hash[i - 1].hash() == hash {
260        i -= 1;
261    }
262    while i < defs_hash.len() && defs_hash[i].hash() == hash {
263        let d = &defs[defs_hash[i].index() as usize];
264        if matches!(DefKind::from(d.kind), DefKind::Struct | DefKind::Enum | DefKind::Union) && r.get_str(d.path_offset()) == path {
265            return true;
266        }
267        i += 1;
268    }
269    false
270}
271
272fn find_enclosing_trait_in_impl_for<'a>(lines: &[&'a str], line_idx: usize) -> Option<&'a str> {
273    let mut brace_depth = 0i32;
274    for l in (line_idx.saturating_sub(120)..=line_idx).rev() {
275        let code = lines[l].split("//").next().unwrap_or(lines[l]);
276        if l < line_idx {
277            brace_depth += code.bytes().rev().map(|b| i32::from(b == b'}') - i32::from(b == b'{')).sum::<i32>();
278        }
279        if brace_depth < 0 {
280            let rest = code.trim_start().strip_prefix("unsafe ").map(str::trim_start).unwrap_or_else(|| code.trim_start());
281            if let Some(after_impl) = rest.strip_prefix("impl").filter(|s| s.starts_with(|c: char| c.is_whitespace() || c == '<')) {
282                let mut header = String::from(after_impl);
283                for extra in lines.iter().take((l + 6).min(lines.len())).skip(l + 1) {
284                    if !header.contains('{') && !header.contains(" for ") {
285                        header.push(' ');
286                        header.push_str(extra.split("//").next().unwrap_or(extra).trim());
287                    }
288                }
289                let (before_for, _) = header.split('{').next().unwrap_or(&header).split_once(" for ")?;
290                let tr = crate::workspace::cursor_path::strip_generics_and_refs(before_for.trim());
291                let idx_in_line = code.find(tr)?;
292                return Some(&code[idx_in_line..idx_in_line + tr.len()]);
293            }
294            if ["trait ", "pub trait ", "pub(crate) trait "].iter().any(|p| rest.starts_with(p)) {
295                return None;
296            }
297        }
298    }
299    None
300}
301
302pub(crate) fn find_enclosing_impl_trait_for_entry<'a>(r: &'a IndexReader<memmap2::Mmap>, impl_def: &DefEntry) -> Option<&'a str> {
303    find_enclosing_impl_trait_at(r, impl_def.span().file_id(), impl_def.span().start_line())
304}
305
306fn find_enclosing_impl_trait_at(r: &IndexReader<memmap2::Mmap>, file_id: u32, line: u32) -> Option<&str> {
307    for d in
308        r.definitions().iter().filter(|d| DefKind::from(d.kind) == DefKind::Impl && d.span().file_id() == file_id && d.span().start_line() <= line && line <= d.span().end_line())
309    {
310        if let (Some(tr), _) = parse_impl_def_path(r.get_str(d.path_offset())) {
311            let base_tr = strip_generics(tr);
312            if !base_tr.contains("::") {
313                if let Some(td) =
314                    r.definitions().iter().find(|td| DefKind::from(td.kind) == DefKind::Trait && td.span().file_id() == file_id && r.get_str(td.name_offset()) == base_tr)
315                {
316                    return Some(r.get_str(td.path_offset()));
317                }
318            }
319            return Some(tr);
320        }
321    }
322    None
323}
324
325fn read_crate_source(ws: &WorkspaceIndex, r_crate: &str, r_file: &str) -> Option<String> {
326    ws.read_source_file(r_file).or_else(|| ws.resolve_path_for_crate(r_crate, r_file).to_str().and_then(|s| ws.read_source_file(s)))
327}
328
329pub(crate) fn is_synthesized_assoc_fn_ref(ws: &WorkspaceIndex, r_crate: &str, r_file: &str, sp: crate::format::Span, def: &ResolvedDefinition<'_>, target_name: &str) -> bool {
330    if sp.start_line() == def.start_line && (r_file == def.file || r_file.ends_with(def.file) || def.file.ends_with(r_file)) {
331        return false;
332    }
333    if sp.start_line() == 0 || sp.start_col() == 0 {
334        return true;
335    }
336    let Some(c) = read_crate_source(ws, r_crate, r_file) else { return false };
337    let (l_idx, lines): (usize, Vec<&str>) = (sp.start_line() as usize - 1, c.lines().collect());
338    let Some(&ln) = lines.get(l_idx) else { return false };
339    if ln.trim_start().starts_with("//") {
340        return false;
341    }
342    let chars: Vec<char> = ln.chars().collect();
343    let (sc, ec) = ((sp.start_col() as usize - 1).min(chars.len()), if sp.end_line() == sp.start_line() { (sp.end_col() as usize - 1).min(chars.len()) } else { 0 });
344    let span_text: String = if sc <= ec { chars[sc..ec].iter().collect() } else { String::new() };
345    if span_text != target_name && span_text.strip_prefix("r#") != Some(target_name) {
346        return true;
347    }
348    let pfx: String = chars[..sc].iter().collect();
349    if !pfx.trim_end().is_empty() {
350        return !pfx.trim_end().ends_with('.') && !pfx.trim_end().ends_with("::");
351    }
352    lines[..l_idx].iter().rev().map(|s| s.split("//").next().unwrap_or(s).trim_end()).find(|s| !s.is_empty()).is_none_or(|p| !p.ends_with('.') && !p.ends_with("::"))
353}
354
355impl WorkspaceIndex {
356    /// Checks the source declaration header to distinguish unrestricted `pub` from private or `pub(...)` items.
357    pub fn is_decl_externally_pub(&self, reader_idx: Option<usize>, file: &str, line_1b: u32, short_name: &str) -> bool {
358        if file.is_empty() || file == "external" || line_1b == 0 || short_name.is_empty() {
359            return true;
360        }
361        let cname = reader_idx.and_then(|ri| self.readers.get(ri)).map(|r| r.crate_name()).unwrap_or("");
362        let Some(c) = read_crate_source(self, cname, file) else { return true };
363        let (l_idx, lines): (usize, Vec<&str>) = (line_1b as usize - 1, c.lines().collect());
364        let Some(&decl_raw) = lines.get(l_idx) else { return true };
365        let (decl_code, is_id) = (decl_raw.split("//").next().unwrap_or(decl_raw), |b: u8| b.is_ascii_alphanumeric() || b == b'_');
366        let db = decl_code.as_bytes();
367        let Some((npos, _)) =
368            decl_code.match_indices(short_name).find(|&(p, _)| (p == 0 || !is_id(db[p - 1])) && (p + short_name.len() >= db.len() || !is_id(db[p + short_name.len()])))
369        else {
370            return true;
371        };
372        let mut raw: String = lines[l_idx.saturating_sub(3)..l_idx].iter().map(|l| l.split("//").next().unwrap_or(l)).collect::<Vec<_>>().join(" ");
373        raw.push(' ');
374        raw.push_str(&decl_code[..npos + short_name.len()]);
375        let (mut clean, mut depth) = (String::with_capacity(raw.len()), 0i32);
376        for ch in raw.chars() {
377            match ch {
378                '[' => depth += 1,
379                ']' => depth = (depth - 1).max(0),
380                '#' if depth == 0 => clean.push(' '),
381                _ if depth == 0 => clean.push(ch),
382                _ => {}
383            }
384        }
385        let seg = clean.rsplit([';', '{', '}']).next().unwrap_or(&clean);
386        let sb = seg.as_bytes();
387        let has_kw = ["fn", "const", "static", "struct", "enum", "union", "type", "trait", "mod"]
388            .iter()
389            .any(|kw| seg.match_indices(kw).any(|(p, _)| (p == 0 || !is_id(sb[p - 1])) && (p + kw.len() < sb.len() && !is_id(sb[p + kw.len()]))));
390        !has_kw
391            || seg
392                .match_indices("pub")
393                .any(|(p, _)| (p == 0 || !is_id(sb[p - 1])) && (p + 3 >= sb.len() || !is_id(sb[p + 3])) && seg[p + 3..].trim_start().as_bytes().first() != Some(&b'('))
394    }
395}