//! Inline a module at the cursor, on the wire: `textDocument/codeAction` under //! LSP's own `refactor.inline`, and `workspace/executeCommand` for the editors //! that have no lightbulb. //! //! Protocol only. The edit is `vlog_refactor::inline_module`; this module //! decides which files that engine is handed, turns its answer into a //! `WorkspaceEdit` and its refusal into a request error. //! //! **The action carries a command, not an edit**, for the same reason the //! extraction's does — laziness rather than a prompt. Answering "what would //! inlining `S` here look like" means reading `S`'s file, every file that //! spells it, and analyzing all of them; a `textDocument/codeAction` arrives //! on every cursor move. So the offer is one parse of one buffer //! (`vlog_refactor::inline_site`) plus a `Command` naming [`INLINE_MODULE`], //! and the workspace is not touched until the user picks the action. See //! `docs/features/extract-inline-module/README.md`. // See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours. #![allow(clippy::mutable_key_type)] use lsp_types::{ CodeAction, CodeActionKind, CodeActionOrCommand, Command, Position, Range, Uri, WorkspaceEdit, }; use serde_json::Value; use crate::module_select::Reach; use crate::state::{Document, Workspace}; /// Inline the module instantiated at a position: `[uri, position]`. pub const INLINE_MODULE: &str = "lucisv.inlineModule"; /// Every command this module executes. pub fn commands() -> Vec { vec![INLINE_MODULE.to_string()] } /// The kind LSP reserves for an inline, which is what an editor's "Refactor…" /// menu asks for by name. pub fn kind() -> CodeActionKind { CodeActionKind::REFACTOR_INLINE } /// The action for the cursor, carrying the command that does the work. /// Whether the cursor is on an instantiation lucisv could inline, asked of the /// buffer's own parse and diagnostics rather than of its text (take 5 §P1b). /// /// A buffer on the large-file fast path keeps the text form, whose parse is of /// the real bytes rather than of the empty analysis that path installs — see /// `ports::modules_at` and `docs/features/perf5-p1/README.md`. fn site_at(doc: &Document, offset: u32) -> Option { match doc.large { true => vlog_refactor::inline_site(&doc.text, offset), false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset), } } pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; if doc.path.is_none() { // An `untitled:` buffer has no path for the engine's file set; nothing // is offered rather than offered and refused. return Vec::new(); } let offset = doc.positions().offset(range.start); let Some(site) = site_at(doc, offset) else { return Vec::new() }; let arguments = vec![ serde_json::to_value(uri).unwrap_or(Value::Null), serde_json::to_value(range.start).unwrap_or(Value::Null), ]; let title = vlog_refactor::inline_title(&site.module); vec![CodeActionOrCommand::CodeAction(CodeAction { title: title.clone(), kind: Some(kind()), command: Some(Command { title, command: INLINE_MODULE.to_string(), arguments: Some(arguments), }), ..Default::default() })] } /// Run `lucisv.inlineModule`, or say why it cannot run. pub fn execute( ws: &Workspace, arguments: &[Value], ) -> Result<(WorkspaceEdit, Vec), String> { let uri: Uri = argument(arguments, 0, "a document URI")?; let position: Position = argument(arguments, 1, "a position")?; let doc = ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?; let path = doc .path .clone() .ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?; let offset = doc.positions().offset(position); let Some(site) = site_at(doc, offset) else { return Err(NOTHING.to_string()); }; // The engine reads the instantiated module's declaration and refuses over // any hierarchical path into the instance, so the file set is the two // units' own fan-out — the declaring file, and every file the index says // mentions either name — **plus the fifth rung**: every file whose tokens // write the instance's own name down. A file naming // `u_wrapper.u_top.u_sub.s` reaches this instance through modules it does // not itself instantiate, and the first four rungs have nothing that asks // for it (topology handshake 33). The rung is the exact census // `no_hierarchy` can refuse from, so this set answers that refusal the way // the whole workspace would. let scopes = [site.instance.clone()]; let files = ws.module_sources_reaching(&path, &site.units, Reach { scopes: &scopes }); let refactoring = vlog_refactor::inline_module(&files, &path, offset)?; Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings)) } fn argument( arguments: &[Value], n: usize, what: &str, ) -> Result { arguments .get(n) .and_then(|value| serde_json::from_value(value.clone()).ok()) .ok_or_else(|| format!("{INLINE_MODULE} wants {what} as argument {}.", n + 1)) } const NOTHING: &str = "there is no module instantiation at this position to inline."; #[cfg(test)] mod tests { use super::*; use crate::uri::path_to_uri; use std::fs; use std::path::PathBuf; /// A scratch workspace root. Removed on drop. struct Tree { path: PathBuf, } impl Tree { fn new(name: &str) -> Tree { let path = std::env::temp_dir() .join(format!("lucisv_server_inline_{}_{name}", std::process::id())); let _ = fs::remove_dir_all(&path); fs::create_dir_all(&path).expect("temp dir"); Tree { path } } fn write(&self, rel: &str, text: &str) { fs::write(self.path.join(rel), text).expect("write"); } } impl Drop for Tree { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.path); } } const SUB: &str = "\ module sub ( input logic a, output logic q ); logic s; // the and assign s = a; assign q = s; endmodule "; const TOP: &str = "\ module top ( input logic x, output logic z ); sub u_sub ( .a(x), .q(z) ); endmodule "; fn opened(tree: &Tree) -> (Workspace, Uri) { tree.write("sub.sv", SUB); tree.write("top.sv", TOP); let mut ws = Workspace::default(); ws.open_whole_workspace(vec![tree.path.clone()]); let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri"); ws.set_document(uri.clone(), TOP.to_string()); (ws, uri) } /// The cursor on the `sub` of `sub u_sub (`. fn cursor() -> Range { let at = Position { line: 4, character: 4 }; Range { start: at, end: at } } #[test] fn the_cursor_on_an_instantiation_is_offered_the_action_with_its_command() { let tree = Tree::new("offer"); let (ws, uri) = opened(&tree); let actions = code_actions(&ws, &uri, cursor()); let [CodeActionOrCommand::CodeAction(action)] = actions.as_slice() else { panic!("one action, got {actions:?}") }; assert_eq!(action.title, "lucisv: inline `sub` here"); assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_INLINE)); assert!(action.edit.is_none(), "the offer reads no workspace"); let command = action.command.as_ref().expect("a command"); assert_eq!(command.command, INLINE_MODULE); assert_eq!(command.arguments.as_ref().expect("arguments").len(), 2); } #[test] fn a_cursor_on_anything_else_is_offered_nothing() { let tree = Tree::new("nothing"); let (ws, uri) = opened(&tree); let elsewhere = Range { start: Position { line: 1, character: 4 }, end: Position { line: 1, character: 4 }, }; assert!(code_actions(&ws, &uri, elsewhere).is_empty()); } #[test] fn the_command_replaces_the_instantiation_with_the_body() { let tree = Tree::new("run"); let (ws, uri) = opened(&tree); let arguments = vec![ serde_json::to_value(&uri).expect("uri"), serde_json::to_value(cursor().start).expect("position"), ]; let (edit, warnings) = execute(&ws, &arguments).expect("inlines"); let changes = edit.changes.as_ref().expect("changes"); assert_eq!(changes.len(), 1, "only the file the cursor is in is edited"); let written = &changes.get(&uri).expect("this file")[0].new_text; assert!(written.contains("assign s = x;"), "{written}"); assert!(written.contains("// the and"), "{written}"); assert!(warnings.iter().any(|w| w.contains("still declared where it was")), "{warnings:?}"); } #[test] fn the_command_says_why_when_there_is_nothing_to_inline() { let tree = Tree::new("refuse"); let (ws, uri) = opened(&tree); let arguments = vec![ serde_json::to_value(&uri).expect("uri"), serde_json::to_value(Position { line: 1, character: 4 }).expect("position"), ]; assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string())); } #[test] fn the_command_wants_both_of_its_arguments() { let tree = Tree::new("arguments"); let (ws, uri) = opened(&tree); let short = vec![serde_json::to_value(&uri).expect("uri")]; let message = execute(&ws, &short).expect_err("a refusal"); assert!(message.contains("argument 2"), "{message}"); } #[test] fn a_client_asking_only_for_refactor_inline_is_answered() { let filter = [CodeActionKind::REFACTOR_INLINE]; assert!(crate::code_action::wanted(Some(&filter), &kind())); assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX)); } }