1pub(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
23static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
28
29const 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
43pub struct Probe {
48 #[allow(dead_code)]
50 inner: Arc<CachedProbe>,
51 pub dot_line: u32,
53 pub dot_col: u32,
55 pub dir: PathBuf,
57 pub src_path: PathBuf,
59}
60
61impl Probe {
62 pub fn new(type_name: &str) -> std::io::Result<Self> {
69 Self::create_probe(type_name, None, None, None)
70 }
71
72 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 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 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 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 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 pub(crate) fn infer_dep(type_name: &str) -> Option<String> {
156 if !type_name.contains("::") {
157 return None; }
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 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 if let Some(probe) = Self::from_memory_cache(&key) {
195 return Ok(probe);
196 }
197
198 if let Some(ra) = ra_path
200 && let Some(probe) = Self::from_persistent_cache(&key, ra)
201 {
202 return Ok(probe);
203 }
204
205 Self::create_on_disk(
207 key,
208 type_name,
209 method_name,
210 effective_deps.as_ref(),
211 ra_path,
212 )
213 }
214
215 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 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 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 #[must_use]
364 pub fn src_uri(&self) -> String {
365 path_to_uri(&self.src_path)
366 }
367
368 #[must_use]
370 pub fn root_uri(&self) -> String {
371 path_to_uri(&self.dir)
372 }
373
374 pub fn source(&self) -> std::io::Result<String> {
384 fs::read_to_string(&self.src_path)
385 }
386}
387
388impl 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 fn preamble_line_count() -> u32 {
411 u32::try_from(PREAMBLE.lines().count()).unwrap()
412 }
413
414 #[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 #[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 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 #[test]
500 fn dot_col_is_seven() {
501 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 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 #[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}