Skip to main content

ridx_format/workspace/
std_map.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//! Standard library path mapping for symbol resolution.
12//!
13//! Standard library types in rustc's canonical definitions (produced with `with_no_visible_paths!`)
14//! originate in `core` or `alloc` rather than `std`. This module maps `std::...` query paths to
15//! their canonical underlying `core::...` and `alloc::...` locations.
16
17/// Returns candidate paths for a query symbol path.
18///
19/// If the path starts with `"std::"`, candidates include:
20/// 1. The original `"std::..."` path.
21/// 2. The `"core::..."` path equivalent.
22/// 3. The `"alloc::..."` path equivalent.
23///
24/// Otherwise, returns only the original path.
25const STD_INTERNAL_PUBLIC_PAIRS: &[(&str, &str)] = &[
26    ("future::future::Future", "future::Future"),
27    ("future::into_future::IntoFuture", "future::IntoFuture"),
28    ("iter::traits::iterator::Iterator", "iter::Iterator"),
29    ("iter::traits::collect::IntoIterator", "iter::IntoIterator"),
30    ("iter::traits::collect::FromIterator", "iter::FromIterator"),
31    ("iter::traits::collect::Extend", "iter::Extend"),
32    ("iter::traits::double_ended::DoubleEndedIterator", "iter::DoubleEndedIterator"),
33    ("iter::traits::exact_size::ExactSizeIterator", "iter::ExactSizeIterator"),
34    ("ops::deref::Deref", "ops::Deref"),
35    ("ops::deref::DerefMut", "ops::DerefMut"),
36    ("ops::drop::Drop", "ops::Drop"),
37];
38
39pub fn std_path_candidates(path: &str) -> Vec<String> {
40    let mut candidates = Vec::with_capacity(8);
41    candidates.push(path.to_string());
42    let rest_and_others: Option<(&str, [&str; 2])> = if let Some(r) = path.strip_prefix("std::") {
43        Some((r, ["core", "alloc"]))
44    } else if let Some(r) = path.strip_prefix("core::") {
45        Some((r, ["std", "alloc"]))
46    } else if let Some(r) = path.strip_prefix("alloc::") {
47        Some((r, ["std", "core"]))
48    } else {
49        None
50    };
51    if let Some((rest, others)) = rest_and_others {
52        for o in others {
53            candidates.push(format!("{o}::{rest}"));
54        }
55        for &(internal, public) in STD_INTERNAL_PUBLIC_PAIRS {
56            let mapped = if let Some(tail) = rest.strip_prefix(internal) {
57                (tail.is_empty() || tail.starts_with("::") || tail.starts_with('<')).then(|| format!("{public}{tail}"))
58            } else if let Some(tail) = rest.strip_prefix(public) {
59                (tail.is_empty() || tail.starts_with("::") || tail.starts_with('<')).then(|| format!("{internal}{tail}"))
60            } else {
61                None
62            };
63            if let Some(alt_rest) = mapped {
64                for root in ["core", "std"] {
65                    let cand = format!("{root}::{alt_rest}");
66                    if !candidates.contains(&cand) {
67                        candidates.push(cand);
68                    }
69                }
70            }
71        }
72        if rest.contains("::<impl ") {
73            let extra: Vec<String> = candidates
74                .iter()
75                .flat_map(|c| {
76                    let mut v = Vec::new();
77                    for from in ["::<impl core::", "::<impl alloc::", "::<impl std::"] {
78                        if c.contains(from) {
79                            for to in ["::<impl std::", "::<impl core::", "::<impl alloc::"] {
80                                if from != to {
81                                    v.push(c.replacen(from, to, 1));
82                                }
83                            }
84                        }
85                    }
86                    v
87                })
88                .collect();
89            for e in extra {
90                if !candidates.contains(&e) {
91                    candidates.push(e);
92                }
93            }
94        }
95    }
96    candidates
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn test_std_path_candidates_with_std() {
105        let candidates = std_path_candidates("std::vec::Vec");
106        assert_eq!(candidates, vec!["std::vec::Vec", "core::vec::Vec", "alloc::vec::Vec"]);
107    }
108
109    #[test]
110    fn test_std_path_candidates_without_std() {
111        let candidates = std_path_candidates("my_crate::Foo");
112        assert_eq!(candidates, vec!["my_crate::Foo"]);
113    }
114
115    #[test]
116    fn test_workspace_find_definition_by_path_std_mapping() {
117        use crate::format::DefKind;
118        use crate::workspace::WorkspaceIndex;
119        use crate::writer::{IndexWriter, RawDefinition};
120        use std::fs::File;
121
122        let mut w = IndexWriter::new("alloc", "1.0.0");
123        w.add_definition(RawDefinition {
124            def_id: 1,
125            name: "Vec".to_string(),
126            path: "alloc::vec::Vec".to_string(),
127            kind: DefKind::Struct,
128            visibility: 1,
129            is_macro_expansion: false,
130            file: "alloc/src/vec/mod.rs".to_string(),
131            start_line: 10,
132            start_col: 1,
133            end_line: 10,
134            end_col: 10,
135            signature: None,
136        });
137
138        let temp_dir = std::env::temp_dir().join(format!("ridx_std_test_{}", std::process::id()));
139        let _ = std::fs::create_dir_all(&temp_dir);
140        let ridx_path = temp_dir.join("alloc.ridx");
141        {
142            let mut fc = File::create(&ridx_path).unwrap();
143            w.write_to(&mut fc).unwrap();
144        }
145
146        let ws = WorkspaceIndex::open(&ridx_path).unwrap();
147
148        // 1. Direct canonical query
149        let def1 = ws.find_definition_by_path("alloc::vec::Vec").expect("found alloc::vec::Vec");
150        assert_eq!(def1.name, "Vec");
151
152        // 2. Query mapped from std::
153        let def2 = ws.find_definition_by_path("std::vec::Vec").expect("found std::vec::Vec via std mapping");
154        assert_eq!(def2.name, "Vec");
155        assert_eq!(def2.path, "alloc::vec::Vec");
156
157        // 3. Search symbols mapped from std::
158        let syms = ws.search_symbols("std::vec::Vec");
159        assert_eq!(syms.len(), 1);
160        assert_eq!(syms[0].name, "Vec");
161
162        let _ = std::fs::remove_dir_all(&temp_dir);
163    }
164}