Skip to main content

ridx_format/reader/
file_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//! Looking a stored file up by its path: the one place where a request's spelling is matched
12//! against the file table of a shard.
13
14use std::path::Path;
15
16use super::IndexReader;
17use crate::paths::normalize_path;
18
19impl<B: AsRef<[u8]>> IndexReader<B> {
20    /// Looks up the file_id of the file stored as `file_path`: the same string, or the same path
21    /// by components (`./src/lib.rs` and `src//lib.rs` name `src/lib.rs`), or a stored path whose
22    /// `..` components resolve lexically to it: a file pulled in by `include!("../test_data/x.rs")`
23    /// is stored as rustc spelled it, `crate/src/../test_data/x.rs`, and `crate/test_data/x.rs`
24    /// names it. `..` on the query side is not resolved here: through a symlinked parent it is a
25    /// filesystem question, which `WorkspaceIndex` settles before asking. A path that merely ends
26    /// with a stored one, such as another crate's `src/lib.rs`, does not match. The stored form is
27    /// the one the driver wrote: relative to the workspace root for workspace crates, relative to
28    /// the package directory for dependencies, relative to the rust-src root for the sysroot;
29    /// `WorkspaceIndex::target_file_for_reader` turns any input into it.
30    pub fn find_file_id(&self, file_path: &str) -> Option<u32> {
31        let clean_wanted = file_path.strip_prefix("./").unwrap_or(file_path);
32        let wanted = Path::new(clean_wanted);
33        let wanted_is_abs = wanted.is_absolute();
34        let wanted_needs_comp = clean_wanted.contains("//") || clean_wanted.contains("/.") || clean_wanted.contains('\\') || clean_wanted.ends_with('/');
35        for id in 0..self.header.files_count {
36            let f = self.get_file(id);
37            if f == file_path || f.strip_prefix("./").unwrap_or(f) == clean_wanted {
38                return Some(id);
39            }
40            let fp = Path::new(f);
41            if fp.is_absolute() != wanted_is_abs {
42                continue;
43            }
44            if (wanted_needs_comp || f.contains("//") || f.contains("./") || f.contains("/.") || f.contains('\\') || f.ends_with('/')) && fp == wanted {
45                return Some(id);
46            }
47            if f.contains("..") && normalize_path(fp) == wanted {
48                return Some(id);
49            }
50        }
51        None
52    }
53}