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 pub fn new(type_name: &str) -> std::io::Result<Self> {
55 Self::create_probe(type_name, None, None)
56 }
57
58 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 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 fn infer_dep(type_name: &str) -> Option<String> {
97 if !type_name.contains("::") {
98 return None; }
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 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 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 src_dir = dir.join("src");
138 fs::create_dir_all(&src_dir)?;
139
140 let effective_deps = deps
141 .map(str::to_owned)
142 .or_else(|| Self::infer_dep(type_name));
143
144 let cargo_toml = effective_deps.map_or_else(
145 || "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n".to_string(),
146 |d| format!(
147 "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n{d}\n"
148 ),
149 );
150
151 fs::write(dir.join("Cargo.toml"), cargo_toml)?;
154
155 let preamble_lines = u32::try_from(PREAMBLE.lines().count())
163 .expect("PREAMBLE is a fixed compile-time constant, line count always fits u32");
164
165 let source = method_name.map_or_else(|| format!("{PREAMBLE}fn main() {{\n let _x: {type_name} = todo!();\n _x.\n}}\n"), |method| format!(
167 "{PREAMBLE}fn main() {{\n let _x: {type_name} = todo!();\n _x.{method}();\n}}\n"
168 ));
169
170 let src_path = src_dir.join("main.rs");
171 fs::write(&src_path, &source)?;
172
173 let dot_line = preamble_lines + 2;
175 let dot_col =
176 u32::try_from(" _x.".len()).expect("string literal length always fits in u32");
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 #[must_use]
197 pub fn src_uri(&self) -> String {
198 path_to_uri(&self.src_path)
199 }
200
201 #[must_use]
203 pub fn root_uri(&self) -> String {
204 path_to_uri(&self.dir)
205 }
206
207 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 fn preamble_line_count() -> u32 {
244 u32::try_from(PREAMBLE.lines().count()).unwrap()
245 }
246
247 #[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 #[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 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 #[test]
333 fn dot_col_is_seven() {
334 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 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 #[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 #[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}