Skip to main content

rust_meth_lib/probe/
mod.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
8pub(crate) mod cache;
9
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::sync::{
13    Arc,
14    atomic::{AtomicU64, Ordering},
15};
16
17pub use cache::{
18    CacheEntry, PersistentCacheEntry, cache_entries, cache_key_hash, clear_persistent_cache,
19    clear_probe_cache, persistent_cache_dir, persistent_cache_entries, ra_version,
20};
21use cache::{CacheKey, CachedProbe, global_cache, load_persistent_probe, save_persistent_probe};
22
23// -- Counter --
24
25/// Global atomic counter ensuring that concurrently generated probe projects
26/// receive unique names within the OS temporary directory.
27static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
28
29// Preamble added to every probe file so common std types resolve without
30// the user needing to fully qualify them (e.g. `HashMap` not `std::collections::HashMap`).
31const PREAMBLE: &str = "\
32#![allow(unused_imports)]
33use std::collections::*;
34use std::sync::*;
35use std::cell::*;
36use std::rc::Rc;
37use std::io::{self, Read, Write, BufRead};
38use std::fmt;
39use std::ops::*;
40use std::path::{Path, PathBuf};
41";
42
43/// Represents an ephemeral Cargo project written to disk for LSP interrogation.
44///
45/// Backed by a cache [`Arc<CachedProbe>`] the directory is only deleted when
46/// both the cache entry and this `Probe` are dropped.
47pub struct Probe {
48    /// Shared ownership of the underlying cached probe data.
49    #[allow(dead_code)]
50    inner: Arc<CachedProbe>,
51    /// The 0-indexed line number in `src/main.rs` pointing to the target interaction point (the dot trigger).
52    pub dot_line: u32,
53    /// The 0-indexed character/column offset pointing exactly after the dot (`_x.`) in `src/main.rs`.
54    pub dot_col: u32,
55    /// The absolute path to the root directory of the temporary Cargo project.
56    pub dir: PathBuf,
57    /// The absolute path to the generated `src/main.rs` file.
58    pub src_path: PathBuf,
59}
60
61impl Probe {
62    /// Creates a new probe project without dependencies (for stdlib types).
63    ///
64    /// # Errors
65    ///
66    /// Returns an [`std::io::Error`] if creating the underlying probe project directory
67    /// or writing its files fails.
68    pub fn new(type_name: &str) -> std::io::Result<Self> {
69        Self::create_probe(type_name, None, None, None)
70    }
71
72    /// Creates a new probe project with optional dependencies (for 3rd party crates).
73    ///
74    /// # Arguments
75    /// * `type_name` - The Rust type to query (e.g., "`Vec<u8>`", "`serde_json::Value`")
76    /// * `deps` - Optional TOML dependencies section (e.g., "`serde_json` = \"1.0\"")
77    ///
78    /// # Errors
79    ///
80    /// Returns an [`std::io::Error`] if generating the probe files or writing the dependency
81    /// configuration fails.
82    pub fn new_with_deps(type_name: &str, deps: Option<&str>) -> std::io::Result<Self> {
83        Self::create_probe(type_name, None, deps, None)
84    }
85
86    /// Creates a probe project with optional dependencies and persistent caching.
87    ///
88    /// Passing `ra_path` enables the persistent cache, the probe directory is saved
89    /// to `$XDG_CACHE_HOME/rust-meth/probes/` and reused across process restarts,
90    /// skipping Cargo resolution on subsequent calls.
91    ///
92    /// ## Errors
93    ///
94    /// Errors on I/O failures, Cache/File System errors
95    pub fn new_with_deps_cached(
96        type_name: &str,
97        deps: Option<&str>,
98        ra_path: &Path,
99    ) -> std::io::Result<Self> {
100        Self::create_probe(type_name, None, deps, Some(ra_path))
101    }
102
103    /// Creates a probe file with `_x.METHOD_NAME()` for go-to-definition queries.
104    /// The cursor position points at the start of the method name.
105    ///
106    /// # Errors
107    ///
108    /// Returns an [`std::io::Error`] if the workspace initialization or file creation fails
109    /// on disk.
110    pub fn for_definition(type_name: &str, method_name: &str) -> std::io::Result<Self> {
111        Self::create_probe(type_name, Some(method_name), None, None)
112    }
113
114    /// Creates a probe file for go-to-definition with custom dependencies.
115    ///
116    /// # Errors
117    ///
118    /// Returns an [`std::io::Error`] if the underlying project boilerplate, file buffers,
119    /// or custom dependency sections cannot be written.
120    pub fn for_definition_with_deps(
121        type_name: &str,
122        method_name: &str,
123        deps: Option<&str>,
124    ) -> std::io::Result<Self> {
125        Self::create_probe(type_name, Some(method_name), deps, None)
126    }
127
128    /// Creates a go-to-definition probe with custom dependencies and persistent caching.
129    ///
130    /// ## Errors
131    ///
132    /// On I/O failures, and Cache/File System errors
133    pub fn for_definition_with_deps_cached(
134        type_name: &str,
135        method_name: &str,
136        deps: Option<&str>,
137        ra_path: &Path,
138    ) -> std::io::Result<Self> {
139        Self::create_probe(type_name, Some(method_name), deps, Some(ra_path))
140    }
141
142    /// Infers a minimal Cargo dependency string from a type path when no explicit
143    /// `--deps` argument is provided.
144    ///
145    /// Returns `Some("crate_name = \"*\"")` if the leading path segment starts with
146    /// a lowercase letter (indicating a third-party crate), or `None` for stdlib/
147    /// primitive types whose leading segment is uppercase (e.g. `Vec`, `HashMap`).
148    ///
149    /// # Examples
150    /// ```text
151    /// assert_eq!(infer_dep("serde_json::Value"), Some(r#"serde_json = "*""#.into()));
152    /// assert_eq!(infer_dep("Vec<u8>"),           None);
153    /// assert_eq!(infer_dep("HashMap<K, V>"),     None);
154    /// ```
155    pub(crate) fn infer_dep(type_name: &str) -> Option<String> {
156        if !type_name.contains("::") {
157            return None; // primitives, String, Vec<u8>, etc. never need an inferred dep
158        }
159        let crate_name = type_name.split("::").next()?;
160        if crate_name.chars().next()?.is_ascii_lowercase() {
161            Some(format!(r#"{crate_name} = "*""#))
162        } else {
163            None
164        }
165    }
166
167    /// Internal probe creation logic shared by all constructors.
168    ///
169    /// Checks the global cache first. On a hit, clones the [`Arc`] and returns
170    /// immediately without touching the filesystem. On a miss, creates the probe
171    /// directory, writes the files, inserts into the cache, and returns.
172    ///
173    /// # Arguments
174    /// * `type_name` - The Rust type to query
175    /// * `method_name` - If Some, creates a definition probe; if None, creates a completion probe
176    /// * `deps` - Optional TOML dependencies to add to Cargo.toml
177    fn create_probe(
178        type_name: &str,
179        method_name: Option<&str>,
180        deps: Option<&str>,
181        ra_path: Option<&Path>,
182    ) -> std::io::Result<Self> {
183        let effective_deps = deps
184            .map(str::to_owned)
185            .or_else(|| Self::infer_dep(type_name));
186
187        let key = CacheKey {
188            type_name: type_name.to_string(),
189            effective_deps: effective_deps.clone(),
190            method_name: method_name.map(str::to_owned),
191        };
192
193        // 1. In-process cache
194        if let Some(probe) = Self::from_memory_cache(&key) {
195            return Ok(probe);
196        }
197
198        // 2. Persistent cache
199        if let Some(ra) = ra_path
200            && let Some(probe) = Self::from_persistent_cache(&key, ra)
201        {
202            return Ok(probe);
203        }
204
205        // 3. Create on disk
206        Self::create_on_disk(
207            key,
208            type_name,
209            method_name,
210            effective_deps.as_ref(),
211            ra_path,
212        )
213    }
214
215    /// Checks the in-process Arc cache. Returns `Some(Probe)` on a hit.
216    fn from_memory_cache(key: &CacheKey) -> Option<Self> {
217        let inner = {
218            let cache = cache::global_cache()
219                .lock()
220                .expect("probe cache lock poisoned");
221            let cached = cache.get(key)?;
222            if !cached.dir.exists() {
223                return None;
224            }
225            let inner = Arc::clone(cached);
226            drop(cache);
227            inner
228        };
229        Some(Self {
230            dir: inner.dir.clone(),
231            src_path: inner.src_path.clone(),
232            dot_line: inner.dot_line,
233            dot_col: inner.dot_col,
234            inner,
235        })
236    }
237
238    /// Checks the persistent disk cache. On a hit, also populates the in-process
239    /// cache so subsequent calls in the same process are instant.
240    fn from_persistent_cache(key: &CacheKey, ra_path: &Path) -> Option<Self> {
241        let version = ra_version(ra_path);
242        let (dir, src_path, dot_line, dot_col) = load_persistent_probe(
243            &key.type_name,
244            key.effective_deps.as_deref(),
245            key.method_name.as_deref(),
246            &version,
247        )?;
248
249        if std::env::var("RUST_METH_DEBUG").is_ok() {
250            eprintln!("[debug] persistent cache hit: {}", dir.display());
251        }
252
253        let inner = Arc::new(CachedProbe {
254            dir: dir.clone(),
255            src_path: src_path.clone(),
256            dot_line,
257            dot_col,
258            owned: false,
259        });
260
261        {
262            let mut cache = global_cache().lock().expect("probe cache lock poisoned");
263            cache.insert(key.clone(), Arc::clone(&inner));
264        }
265
266        Some(Self {
267            inner,
268            dot_line,
269            dot_col,
270            dir,
271            src_path,
272        })
273    }
274
275    /// Creates a new probe directory on disk, writes Cargo.toml and src/main.rs,
276    /// saves to the persistent cache if `ra_path` is provided, and inserts into
277    /// the in-process cache.
278    fn create_on_disk(
279        key: CacheKey,
280        type_name: &str,
281        method_name: Option<&str>,
282        effective_deps: Option<&String>,
283        ra_path: Option<&Path>,
284    ) -> std::io::Result<Self> {
285        let id = PROBE_COUNTER.fetch_add(1, Ordering::Relaxed);
286        let suffix = method_name.map_or("probe", |_| "probe-def");
287        let dir =
288            std::env::temp_dir().join(format!("rust-meth-{suffix}-{}-{id}", std::process::id()));
289        let src_dir = dir.join("src");
290        fs::create_dir_all(&src_dir)?;
291
292        let cargo_toml = effective_deps.map_or_else(
293        || "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n".to_string(),
294        |d| format!(
295            "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n{d}\n"
296        ),
297    );
298        fs::write(dir.join("Cargo.toml"), cargo_toml)?;
299
300        let preamble_lines = u32::try_from(PREAMBLE.lines().count())
301            .expect("PREAMBLE is a fixed compile-time constant");
302
303        let source = method_name.map_or_else(
304        || format!("{PREAMBLE}fn main() {{\n    let _x: {type_name} = todo!();\n    _x.\n}}\n"),
305        |method| format!(
306            "{PREAMBLE}fn main() {{\n    let _x: {type_name} = todo!();\n    _x.{method}();\n}}\n"
307        ),
308    );
309
310        let src_path = src_dir.join("main.rs");
311        fs::write(&src_path, &source)?;
312
313        let dot_line = preamble_lines + 2;
314        let dot_col =
315            u32::try_from("    _x.".len()).expect("string literal length always fits in u32");
316
317        if std::env::var("RUST_METH_DEBUG").is_ok() {
318            eprintln!("=== probe source ===");
319            for (i, line) in source.lines().enumerate() {
320                eprintln!("{i:3}: {line}");
321            }
322            eprintln!("cursor → line={dot_line} col={dot_col}");
323        }
324
325        if let Some(ra) = ra_path {
326            let version = ra_version(ra);
327            save_persistent_probe(
328                &dir,
329                type_name,
330                effective_deps.map(String::as_str),
331                method_name,
332                &version,
333                dot_line,
334                dot_col,
335            );
336        }
337
338        let inner = Arc::new(CachedProbe {
339            dir: dir.clone(),
340            src_path: src_path.clone(),
341            dot_line,
342            dot_col,
343            owned: true,
344        });
345
346        {
347            let mut cache = global_cache().lock().expect("probe cache lock poisoned");
348            cache.insert(key, Arc::clone(&inner));
349        }
350
351        Ok(Self {
352            inner,
353            dot_line,
354            dot_col,
355            dir,
356            src_path,
357        })
358    }
359
360    /// Converts the generated `src/main.rs` file path into a formatted `file://` URI string.
361    ///
362    /// Useful for protocols like LSP that require document paths formatted as URLs.
363    #[must_use]
364    pub fn src_uri(&self) -> String {
365        path_to_uri(&self.src_path)
366    }
367
368    /// Converts the root workspace directory path into a formatted `file://` URI string.
369    #[must_use]
370    pub fn root_uri(&self) -> String {
371        path_to_uri(&self.dir)
372    }
373
374    /// Reads and returns the contents of the source file as a string.
375    ///
376    /// # Errors
377    ///
378    /// This function will return an `Err` if the file cannot be read.
379    /// Common reasons include:
380    /// * The file at `src_path` does not exist.
381    /// * The user lacks permissions to read the file.
382    /// * The file contents are not valid UTF-8.
383    pub fn source(&self) -> std::io::Result<String> {
384        fs::read_to_string(&self.src_path)
385    }
386}
387
388// `CachedProbe::drop` handles cleanup
389// when the Arc refcount reaches zero. Nothing to do here.
390impl Drop for Probe {
391    fn drop(&mut self) {}
392}
393
394fn path_to_uri(path: &Path) -> String {
395    let s = path.to_string_lossy();
396    if s.starts_with('/') {
397        format!("file://{s}")
398    } else {
399        format!("file:///{s}")
400    }
401}
402
403#[cfg(test)]
404#[allow(clippy::unwrap_used)]
405mod tests {
406    use super::*;
407
408    // -- helpers -------------------------------------------------------
409
410    fn preamble_line_count() -> u32 {
411        u32::try_from(PREAMBLE.lines().count()).unwrap()
412    }
413
414    // -- Cargo.toml generation ------------------------------------------
415
416    #[test]
417    fn no_deps_omits_dependencies_section() {
418        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
419        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
420        assert!(
421            !cargo.contains("[dependencies]"),
422            "Cargo.toml should not have a [dependencies] section when deps is None"
423        );
424        assert!(cargo.contains("[package]"));
425        assert!(cargo.contains(r#"name = "probe""#));
426        assert!(cargo.contains(r#"edition = "2024""#));
427    }
428
429    #[test]
430    fn with_deps_injects_dependencies_section() {
431        let p = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "1.0""#)).unwrap();
432        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
433        assert!(cargo.contains("[dependencies]"));
434        assert!(cargo.contains(r#"serde_json = "1.0""#));
435    }
436
437    #[test]
438    fn multiple_deps_all_appear_in_cargo_toml() {
439        let deps = "serde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"";
440        let p = Probe::new_with_deps("serde_json::Value", Some(deps)).unwrap();
441        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
442        assert!(cargo.contains("[dependencies]"));
443        assert!(cargo.contains("serde ="));
444        assert!(cargo.contains(r#"serde_json = "1.0""#));
445    }
446
447    // ── source content ───────────────────────────────────────────────────────
448
449    #[test]
450    fn completion_probe_source_has_dot_trigger() {
451        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
452        let src = p.source().unwrap();
453        assert!(
454            src.contains("let _x: Vec<u8> = todo!();"),
455            "source should declare the type"
456        );
457        // ends with `_x.` NOT `_x.something()`
458        assert!(
459            src.contains("    _x.\n"),
460            "completion probe should have bare dot trigger"
461        );
462    }
463
464    #[test]
465    fn definition_probe_source_has_method_call() {
466        let p = Probe::for_definition_with_deps("Vec<u8>", "push", None).unwrap();
467        let src = p.source().unwrap();
468        assert!(src.contains("let _x: Vec<u8> = todo!();"));
469        assert!(
470            src.contains("_x.push();"),
471            "definition probe should contain the method call"
472        );
473    }
474
475    #[test]
476    fn completion_probe_with_deps_type_in_source() {
477        let p = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "1.0""#)).unwrap();
478        let src = p.source().unwrap();
479        assert!(src.contains("let _x: serde_json::Value = todo!();"));
480    }
481
482    #[test]
483    fn definition_probe_with_deps_cargo_and_source_correct() {
484        let p = Probe::for_definition_with_deps(
485            "serde_json::Value",
486            "as_str",
487            Some(r#"serde_json = "1.0""#),
488        )
489        .unwrap();
490        let cargo = fs::read_to_string(p.dir.join("Cargo.toml")).unwrap();
491        assert!(cargo.contains("[dependencies]"));
492        let src = p.source().unwrap();
493        assert!(src.contains("serde_json::Value"));
494        assert!(src.contains("_x.as_str();"));
495    }
496
497    // ── dot position ─────────────────────────────────────────────────────────
498
499    #[test]
500    fn dot_col_is_seven() {
501        // "    _x." is always 7 characters
502        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
503        assert_eq!(p.dot_col, 7, r#""    _x." should be 7 chars"#);
504    }
505
506    #[test]
507    fn dot_line_is_preamble_plus_two() {
508        // layout: preamble lines, fn main() {, let _x = …, _x.
509        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
510        assert_eq!(p.dot_line, preamble_line_count() + 2);
511    }
512
513    #[test]
514    fn dot_line_same_for_definition_probe() {
515        let p = Probe::for_definition_with_deps("Vec<u8>", "len", None).unwrap();
516        assert_eq!(p.dot_line, preamble_line_count() + 2);
517    }
518
519    // ── URI helpers ──────────────────────────────────────────────────────────
520
521    #[test]
522    fn src_uri_is_file_uri_ending_in_main_rs() {
523        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
524        let uri = p.src_uri();
525        assert!(
526            uri.starts_with("file://"),
527            "src_uri should be a file:// URI"
528        );
529        assert!(
530            uri.ends_with("/src/main.rs"),
531            "src_uri should end in /src/main.rs"
532        );
533    }
534
535    #[test]
536    fn root_uri_is_file_uri_not_ending_in_main_rs() {
537        let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
538        let uri = p.root_uri();
539        assert!(uri.starts_with("file://"));
540        assert!(!uri.ends_with("main.rs"));
541    }
542}