1use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
18
19const 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
33pub struct Probe {
37 pub dir: PathBuf,
39 pub src_path: PathBuf,
41 pub dot_line: u32,
43 pub dot_col: u32,
45}
46
47impl Probe {
48 #[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 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 #[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 fn infer_dep(type_name: &str) -> Option<String> {
99 if !type_name.contains("::") {
100 return None; }
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 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 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 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 fs::write(dir.join("Cargo.toml"), cargo_toml)?;
165
166 let preamble_lines =
174 u32::try_from(PREAMBLE.lines().count()).expect("Preamble is too long to fit in u32");
175
176 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 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 #[must_use]
207 pub fn src_uri(&self) -> String {
208 path_to_uri(&self.src_path)
209 }
210
211 #[must_use]
213 pub fn root_uri(&self) -> String {
214 path_to_uri(&self.dir)
215 }
216
217 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 fn preamble_line_count() -> u32 {
254 u32::try_from(PREAMBLE.lines().count()).unwrap()
255 }
256
257 #[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 #[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 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 #[test]
343 fn dot_col_is_seven() {
344 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 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 #[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 #[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}