Skip to main content

rust_meth_lib/
probe.rs

1//! A utility for generating ephemeral, minimal Cargo projects ("probes") used to query
2//! Language Server Protocol (LSP) intelligence like autocompletions or go-to-definitions.
3//!
4//! A `Probe` creates a temporary directory containing a valid Cargo package with a single source file.
5//! The source file declares an isolated variable statement `let _x: TYPE = todo!();` followed by a target
6//! interaction point (such as `_x.` or `_x.method()`).
7//!
8//! When the [`Probe`] instance goes out of scope, its [`Drop`] implementation automatically deletes
9//! the entire temporary directory and its contents from the disk.
10
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15/// Global atomic counter ensuring that concurrently generated probe projects
16/// receive unique names within the OS temporary directory.
17static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
18
19// Preamble added to every probe file so common std types resolve without
20// the user needing to fully qualify them (e.g. `HashMap` not `std::collections::HashMap`).
21const PREAMBLE: &str = "\
22#![allow(unused_imports)]
23use std::collections::*;
24use std::sync::*;
25use std::cell::*;
26use std::rc::Rc;
27use std::io::{self, Read, Write, BufRead};
28use std::fmt;
29use std::ops::*;
30use std::path::{Path, PathBuf};
31";
32
33/// Represents an ephemeral Cargo project written to disk for LSP interrogation.
34///
35/// Deletes itself automatically when dropped.
36pub struct Probe {
37    /// The absolute path to the root directory of the temporary Cargo project.
38    pub dir: PathBuf,
39    /// The absolute path to the generated `src/main.rs` file.
40    pub src_path: PathBuf,
41    /// The 0-indexed line number in `src/main.rs` pointing to the target interaction point (the dot trigger).
42    pub dot_line: u32,
43    /// The 0-indexed character/column offset pointing exactly after the dot (`_x.`) in `src/main.rs`.
44    pub dot_col: u32,
45}
46
47impl Probe {
48    /// Creates a new probe project without dependencies (for stdlib types).
49    ///
50    /// # Errors
51    ///
52    /// Returns an [`std::io::Error`] if creating the underlying probe project directory
53    /// or writing its files fails.
54    pub fn new(type_name: &str) -> std::io::Result<Self> {
55        Self::create_probe(type_name, None, None)
56    }
57
58    /// Creates a new probe project with optional dependencies (for 3rd party crates).
59    ///
60    /// # Arguments
61    /// * `type_name` - The Rust type to query (e.g., "`Vec<u8>`", "`serde_json::Value`")
62    /// * `deps` - Optional TOML dependencies section (e.g., "`serde_json` = \"1.0\"")
63    ///
64    /// # Errors
65    ///
66    /// Returns an [`std::io::Error`] if generating the probe files or writing the dependency
67    /// configuration fails.
68    pub fn new_with_deps(type_name: &str, deps: Option<&str>) -> std::io::Result<Self> {
69        Self::create_probe(type_name, None, deps)
70    }
71
72    /// Creates a probe file with `_x.METHOD_NAME()` for go-to-definition queries.
73    /// The cursor position points at the start of the method name.
74    ///
75    /// # Errors
76    ///
77    /// Returns an [`std::io::Error`] if the workspace initialization or file creation fails
78    /// on disk.
79    pub fn for_definition(type_name: &str, method_name: &str) -> std::io::Result<Self> {
80        Self::create_probe(type_name, Some(method_name), None)
81    }
82
83    /// Infers a minimal Cargo dependency string from a type path when no explicit
84    /// `--deps` argument is provided.
85    ///
86    /// Returns `Some("crate_name = \"*\"")` if the leading path segment starts with
87    /// a lowercase letter (indicating a third-party crate), or `None` for stdlib/
88    /// primitive types whose leading segment is uppercase (e.g. `Vec`, `HashMap`).
89    ///
90    /// # Examples
91    /// ```text
92    /// assert_eq!(infer_dep("serde_json::Value"), Some(r#"serde_json = "*""#.into()));
93    /// assert_eq!(infer_dep("Vec<u8>"),           None);
94    /// assert_eq!(infer_dep("HashMap<K, V>"),     None);
95    /// ```
96    fn infer_dep(type_name: &str) -> Option<String> {
97        if !type_name.contains("::") {
98            return None; // primitives, String, Vec<u8>, etc. — never need an inferred dep
99        }
100        let crate_name = type_name.split("::").next()?;
101        if crate_name.chars().next()?.is_ascii_lowercase() {
102            Some(format!(r#"{crate_name} = "*""#))
103        } else {
104            None
105        }
106    }
107    /// Creates a probe file for go-to-definition with custom dependencies.
108    ///
109    /// # Errors
110    ///
111    /// Returns an [`std::io::Error`] if the underlying project boilerplate, file buffers,
112    /// or custom dependency sections cannot be written.
113    pub fn for_definition_with_deps(
114        type_name: &str,
115        method_name: &str,
116        deps: Option<&str>,
117    ) -> std::io::Result<Self> {
118        Self::create_probe(type_name, Some(method_name), deps)
119    }
120
121    /// Internal probe creation logic shared by all constructors.
122    ///
123    /// # Arguments
124    /// * `type_name` - The Rust type to query
125    /// * `method_name` - If Some, creates a definition probe; if None, creates a completion probe
126    /// * `deps` - Optional TOML dependencies to add to Cargo.toml
127    fn create_probe(
128        type_name: &str,
129        method_name: Option<&str>,
130        deps: Option<&str>,
131    ) -> std::io::Result<Self> {
132        let id = PROBE_COUNTER.fetch_add(1, Ordering::Relaxed);
133        let suffix = method_name.map_or("probe", |_| "probe-def");
134        let dir =
135            std::env::temp_dir().join(format!("rust-meth-{suffix}-{}-{id}", std::process::id()));
136
137        // let dir = std::env::temp_dir().join(format!("rust-meth-{suffix}-{}", std::process::id()));
138        let src_dir = dir.join("src");
139        fs::create_dir_all(&src_dir)?;
140
141        let effective_deps = deps
142            .map(str::to_owned)
143            .or_else(|| Self::infer_dep(type_name));
144
145        let cargo_toml = effective_deps.map_or_else(
146        || "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n".to_string(),
147        |d| format!(
148            "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n{d}\n"
149        ),
150    );
151
152        // Build Cargo.toml with optional dependencies
153
154        fs::write(dir.join("Cargo.toml"), cargo_toml)?;
155
156        // Source file layout (preamble lines + fn main):
157        //
158        //   0..N  preamble use statements
159        //   N+0:  fn main() {
160        //   N+1:      let _x: TYPE = todo!();
161        //   N+2:      _x.         <-- completion trigger after the dot (or _x.METHOD() for definition)
162        //   N+3:  }
163        let preamble_lines =
164            u32::try_from(PREAMBLE.lines().count()).expect("Preamble is too long to fit in u32");
165
166        // Generate source based on whether we're doing completion or definition
167        let source = method_name.map_or_else(|| format!("{PREAMBLE}fn main() {{\n    let _x: {type_name} = todo!();\n    _x.\n}}\n"), |method| format!(
168                      "{PREAMBLE}fn main() {{\n    let _x: {type_name} = todo!();\n    _x.{method}();\n}}\n"
169                 ));
170
171        let src_path = src_dir.join("main.rs");
172        fs::write(&src_path, &source)?;
173
174        // Dot is at preamble_lines + 2, col = len("    _x.")
175        let dot_line = preamble_lines + 2;
176        let dot_col = u32::try_from("    _x.".len()).expect("failed");
177
178        if std::env::var("RUST_METH_DEBUG").is_ok() {
179            eprintln!("=== probe source ===");
180            for (i, line) in source.lines().enumerate() {
181                eprintln!("{i:3}: {line}");
182            }
183            eprintln!("cursor → line={dot_line} col={dot_col}");
184        }
185        Ok(Self {
186            dir,
187            src_path,
188            dot_line,
189            dot_col,
190        })
191    }
192
193    /// Converts the generated `src/main.rs` file path into a formatted `file://` URI string.
194    ///
195    /// Useful for protocols like LSP that require document paths formatted as URLs.
196    #[must_use]
197    pub fn src_uri(&self) -> String {
198        path_to_uri(&self.src_path)
199    }
200
201    /// Converts the root workspace directory path into a formatted `file://` URI string.
202    #[must_use]
203    pub fn root_uri(&self) -> String {
204        path_to_uri(&self.dir)
205    }
206
207    /// Reads and returns the contents of the source file as a string.
208    ///
209    /// # Errors
210    ///
211    /// This function will return an `Err` if the file cannot be read.
212    /// Common reasons include:
213    /// * The file at `src_path` does not exist.
214    /// * The user lacks permissions to read the file.
215    /// * The file contents are not valid UTF-8.
216    pub fn source(&self) -> std::io::Result<String> {
217        fs::read_to_string(&self.src_path)
218    }
219}
220
221impl Drop for Probe {
222    fn drop(&mut self) {
223        let _ = fs::remove_dir_all(&self.dir);
224    }
225}
226
227fn path_to_uri(path: &Path) -> String {
228    let s = path.to_string_lossy();
229    if s.starts_with('/') {
230        format!("file://{s}")
231    } else {
232        format!("file:///{s}")
233    }
234}
235
236#[cfg(test)]
237#[allow(clippy::unwrap_used)]
238mod tests {
239    use super::*;
240
241    // -- helpers -------------------------------------------------------
242
243    fn preamble_line_count() -> u32 {
244        u32::try_from(PREAMBLE.lines().count()).unwrap()
245    }
246
247    // -- Cargo.toml generation ------------------------------------------
248
249    #[test]
250    fn no_deps_omits_dependencies_section() {
251        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
252        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
253        assert!(
254            !cargo.contains("[dependencies]"),
255            "Cargo.toml should not have a [dependencies] section when deps is None"
256        );
257        assert!(cargo.contains("[package]"));
258        assert!(cargo.contains(r#"name = "probe""#));
259        assert!(cargo.contains(r#"edition = "2024""#));
260    }
261
262    #[test]
263    fn with_deps_injects_dependencies_section() {
264        let p = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "1.0""#)).unwrap();
265        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
266        assert!(cargo.contains("[dependencies]"));
267        assert!(cargo.contains(r#"serde_json = "1.0""#));
268    }
269
270    #[test]
271    fn multiple_deps_all_appear_in_cargo_toml() {
272        let deps = "serde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"";
273        let p = Probe::new_with_deps("serde_json::Value", Some(deps)).unwrap();
274        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
275        assert!(cargo.contains("[dependencies]"));
276        assert!(cargo.contains("serde ="));
277        assert!(cargo.contains(r#"serde_json = "1.0""#));
278    }
279
280    // ── source content ───────────────────────────────────────────────────────
281
282    #[test]
283    fn completion_probe_source_has_dot_trigger() {
284        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
285        let src = p.source().unwrap();
286        assert!(
287            src.contains("let _x: Vec<u8> = todo!();"),
288            "source should declare the type"
289        );
290        // ends with `_x.` NOT `_x.something()`
291        assert!(
292            src.contains("    _x.\n"),
293            "completion probe should have bare dot trigger"
294        );
295    }
296
297    #[test]
298    fn definition_probe_source_has_method_call() {
299        let p = Probe::for_definition_with_deps("Vec<u8>", "push", None).unwrap();
300        let src = p.source().unwrap();
301        assert!(src.contains("let _x: Vec<u8> = todo!();"));
302        assert!(
303            src.contains("_x.push();"),
304            "definition probe should contain the method call"
305        );
306    }
307
308    #[test]
309    fn completion_probe_with_deps_type_in_source() {
310        let p = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "1.0""#)).unwrap();
311        let src = p.source().unwrap();
312        assert!(src.contains("let _x: serde_json::Value = todo!();"));
313    }
314
315    #[test]
316    fn definition_probe_with_deps_cargo_and_source_correct() {
317        let p = Probe::for_definition_with_deps(
318            "serde_json::Value",
319            "as_str",
320            Some(r#"serde_json = "1.0""#),
321        )
322        .unwrap();
323        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
324        assert!(cargo.contains("[dependencies]"));
325        let src = p.source().unwrap();
326        assert!(src.contains("serde_json::Value"));
327        assert!(src.contains("_x.as_str();"));
328    }
329
330    // ── dot position ─────────────────────────────────────────────────────────
331
332    #[test]
333    fn dot_col_is_seven() {
334        // "    _x." is always 7 characters
335        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
336        assert_eq!(p.dot_col, 7, r#""    _x." should be 7 chars"#);
337    }
338
339    #[test]
340    fn dot_line_is_preamble_plus_two() {
341        // layout: preamble lines, fn main() {, let _x = …, _x.
342        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
343        assert_eq!(p.dot_line, preamble_line_count() + 2);
344    }
345
346    #[test]
347    fn dot_line_same_for_definition_probe() {
348        let p = Probe::for_definition_with_deps("Vec<u8>", "len", None).unwrap();
349        assert_eq!(p.dot_line, preamble_line_count() + 2);
350    }
351
352    // ── URI helpers ──────────────────────────────────────────────────────────
353
354    #[test]
355    fn src_uri_is_file_uri_ending_in_main_rs() {
356        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
357        let uri = p.src_uri();
358        assert!(
359            uri.starts_with("file://"),
360            "src_uri should be a file:// URI"
361        );
362        assert!(
363            uri.ends_with("/src/main.rs"),
364            "src_uri should end in /src/main.rs"
365        );
366    }
367
368    #[test]
369    fn root_uri_is_file_uri_not_ending_in_main_rs() {
370        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
371        let uri = p.root_uri();
372        assert!(uri.starts_with("file://"));
373        assert!(!uri.ends_with("main.rs"));
374    }
375
376    // ── cleanup ──────────────────────────────────────────────────────────────
377
378    #[test]
379    fn drop_removes_temp_directory() {
380        let dir = {
381            let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
382            assert!(p.dir.exists(), "dir should exist while probe is alive");
383            p.dir.clone()
384        };
385        assert!(!dir.exists(), "temp dir should be removed after drop");
386    }
387
388    #[test]
389    fn definition_probe_drop_removes_temp_directory() {
390        let dir = {
391            let p = Probe::for_definition_with_deps("Vec<u8>", "len", None).unwrap();
392            p.dir.clone()
393        };
394        assert!(!dir.exists());
395    }
396}