Skip to main content

ridx_format/workspace/path_index/
build.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//! Builder logic for `PathIndex`.
12
13use super::{has_parent_dir, OriginMeta, PathIndex, ReaderPathMeta, UniquePathEntry};
14use crate::paths::normalize_path;
15use crate::workspace::WorkspaceIndex;
16use std::collections::HashMap;
17use std::ffi::OsString;
18use std::path::{Path, PathBuf};
19use std::sync::OnceLock;
20
21impl PathIndex {
22    /// Builds the path index from the current `WorkspaceIndex` state.
23    pub fn build(ws: &WorkspaceIndex) -> Self {
24        let mut canon_cache: HashMap<PathBuf, Option<PathBuf>> = HashMap::new();
25        let mut canon_of = |p: &Path| -> Option<PathBuf> { canon_cache.entry(p.to_path_buf()).or_insert_with(|| p.canonicalize().ok()).clone() };
26
27        let mut origins: Vec<OriginMeta> = Vec::new();
28        let mut origin_map: HashMap<PathBuf, u32> = HashMap::new();
29        let mut readers_meta: Vec<ReaderPathMeta> = Vec::with_capacity(ws.readers.len());
30
31        for i in 0..ws.readers.len() {
32            let origin_path = ws.source_roots.get(i).and_then(|r| r.as_deref()).or(ws.workspace_root.as_deref()).or(ws.root_dir.as_deref());
33            let origin_id = origin_path.map(|op| {
34                if let Some(&id) = origin_map.get(op) {
35                    return id;
36                }
37                let id = origins.len() as u32;
38                let raw = op.to_path_buf();
39                origins.push(OriginMeta { norm: normalize_path(&raw), canon: canon_of(&raw), has_dotdot: has_parent_dir(&raw), raw: raw.clone() });
40                origin_map.insert(raw, id);
41                id
42            });
43            let sroot = ws.source_roots.get(i).and_then(|r| r.as_deref());
44            readers_meta.push(ReaderPathMeta {
45                origin_id,
46                norm_source_root: sroot.map(normalize_path),
47                canon_source_root: sroot.and_then(&mut canon_of),
48                is_dep: ws.reader_is_dependency.get(i).copied().unwrap_or(false) || sroot.is_some(),
49            });
50        }
51
52        let mut entries: Vec<UniquePathEntry> = Vec::new();
53        let mut entry_map: HashMap<(Option<u32>, String), u32> = HashMap::new();
54        let mut by_key: HashMap<PathBuf, Vec<u32>> = HashMap::new();
55        let mut by_file_name: HashMap<OsString, Vec<u32>> = HashMap::new();
56        let mut dotdot_uids: Vec<u32> = Vec::new();
57
58        let push_u = |vec: &mut Vec<u32>, uid: u32| {
59            if vec.last().copied() != Some(uid) && !vec.contains(&uid) {
60                vec.push(uid);
61            }
62        };
63
64        let mut intern = |entries: &mut Vec<UniquePathEntry>, origin_id: Option<u32>, entry_str: &str| -> usize {
65            let key = (origin_id, entry_str.to_string());
66            if let Some(&uid) = entry_map.get(&key) {
67                return uid as usize;
68            }
69            let uid = entries.len() as u32;
70            let entry_p = Path::new(entry_str);
71            let entry_orig = match (entry_p.is_absolute(), origin_id) {
72                (true, _) | (false, None) => entry_p.to_path_buf(),
73                (false, Some(oid)) => origins[oid as usize].raw.join(entry_p),
74            };
75            let norm_entry = normalize_path(&entry_orig);
76
77            for k in [PathBuf::from(entry_str), entry_orig.clone(), norm_entry.clone()] {
78                push_u(by_key.entry(k).or_default(), uid);
79            }
80            if let Some(oid) = origin_id {
81                let orig = &origins[oid as usize];
82                if let Ok(rel) = norm_entry.strip_prefix(&orig.norm) {
83                    let nrel = normalize_path(rel);
84                    if let Some(ref co) = orig.canon {
85                        push_u(by_key.entry(normalize_path(&co.join(&nrel))).or_default(), uid);
86                    }
87                    push_u(by_key.entry(rel.to_path_buf()).or_default(), uid);
88                    push_u(by_key.entry(nrel).or_default(), uid);
89                }
90                if entry_p.is_relative() {
91                    if let Some(ref co) = orig.canon {
92                        let cj = normalize_path(&co.join(entry_p));
93                        if let Ok(rel) = cj.strip_prefix(co) {
94                            push_u(by_key.entry(rel.to_path_buf()).or_default(), uid);
95                            push_u(by_key.entry(normalize_path(rel)).or_default(), uid);
96                        }
97                        push_u(by_key.entry(cj).or_default(), uid);
98                    }
99                }
100            }
101            for fname in [entry_orig.file_name(), norm_entry.file_name()].into_iter().flatten() {
102                push_u(by_file_name.entry(fname.to_os_string()).or_default(), uid);
103            }
104            if has_parent_dir(&entry_orig) && (entry_orig.file_name().is_none() || norm_entry.file_name().is_none()) {
105                push_u(&mut dotdot_uids, uid);
106            }
107            entries.push(UniquePathEntry { entry_str: key.1.clone(), origin_id, entry_orig, norm_entry, fs_meta: OnceLock::new(), phase1: Vec::new(), phase2: Vec::new() });
108            entry_map.insert(key, uid);
109            uid as usize
110        };
111
112        let mut bare_reader_files: Vec<String> = Vec::new();
113        for (i, reader) in ws.readers.iter().enumerate() {
114            let oid = readers_meta[i].origin_id;
115            for fid in 0..reader.files_count() {
116                let s = reader.get_file(fid);
117                if !s.is_empty() {
118                    if !s.contains('/') && !s.contains('\\') && !bare_reader_files.iter().any(|b| b == s) {
119                        bare_reader_files.push(s.to_string());
120                    }
121                    let uid = intern(&mut entries, oid, s);
122                    entries[uid].phase1.push((i as u32, fid, reader.file_source_hash(fid)));
123                }
124            }
125            if let Some(map) = ws.reader_file_hashes.get(i) {
126                for (ord, (k, &h)) in map.iter().enumerate() {
127                    if !k.is_empty() {
128                        let uid = intern(&mut entries, oid, k);
129                        entries[uid].phase2.push((i as u32, ord as u32, h));
130                    }
131                }
132            }
133        }
134        Self {
135            generation: ws.generation,
136            reader_count: ws.readers.len(),
137            origins,
138            readers_meta,
139            entries,
140            by_key,
141            by_file_name,
142            dotdot_uids,
143            bare_reader_files,
144            blast_radius: crate::workspace::navigation::BlastRadiusIndex::build(ws),
145        }
146    }
147}