Skip to main content

ridx_format/
paths.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//! Path spellings shared by the shard reader and the workspace layer: the lexical form of a path
12//! as rustc, cargo and the driver may spell it, without touching the filesystem.
13
14use std::path::{Path, PathBuf};
15
16/// Normalizes a path by removing redundant `.` and resolving `..` components lexically. A `..`
17/// after a normal component removes it; a leading `..` of a relative path is kept, a `..` right
18/// after the root of an absolute path is dropped. Symlinks are not consulted: callers that need
19/// filesystem identity resolve the path first.
20pub fn normalize_path(path: &Path) -> PathBuf {
21    use std::path::Component;
22    let mut components = Vec::new();
23    for c in path.components() {
24        match c {
25            Component::CurDir => {}
26            Component::ParentDir => {
27                if let Some(Component::Normal(_)) = components.last() {
28                    components.pop();
29                } else if !components.iter().any(|comp| matches!(comp, Component::RootDir | Component::Prefix(_))) {
30                    components.push(c);
31                }
32            }
33            _ => components.push(c),
34        }
35    }
36    components.into_iter().collect()
37}
38
39/// Canonicalizes `path`, falling back to canonicalizing its deepest existing ancestor and
40/// appending any non-existent suffix components normalized via [`normalize_path`].
41pub fn canonicalize_best_effort(path: &Path) -> PathBuf {
42    if let Ok(canon) = std::fs::canonicalize(path) {
43        return canon;
44    }
45    for ancestor in path.ancestors().skip(1) {
46        if ancestor.as_os_str().is_empty() {
47            continue;
48        }
49        if let Ok(canon_ancestor) = std::fs::canonicalize(ancestor) {
50            if let Ok(tail) = path.strip_prefix(ancestor) {
51                return normalize_path(&canon_ancestor.join(tail));
52            }
53        }
54    }
55    normalize_path(path)
56}
57
58/// [`canonicalize_best_effort`], remembered per path: lookups run per shard on every request, and a
59/// directory's links do not change while the server runs (a later file under it resolves the same way).
60pub fn canonicalize_cached(path: &Path) -> PathBuf {
61    use std::collections::HashMap;
62    use std::sync::{Mutex, OnceLock};
63    static MEMO: OnceLock<Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
64    let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));
65    if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(path) {
66        return hit.clone();
67    }
68    let canon = canonicalize_best_effort(path);
69    let mut m = memo.lock().unwrap_or_else(|e| e.into_inner());
70    if m.len() >= 16_384 {
71        m.clear();
72    }
73    m.insert(path.to_path_buf(), canon.clone());
74    canon
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn canonicalize_best_effort_resolves_symlink_prefix_for_missing_descendant() {
83        let dir = std::env::temp_dir().join(format!("ridx_paths_test_{}", std::process::id()));
84        let _ = std::fs::remove_dir_all(&dir);
85        let real_sub = dir.join("real");
86        std::fs::create_dir_all(&real_sub).unwrap();
87
88        #[cfg(unix)]
89        {
90            let link_sub = dir.join("link");
91            std::os::unix::fs::symlink(&real_sub, &link_sub).unwrap();
92
93            let expected = std::fs::canonicalize(&real_sub).unwrap().join("missing/leaf.rs");
94            let via_link = canonicalize_best_effort(&link_sub.join("missing/./sub/../leaf.rs"));
95            assert_eq!(via_link, expected);
96
97            // Relative path without existing prefix keeps lexical form.
98            assert_eq!(canonicalize_best_effort(Path::new("no_such_dir/a/../b.rs")), PathBuf::from("no_such_dir/b.rs"));
99        }
100
101        let _ = std::fs::remove_dir_all(&dir);
102    }
103}