//! Completion, hover and signature help (M3.4) against `lutra-lsp-fake`, //! whose answers are scripted (see its `completion` function). The //! commands return pending results, which the tests wait for without the //! engine lock and resolve with it (`run_waiting`), as hosts do. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing )] use std::ffi::OsString; use std::fs; use std::path::PathBuf; use lutra_engine::lsp::Launch; use lutra_engine::{Engine, EngineError}; use lutra_lsp::ServerOptions; use serde_json::{Value, json}; use tempfile::TempDir; /// The fake server binary, built on demand when this test runs without /// the rest of the workspace (`cargo test -p lutra-engine`). fn fake_server() -> PathBuf { let exe = format!("lutra-lsp-fake{}", std::env::consts::EXE_SUFFIX); let deps = std::env::current_exe().unwrap(); let path = deps.parent().unwrap().parent().unwrap().join(exe); if !path.exists() { let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); let status = std::process::Command::new(cargo) .args(["build", "-p", "lutra-lsp", "--bin", "lutra-lsp-fake"]) .status() .unwrap(); assert!(status.success(), "building lutra-lsp-fake failed"); } path } /// A temp project with `files`, opened in an engine that runs the fake /// server (or none). fn project(files: &[(&str, &str)], server: bool) -> (TempDir, Engine) { let dir = tempfile::tempdir().unwrap(); for (name, text) in files { fs::write(dir.path().join(name), text).unwrap(); } let mut engine = Engine::new().unwrap(); if server { engine.set_language_server(Some(Launch { command: fake_server().into(), args: Vec::::new(), options: ServerOptions::default(), tick: None, })); } engine .execute("project.open", json!({"path": dir.path()})) .unwrap(); (dir, engine) } /// Opens `path`; returns the buffer id. fn open(engine: &mut Engine, path: &str) -> u64 { engine .execute("file.open", json!({"path": path})) .unwrap() .value["id"] .as_u64() .unwrap() } /// Runs `command` and waits for its pending result, as a host does. fn ask(engine: &mut Engine, command: &str, params: Value) -> Result { let mut outcome = engine.execute(command, params)?; match outcome.pending.take() { Some(pending) => Ok(engine.resolve(pending.wait())?.value), None => Ok(outcome.value), } } #[test] fn completion_converts_the_servers_list() { let (_dir, mut engine) = project(&[("a.php", "fo")], true); let id = open(&mut engine, "a.php"); let out = ask( &mut engine, "lsp.completion", json!({"id": id, "position": {"line": 1, "column": 6}}), ) .unwrap(); assert_eq!(out["incomplete"], true); let items = out["items"].as_array().unwrap(); let labels: Vec<&str> = items.iter().map(|i| i["label"].as_str().unwrap()).collect(); assert_eq!(labels, ["format", "$value", "pair", "trigger:none"]); let format = &items[0]; assert_eq!(format["kind"], "method"); assert_eq!(format["detail"], "format(string $pattern): string"); assert_eq!(format["documentation"], "Formats **text**."); assert_eq!(format["insertText"], "format("); assert_eq!( format["textEdit"], json!({"range": {"start": {"line": 1, "column": 4}, "end": {"line": 1, "column": 6}}, "newText": "format("}) ); assert_eq!( format["additionalTextEdits"][0]["newText"], "\nuse App\\Fmt;" ); assert_eq!(items[1]["kind"], "variable"); assert_eq!(items[1]["insertText"], "$value"); assert_eq!(items[2]["insertText"], "pair($a, )"); let triggered = ask( &mut engine, "lsp.completion", json!({"id": id, "position": {"line": 1, "column": 4}, "triggerCharacter": ">"}), ) .unwrap(); assert_eq!(triggered["items"][3]["label"], "trigger:>"); } #[test] fn completion_sees_the_edit_before_it_and_is_capped() { let (_dir, mut engine) = project(&[("a.php", " u128 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_millis() } /// Times `f`. fn timed(f: impl FnOnce() -> T) -> (T, f64) { let start = std::time::Instant::now(); let value = f(); (value, start.elapsed().as_secs_f64() * 1000.0) } /// Replaces line `line` (0-based) of buffer `id` with `text`. fn set_line(engine: &mut Engine, id: u64, line: usize, text: &str) { let current = engine .execute("buffer.get", json!({"id": id})) .unwrap() .value; let whole = current["text"].as_str().unwrap(); let from: usize = whole .split('\n') .take(line) .map(|l| l.encode_utf16().count() + 1) .sum(); let to = from + whole.split('\n').nth(line).unwrap().encode_utf16().count(); engine .execute( "buffer.edit", json!({"id": id, "baseVersion": current["version"], "edits": [{"from": from, "to": to, "insert": text}]}), ) .unwrap(); } /// Min, median and max of `samples` in ms. fn summary(samples: &mut [f64]) -> String { samples.sort_by(f64::total_cmp); let n = samples.len(); format!( "n={n} min={:.0} median={:.0} max={:.0} ms", samples[0], samples[n / 2], samples[n - 1] ) } /// A shop-like project: `classes` classes in `src/` plus the file the /// test types in. fn shop(classes: usize) -> Vec<(String, String)> { let mut files = Vec::new(); for i in 0..classes { files.push(( format!("src/Product{i}.php"), format!( "name;\n }}\n\n /** The price in cents, times `$count`. */\n public function price(int $count = 1, bool $gross = true): int\n {{\n return $this->price * $count;\n }}\n}}\n" ), )); } files.push(( "src/Cart.php".into(), "\n }\n}\n".into(), )); files } /// Completion, hover and signature help against the real Phpactor, with /// latencies and phase timestamps (`PHASE `) /// for an outside sampler of the Phpactor process: /// /// `LUTRA_PHPACTOR= [LUTRA_PHP=php] [LUTRA_SHOP_CLASSES=20] cargo test -p lutra-engine --test lsp_assist real_phpactor -- --ignored --nocapture` #[test] #[ignore = "needs PHP and Phpactor (LUTRA_PHPACTOR)"] fn real_phpactor_assist_latency() { let phar = std::env::var("LUTRA_PHPACTOR").expect("LUTRA_PHPACTOR"); let php = std::env::var("LUTRA_PHP").unwrap_or_else(|_| "php".into()); let classes: usize = std::env::var("LUTRA_SHOP_CLASSES") .ok() .and_then(|n| n.parse().ok()) .unwrap_or(20); let dir = tempfile::tempdir().unwrap(); for (name, text) in shop(classes) { let path = dir.path().join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, text).unwrap(); } let mut engine = Engine::new().unwrap(); engine.set_language_server(Some(lutra_engine::lsp::phpactor_launch( &php, &phar, cfg!(windows), ))); engine .execute("project.open", json!({"path": dir.path()})) .unwrap(); let started = std::time::Instant::now(); loop { let ready = engine .pump_vfs() .unwrap() .iter() .any(|e| serde_json::to_value(e).unwrap()["state"] == "ready"); if ready { break; } assert!(started.elapsed().as_secs() < 60, "Phpactor not ready"); std::thread::sleep(std::time::Duration::from_millis(10)); } println!("ready after {:?} ({classes} classes)", started.elapsed()); let id = open(&mut engine, "src/Cart.php"); let at_arrow = json!({"id": id, "position": {"line": 8, "column": 18}, "triggerCharacter": ">"}); let opened = std::time::Instant::now(); let mut attempts = 0; let first = loop { attempts += 1; let (out, ms) = timed(|| ask(&mut engine, "lsp.completion", at_arrow.clone()).unwrap()); let found = out["items"] .as_array() .unwrap() .iter() .any(|i| i["label"] == "price"); if attempts == 1 { println!("first completion after -> {ms:.0} ms: {out}"); } if found { break out; } assert!( opened.elapsed().as_secs() < 90, "no useful completion within 90 s: {out}" ); std::thread::sleep(std::time::Duration::from_millis(250)); }; println!( "useful completion {:?} after file.open ({attempts} attempts)", opened.elapsed() ); let labels: Vec<&str> = first["items"] .as_array() .unwrap() .iter() .map(|i| i["label"].as_str().unwrap()) .collect(); println!("labels: {labels:?}"); println!("first item: {}", first["items"][0]); println!("PHASE idle start {}", epoch_ms()); std::thread::sleep(std::time::Duration::from_secs(70)); println!("PHASE idle end {}", epoch_ms()); let (_, after_idle) = timed(|| ask(&mut engine, "lsp.completion", at_arrow.clone()).unwrap()); println!("completion after 70 s idle (ticks stopped) {after_idle:.0} ms"); println!("PHASE typing start {}", epoch_ms()); let mut completion = Vec::new(); for round in 0..15 { let typed = ["", "p", "pr"][round % 3]; let line = format!(" $product->{typed}"); set_line(&mut engine, id, 8, &line); let (_, ms) = timed(|| { ask( &mut engine, "lsp.completion", json!({"id": id, "position": {"line": 8, "column": line.encode_utf16().count()}}), ) .unwrap() }); completion.push(ms); std::thread::sleep(std::time::Duration::from_millis(150)); } println!("completion while typing: {}", summary(&mut completion)); let call = " $product->price(1, "; set_line(&mut engine, id, 8, call); let mut signature = Vec::new(); for _ in 0..10 { let (out, ms) = timed(|| { ask( &mut engine, "lsp.signatureHelp", json!({"id": id, "position": {"line": 8, "column": call.encode_utf16().count()}}), ) .unwrap() }); signature.push(ms); if signature.len() == 1 { println!("signature help: {out}"); } } println!("signature help: {}", summary(&mut signature)); let mut hover = Vec::new(); for _ in 0..10 { let (out, ms) = timed(|| { ask( &mut engine, "lsp.hover", json!({"id": id, "position": {"line": 6, "column": 26}}), ) .unwrap() }); hover.push(ms); assert!( out["contents"].as_str().unwrap().contains("Product0"), "{out}" ); } println!("hover on a class: {}", summary(&mut hover)); let text = ask( &mut engine, "lsp.hover", json!({"id": id, "position": {"line": 6, "column": 26}}), ) .unwrap(); println!("hover contents: {}", text["contents"]); println!("PHASE typing end {}", epoch_ms()); }