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