Skip to main content

ridx_format/
relocate.rs

1/*
2 * rust-intelligence — Compiler-backed, mmap-indexed 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//! Moving the targets of a shard's references to where their definitions now are, without compiling the crate again.
12//! A reference records the line and column of the definition it resolved to (`RefEntry::target_line`/`target_col`),
13//! and references, rename and safe delete compare them with the definition's current position: when a crate is edited
14//! without a change of what its dependents see, only these numbers in the dependents' shards are out of date.
15
16use crate::format::RefEntry;
17use crate::reader::IndexReader;
18use std::collections::HashMap;
19use std::fs;
20use std::io;
21use std::path::Path;
22
23/// Where the definition a reference targets is now.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Placement {
26    /// Where it was: the reference stays as it is.
27    Same,
28    /// At this line and column (1-based, the column in characters as the driver records it).
29    Moved(u32, u32),
30    /// Cannot be told: the shard is not rewritten, the crate is to be compiled.
31    Unknown,
32}
33
34/// Rewrites the target position of each reference of the shard at `path` as `place` says, given the reference's target
35/// file (as recorded) and its target line and column; a reference with no target line is left as it is. The file is
36/// replaced whole (written next to it, then renamed over it), so a server holding the old one mapped keeps reading it.
37/// Returns how many references moved, or `None` when `place` answered [`Placement::Unknown`] for one: nothing is then
38/// written.
39pub fn relocate_reference_targets(path: &Path, mut place: impl FnMut(&str, u32, u32) -> Placement) -> io::Result<Option<usize>> {
40    let reader = IndexReader::open(path)?;
41    let refs_offset = reader.header().refs_offset as usize;
42    let mut moves = Vec::new();
43    // Many references share a target: each is placed once.
44    let mut placed: HashMap<(u32, u32, u32), Placement> = HashMap::new();
45    for (i, r) in reader.references().iter().enumerate() {
46        let (line, col) = (r.target_line(), r.target_col());
47        if line == 0 {
48            continue;
49        }
50        let key = (r.target_file_offset(), line, col);
51        let placement = *placed.entry(key).or_insert_with(|| place(reader.get_str(r.target_file_offset()), line, col));
52        match placement {
53            Placement::Same => {}
54            Placement::Moved(l, c) if (l, c) == (line, col) => {}
55            Placement::Moved(l, c) => moves.push((i, l, c)),
56            Placement::Unknown => return Ok(None),
57        }
58    }
59    drop(reader);
60    if moves.is_empty() {
61        return Ok(Some(0));
62    }
63    let mut bytes = fs::read(path)?;
64    let size = std::mem::size_of::<RefEntry>();
65    let (line_at, col_at) = (std::mem::offset_of!(RefEntry, target_line), std::mem::offset_of!(RefEntry, target_col));
66    for &(i, line, col) in &moves {
67        let entry = refs_offset + i * size;
68        bytes[entry + line_at..entry + line_at + 4].copy_from_slice(&line.to_le_bytes());
69        bytes[entry + col_at..entry + col_at + 4].copy_from_slice(&col.to_le_bytes());
70    }
71    let tmp = path.with_extension(format!("ridx.relocate.{}", std::process::id()));
72    if let Err(e) = fs::write(&tmp, &bytes).and_then(|()| fs::rename(&tmp, path)) {
73        let _ = fs::remove_file(&tmp);
74        return Err(e);
75    }
76    Ok(Some(moves.len()))
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::writer::{IndexWriter, RawReference};
83
84    fn reference(line: u32, target_file: &str, target_line: u32, target_col: u32) -> RawReference {
85        RawReference {
86            file: "src/lib.rs".into(),
87            start_line: line,
88            start_col: 5,
89            end_line: line,
90            end_col: 9,
91            target_def_id: None,
92            target_path: "a::f".into(),
93            target_file: Some(target_file.into()),
94            target_unit: Some("unit-a".into()),
95            target_line,
96            target_col,
97            kind: crate::DefKind::Fn,
98            is_write: false,
99            is_macro_expansion: false,
100        }
101    }
102
103    fn shard(dir: &Path, refs: Vec<RawReference>) -> std::path::PathBuf {
104        let mut w = IndexWriter::new("b", "0.1.0");
105        for r in refs {
106            w.add_reference(r);
107        }
108        let path = dir.join("b.ridx");
109        w.write_to(&mut fs::File::create(&path).unwrap()).unwrap();
110        path
111    }
112
113    #[test]
114    fn test_reference_targets_move_and_the_rest_stays() {
115        let dir = tempfile::tempdir().unwrap();
116        let path =
117            shard(dir.path(), vec![reference(1, "a/src/lib.rs", 3, 8), reference(2, "a/src/lib.rs", 3, 8), reference(3, "other.rs", 3, 8), reference(4, "a/src/lib.rs", 0, 0)]);
118        let mut asked = Vec::new();
119        let moved = relocate_reference_targets(&path, |file, line, col| {
120            asked.push((file.to_string(), line, col));
121            if file == "a/src/lib.rs" {
122                Placement::Moved(13, 8)
123            } else {
124                Placement::Same
125            }
126        })
127        .unwrap();
128        assert_eq!(moved, Some(2), "both references of the moved definition");
129        assert_eq!(asked, [("a/src/lib.rs".to_string(), 3, 8), ("other.rs".to_string(), 3, 8)], "each target placed once, none without a line");
130        let reader = IndexReader::open(&path).unwrap();
131        let targets: Vec<(u32, u32)> = reader.references().iter().map(|r| (r.target_line(), r.target_col())).collect();
132        assert_eq!(targets, [(13, 8), (13, 8), (3, 8), (0, 0)]);
133        assert_eq!(reader.references()[0].target_path_offset(), reader.references()[2].target_path_offset(), "paths, by which the target index hashes, stay");
134    }
135
136    #[test]
137    fn test_an_unknown_target_leaves_the_shard_as_it_is() {
138        let dir = tempfile::tempdir().unwrap();
139        let path = shard(dir.path(), vec![reference(1, "a/src/lib.rs", 3, 8), reference(2, "a/src/lib.rs", 9, 1)]);
140        let before = fs::read(&path).unwrap();
141        let moved = relocate_reference_targets(&path, |_, line, _| if line == 3 { Placement::Moved(4, 8) } else { Placement::Unknown }).unwrap();
142        assert_eq!(moved, None);
143        assert_eq!(fs::read(&path).unwrap(), before);
144    }
145}