diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 2a6dd1b..e093347 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -146,6 +146,7 @@ fn main() -> Result<(), Box> { semantic_tokens_refresh: semantic_tokens_refresh_support(¶ms), hierarchy_view, code_action_resolve: code_action_resolve_support(¶ms), + document_changes: document_changes_support(¶ms), create_files: create_files_support(¶ms), completion_item_defaults: completion::item_defaults_support(¶ms), }; @@ -576,6 +577,18 @@ fn create_files_support(params: &InitializeParams) -> bool { edits.document_changes.unwrap_or(false) && creates } +/// Whether the client accepts versioned `documentChanges` arrays inside a +/// `WorkspaceEdit` (`workspace.workspaceEdit.documentChanges`). +fn document_changes_support(params: &InitializeParams) -> bool { + params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.workspace_edit.as_ref()) + .and_then(|edits| edits.document_changes) + .unwrap_or(false) +} + /// Whether the client applies a `workspace/applyEdit` request. /// /// A client that did not say so gets a command's edit back as the request @@ -1307,6 +1320,30 @@ mod tests { assert!(!create_files_support(&saying(Some(false), Some(&create)))); } + #[test] + fn document_changes_support_reads_workspace_edit_capability() { + use lsp_types::{ + ClientCapabilities, WorkspaceClientCapabilities, WorkspaceEditClientCapabilities, + }; + assert!(!document_changes_support(&InitializeParams::default())); + let saying = |document_changes: Option| InitializeParams { + capabilities: ClientCapabilities { + workspace: Some(WorkspaceClientCapabilities { + workspace_edit: Some(WorkspaceEditClientCapabilities { + document_changes, + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(document_changes_support(&saying(Some(true)))); + assert!(!document_changes_support(&saying(Some(false)))); + assert!(!document_changes_support(&saying(None))); + } + #[test] fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() { use lsp_types::{ diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index d50741e..efb6202 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -30,7 +30,9 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use lsp_types::{ - CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit, + CodeAction, CodeActionKind, CodeActionOrCommand, DocumentChanges, OneOf, + OptionalVersionedTextDocumentIdentifier, Position, TextDocumentEdit, TextEdit, Uri, + WorkspaceEdit, }; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -93,7 +95,20 @@ fn modules_at(doc: &Document, offset: u32) -> Vec { } } +#[cfg(test)] pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + code_actions_for(ws, uri, offset, false) +} + +/// [`code_actions`] emitting versioned `DocumentChanges::Edits` when +/// `versioned` is true and at least one edited buffer has an attached LSP +/// version (topo #52). +pub fn code_actions_for( + ws: &Workspace, + uri: &Uri, + offset: u32, + versioned: bool, +) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; let Some(path) = doc.path.clone() else { return Vec::new() }; // A code-action request arrives on every cursor move, so neither half of @@ -110,7 +125,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec Result { + resolve_for(ws, action, false) +} + +/// [`resolve`] emitting versioned `DocumentChanges::Edits` when `versioned` +/// is true and at least one edited buffer has an attached LSP version (topo +/// #52). +pub fn resolve_for( + ws: &Workspace, + action: CodeAction, + versioned: bool, +) -> Result { if action.edit.is_some() { return Ok(action); } @@ -279,7 +306,7 @@ pub fn resolve(ws: &Workspace, action: CodeAction) -> Result // lightbulb is not a reason to break it. let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?; let offset = doc.positions().offset(offer.position); - code_actions(ws, &offer.uri, offset) + code_actions_for(ws, &offer.uri, offset, versioned) .into_iter() .find_map(|offered| match offered { CodeActionOrCommand::CodeAction(found) if key(&found.title) == key(&offer.title) => { @@ -347,10 +374,23 @@ fn declared_twice(ws: &Workspace, name: &str) -> bool { /// it reaches the editor is `server.rs`'s business: it is pushed as a /// `workspace/applyEdit` request, or — for a client that cannot be pushed one /// — returned as the command's result (`docs/features/apply-edit/README.md`). +#[cfg(test)] pub fn execute( ws: &Workspace, command: &str, arguments: &[Value], +) -> Result<(WorkspaceEdit, Vec), String> { + execute_for(ws, command, arguments, false) +} + +/// [`execute`] emitting versioned `DocumentChanges::Edits` when `versioned` +/// is true and at least one edited buffer has an attached LSP version (topo +/// #52). +pub fn execute_for( + ws: &Workspace, + command: &str, + arguments: &[Value], + versioned: bool, ) -> Result<(WorkspaceEdit, Vec), String> { let refactoring = match command { ADD_PORT => { @@ -409,7 +449,7 @@ pub fn execute( } other => return Err(format!("`{other}` is not a lucisv command.")), }; - Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings)) + Ok((workspace_edit_for(ws, &refactoring, versioned)?, refactoring.warnings)) } /// The files a port refactoring **at a position** reads: the fan-out of every @@ -487,30 +527,76 @@ fn offset_of(ws: &Workspace, uri: Option<&Value>, position: Position) -> Result< /// A whole refactoring as a `WorkspaceEdit`, with every range computed against /// the text the engine actually edited — the open buffer's when there is one. pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result { - let mut changes: HashMap> = HashMap::new(); - for (path, edits) in &refactoring.edits { - let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else { - return Err(format!( - "lucisv could not address {} as a document; no edits were made.", - path.display() - )); + workspace_edit_for(ws, refactoring, false) +} + +/// A refactoring encoded as versioned `DocumentChanges::Edits` when +/// `versioned` is true and at least one touched document has a recorded LSP +/// version, falling back to `WorkspaceEdit { changes: Some(...), .. }` +/// otherwise (topo #52). +pub(crate) fn workspace_edit_for( + ws: &Workspace, + refactoring: &RefactorEdit, + versioned: bool, +) -> Result { + encode_edit(ws, &refactoring.edits, versioned) +} + +/// Shared encoder turning a map of byte-range file edits into either a +/// sorted `DocumentChanges::Edits` list carrying `OptionalVersionedTextDocumentIdentifier` +/// entries or an unversioned `changes` map. +pub(crate) fn encode_edit( + ws: &Workspace, + files: &[(PathBuf, Vec)], + versioned: bool, +) -> Result { + let mut pairs: Vec<(Uri, Option, Vec)> = Vec::new(); + for (path, edits) in files { + let open = ws.open_documents().find(|(_, doc)| doc.path.as_deref() == Some(path)); + let (target, version, mapped) = match open { + Some((uri, doc)) => (uri.clone(), doc.version(), map_edits(&doc.positions(), edits)), + None => { + let (Some(uri), Some(text)) = (path_to_uri(path), ws.text_of(path)) else { + return Err(format!( + "lucisv could not address {} as a document; no edits were made.", + path.display() + )); + }; + let index = LineIndex::new(&text); + (uri, None, map_edits(&Positions::new(&text, &index), edits)) + } }; - let index = LineIndex::new(&text); - let positions = Positions::new(&text, &index); - changes.insert( - target, - edits - .iter() - .map(|edit| TextEdit { - range: positions.range(edit.range), - new_text: edit.new_text.clone(), - }) - .collect(), - ); + pairs.push((target, version, mapped)); } + if versioned && pairs.iter().any(|(_, version, _)| version.is_some()) { + pairs.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); + let edits = pairs + .into_iter() + .map(|(uri, version, edits)| TextDocumentEdit { + text_document: OptionalVersionedTextDocumentIdentifier { uri, version }, + edits: edits.into_iter().map(OneOf::Left).collect(), + }) + .collect(); + return Ok(WorkspaceEdit { + document_changes: Some(DocumentChanges::Edits(edits)), + ..Default::default() + }); + } + let changes: HashMap> = + pairs.into_iter().map(|(uri, _, edits)| (uri, edits)).collect(); Ok(WorkspaceEdit::new(changes)) } +fn map_edits(positions: &Positions<'_>, edits: &[vlog_refactor::TextEdit]) -> Vec { + edits + .iter() + .map(|edit| TextEdit { + range: positions.range(edit.range), + new_text: edit.new_text.clone(), + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -1563,6 +1649,130 @@ mod tests { vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI] ); } + + #[test] + fn port_edits_use_versioned_document_changes_when_requested_and_version_exists() { + let tree = Tree::new("versioned_ports"); + let (ws, top_uri, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + Value::String("sub".into()), + Value::String("input logic cfg".into()), + ]; + + // Versionless document falls back to `changes` even when `versioned = true`. + let (fallback, _) = + execute_for(&ws, ADD_PORT, &arguments, true).expect("fallback add port"); + assert!(fallback.changes.is_some()); + assert!(fallback.document_changes.is_none()); + + // Attached version emits `DocumentChanges::Edits` across `execute_for`, + // `code_actions_for`, and `resolve_for`. + ws.document(&top_uri).expect("open").set_version(Some(4)); + let (exec_edit, _) = execute_for(&ws, ADD_PORT, &arguments, true).expect("versioned add"); + assert!(exec_edit.changes.is_none()); + let Some(DocumentChanges::Edits(exec_docs)) = exec_edit.document_changes else { + panic!("expected DocumentChanges::Edits"); + }; + let mut expected = vec![(sub_uri.clone(), None), (top_uri.clone(), Some(4))]; + expected.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); + let actual: Vec<_> = exec_docs + .iter() + .map(|d| (d.text_document.uri.clone(), d.text_document.version)) + .collect(); + assert_eq!(actual, expected); + + let (legacy_ws, legacy_uri) = legacy(&tree); + legacy_ws.document(&legacy_uri).expect("open").set_version(Some(11)); + let offset = LEGACY.find("legacy (").expect("the name") as u32; + let eager = code_actions_for(&legacy_ws, &legacy_uri, offset, true); + let CodeActionOrCommand::CodeAction(action) = &eager[0] else { + panic!("expected code action"); + }; + let Some(DocumentChanges::Edits(docs)) = + action.edit.as_ref().and_then(|e| e.document_changes.as_ref()) + else { + panic!("expected DocumentChanges::Edits on code_actions_for"); + }; + assert_eq!(docs[0].text_document.version, Some(11)); + + let lazy = offered(&legacy_ws, &legacy_uri, offset); + let CodeActionOrCommand::CodeAction(offer) = &lazy[0] else { + panic!("expected offer"); + }; + let resolved = resolve_for(&legacy_ws, offer.clone(), true).expect("resolved"); + assert_eq!(resolved.edit, action.edit); + } + + #[test] + fn encode_edit_preserves_non_canonical_client_uri_and_version() { + let tree = Tree::new("non_canonical_uri"); + let sub_path = tree.write("sub.sv", SUB); + let cafe_text = "module cafe_mod;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"; + let cafe_path = tree.write("café.sv", cafe_text); + let top_path = tree.write("top.sv", TOP); + + let localhost_uri: Uri = path_to_uri(&sub_path) + .expect("sub uri") + .as_str() + .replacen("file:///", "file://localhost/", 1) + .parse() + .expect("localhost uri"); + let cafe_uri: Uri = path_to_uri(&cafe_path) + .expect("cafe uri") + .as_str() + .replace("%C3%A9", "%c3%a9") + .parse() + .expect("lowercase pct uri"); + assert_ne!(localhost_uri, path_to_uri(&sub_path).expect("canonical sub")); + assert_ne!(cafe_uri, path_to_uri(&cafe_path).expect("canonical cafe")); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + ws.set_document(localhost_uri.clone(), SUB.to_string()); + ws.set_document(cafe_uri.clone(), cafe_text.to_string()); + ws.document(&localhost_uri).expect("open sub").set_version(Some(12)); + ws.document(&cafe_uri).expect("open cafe").set_version(Some(7)); + + let top_uri = path_to_uri(&top_path).expect("top uri"); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + Value::String("sub".into()), + Value::String("input logic cfg".into()), + ]; + let (edit, _) = execute_for(&ws, ADD_PORT, &arguments, true).expect("versioned add"); + let Some(DocumentChanges::Edits(docs)) = edit.document_changes else { + panic!("expected DocumentChanges::Edits"); + }; + let mut expected = vec![(localhost_uri.clone(), Some(12)), (top_uri.clone(), None)]; + expected.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); + assert_eq!( + docs.iter() + .map(|d| (d.text_document.uri.clone(), d.text_document.version)) + .collect::>(), + expected, + ); + + let span = vlog_parser::TextRange::new( + cafe_text.find("sig").expect("sig") as u32, + cafe_text.find("sig").expect("sig") as u32 + 3, + ); + let cafe_edits = vec![( + cafe_path, + vec![vlog_refactor::TextEdit { range: span, new_text: "sig_r".to_string() }], + )]; + let versioned_cafe = encode_edit(&ws, &cafe_edits, true).expect("versioned cafe"); + let Some(DocumentChanges::Edits(cafe_docs)) = versioned_cafe.document_changes else { + panic!("expected DocumentChanges::Edits for lowercase pct uri"); + }; + assert_eq!(cafe_docs[0].text_document.uri, cafe_uri); + assert_eq!(cafe_docs[0].text_document.version, Some(7)); + + let unversioned_cafe = encode_edit(&ws, &cafe_edits, false).expect("unversioned cafe"); + assert!(unversioned_cafe.document_changes.is_none()); + let changes = unversioned_cafe.changes.expect("changes map"); + assert!(changes.contains_key(&cafe_uri), "changes map must use client URI: {changes:?}"); + } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/rename.rs b/crates/lucisv_server/src/rename.rs index 36db893..a0cf1bf 100644 --- a/crates/lucisv_server/src/rename.rs +++ b/crates/lucisv_server/src/rename.rs @@ -14,18 +14,14 @@ // ours. #![allow(clippy::mutable_key_type)] -use std::collections::HashMap; use std::path::PathBuf; -use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit}; -use vlog_parser::LineIndex; +use lsp_types::{PrepareRenameResponse, Uri, WorkspaceEdit}; use vlog_semantic::FileFacts; -use crate::convert::Positions; use crate::locate::display_name; use crate::rename_trace::SelectionTrace; use crate::state::Workspace; -use crate::uri::path_to_uri; /// The identifier at `offset` and its current name, or the reason it cannot /// be renamed. Returning the reason — rather than `null` — is what puts the @@ -59,12 +55,27 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result, +) -> Result<(WorkspaceEdit, Vec), String> { + rename_traced_for(ws, uri, offset, new_name, false, trace) +} + +/// [`rename_traced`] emitting versioned `DocumentChanges::Edits` when +/// `versioned` is true and at least one edited buffer has an attached LSP +/// version (topo #52). +pub fn rename_traced_for( + ws: &Workspace, + uri: &Uri, + offset: u32, + new_name: &str, + versioned: bool, + trace: &mut Option, ) -> Result<(WorkspaceEdit, Vec), String> { let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?; let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?; @@ -109,36 +120,12 @@ pub fn rename_traced( *trace = Some(format!("{} {}", selection.line(), engine.line())); let refactoring = outcome?; - let mut changes: HashMap> = HashMap::new(); - for (path, edits) in &refactoring.edits { - // The engine edited the text `sources()` handed it, which is the open - // buffer's when there is one — the same precedence every other - // cross-file answer uses, so the ranges are never computed against - // text nobody has. - let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else { - return Err(format!( - "lucisv could not address {} as a document; no edits were made.", - path.display() - )); - }; - let index = LineIndex::new(&text); - let positions = Positions::new(&text, &index); - changes.insert( - target, - edits - .iter() - .map(|edit| TextEdit { - range: positions.range(edit.range), - new_text: edit.new_text.clone(), - }) - .collect(), - ); - } + let workspace_edit = crate::ports::encode_edit(ws, &refactoring.edits, versioned)?; let mut warnings = refactoring.warnings; if let Some(name) = &old_name { warnings.extend(unread_macro_warnings(ws, name, &sources)); } - Ok((WorkspaceEdit::new(changes), warnings)) + Ok((workspace_edit, warnings)) } /// The workspace answering the engine's `KnownFacts` question, and nothing @@ -195,6 +182,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file."; #[cfg(test)] mod tests { use super::*; + use crate::uri::path_to_uri; use std::fs; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -1294,6 +1282,36 @@ mod tests { `server/large_file.rs` must answer this method before we are reached" ); } + + #[test] + fn rename_emits_versioned_document_changes_when_requested_and_falls_back() { + let tree = Tree::new("versioned_rename"); + let (ws, top_uri) = opened(&tree); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + + // Unversioned buffer + `versioned = true` falls back to `changes`. + let (fallback, _) = + rename_traced_for(&ws, &top_uri, at(TOP, "clk"), "clk_x", true, &mut None) + .expect("rename"); + assert!(fallback.changes.is_some()); + assert!(fallback.document_changes.is_none()); + + // Attached buffer version emits sorted `DocumentChanges::Edits` with + // `Some(v)` for open buffers and `None` for closed on-disk files. + ws.document(&top_uri).expect("open").set_version(Some(7)); + let (versioned_edit, _) = + rename_traced_for(&ws, &top_uri, at(TOP, "clk"), "clk_x", true, &mut None) + .expect("rename"); + assert!(versioned_edit.changes.is_none()); + let Some(lsp_types::DocumentChanges::Edits(docs)) = versioned_edit.document_changes else { + panic!("expected DocumentChanges::Edits, got {versioned_edit:?}"); + }; + let mut expected = vec![(sub_uri, None), (top_uri, Some(7))]; + expected.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str())); + let actual: Vec<_> = + docs.iter().map(|d| (d.text_document.uri.clone(), d.text_document.version)).collect(); + assert_eq!(actual, expected); + } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/same_file.rs b/crates/lucisv_server/src/same_file.rs index c9ce551..40fb51e 100644 --- a/crates/lucisv_server/src/same_file.rs +++ b/crates/lucisv_server/src/same_file.rs @@ -44,6 +44,7 @@ use lsp_types::request::{ }; use lsp_types::Position; use serde_json::Value; +use vlog_semantic::{Semantics, Symbol, SymbolKind}; use crate::state::Document; use crate::{caret, hover, includes, nav, pairs, signature, type_def}; @@ -177,10 +178,11 @@ fn cannot_leave(doc: &Document, offset: u32) -> bool { } /// Mirrors `vlog_refactor::prepare_rename_here`: a declaration, or a use the -/// binder resolved, is judged on the buffer — except at file scope, where a -/// second unit of the same name in the index makes it ambiguous. Any use the -/// binder did not resolve waits, which keeps the refusals' wording the -/// settled server's. +/// binder resolved, is judged on the buffer — except at file scope or inside a +/// file-scope unit (`Module`, `Interface`, `Package`, `Typedef`, `Class`), +/// where a second unit of the same name in the index makes it ambiguous. Any +/// use the binder did not resolve waits, which keeps the refusals' wording +/// the settled server's. fn renamed_here(doc: &Document, offset: u32) -> bool { if doc.path.is_none() { return true; @@ -193,7 +195,39 @@ fn renamed_here(doc: &Document, offset: u32) -> bool { // An unresolved use waits; a cursor on nothing is refused alike. return doc.semantics.reference_at(offset).is_none(); }; - symbol.scope != doc.semantics.file_scope() + !enclosed_by_unit(&doc.semantics, symbol) +} + +/// Whether `symbol` sits at file scope or inside a file-scope unit +/// (`Module`, `Interface`, `Package`, `Typedef`, `Class`), whose ambiguity +/// across files only the workspace index can judge. +fn enclosed_by_unit(semantics: &Semantics, symbol: &Symbol) -> bool { + let file_scope = semantics.file_scope(); + if symbol.scope == file_scope { + return true; + } + let mut current = Some(symbol.scope); + while let Some(scope_id) = current { + let Some(scope) = semantics.scope(scope_id) else { + break; + }; + if let Some(owner) = scope.owner.and_then(|id| semantics.symbol(id)) { + if owner.scope == file_scope + && matches!( + owner.kind, + SymbolKind::Module + | SymbolKind::Interface + | SymbolKind::Package + | SymbolKind::Typedef + | SymbolKind::Class + ) + { + return true; + } + } + current = scope.parent; + } + false } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/same_file/tests.rs b/crates/lucisv_server/src/same_file/tests.rs index bbb7606..48b6b16 100644 --- a/crates/lucisv_server/src/same_file/tests.rs +++ b/crates/lucisv_server/src/same_file/tests.rs @@ -134,12 +134,41 @@ fn an_untitled_buffer_never_leaves_itself() { } #[test] -fn prepare_rename_waits_at_file_scope_and_on_an_unresolved_use() { +fn prepare_rename_waits_at_file_scope_inside_units_and_on_an_unresolved_use() { let ws = buffer(WITH_IMPORT); assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "m;", 0)), "a unit name"); - assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig;", 0))); - assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig = st", 0))); + assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig;", 0)), "inside a module"); + assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig = st", 0)), "inside a module"); + assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "tmp = sig", 0)), "nested in unit"); assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "IDLE", 0))); + assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "always_comb", 2)), "not a symbol"); + + let pkg = buffer( + "package p;\n typedef struct { logic f; } s_t;\n localparam int W = 1;\nendpackage\n", + ); + assert!(!local(&pkg, PrepareRenameRequest::METHOD, &at(&pkg, "W =", 0)), "inside a package"); + assert!( + !local(&pkg, PrepareRenameRequest::METHOD, &at(&pkg, "f;", 0)), + "inside a typedef in package" + ); + + let iface = buffer("interface bus_if;\n logic v;\nendinterface\n"); + assert!( + !local(&iface, PrepareRenameRequest::METHOD, &at(&iface, "v;", 0)), + "inside an interface" + ); + + let cls = buffer("class c;\n int m;\nendclass\n"); + assert!(!local(&cls, PrepareRenameRequest::METHOD, &at(&cls, "m;", 0)), "inside a class"); + + let td = buffer("typedef struct { logic f; } top_t;\n"); + assert!(!local(&td, PrepareRenameRequest::METHOD, &at(&td, "f;", 0)), "inside a typedef"); + + let frag = buffer("initial begin\n logic frag_sig;\n frag_sig = 1;\nend\n"); + assert!( + local(&frag, PrepareRenameRequest::METHOD, &at(&frag, "frag_sig;", 0)), + "outside any unit" + ); } #[test] diff --git a/crates/lucisv_server/src/server/ahead.rs b/crates/lucisv_server/src/server/ahead.rs index 5063a5a..b4930c6 100644 --- a/crates/lucisv_server/src/server/ahead.rs +++ b/crates/lucisv_server/src/server/ahead.rs @@ -49,10 +49,27 @@ //! everything else being held in arrival order — so the widen stays the //! effect of one applied message and no notification overtakes an older one. +#[cfg(test)] +use std::cell::RefCell; use std::collections::HashSet; use std::error::Error; use lsp_server::{Message, Notification, Request, RequestId, Response}; + +#[cfg(test)] +thread_local! { + /// For each request answered ahead via [`Server::answered_ahead`], the + /// server's applied state-change counter at the moment the early answer was + /// produced. + static AHEAD_APPLIED: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Take the `(request_id, applied_changes)` log accumulated by +/// [`Server::answered_ahead`] on this thread. +#[cfg(test)] +pub(super) fn take_ahead_applied() -> Vec<(RequestId, usize)> { + AHEAD_APPLIED.with(|log| std::mem::take(&mut *log.borrow_mut())) +} use lsp_types::notification::{ Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, @@ -176,6 +193,7 @@ impl Server { } if !colours { self.flush_buffer(&uri); + self.sync_document_versions(); let doc = self.workspace.document(&uri)?; if !same_file::answered_by_the_buffer(doc, &request.method, &request.params) { return None; @@ -215,7 +233,12 @@ impl Server { return Ok(false); }; #[cfg(test)] - super::probe::went_ahead(&request.id); + { + let id = request.id.clone(); + let applied = self.applied_changes; + super::probe::went_ahead(&id); + AHEAD_APPLIED.with(|log| log.borrow_mut().push((id, applied))); + } self.connection.sender.send(Message::Response(response))?; Ok(true) } @@ -372,7 +395,11 @@ impl Server { let mut cancelled = cancelled_in(&arrived); let mut kept = Vec::new(); self.set_aside(&mut kept, arrived.into_iter(), &mut cancelled)?; - self.held.extend(kept); + if !self.after_scan.is_empty() && self.held.is_empty() { + self.after_scan.extend(kept); + } else { + self.held.extend(kept); + } Ok(()) } @@ -392,7 +419,12 @@ impl Server { fn nothing_unapplied_for(&self, uri: &Uri, ahead: &[Message]) -> bool { self.workspace.document(uri).is_some() && self.behind == 0 - && !self.held.iter().chain(ahead).any(|older| self.can_reach(older, uri)) + && !self + .held + .iter() + .chain(&self.after_scan) + .chain(ahead) + .any(|older| self.can_reach(older, uri)) } /// Whether applying `message` can change the `Document` of the buffer @@ -405,7 +437,7 @@ impl Server { /// touches a buffer (`Server::response`). A **notification** is read off /// [`REACH`]; one that should name a buffer and names none that parses is /// taken as naming this one. - fn can_reach(&self, message: &Message, uri: &Uri) -> bool { + pub(super) fn can_reach(&self, message: &Message, uri: &Uri) -> bool { let notification = match message { Message::Request(_) => return false, Message::Response(response) => { diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 3a31cd8..4b95823 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -169,6 +169,7 @@ impl Server { // burst is coalesced: the changes before this request all become one // `set_document` in `flush_dirty`. self.flush_dirty_traced(); + self.sync_document_versions(); self.answer_flushed(request) } @@ -393,7 +394,12 @@ impl Server { // gets the whole edit, exactly as before. actions.extend(match self.abilities.code_action_resolve { true => ports::offers(&self.workspace, &uri, p.range.start, offset), - false => ports::code_actions(&self.workspace, &uri, offset), + false => ports::code_actions_for( + &self.workspace, + &uri, + offset, + self.abilities.document_changes, + ), }); } // Organizing imports is filed under LSP's own @@ -431,7 +437,9 @@ impl Server { let organize = action.kind.as_ref() == Some(&imports::kind()); let resolved = match organize { true => imports::resolve(&self.workspace, action), - false => ports::resolve(&self.workspace, action), + false => { + ports::resolve_for(&self.workspace, action, self.abilities.document_changes) + } }; match resolved { Ok(resolved) => to_value(resolved), @@ -479,8 +487,14 @@ impl Server { // nothing at all otherwise: where a rename's selection, its // stages and its whole-file parses went (take 5 §P2a). let mut trace = None; - let outcome = - rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace); + let outcome = rename::rename_traced_for( + &self.workspace, + &uri, + offset, + &new_name, + self.abilities.document_changes, + &mut trace, + ); if let (true, Some(line)) = (self.verbose, trace) { self.timing(format!("rename trace {line}")); } @@ -536,7 +550,12 @@ impl Server { Err(message) => Err(Failure::Request(message)), }; } - match ports::execute(&self.workspace, &p.command, &p.arguments) { + match ports::execute_for( + &self.workspace, + &p.command, + &p.arguments, + self.abilities.document_changes, + ) { Ok((edit, warnings)) => { self.report_scope(warnings); self.deliver(&p.command, edit) diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index b37ce0f..4515572 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -135,6 +135,9 @@ pub struct ClientAbilities { /// which is what every client got before this was read /// (`docs/features/lazy-code-action/README.md`). pub code_action_resolve: bool, + /// Whether the client accepts versioned `documentChanges` inside a + /// `WorkspaceEdit` (`workspace.workspaceEdit.documentChanges`). + pub document_changes: bool, /// Whether the client can apply a `WorkspaceEdit` that creates a file — /// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations` /// list containing `create`. Only then does an extracted module get a @@ -272,6 +275,19 @@ pub struct Server { /// [`Server::must_wait`] — this is the order contract, not a queue of its /// own. held: Vec, + /// Workspace-wide mutating requests (and anything behind them) set aside + /// until the active scan completes cleanly rather than re-drained at each + /// single-file publish during `scanning`. + after_scan: Vec, + /// Latest LSP buffer versions announced by `didOpen` / `didChange`, kept + /// here so rebuilt `Document` instances (on dirty flush or large-file + /// reclassification) keep their client version. + versions: HashMap, + /// Test-only counter of state-changing notifications and configuration + /// responses applied by this server, used to pair each early answer with + /// the exact state in which it was computed. + #[cfg(test)] + pub(super) applied_changes: usize, /// How many notifications older than the message being handled are still /// unapplied in the bursts it is nested inside — the tail of a burst /// whose message started a scan, while that scan answers newer ones. One @@ -399,6 +415,15 @@ impl Server { } continue; } + // Workspace-wide mutating requests held until the scan finishes are + // released only here, outside every scan, once `held` is clear. + if !self.after_scan.is_empty() { + let batch = std::mem::take(&mut self.after_scan); + if self.process_batch(batch)? { + return Ok(()); + } + continue; + } // A connection entry whose grace ran out while messages kept // arriving is released here, not only when the wait below times // out (`docs/features/port-entry-grace/README.md`). @@ -416,6 +441,7 @@ impl Server { Ok(message) => message, Err(RecvTimeoutError::Timeout) => { self.flush_dirty(); + self.sync_document_versions(); self.release_port_entries(); continue; } @@ -447,6 +473,7 @@ impl Server { // so what is held from here goes in front of those and behind whatever // was already waiting when the burst began. let already_waiting = self.held.len(); + let already_after = self.after_scan.len(); // The `$/cancelRequest`s this burst has already carried, kept only // long enough to put them back if a request behind them has to wait. let mut consumed_cancels: Vec = Vec::new(); @@ -474,10 +501,14 @@ impl Server { } self.cancel_deferred(&message)?; self.say_held(&message); + let waits_for_scan = matches!( + &message, + Message::Request(request) if waits_for_whole_scan(&request.method) + ); let mut rest: Vec = std::mem::take(&mut consumed_cancels); rest.push(message); self.set_aside(&mut rest, messages, &mut cancelled)?; - self.hold(rest, already_waiting); + self.hold(rest, already_waiting, already_after, waits_for_scan); return Ok(false); } unapplied = unapplied.saturating_sub(usize::from(self.owes_a_state_change(&message))); @@ -516,7 +547,13 @@ impl Server { messages = self.answer_ahead_of(¬ification, messages, &mut cancelled)?; messages = self.apply_in_burst(notification, messages, &mut cancelled)?; } - Message::Response(response) => self.response(response), + Message::Response(response) => { + #[cfg(test)] + if self.is_configuration_response(&response) { + self.applied_changes += 1; + } + self.response(response); + } } } self.behind = outer; @@ -561,11 +598,43 @@ impl Server { /// front of what they cancel because `cancelled_in` runs again over the /// held batch; one naming nothing in it is dropped there, as it would /// have been here. - fn hold(&mut self, mut rest: Vec, already_waiting: usize) { + fn hold( + &mut self, + mut rest: Vec, + already_waiting: usize, + already_after: usize, + waits_for_scan: bool, + ) { + if !self.after_scan.is_empty() || (self.held.is_empty() && self.scanning && waits_for_scan) + { + rest.extend(self.after_scan.split_off(already_after)); + self.after_scan.extend(rest); + return; + } rest.extend(self.held.split_off(already_waiting)); self.held.extend(rest); } + /// Record the latest LSP version for `uri` and attach it to any currently + /// loaded `Document`. + pub(super) fn record_document_version(&mut self, uri: &Uri, version: i32) { + self.versions.insert(uri.clone(), version); + if let Some(doc) = self.workspace.document(uri) { + doc.set_version(Some(version)); + } + } + + /// Re-attach recorded LSP versions onto every loaded `Document` whose + /// revision was replaced (for example by dirty-buffer flushing or + /// large-file reclassification). + pub(super) fn sync_document_versions(&self) { + for (uri, &version) in &self.versions { + if let Some(doc) = self.workspace.document(uri) { + doc.set_version(Some(version)); + } + } + } + /// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]: /// take it out and answer it cancelled. A cancel naming anything else is /// left to the batch's own rule. @@ -624,10 +693,19 @@ impl Server { self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty() + || !self.after_scan.is_empty() || self.staging || self.head_owed } + /// Whether a request of `method` must wait right now: everything + /// [`Server::must_wait`] names, plus holding workspace-wide mutating + /// requests until an active startup scan finishes rather than running + /// against a partial index prefix (topo #53). + fn must_wait_for(&self, method: &str) -> bool { + self.must_wait() || (self.scanning && waits_for_whole_scan(method)) + } + /// Whether `message`, reaching `process_batch` right now, must be held /// instead of handled. /// @@ -667,25 +745,35 @@ impl Server { /// ended, or answered, in a state the client never had. fn must_hold(&self, message: &Message) -> bool { match message { - Message::Request(_) => self.must_wait(), - Message::Notification(_) if !changes_state(message) => !self.held.is_empty(), + Message::Request(request) => self.must_wait_for(&request.method), + Message::Notification(_) if !changes_state(message) => { + !self.held.is_empty() || !self.after_scan.is_empty() + } _ if self.owes_a_state_change(message) => { - self.behind > 0 || self.held.iter().any(|older| self.owes_a_state_change(older)) + self.behind > 0 + || self + .held + .iter() + .chain(&self.after_scan) + .any(|older| self.owes_a_state_change(older)) } _ => false, } } + /// Whether `response` answers a pending `workspace/configuration` pull. + pub(super) fn is_configuration_response(&self, response: &lsp_server::Response) -> bool { + matches!(self.pending.get(&response.id), Some(Pending::Configuration(_))) + } + /// Whether `message`, still unapplied, is a state change the messages /// behind it are owed: any notification but a cancel /// ([`changes_state`]), and the client's answer to a settings pull — /// the one response the server applies as it applies a notification /// (`configured` → `apply_settings`). What [`Server::behind`] counts. - fn owes_a_state_change(&self, message: &Message) -> bool { + pub(super) fn owes_a_state_change(&self, message: &Message) -> bool { match message { - Message::Response(response) => { - matches!(self.pending.get(&response.id), Some(Pending::Configuration(_))) - } + Message::Response(response) => self.is_configuration_response(response), _ => changes_state(message), } } @@ -723,4 +811,20 @@ impl Server { } } +/// Request methods that rewrite or validate across the whole workspace and must +/// therefore wait until an active startup scan finishes rather than running +/// against a partial index prefix. +fn waits_for_whole_scan(method: &str) -> bool { + use lsp_types::request::{ + CodeActionResolveRequest, ExecuteCommand, Rename, Request as _, WillRenameFiles, + }; + matches!( + method, + Rename::METHOD + | CodeActionResolveRequest::METHOD + | ExecuteCommand::METHOD + | WillRenameFiles::METHOD + ) +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 4b09101..a6c795e 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -42,6 +42,10 @@ impl Server { } fn handle_notification(&mut self, notification: Notification) { + #[cfg(test)] + { + self.applied_changes += 1; + } let method = notification.method.clone(); // A closing buffer's pending text is dropped *before* the flush, not // in the `didClose` arm below it: the flush would otherwise analyze @@ -65,6 +69,7 @@ impl Server { // thing being deferred. if method != DidChangeTextDocument::METHOD { self.flush_dirty(); + self.sync_document_versions(); } // A save of a buffer that was not dirty: nothing above said the full // list, so it is said here, under a new generation for a pulling @@ -98,6 +103,7 @@ impl Server { // rungs, which an open buffer cannot widen. let before = self.workspace.scope_dirs(); self.set_document(uri.clone(), p.text_document.text); + self.record_document_version(&uri, p.text_document.version); // Mid-scan, the work list is re-ordered round this buffer // once the batch carrying it is handled, and what is behind // it in that batch waits for the new order @@ -124,9 +130,11 @@ impl Server { // `set_document` — one reparse, one generation bump — when // the buffer is flushed; see `mark_dirty`. if p.content_changes.is_empty() { + self.record_document_version(&p.text_document.uri, p.text_document.version); return; } let uri = p.text_document.uri; + self.record_document_version(&uri, p.text_document.version); let (text, end) = { let base = self .dirty @@ -157,6 +165,7 @@ impl Server { let uri = p.text_document.uri.clone(); if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) { self.set_document(uri.clone(), text); + self.sync_document_versions(); self.publish(&uri); } } @@ -272,6 +281,7 @@ impl Server { DidCloseTextDocument::METHOD => { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; + self.versions.remove(&uri); self.config_warnings.remove(&uri); // The buffer's unanalyzed change is already gone — it was // dropped at the top of this function, ahead of the flush @@ -354,6 +364,7 @@ impl Server { // Before the rescan, so the index takes each buffer in the mode the // new threshold gives it. self.reclassify_large_buffers(threshold); + self.sync_document_versions(); if rescan { self.reindex(); } else if self.lint_selection() != linted { diff --git a/crates/lucisv_server/src/server/startup.rs b/crates/lucisv_server/src/server/startup.rs index a1e849b..07d0647 100644 --- a/crates/lucisv_server/src/server/startup.rs +++ b/crates/lucisv_server/src/server/startup.rs @@ -29,6 +29,7 @@ use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; use lsp_server::{Connection, Message}; +use lsp_types::notification::{DidChangeConfiguration, Notification as _}; use super::batch::{burst, forward}; use super::{ClientAbilities, Pending, Server}; @@ -172,6 +173,10 @@ impl Server { answering_a_rescan: false, stopped: false, held: Vec::new(), + after_scan: Vec::new(), + versions: HashMap::new(), + #[cfg(test)] + applied_changes: 0, behind: 0, settings_announced: None, deferred: Vec::new(), @@ -358,23 +363,36 @@ impl Server { /// requests included, keeps its place and its order. fn take_the_answer_out_of_held(&mut self) { let waiting = std::mem::take(&mut self.held); + let last_answer = waiting.iter().rposition(|message| { + matches!( + message, + Message::Response(response) if self.is_configuration_response(response) + ) + }); let mut answers = Vec::new(); - for message in waiting { + for (idx, message) in waiting.into_iter().enumerate() { match message { - Message::Response(response) - if matches!( - self.pending.get(&response.id), - Some(Pending::Configuration(_)) - ) => - { + Message::Response(response) if self.is_configuration_response(&response) => { answers.push(response); } + // Any configuration push sitting earlier in `held` than a + // pulled configuration response is older than the client state + // that pull observed; drain it so it cannot replay later and + // overwrite newer settings (topo #61). + Message::Notification(ref notification) + if last_answer.is_some_and(|last| idx < last) + && notification.method == DidChangeConfiguration::METHOD => {} kept => self.held.push(kept), } } for answer in answers { + #[cfg(test)] + { + self.applied_changes += 1; + } self.response(answer); } + self.sync_document_versions(); } } diff --git a/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs b/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs index 3116ea2..65816e2 100644 --- a/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs +++ b/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs @@ -33,7 +33,7 @@ use std::collections::HashMap; use lsp_types::notification::Cancel; -use super::super::probe; +use super::super::{ahead, dispatch, probe}; use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle}; use super::*; @@ -378,7 +378,7 @@ fn run(seed: u64, rounds: usize) -> Tally { let _ = heard.heard(); } } - let _ = (probe::take_counts(), probe::take_ahead()); + let _ = (probe::take_counts(), probe::take_ahead(), ahead::take_ahead_applied()); let mut tally = Tally::default(); for round in 0..rounds { let said = client.round(); @@ -388,37 +388,75 @@ fn run(seed: u64, rounds: usize) -> Tally { // The early server: the first burst to the loop, the rest wherever a // rescan's interleave points — or the wait after it — puts them. + let early_base = early.session.server.applied_changes; + let _ = ahead::take_ahead_applied(); let mut bursts: Vec> = said.iter().map(|b| early.wire(b)).collect(); let first = bursts.remove(0); probe::script(bursts); assert!(!early.session.batch(first), "no shutdown"); settle(&mut early.session); let ahead = probe::take_ahead(); + let ahead_applied: HashMap = + ahead::take_ahead_applied().into_iter().collect(); let early_answers = early.heard(); - // The reference: the same stream, one message at a time. A request - // the early server answered ahead is asked again after every later - // state change of the round: the states it may rightly have seen. - let mut gone_ahead: Vec<(RequestId, String, Value)> = Vec::new(); - let mut later: HashMap> = HashMap::new(); - for burst in &said { - for message in reference.wire(burst) { - let asked = match &message { - Message::Request(r) if ahead.contains(&r.id) => { - Some((r.id.clone(), r.method.clone(), r.params.clone())) - } - _ => None, - }; - let changes = !matches!(message, Message::Request(_)); - assert!(!reference.session.batch(vec![message]), "no shutdown"); - settle(&mut reference.session); - gone_ahead.extend(asked); - for (id, method, params) in gone_ahead.iter().filter(|_| changes) { - later.entry(id.clone()).or_default().push(reference.says(method, params)); + // The reference: the same stream, one message at a time. For every + // request the early server answered ahead, capture the reference + // server's answer at every applied state-change step 0..=total so we + // can check `e == reference_at[applied]` AND that no affecting earlier + // change was skipped (`applied >= must_have_applied`, topo #62). + let ref_messages: Vec = said.iter().flat_map(|b| reference.wire(b)).collect(); + let ahead_requests: Vec<(RequestId, String, Value)> = ref_messages + .iter() + .filter_map(|message| match message { + Message::Request(r) if ahead.contains(&r.id) => { + Some((r.id.clone(), r.method.clone(), r.params.clone())) + } + _ => None, + }) + .collect(); + let mut states: HashMap> = HashMap::new(); + for (id, method, params) in &ahead_requests { + states.entry(id.clone()).or_default().push(reference.says(method, params)); + } + let mut step = 0usize; + let mut prior_changes: Vec<(usize, Message, bool)> = Vec::new(); + let mut must_have_applied: HashMap = HashMap::new(); + for message in ref_messages { + let is_config_resp = matches!( + &message, + Message::Response(resp) if reference.session.server.is_configuration_response(resp) + ); + let changes = reference.session.server.owes_a_state_change(&message); + if let Message::Request(r) = &message { + if ahead.contains(&r.id) { + let uri = dispatch::document_uri(&r.params); + let required = prior_changes + .iter() + .rev() + .find(|(_, msg, is_cfg)| { + *is_cfg + || uri + .as_ref() + .is_none_or(|u| reference.session.server.can_reach(msg, u)) + }) + .map_or(0, |(at, _, _)| *at); + must_have_applied.insert(r.id.clone(), required); + } + } + if changes { + step += 1; + prior_changes.push((step, message.clone(), is_config_resp)); + } + assert!(!reference.session.batch(vec![message]), "no shutdown"); + settle(&mut reference.session); + if changes { + for (id, method, params) in &ahead_requests { + states.entry(id.clone()).or_default().push(reference.says(method, params)); } } } - let _ = probe::take_ahead(); + let _ = (probe::take_ahead(), ahead::take_ahead_applied()); let reference_answers = reference.heard(); for id in asked.iter().map(|id| RequestId::from(*id)) { @@ -429,15 +467,44 @@ fn run(seed: u64, rounds: usize) -> Tally { tally.asked += 1; if ahead.contains(&id) { tally.ahead += 1; - let (e, at_its_place) = (rendered(e), rendered(r)); - let after = later.remove(&id).unwrap_or_default(); - tally.later += usize::from(e != at_its_place); + let applied = ahead_applied + .get(&id) + .copied() + .and_then(|total| total.checked_sub(early_base)) + .unwrap_or_else(|| { + panic!( + "{}", + context(&format!("{id} went ahead without recorded applied count")) + ) + }); + let required = *must_have_applied.get(&id).expect("required step"); + let reference_at = states.get(&id).map(Vec::as_slice).unwrap_or(&[]); assert!( - e == at_its_place || after.contains(&e), + applied >= required, "{}", context(&format!( - "{id} went ahead with an answer the client's stream never gave it\n \ - early: {e}\n at its place: {at_its_place}\n later: {after:?}" + "{id} answered at applied={applied} ahead of reaching change {required}" + )) + ); + let Some(expected) = reference_at.get(applied) else { + panic!( + "{}", + context(&format!( + "{id} applied={applied} outside round states 0..{}", + reference_at.len() + )) + ); + }; + let (e, at_its_place) = (rendered(e), rendered(r)); + tally.later += usize::from(e != at_its_place); + assert_eq!( + e, + *expected, + "{}", + context(&format!( + "{id} went ahead at applied={applied} (required >= {required}) with \ + wrong state\n early: {e}\n expected: {expected}\n \ + at its place: {at_its_place}\n states: {reference_at:?}" )) ); } diff --git a/crates/lucisv_server/src/server/tests/fast_actions_differential.rs b/crates/lucisv_server/src/server/tests/fast_actions_differential.rs index e7d7d48..ffb7930 100644 --- a/crates/lucisv_server/src/server/tests/fast_actions_differential.rs +++ b/crates/lucisv_server/src/server/tests/fast_actions_differential.rs @@ -269,7 +269,9 @@ fn early_answers_equal_settled_over_the_locality_shapes() { let mut settled = Session::started(vec![tree.path.clone()], ClientAbilities::default(), listed); let mut early = early_session(&empty.path); let mut tally = Tally::default(); - for file in ["top.sv", "pkg.sv", "sub.sv", "cls.sv", "bus.sv", "dup_a.sv", "inc/defs.svh"] { + for file in + ["top.sv", "pkg.sv", "sub.sv", "cls.sv", "bus.sv", "dup_a.sv", "dup_b.sv", "inc/defs.svh"] + { let path = tree.path.join(file); let text = std::fs::read_to_string(&path).expect("fixture"); compare_file(&mut early, &mut settled, &path, &positions(&text, || true), &mut tally); diff --git a/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs b/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs index ea17235..29ffa9d 100644 --- a/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs +++ b/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs @@ -439,8 +439,11 @@ fn a_dirty_buffer_is_analyzed_for_it_under_the_settings_in_force() { #[test] fn what_staging_held_behind_a_push_is_not_released_ahead_of_it() { - // `[open, lens, push, hover]`, then the pull's answer: the settings have - // landed, but the hover is still behind a push nobody has applied. + // `[open, lens, answer, push, hover]`: the settings answer has landed, + // while the newer push and the hover behind it stay held (`push` *before* + // the pull answer is superseded on extraction per topo #61); + // `answer_held_ahead` must not release the hover ahead of the unapplied + // push. let tree = Tree::new("fa_pre_staged"); tree.write("a.sv", &wide("sig_a")); let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); @@ -448,9 +451,9 @@ fn what_staging_held_behind_a_push_is_not_released_ahead_of_it() { let queued = vec![ opened(&uri, &wide("sig_a")), lens(1, &uri), + settings_answer(&pull, threshold(0)), push(threshold(1000)), hover(2, &uri), - settings_answer(&pull, threshold(0)), ]; let abilities = ClientAbilities { configuration: true, ..Default::default() }; let _ = probe::take_ahead(); diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index e677d48..e543df2 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -65,6 +65,7 @@ mod index; mod large_file; mod lint_snapshot; mod localized_reindex; +mod ordering_r1; mod ordering_random; mod progress; mod pull_diagnostics; diff --git a/crates/lucisv_server/src/server/tests/ordering_r1.rs b/crates/lucisv_server/src/server/tests/ordering_r1.rs new file mode 100644 index 0000000..b4f4b82 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/ordering_r1.rs @@ -0,0 +1,1247 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Regression tests for Round 1 ordering, versioned edits, and #53/#61 fixes. + +use serde_json::Value; + +use super::super::probe; +use super::scan::positions; +use super::scan_ordering::{ask, note, opened, settle}; +use super::*; +use crate::ports; + +fn mid_scan_workspace(name: &str, filler_count: usize) -> Tree { + let tree = Tree::new(name); + for i in 0..filler_count { + tree.package(&format!("b/p{i:03}.sv"), &format!("p{i}")); + } + tree +} + +fn rename_req(id: i32, uri: &Uri, line: u32, character: u32, new_name: &str) -> Message { + ask( + id, + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + "newName": new_name, + }), + ) +} + +fn hover_req(id: i32, uri: &Uri, line: u32, character: u32) -> Message { + ask( + id, + HoverRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + }), + ) +} + +fn response_of(messages: &[Message], id: i32) -> Option<&Response> { + messages.iter().find_map(|m| match m { + Message::Response(r) if r.id == RequestId::from(id) => Some(r), + _ => None, + }) +} + +fn edit_uris(edit: &Value) -> Vec { + let mut uris = Vec::new(); + if let Some(changes) = edit["changes"].as_object() { + uris.extend(changes.keys().cloned()); + } + if let Some(doc_changes) = edit["documentChanges"].as_array() { + for change in doc_changes { + if let Some(uri) = change["textDocument"]["uri"].as_str() { + uris.push(uri.to_string()); + } + } + } + uris.sort(); + uris +} + +#[test] +fn topo_53_rename_queued_at_startup_waits_for_full_scan_and_sees_cross_folder_duplicates() { + let tree = mid_scan_workspace("r1_53_dup", INTERLEAVE_ABOVE + 8); + tree.write("a/dup.sv", "module dup;\nendmodule\n"); + tree.write("z/dup.sv", "module dup;\nendmodule\n"); + let a_dup = path_to_uri(&tree.path.join("a/dup.sv")).expect("uri"); + + let _ = probe::take_counts(); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_dup, "module dup;\nendmodule\n"), rename_req(10, &a_dup, 0, 8, "dup_new")], + ); + + let counts = probe::take_counts(); + let during_scan = session.drain(); + let (ended, answered) = positions(&during_scan, 10); + assert!(ended.is_some(), "startup scan finished: {during_scan:#?}"); + assert!( + answered.is_none(), + "textDocument/rename must wait until startup scan finishes: {during_scan:#?}" + ); + assert!(counts.handed_back <= 1, "held rename must not spin across scan publishes: {counts:?}"); + assert_eq!(session.server.after_scan.len(), 1); + + settle(&mut session); + assert!(session.server.after_scan.is_empty()); + let settled = session.drain(); + let resp = response_of(&settled, 10).expect("rename answered after scan"); + let err = resp.response_result.as_ref().expect_err("duplicate across folders must refuse"); + assert!( + err.message.contains("declared in more than one indexed file"), + "expected cross-folder duplicate refusal, got: {}", + err.message + ); +} + +#[test] +fn topo_53_mid_scan_rename_waits_while_same_file_hover_answers_ahead() { + let tree = mid_scan_workspace("r1_53_late", INTERLEAVE_ABOVE + 8); + let sub_text = "module sub (input logic clk);\nendmodule\n"; + let late_text = "module late_top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + tree.write("a/sub.sv", sub_text); + tree.write("z/late_top.sv", late_text); + let a_sub = path_to_uri(&tree.path.join("a/sub.sv")).expect("uri"); + let z_late = path_to_uri(&tree.path.join("z/late_top.sv")).expect("uri"); + let clk_col = sub_text.find("clk").expect("clk") as u32; + + let _ = probe::take_counts(); + probe::script(vec![vec![ + hover_req(8, &a_sub, 0, clk_col), + rename_req(9, &a_sub, 0, clk_col, "clk_r"), + hover_req(10, &a_sub, 0, clk_col), + ]]); + + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_sub, sub_text)], + ); + let counts = probe::take_counts(); + let during_scan = session.drain(); + assert!(probe::unarrived().is_empty(), "mid-scan burst must be consumed"); + + let (ended, ans8) = positions(&during_scan, 8); + let (_, ans9) = positions(&during_scan, 9); + let (_, ans10) = positions(&during_scan, 10); + let ended = ended.expect("scan ended"); + assert!(ans8.is_some_and(|i| i < ended), "same-file hover 8 goes ahead: {during_scan:#?}"); + assert!( + ans10.is_some_and(|i| i < ended), + "same-file hover 10 behind rename goes ahead: {during_scan:#?}" + ); + assert!(ans9.is_none(), "rename must wait for scan completion: {during_scan:#?}"); + assert!(counts.handed_back <= 1, "rename must not spin in held: {counts:?}"); + + settle(&mut session); + let after = session.drain(); + let rename_resp = response_of(&after, 9).expect("rename answered after scan"); + let value = rename_resp.response_result.as_ref().expect("rename edit"); + let mut expected = vec![a_sub.to_string(), z_late.to_string()]; + expected.sort(); + assert_eq!(edit_uris(value), expected, "rename must reach z/late_top.sv: {value:#?}"); +} + +#[test] +fn topo_53_resolve_execute_command_and_will_rename_wait_for_whole_scan() { + let tree = mid_scan_workspace("r1_53_others", INTERLEAVE_ABOVE + 8); + let sub_text = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + let late_top = + "module late_top;\n `include \"../a/defs.svh\"\n sub u_sub (.clk(1'b0));\nendmodule\n"; + tree.write("a/defs.svh", "`define W 8\n"); + tree.write("a/sub.sv", sub_text); + tree.write("z/late_top.sv", late_top); + let a_sub = path_to_uri(&tree.path.join("a/sub.sv")).expect("uri"); + let z_late = path_to_uri(&tree.path.join("z/late_top.sv")).expect("uri"); + let a_defs = path_to_uri(&tree.path.join("a/defs.svh")).expect("uri"); + let new_defs = path_to_uri(&tree.path.join("a/widths.svh")).expect("uri"); + + let offer_data = serde_json::json!({ + "uri": a_sub, + "position": { "line": 1, "character": 14 }, + "title": "lucisv: remove port `clk`", + }); + let resolve_req = ask( + 11, + CodeActionResolveRequest::METHOD, + serde_json::json!({ + "title": "lucisv: remove port `clk` (updates 0 instantiations)", + "kind": ports::REFACTOR_PORTS, + "data": offer_data, + }), + ); + let exec_req = ask( + 12, + ExecuteCommand::METHOD, + serde_json::json!({ + "command": ports::ADD_PORT, + "arguments": [a_sub, "sub", "input logic en"], + }), + ); + let will_rename_req = ask( + 13, + WillRenameFiles::METHOD, + serde_json::json!({ + "files": [{ "oldUri": a_defs, "newUri": new_defs }], + }), + ); + + let _ = probe::take_counts(); + probe::script(vec![vec![resolve_req, exec_req, will_rename_req]]); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_sub, sub_text)], + ); + let counts = probe::take_counts(); + let during_scan = session.drain(); + assert!(probe::unarrived().is_empty()); + for id in [11, 12, 13] { + assert!( + positions(&during_scan, id).1.is_none(), + "request {id} must wait until startup scan completes" + ); + } + assert_eq!(session.server.after_scan.len(), 3); + assert!(counts.handed_back <= 1, "mutators must not spin: {counts:?}"); + + settle(&mut session); + assert!(session.server.after_scan.is_empty()); + let settled = session.drain(); + + let resolved = response_of(&settled, 11) + .expect("resolve answered") + .response_result + .as_ref() + .expect("resolved action"); + let mut sub_and_top = vec![a_sub.to_string(), z_late.to_string()]; + sub_and_top.sort(); + assert_eq!(edit_uris(&resolved["edit"]), sub_and_top, "resolve sees late_top: {resolved:#?}"); + + let exec_edit = response_of(&settled, 12) + .expect("executeCommand answered") + .response_result + .as_ref() + .expect("command edit"); + assert_eq!(edit_uris(exec_edit), sub_and_top, "execute sees late_top: {exec_edit:#?}"); + + let rename_files_edit = response_of(&settled, 13) + .expect("willRenameFiles answered") + .response_result + .as_ref() + .expect("willRename edit"); + assert_eq!( + edit_uris(rename_files_edit), + vec![z_late.to_string()], + "willRenameFiles sees late_top include: {rename_files_edit:#?}" + ); +} + +#[test] +fn topo_52_session_tracks_versions_and_emits_versioned_document_changes() { + let tree = Tree::new("r1_52_versions"); + let sub_text = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + let top_text = "module top;\n sub u_sub (.clk(1'b0), .rst(1'b0));\nendmodule\n"; + tree.write("sub.sv", sub_text); + tree.write("top.sv", top_text); + let sub_path = tree.path.join("sub.sv"); + let top_path = tree.path.join("top.sv"); + let sub_uri = path_to_uri(&sub_path).expect("uri"); + let top_uri = path_to_uri(&top_path).expect("uri"); + + let abilities = + ClientAbilities { document_changes: true, code_action_resolve: true, ..Default::default() }; + let mut versioned = Session::started(vec![tree.path.clone()], abilities, wide_ish()); + // Open `top.sv` at version 1; leave `sub.sv` closed so its version is `None`. + versioned.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": top_uri, "languageId": "systemverilog", "version": 1, "text": top_text, + } + }), + ); + // Coalesced `didChange` burst ending at version 3. + let edited_top = "module top;\n logic en;\n sub u_sub (.clk(1'b0), .rst(1'b0));\nendmodule\n"; + versioned.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri, "version": 2 }, + "contentChanges": [{ "text": top_text }], + }), + ); + versioned.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri, "version": 3 }, + "contentChanges": [{ "text": edited_top }], + }), + ); + + let rename_edit = versioned.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 2, "character": 14 }, + "newName": "clk_v", + }), + ); + assert!(rename_edit["changes"].is_null(), "{rename_edit:#?}"); + let docs = rename_edit["documentChanges"].as_array().expect("documentChanges array"); + let mut expected = vec![ + serde_json::json!({ "uri": sub_uri, "version": Value::Null }), + serde_json::json!({ "uri": top_uri, "version": 3 }), + ]; + expected.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got: Vec = docs.iter().map(|d| d["textDocument"].clone()).collect(); + assert_eq!(got, expected, "mixed open/closed versions: {rename_edit:#?}"); + + // Open `sub.sv` at version 5 and verify version survives large-file reclassification. + versioned.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": sub_uri, "languageId": "systemverilog", "version": 5, "text": sub_text, + } + }), + ); + versioned.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 1 } } } }), + ); + versioned.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 4_194_304 } } } }), + ); + + let cmd_edit = versioned.result( + ExecuteCommand::METHOD, + serde_json::json!({ + "command": ports::ADD_PORT, + "arguments": [top_uri, "sub", "input logic en"], + }), + ); + let mut both_open = vec![ + serde_json::json!({ "uri": sub_uri, "version": 5 }), + serde_json::json!({ "uri": top_uri, "version": 3 }), + ]; + both_open.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let cmd_ids: Vec = cmd_edit["documentChanges"] + .as_array() + .expect("documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(cmd_ids, both_open, "executeCommand versions preserved: {cmd_edit:#?}"); + + let resolved = versioned.result( + CodeActionResolveRequest::METHOD, + serde_json::json!({ + "title": "lucisv: remove port `clk` (updates 1 instantiation)", + "kind": ports::REFACTOR_PORTS, + "data": { + "uri": sub_uri, + "position": { "line": 1, "character": 14 }, + "title": "lucisv: remove port `clk`", + }, + }), + ); + let resolved_ids: Vec = resolved["edit"]["documentChanges"] + .as_array() + .expect("resolved documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(resolved_ids, both_open, "codeAction/resolve versions: {resolved:#?}"); + + // Closing removes old version; reopening at version 15 updates it. + versioned.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": sub_uri } }), + ); + versioned.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": sub_uri, "languageId": "systemverilog", "version": 15, "text": sub_text, + } + }), + ); + let reopened = versioned.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 2, "character": 14 }, + "newName": "clk_v2", + }), + ); + let mut expected_reopened = vec![ + serde_json::json!({ "uri": sub_uri, "version": 15 }), + serde_json::json!({ "uri": top_uri, "version": 3 }), + ]; + expected_reopened.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got_reopened: Vec = reopened["documentChanges"] + .as_array() + .expect("documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(got_reopened, expected_reopened); + + // Without `documentChanges` capability, the server falls back to `changes`. + let mut plain = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), wide_ish()); + plain.open(&top_path, top_text); + let plain_edit = plain.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 1, "character": 14 }, + "newName": "clk_plain", + }), + ); + assert!(plain_edit["changes"].is_object()); + assert!(plain_edit["documentChanges"].is_null()); +} + +#[test] +fn topo_61_staging_drains_older_configuration_push_before_applying_pull_answer() { + let tree = Tree::new("r1_61_drain"); + let small_text = + format!("module qa_61;\n logic sig_a;\nendmodule\n{}", "// pad pad pad\n".repeat(30)); + tree.write("a.sv", &small_text); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + + let stale_push = note( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 0 } } } + }), + ); + let pull_answer = Message::Response(Response::new_ok( + RequestId::from("lucisv-0".to_string()), + serde_json::json!([{ + "index": { "scope": "workspace" }, + "largeFile": { "threshold": 4_194_304 }, + }]), + )); + let lens = + ask(1, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + let queued = vec![opened(&uri, &small_text), lens, stale_push, pull_answer]; + let abilities = ClientAbilities { configuration: true, ..Default::default() }; + + let mut session = + Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued); + settle(&mut session); + assert_eq!( + session.server.workspace.client_settings().large_file_threshold, + 4_194_304, + "stale DidChangeConfiguration before the pull answer must be drained rather than replayed" + ); + let hover = session.result( + HoverRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 10 }, + }), + ); + assert_ne!(hover, Value::Null, "buffer must stay analyzed under the 4 MiB pulled threshold"); +} + +#[test] +fn topo_61_staging_preserves_configuration_push_newer_than_pull_answer() { + let tree = Tree::new("r1_61_newer"); + let small_text = "module qa_61_newer;\n logic sig_a;\nendmodule\n"; + tree.write("a.sv", small_text); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + + let newer_push = note( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 0 } } } + }), + ); + let pull_answer = Message::Response(Response::new_ok( + RequestId::from("lucisv-0".to_string()), + serde_json::json!([{ + "index": { "scope": "workspace" }, + "largeFile": { "threshold": 4_194_304 }, + }]), + )); + let lens = + ask(1, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + let queued = vec![opened(&uri, small_text), lens, pull_answer, newer_push]; + let abilities = ClientAbilities { configuration: true, ..Default::default() }; + + let mut session = + Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued); + settle(&mut session); + assert_eq!( + session.server.workspace.client_settings().large_file_threshold, + 0, + "DidChangeConfiguration arriving after the pull answer must still apply" + ); +} + +#[test] +fn qa_topo_53_cancel_in_later_burst_cancels_rename_in_after_scan() { + let tree = mid_scan_workspace("qa_53_cancel_later", INTERLEAVE_ABOVE + 8); + let sub_text = "module sub (input logic clk);\nendmodule\n"; + tree.write("a/sub.sv", sub_text); + let a_sub = path_to_uri(&tree.path.join("a/sub.sv")).expect("uri"); + let clk_col = sub_text.find("clk").expect("clk") as u32; + + let cancel = note(lsp_types::notification::Cancel::METHOD, serde_json::json!({ "id": 21 })); + probe::script(vec![ + Vec::new(), + Vec::new(), + vec![rename_req(21, &a_sub, 0, clk_col, "clk_c")], + vec![cancel], + ]); + + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_sub, sub_text)], + ); + let during = session.drain(); + assert!(positions(&during, 21).1.is_none(), "rename waited for scan end"); + assert_eq!(session.server.after_scan.len(), 2, "rename + cancel held in after_scan"); + + settle(&mut session); + assert!(session.server.after_scan.is_empty()); + let settled = session.drain(); + let resp = response_of(&settled, 21).expect("cancelled response after scan"); + let err = resp.response_result.as_ref().expect_err("expected RequestCanceled"); + assert_eq!(err.code, lsp_server::ErrorCode::RequestCanceled as i32); +} + +#[test] +fn qa_topo_53_cancel_same_burst_while_head_owed_transitions_held_to_after_scan() { + let tree = mid_scan_workspace("qa_53_cancel_head", INTERLEAVE_ABOVE + 8); + let sub_text = "module sub (input logic clk);\nendmodule\n"; + tree.write("a/sub.sv", sub_text); + let a_sub = path_to_uri(&tree.path.join("a/sub.sv")).expect("uri"); + let clk_col = sub_text.find("clk").expect("clk") as u32; + let cancel = note(lsp_types::notification::Cancel::METHOD, serde_json::json!({ "id": 31 })); + + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_sub, sub_text), rename_req(31, &a_sub, 0, clk_col, "clk_c"), cancel], + ); + let during = session.drain(); + assert!(positions(&during, 31).1.is_none()); + settle(&mut session); + let settled = session.drain(); + let resp = response_of(&settled, 31).expect("cancelled response"); + let err = resp.response_result.as_ref().expect_err("expected RequestCanceled"); + assert_eq!(err.code, lsp_server::ErrorCode::RequestCanceled as i32); +} + +#[test] +fn qa_topo_53_incremental_did_changes_and_rescan_wanted_preserve_order_across_after_scan() { + let tree = mid_scan_workspace("qa_53_incr_order", INTERLEAVE_ABOVE + 8); + let sub_text = "module sub (\n input logic clk\n);\nendmodule\n"; + let late_text = "module late_top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + tree.write("a/sub.sv", sub_text); + tree.write("z/late_top.sv", late_text); + let a_sub = path_to_uri(&tree.path.join("a/sub.sv")).expect("uri"); + let z_late = path_to_uri(&tree.path.join("z/late_top.sv")).expect("uri"); + + let incr1 = note( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_sub, "version": 2 }, + "contentChanges": [{ + "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }, + "text": " // edit1\n" + }], + }), + ); + let incr2 = note( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_sub, "version": 3 }, + "contentChanges": [{ + "range": { "start": { "line": 2, "character": 0 }, "end": { "line": 2, "character": 0 } }, + "text": " // edit2\n" + }], + }), + ); + // Add a second late file mid-scan via didSave (rescan_wanted = true). + let extra_path = tree.path.join("z/extra.sv"); + let extra_uri = path_to_uri(&extra_path).expect("uri"); + let extra_text = "module extra;\n sub u_extra (.clk(1'b0));\nendmodule\n"; + std::fs::write(&extra_path, extra_text).expect("write extra"); + let save_extra = note( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": extra_uri } }), + ); + + // Put `save_extra` mid-scan (sets `rescan_wanted = true`), then `[rename, incr1]`, then `incr2`. + probe::script(vec![ + Vec::new(), + Vec::new(), + vec![save_extra], + vec![rename_req(41, &a_sub, 1, 14, "clk_r"), incr1], + vec![incr2], + ]); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a_sub, sub_text)], + ); + let during = session.drain(); + // Both scans finished before `after_scan` drains. + let end_count = during + .iter() + .filter(|m| { + matches!(m, Message::Notification(n) if n.method == Progress::METHOD && n.params["value"]["kind"] == "end") + }) + .count(); + assert_eq!(end_count, 2, "startup scan + follow-up rescan both completed: {during:#?}"); + assert!(positions(&during, 41).1.is_none()); + + settle(&mut session); + let expected_text = "module sub (\n // edit1\n // edit2\n input logic clk\n);\nendmodule\n"; + assert_eq!(buffer(&session, &a_sub), expected_text); + let settled = session.drain(); + let resp = response_of(&settled, 41).expect("rename answered after both scans"); + let value = resp.response_result.as_ref().expect("rename edit"); + let mut expected_uris = vec![a_sub.to_string(), extra_uri.to_string(), z_late.to_string()]; + expected_uris.sort(); + assert_eq!(edit_uris(value), expected_uris); +} + +#[test] +fn qa_topo_52_full_version_lifecycle_open_change_save_empty_change_rename_and_overlay() { + let tree = Tree::new("qa_52_lifecycle"); + let sub_text = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + let top_text = "module top;\n sub u_sub (.clk(1'b0), .rst(1'b0));\nendmodule\n"; + tree.write("sub.sv", sub_text); + tree.write("top.sv", top_text); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + let top_uri = path_to_uri(&tree.path.join("top.sv")).expect("uri"); + + let abilities = ClientAbilities { + document_changes: true, + apply_edit: true, + code_action_resolve: false, + ..Default::default() + }; + let mut s = Session::started(vec![tree.path.clone()], abilities, wide_ish()); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri, "languageId": "systemverilog", "version": 1, "text": top_text } + }), + ); + let edited = "module top;\n logic en;\n sub u_sub (.clk(1'b0), .rst(1'b0));\nendmodule\n"; + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri, "version": 2 }, + "contentChanges": [{ "text": edited }], + }), + ); + // didSave without text (`includeText: false` default) -> flushes dirty buffer. + s.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": top_uri } }), + ); + // Empty contentChanges at version 3. + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri, "version": 3 }, + "contentChanges": [], + }), + ); + // Refresh overlay via watched file change. + tree.write("other.sv", "module other;\nendmodule\n"); + s.watched(&[tree.path.join("other.sv")]); + assert_eq!(s.server.workspace.document(&top_uri).expect("doc").version(), Some(3)); + + let rename_edit = s.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 2, "character": 14 }, + "newName": "clk_3", + }), + ); + let docs = rename_edit["documentChanges"].as_array().expect("documentChanges"); + let mut expected = vec![ + serde_json::json!({ "uri": sub_uri, "version": Value::Null }), + serde_json::json!({ "uri": top_uri, "version": 3 }), + ]; + expected.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got: Vec = docs.iter().map(|d| d["textDocument"].clone()).collect(); + assert_eq!(got, expected); + + // Eager codeAction (code_action_resolve = false) & executeCommand (apply_edit = true). + // Open `sub.sv` at version 4 as well; request port action on `sub.sv` line 1 char 14 (`clk`). + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": sub_uri, "languageId": "systemverilog", "version": 4, "text": sub_text } + }), + ); + let _ = s.drain(); + let actions = s.result( + CodeActionRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": sub_uri }, + "range": { "start": { "line": 1, "character": 14 }, "end": { "line": 1, "character": 14 } }, + "context": { "diagnostics": [] }, + }), + ); + let port_action = actions + .as_array() + .expect("actions") + .iter() + .find(|a| a["kind"] == ports::REFACTOR_PORTS) + .expect("eager port action"); + assert!(port_action["edit"]["documentChanges"].is_array()); + assert!(port_action["edit"]["changes"].is_null()); + let mut both = vec![ + serde_json::json!({ "uri": sub_uri, "version": 4 }), + serde_json::json!({ "uri": top_uri, "version": 3 }), + ]; + both.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let action_docs: Vec = port_action["edit"]["documentChanges"] + .as_array() + .expect("action documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(action_docs, both); + + let cmd_res = s.result( + ExecuteCommand::METHOD, + serde_json::json!({ + "command": ports::ADD_PORT, + "arguments": [top_uri, "sub", "input logic en"], + }), + ); + assert_eq!(cmd_res, Value::Null, "apply_edit=true delivers via workspace/applyEdit"); + let reqs = s.requests(); + let apply = + reqs.iter().find(|(m, _)| m == ApplyWorkspaceEdit::METHOD).expect("applyEdit request"); + let apply_docs: Vec = apply.1["edit"]["documentChanges"] + .as_array() + .expect("applyEdit documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(apply_docs, both); + + // Closing `sub.sv` without reopening drops its recorded version back to `None`. + s.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": sub_uri } }), + ); + let after_close = s.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 2, "character": 14 }, + "newName": "clk_4", + }), + ); + let closed_docs: Vec = after_close["documentChanges"] + .as_array() + .expect("documentChanges after close") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(closed_docs, expected); +} + +#[test] +fn qa_topo_61_attack_burst_didopen_push_a_hover_answer_b_push_c() { + for with_lens in [false, true] { + let tree = Tree::new(if with_lens { "qa_61_lens" } else { "qa_61_nolens" }); + let text = + format!("module qa_61_atk;\n logic sig_a;\nendmodule\n{}", "// pad pad\n".repeat(30)); + tree.write("a.sv", &text); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + + let push_a = note( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 0 } } } + }), + ); + let answer_b = Message::Response(Response::new_ok( + RequestId::from("lucisv-0".to_string()), + serde_json::json!([{ + "index": { "scope": "workspace" }, + "largeFile": { "threshold": 100 }, + }]), + )); + let push_c = note( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 4_194_304 } } } + }), + ); + let hover_req = hover_req(77, &uri, 1, 10); + let mut queued = vec![opened(&uri, &text)]; + if with_lens { + queued.push(ask( + 76, + CodeLensRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + )); + } + queued.extend([push_a, hover_req, answer_b, push_c]); + + let _ = probe::take_ahead(); + let _ = super::super::ahead::take_ahead_applied(); + let abilities = ClientAbilities { configuration: true, ..Default::default() }; + let mut session = + Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued); + // Before `push_c` runs from `held`, `B` beat `A` (threshold=100), so `hover` (before `push_c`) saw B (Null). + let at_staging_end = session.drain(); + let hover_resp = response_of(&at_staging_end, 77).expect("hover must not be dropped"); + assert_eq!( + hover_resp.response_result.as_ref().expect("ok"), + &Value::Null, + "B beats A for hover" + ); + assert_eq!( + session.server.workspace.client_settings().large_file_threshold, + 100, + "B beat A at end of staging" + ); + let expected_applied = if with_lens { 2 } else { 3 }; + assert_eq!( + session.server.applied_changes, expected_applied, + "applied_changes at end of staging" + ); + + settle(&mut session); + assert_eq!( + session.server.workspace.client_settings().large_file_threshold, + 4_194_304, + "C beats B after staging settles" + ); + assert_eq!( + session.server.applied_changes, + expected_applied + 1, + "applied_changes incremented for push(C)" + ); + let hover_after = session.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 1, "character": 10 } }), + ); + assert_ne!(hover_after, Value::Null, "buffer re-analyzed under C"); + } +} + +#[test] +fn qa_f1_non_canonical_client_uris_preserve_uri_and_version_in_edits() { + let tree = Tree::new("qa_f1_non_canonical"); + let sub_text = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + let top_text = "module top;\n sub u_sub (.clk(1'b0), .rst(1'b0));\nendmodule\n"; + let cafe_text = "module cafe_mod;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"; + let sub_path = tree.path.join("sub.sv"); + let top_path = tree.path.join("top.sv"); + let cafe_path = tree.path.join("café.sv"); + tree.write("sub.sv", sub_text); + tree.write("top.sv", top_text); + tree.write("café.sv", cafe_text); + + let sub_localhost_uri: Uri = path_to_uri(&sub_path) + .expect("sub uri") + .as_str() + .replacen("file:///", "file://localhost/", 1) + .parse() + .expect("localhost uri"); + let cafe_lower_uri: Uri = path_to_uri(&cafe_path) + .expect("cafe uri") + .as_str() + .replace("%C3%A9", "%c3%a9") + .parse() + .expect("lowercase percent uri"); + let top_uri = path_to_uri(&top_path).expect("top uri"); + + let abilities = + ClientAbilities { document_changes: true, code_action_resolve: true, ..Default::default() }; + let mut s = Session::started(vec![tree.path.clone()], abilities, wide_ish()); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": sub_localhost_uri, + "languageId": "systemverilog", + "version": 12, + "text": sub_text, + } + }), + ); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": top_uri, + "languageId": "systemverilog", + "version": 2, + "text": top_text, + } + }), + ); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": cafe_lower_uri, + "languageId": "systemverilog", + "version": 9, + "text": cafe_text, + } + }), + ); + + let cross_rename = s.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": top_uri }, + "position": { "line": 1, "character": 14 }, + "newName": "clk_v", + }), + ); + assert!(cross_rename["changes"].is_null(), "{cross_rename:#?}"); + let docs = cross_rename["documentChanges"].as_array().expect("documentChanges"); + let mut expected = vec![ + serde_json::json!({ "uri": sub_localhost_uri, "version": 12 }), + serde_json::json!({ "uri": top_uri, "version": 2 }), + ]; + expected.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got: Vec = docs.iter().map(|d| d["textDocument"].clone()).collect(); + assert_eq!(got, expected, "localhost URI must keep version 12: {cross_rename:#?}"); + + let cafe_rename = s.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": cafe_lower_uri }, + "position": { "line": 1, "character": 8 }, + "newName": "sig_v", + }), + ); + assert!(cafe_rename["changes"].is_null(), "{cafe_rename:#?}"); + let cafe_docs = cafe_rename["documentChanges"].as_array().expect("cafe documentChanges"); + assert_eq!(cafe_docs.len(), 1); + assert_eq!( + cafe_docs[0]["textDocument"], + serde_json::json!({ "uri": cafe_lower_uri, "version": 9 }), + ); +} + +#[test] +fn qa_f2_document_version_survives_flush_dirty_and_flush_buffer_immediately() { + let tree = Tree::new("qa_f2_flush_versions"); + let a_text = "module a;\n logic sig;\nendmodule\n"; + let b_text = "module b;\n logic other;\nendmodule\n"; + tree.write("a.sv", a_text); + tree.write("b.sv", b_text); + let a_uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let b_uri = path_to_uri(&tree.path.join("b.sv")).expect("uri"); + + let mut s = Session::started( + vec![tree.path.clone()], + ClientAbilities { document_changes: true, ..Default::default() }, + wide_ish(), + ); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "languageId": "systemverilog", "version": 1, "text": a_text } + }), + ); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": b_uri, "languageId": "systemverilog", "version": 1, "text": b_text } + }), + ); + + let edited_a = "module a;\n logic sig;\n logic extra;\nendmodule\n"; + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "version": 2 }, + "contentChanges": [{ "text": edited_a }], + }), + ); + // `didSave` without `text` flushes `a_uri` via `notification.rs` `flush_dirty`. + s.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": a_uri } })); + assert_eq!( + s.server.workspace.document(&a_uri).expect("doc").version(), + Some(2), + "version must remain Some(2) immediately after didSave(text: None)" + ); + + // `didClose` of another file also flushes dirty `a_uri` via `notification.rs` `flush_dirty`. + let edited_a2 = "module a;\n logic sig;\n logic extra2;\nendmodule\n"; + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "version": 3 }, + "contentChanges": [{ "text": edited_a2 }], + }), + ); + s.notify(DidCloseTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": b_uri } })); + assert_eq!( + s.server.workspace.document(&a_uri).expect("doc").version(), + Some(3), + "version must remain Some(3) immediately after didClose of another file" + ); + + // Mid-scan `same_file` request flushes `a_uri` via `ahead.rs` `flush_buffer`. + let edited_a3 = "module a;\n logic sig;\n logic extra3;\nendmodule\n"; + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "version": 4 }, + "contentChanges": [{ "text": edited_a3 }], + }), + ); + s.drain(); + s.server.scanning = true; + s.server.answering_a_rescan = true; + s.batch(vec![ + ask(50, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": a_uri } })), + hover_req(51, &a_uri, 2, 9), + ]); + s.server.scanning = false; + s.server.answering_a_rescan = false; + assert_eq!( + s.server.workspace.document(&a_uri).expect("doc").version(), + Some(4), + "version must remain Some(4) immediately after ahead.rs flush_buffer" + ); +} + +#[test] +fn qa_r2_f1_multifile_rename_open_noncanonical_and_closed_doc_with_and_without_document_changes() { + let tree = Tree::new("qa_r2_f1_multifile"); + let sub_text = "module sub (input logic clk);\nendmodule\n"; + let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + let cafe_text = "module cafe_mod (input logic sig);\nendmodule\n"; + let use_cafe_text = "module use_cafe;\n cafe_mod u_c (.sig(1'b0));\nendmodule\n"; + + let sub_path = tree.path.join("sub.sv"); + let top_path = tree.path.join("top.sv"); + let cafe_path = tree.path.join("café.sv"); + let use_cafe_path = tree.path.join("use_cafe.sv"); + tree.write("sub.sv", sub_text); + tree.write("top.sv", top_text); + tree.write("café.sv", cafe_text); + tree.write("use_cafe.sv", use_cafe_text); + + let sub_canonical = path_to_uri(&sub_path).expect("sub canonical"); + let sub_localhost: Uri = + sub_canonical.as_str().replacen("file:///", "file://localhost/", 1).parse().expect("uri"); + let cafe_canonical = path_to_uri(&cafe_path).expect("cafe canonical"); + let cafe_lower: Uri = cafe_canonical.as_str().replace("%C3%A9", "%c3%a9").parse().expect("uri"); + let top_uri = path_to_uri(&top_path).expect("top uri"); + let use_cafe_uri = path_to_uri(&use_cafe_path).expect("use_cafe uri"); + + assert_ne!(sub_localhost, sub_canonical); + assert_ne!(cafe_lower, cafe_canonical); + + // Case 1: `documentChanges: true` — 1 open non-canonical doc + 1 closed doc (`version: null`). + let abilities_dc = ClientAbilities { document_changes: true, ..Default::default() }; + let mut s_dc = Session::started(vec![tree.path.clone()], abilities_dc, wide_ish()); + for (uri, ver, text) in [(&sub_localhost, 12, sub_text), (&cafe_lower, 7, cafe_text)] { + s_dc.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": ver, "text": text, + } + }), + ); + } + + let rename_localhost = s_dc.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": sub_localhost }, + "position": { "line": 0, "character": 24 }, + "newName": "clk_r1", + }), + ); + assert!(rename_localhost["changes"].is_null()); + let mut expected_localhost = vec![ + serde_json::json!({ "uri": sub_localhost, "version": 12 }), + serde_json::json!({ "uri": top_uri, "version": Value::Null }), + ]; + expected_localhost.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got_localhost: Vec = rename_localhost["documentChanges"] + .as_array() + .expect("documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(got_localhost, expected_localhost); + + let rename_cafe = s_dc.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": cafe_lower }, + "position": { "line": 0, "character": 29 }, + "newName": "sig_r1", + }), + ); + assert!(rename_cafe["changes"].is_null()); + let mut expected_cafe = vec![ + serde_json::json!({ "uri": cafe_lower, "version": 7 }), + serde_json::json!({ "uri": use_cafe_uri, "version": Value::Null }), + ]; + expected_cafe.sort_by(|a, b| a["uri"].as_str().cmp(&b["uri"].as_str())); + let got_cafe: Vec = rename_cafe["documentChanges"] + .as_array() + .expect("documentChanges") + .iter() + .map(|d| d["textDocument"].clone()) + .collect(); + assert_eq!(got_cafe, expected_cafe); + + // Case 2: `documentChanges: false` — `changes` map keys must still use client's open URI. + let mut s_plain = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), wide_ish()); + for (uri, ver, text) in [(&sub_localhost, 12, sub_text), (&cafe_lower, 7, cafe_text)] { + s_plain.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": ver, "text": text, + } + }), + ); + } + + let plain_localhost = s_plain.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": sub_localhost }, + "position": { "line": 0, "character": 24 }, + "newName": "clk_r2", + }), + ); + assert!(plain_localhost["documentChanges"].is_null()); + let mut keys_localhost: Vec = + plain_localhost["changes"].as_object().expect("changes map").keys().cloned().collect(); + keys_localhost.sort(); + let mut want_keys_localhost = vec![sub_localhost.to_string(), top_uri.to_string()]; + want_keys_localhost.sort(); + assert_eq!(keys_localhost, want_keys_localhost); + + let plain_cafe = s_plain.result( + Rename::METHOD, + serde_json::json!({ + "textDocument": { "uri": cafe_lower }, + "position": { "line": 0, "character": 29 }, + "newName": "sig_r2", + }), + ); + assert!(plain_cafe["documentChanges"].is_null()); + let mut keys_cafe: Vec = + plain_cafe["changes"].as_object().expect("changes map").keys().cloned().collect(); + keys_cafe.sort(); + let mut want_keys_cafe = vec![cafe_lower.to_string(), use_cafe_uri.to_string()]; + want_keys_cafe.sort(); + assert_eq!(keys_cafe, want_keys_cafe); +} + +#[test] +fn qa_r2_f2_document_version_survives_reclassify_incremental_apply_changes_and_didsave_with_text() { + let tree = Tree::new("qa_r2_f2_rebuilds"); + let a_text = "module a;\n logic sig;\nendmodule\n"; + tree.write("a.sv", a_text); + let a_uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + + let mut s = Session::started( + vec![tree.path.clone()], + ClientAbilities { document_changes: true, ..Default::default() }, + wide_ish(), + ); + s.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "languageId": "systemverilog", "version": 1, "text": a_text } + }), + ); + + // Incremental `didChange` (`apply_changes_at`) followed by request flush (`answer_request`). + s.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": a_uri, "version": 5 }, + "contentChanges": [{ + "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }, + "text": " logic inc;\n", + }], + }), + ); + assert_eq!(s.server.workspace.document(&a_uri).expect("doc").version(), Some(5)); + let _ = s.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": a_uri }, "position": { "line": 1, "character": 9 } }), + ); + assert_eq!(s.server.workspace.document(&a_uri).expect("doc").version(), Some(5)); + + // `didSave` carrying differing `text` (`didSave(text: Some(...))`) preserves version immediately. + let saved_text = "module a;\n logic saved_only;\nendmodule\n"; + s.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": a_uri }, "text": saved_text }), + ); + assert_eq!(s.server.workspace.document(&a_uri).expect("doc").version(), Some(5)); + + // `reclassify_large_buffers` (normal -> large -> normal) preserves version immediately. + s.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 1 } } } + }), + ); + let large_doc = s.server.workspace.document(&a_uri).expect("doc"); + assert!(large_doc.large); + assert_eq!(large_doc.version(), Some(5)); + + s.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "scope": "workspace" }, "largeFile": { "threshold": 4_194_304 } } } + }), + ); + let normal_doc = s.server.workspace.document(&a_uri).expect("doc"); + assert!(!normal_doc.large); + assert_eq!(normal_doc.version(), Some(5)); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/server/tests/scan_ordering.rs b/crates/lucisv_server/src/server/tests/scan_ordering.rs index 69103c1..c9d5ceb 100644 --- a/crates/lucisv_server/src/server/tests/scan_ordering.rs +++ b/crates/lucisv_server/src/server/tests/scan_ordering.rs @@ -89,8 +89,12 @@ fn deliver(session: &mut Session, burst: Vec) { /// left, then take the scripted bursts that arrived after every scan ended. pub(super) fn settle(session: &mut Session) { loop { - while !session.server.held.is_empty() { - let held = std::mem::take(&mut session.server.held); + while !session.server.held.is_empty() || !session.server.after_scan.is_empty() { + let held = if !session.server.held.is_empty() { + std::mem::take(&mut session.server.held) + } else { + std::mem::take(&mut session.server.after_scan) + }; assert!(!session.batch(held), "no shutdown"); } let late = probe::unarrived(); diff --git a/crates/lucisv_server/src/state/document.rs b/crates/lucisv_server/src/state/document.rs index ba75c92..5e3a054 100644 --- a/crates/lucisv_server/src/state/document.rs +++ b/crates/lucisv_server/src/state/document.rs @@ -5,6 +5,7 @@ //! token in it by offset without sweeping the buffer. use std::path::PathBuf; +use std::sync::atomic::{AtomicI64, Ordering}; use vlog_parser::ast::SourceFile; use vlog_parser::defines::{collect_defines, DefineTable}; @@ -16,6 +17,10 @@ use vlog_semantic::{ use crate::convert::Positions; +/// Sentinel stored in [`Document::version`] before an LSP buffer version has +/// been attached; outside the `i32` range so every valid version fits. +const NO_VERSION: i64 = i64::MAX; + /// One open buffer, fully analyzed. Every field is derived from `text`, so a /// change throws the whole thing away and builds a new one. pub struct Document { @@ -55,6 +60,10 @@ pub struct Document { /// `Document` are the snapshot's own key, and the index moving is /// [`Document::refresh_overlay`], which clears it. pub lint: crate::lint_snapshot::Slot, + /// The latest LSP buffer version attached to this document, if any + /// (`NO_VERSION` when unversioned). Updated when notifications arrive or + /// rebuilt documents are installed so concurrent readers stay lock-free. + version: AtomicI64, } impl Document { @@ -92,6 +101,7 @@ impl Document { large, fences: std::sync::OnceLock::new(), lint: crate::lint_snapshot::Slot::new(), + version: AtomicI64::new(NO_VERSION), } } @@ -119,9 +129,23 @@ impl Document { large: true, fences: std::sync::OnceLock::new(), lint: crate::lint_snapshot::Slot::new(), + version: AtomicI64::new(NO_VERSION), } } + /// The LSP version last recorded for this buffer, or `None` for unversioned + /// workspace reads. + pub fn version(&self) -> Option { + let raw = self.version.load(Ordering::Relaxed); + (raw != NO_VERSION).then(|| i32::try_from(raw).ok()).flatten() + } + + /// Attach or clear the LSP buffer version for this document. + pub fn set_version(&self, version: Option) { + let raw = version.map_or(NO_VERSION, i64::from); + self.version.store(raw, Ordering::Relaxed); + } + /// This document's position converter. pub fn positions(&self) -> Positions<'_> { Positions::new(&self.text, &self.line_index) diff --git a/crates/vlog_refactor/src/extract/mod.rs b/crates/vlog_refactor/src/extract/mod.rs index fe7821d..c719ce0 100644 --- a/crates/vlog_refactor/src/extract/mod.rs +++ b/crates/vlog_refactor/src/extract/mod.rs @@ -205,15 +205,17 @@ impl Extraction { Crossing::read(text, &semantics, ®ion, &flow, &packages, created.is_some())?; // The new module, then the instantiation read back out of it. + let eol = line_ending(text); let body = format!("{}{}", region.indent, slice(text, region.span)); let module_text = render::new_module( new_name, &crossing.imports, &crossing.params, &crossing.ports, - &ensure_newline(&body), + &ensure_newline(&body, eol), + eol, ); - let instance = render::instantiation(new_name, &module_text, ®ion.indent)?; + let instance = render::instantiation(new_name, &module_text, ®ion.indent, eol)?; let mut edits: Vec<(usize, Vec)> = Vec::new(); // What the verifier is allowed to let travel, and between which bytes: @@ -238,7 +240,7 @@ impl Extraction { None => { let append = TextEdit { range: TextRange::empty(region.module_span.end), - new_text: format!("\n\n{module_text}"), + new_text: format!("{eol}{eol}{module_text}"), }; edits.push((here, vec![replace, append])); } @@ -313,10 +315,20 @@ fn slice(text: &str, span: TextRange) -> &str { text.get(span.start as usize..span.end as usize).unwrap_or("") } -fn ensure_newline(text: &str) -> String { - match text.ends_with('\n') { - true => text.to_string(), - false => format!("{text}\n"), +fn line_ending(text: &str) -> &'static str { + match text.contains("\r\n") { + true => "\r\n", + false => "\n", + } +} + +fn ensure_newline(text: &str, eol: &str) -> String { + if text.ends_with(eol) { + text.to_string() + } else if let Some(prefix) = text.strip_suffix('\n') { + format!("{prefix}{eol}") + } else { + format!("{text}{eol}") } } diff --git a/crates/vlog_refactor/src/extract/render.rs b/crates/vlog_refactor/src/extract/render.rs index e624fa1..874a747 100644 --- a/crates/vlog_refactor/src/extract/render.rs +++ b/crates/vlog_refactor/src/extract/render.rs @@ -281,10 +281,12 @@ pub(super) fn new_module( params: &[Param], ports: &[Port], body: &str, + eol: &str, ) -> String { let mut out = format!("module {name}"); for path in imports { - out.push_str("\n import "); + out.push_str(eol); + out.push_str(" import "); out.push_str(path); out.push(';'); } @@ -293,11 +295,12 @@ pub(super) fn new_module( // continuing with a space. let sep = match imports.is_empty() { true => " ", - false => "\n", + false => eol, }; if !params.is_empty() { out.push_str(sep); - out.push_str("#(\n"); + out.push_str("#("); + out.push_str(eol); for (i, param) in params.iter().enumerate() { out.push_str(" "); out.push_str(¶m.prefix); @@ -306,7 +309,10 @@ pub(super) fn new_module( out.push_str(" = "); out.push_str(¶m.default); } - out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" }); + if i + 1 < params.len() { + out.push(','); + } + out.push_str(eol); } out.push(')'); } @@ -317,25 +323,32 @@ pub(super) fn new_module( match ports.is_empty() { true => { out.push_str(sep); - out.push_str("();\n"); + out.push_str("();"); + out.push_str(eol); } false => { out.push_str(sep); - out.push_str("(\n"); + out.push('('); + out.push_str(eol); for (i, port) in ports.iter().enumerate() { out.push_str(" "); out.push_str(&port.prefix); out.push_str(&port.name); - out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" }); + if i + 1 < ports.len() { + out.push(','); + } + out.push_str(eol); } - out.push_str(");\n"); + out.push_str(");"); + out.push_str(eol); } } out.push_str(body); if !body.ends_with('\n') { - out.push('\n'); + out.push_str(eol); } - out.push_str("endmodule\n"); + out.push_str("endmodule"); + out.push_str(eol); out } @@ -345,7 +358,12 @@ pub(super) fn new_module( /// Every port connects to the signal of the same name — which is what the /// extraction just made true — and every parameter to the parameter of the /// same name. -pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result { +pub(super) fn instantiation( + name: &str, + module_text: &str, + indent: &str, + eol: &str, +) -> Result { let mut plan = instantiation_plan(name, module_text, None)?; for port in &mut plan.ports { port.auto_connect = true; @@ -353,10 +371,11 @@ pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Resu let params = plan.params.len(); let names: Vec = plan.params.iter().map(|param| param.name.clone()).collect(); let layout = Layout { base: indent.to_string(), step: " ".to_string() }; - Ok(plan.render_with(&layout, &mut |n, default| match n <= params { + let rendered = plan.render_with(&layout, &mut |n, default| match n <= params { true => names.get(n - 1).cloned().unwrap_or_default(), false => default.to_string(), - })) + }); + Ok(if eol == "\n" { rendered } else { rendered.replace('\n', eol) }) } // ---------------------------------------------------------------------- diff --git a/crates/vlog_refactor/src/ports/offer.rs b/crates/vlog_refactor/src/ports/offer.rs index ac92a00..56031a9 100644 --- a/crates/vlog_refactor/src/ports/offer.rs +++ b/crates/vlog_refactor/src/ports/offer.rs @@ -295,11 +295,11 @@ fn removal(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option body_uses_in(text, &analysis.semantics, module, port, &header), + Some(analysis) => body_uses_in(text, &analysis.semantics, module_range, port, &header), None => Vec::new(), }; if !used.is_empty() { @@ -206,23 +206,24 @@ pub(super) fn header_removal( Ok(header) } -/// The lines of the module's body that still name the port, ignoring the -/// declarations the removal is itself deleting. +/// The lines of the module (header defaults and body) that still name the +/// port, ignoring the declarations the removal is itself deleting. /// +/// `module_range` is the module item's full `module ... endmodule` span from +/// [`find_module`], so header port default expressions are checked even when +/// `module.items` is empty while sibling modules in the same file stay outside. /// `semantics` must be the analysis of `text` — [`Scope::analysis`]'s, or the /// open buffer's own, which is the same thing computed once instead of twice. pub(super) fn body_uses_in( text: &str, semantics: &vlog_semantic::Semantics, - module: &Module, + module_range: TextRange, port: &str, removed: &[TextEdit], ) -> Vec { let lines = LineIndex::new(text); let Some(symbol) = semantics.symbols().iter().position(|s| { - s.name == port - && s.kind == SymbolKind::Port - && module_span(module).contains(s.name_span.start) + s.name == port && s.kind == SymbolKind::Port && module_range.contains(s.name_span.start) }) else { return Vec::new(); }; @@ -230,6 +231,9 @@ pub(super) fn body_uses_in( let mut out: Vec = Vec::new(); for reference in semantics.references_of(id) { let span = reference.name_span; + if !module_range.contains(span.start) || span.end > module_range.end { + continue; + } if removed.iter().any(|e| e.range.start <= span.start && span.end <= e.range.end) { continue; } @@ -241,13 +245,6 @@ pub(super) fn body_uses_in( out } -/// The bytes a module covers, taken from its name and its last item — the -/// `Module` node carries no span of its own. -fn module_span(module: &Module) -> TextRange { - let end = module.items.last().map_or(module.name_span.end, |item| item.span.end); - TextRange::new(module.name_span.start, end.max(module.name_span.end)) -} - /// Delete the non-ANSI body declaration of a port: the whole item when it /// declares only this port, otherwise just its declarator. fn non_ansi_declaration_removal( diff --git a/crates/vlog_refactor/src/rename/carry.rs b/crates/vlog_refactor/src/rename/carry.rs index ad43d46..77536e7 100644 --- a/crates/vlog_refactor/src/rename/carry.rs +++ b/crates/vlog_refactor/src/rename/carry.rs @@ -18,7 +18,7 @@ //! is news (as a `bind` statement's would be), and a file invoking it is home //! (K2). -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet}; use super::contains_word; use super::home::{macro_names, skip_string}; @@ -34,28 +34,24 @@ pub(crate) struct MacroDef { } /// Macro name → every `` `define`` of it in the set. -pub(crate) type Defs = HashMap>; +pub(crate) type Defs = BTreeMap>; /// Which arguments of which macros are carried, for one declaring unit. #[derive(Default)] pub(super) struct Carriers { /// Macro → per formal position, whether it is carried; `None` when every /// position is (a binder). - formals: HashMap>>, + formals: BTreeMap>>, /// The macros that expand to a `bind` into the unit. - binders: HashSet, + binders: BTreeSet, } impl Carriers { /// The carried arguments of every macro in `defs`, for members of `unit`. pub(super) fn of(defs: &Defs, unit: &str) -> Carriers { - let mut walk = Walk { defs, unit, binder: HashMap::new(), formals: HashMap::new() }; - let names: Vec<&String> = defs.keys().collect(); - for name in names { - walk.formals_of(name, &mut HashSet::new()); - } - let binders = walk.binder.into_iter().filter(|(_, b)| *b).map(|(n, _)| n).collect(); - Carriers { formals: walk.formals, binders } + let binders = find_binders(defs, unit); + let formals = compute_formals(defs, &binders); + Carriers { formals, binders } } /// Whether argument `position` (0-based) of an invocation of @@ -78,95 +74,126 @@ impl Carriers { } } -/// The memoized recursion over the set's macros. -struct Walk<'a> { - defs: &'a Defs, - unit: &'a str, - binder: HashMap, - formals: HashMap>>, +/// Every macro in `defs` that expands to a `bind` into `unit` directly or +/// through macros its body invokes (least fixed point, order-independent). +fn find_binders(defs: &Defs, unit: &str) -> BTreeSet { + let mut binders = BTreeSet::new(); + let mut edges: BTreeMap<&str, BTreeSet> = BTreeMap::new(); + for (name, list) in defs { + if list.iter().any(|d| body_binds(&d.body, unit)) { + binders.insert(name.clone()); + } else { + let calls: BTreeSet = list.iter().flat_map(|d| macro_names(&d.body)).collect(); + edges.insert(name.as_str(), calls); + } + } + loop { + let mut changed = false; + for (name, calls) in &edges { + if binders.contains(*name) { + continue; + } + if calls.iter().any(|callee| binders.contains(callee.as_str())) { + binders.insert((*name).to_string()); + changed = true; + } + } + if !changed { + return binders; + } + } } -impl Walk<'_> { - /// Whether `name` expands to a `bind` into the unit, directly or through - /// a macro its body invokes. A cycle (an illegal macro) answers `false`. - fn is_binder(&mut self, name: &str, active: &mut HashSet) -> bool { - if let Some(&known) = self.binder.get(name) { - return known; +/// Per-macro formal carry bitvectors via monotonic greatest fixed point: +/// every position starts `true` (cycles stay `true` = doubt) and lowers to +/// `false` once none of its forwarding paths remain carried. +fn compute_formals(defs: &Defs, binders: &BTreeSet) -> BTreeMap>> { + let mut direct: BTreeMap> = BTreeMap::new(); + let mut deps: BTreeMap>> = BTreeMap::new(); + let mut state: BTreeMap> = BTreeMap::new(); + + for (name, list) in defs { + if binders.contains(name) { + continue; } - let Some(defs) = self.defs.get(name) else { return false }; - if !active.insert(name.to_string()) { - return false; - } - let mut found = defs.iter().any(|d| body_binds(&d.body, self.unit)); - if !found { - let inner: Vec = defs.iter().flat_map(|d| macro_names(&d.body)).collect(); - found = inner.iter().any(|n| self.is_binder(n, active)); - } - active.remove(name); - self.binder.insert(name.to_string(), found); - found + let arity = list.iter().map(|d| d.params.len()).max().unwrap_or(0); + state.insert(name.clone(), vec![true; arity]); + direct.insert(name.clone(), vec![false; arity]); + deps.insert(name.clone(), vec![Vec::new(); arity]); } - /// The carried formal positions of `name`; `None` when every position is - /// (a binder, an unknown macro, or a cycle — nothing shows otherwise). - fn formals_of(&mut self, name: &str, active: &mut HashSet) -> Option> { - if let Some(known) = self.formals.get(name) { - return known.clone(); + for (name, list) in defs { + if binders.contains(name) { + continue; } - let defs = self.defs.get(name)?; - if active.contains(name) { - return None; - } - if self.is_binder(name, &mut HashSet::new()) { - self.formals.insert(name.to_string(), None); - return None; - } - active.insert(name.to_string()); - let mut carried: Vec = Vec::new(); - for def in defs { - for (position, formal) in def.params.iter().enumerate() { - let formal = formal.split('=').next().unwrap_or_default().trim(); - if carried.len() <= position { - carried.resize(position + 1, false); - } - carried[position] |= self.formal_is_carried(&def.body, formal, active); - } - } - active.remove(name); - self.formals.insert(name.to_string(), Some(carried.clone())); - Some(carried) - } - - /// Whether `body` spells `formal` after a `.`, or passes it to a macro - /// argument that is carried. - fn formal_is_carried( - &mut self, - body: &str, - formal: &str, - active: &mut HashSet, - ) -> bool { - if formal.is_empty() || !contains_word(body, formal) { - return false; - } - if spellings(body, formal).1 { - return true; - } - for (inner, arguments) in invocations(body) { - for (position, argument) in arguments.iter().enumerate() { - if !contains_word(argument, formal) { + let Some(dir) = direct.get_mut(name) else { continue }; + let Some(pos_deps) = deps.get_mut(name) else { continue }; + for def in list { + for (pos, raw_formal) in def.params.iter().enumerate() { + let formal = raw_formal.split('=').next().unwrap_or_default().trim(); + if formal.is_empty() || !contains_word(&def.body, formal) { continue; } - let carried = match self.formals_of(&inner, active) { - Some(formals) => formals.get(position).copied().unwrap_or(true), - None => true, - }; - if carried { - return true; + if spellings(&def.body, formal).1 { + dir[pos] = true; + continue; + } + for (inner, arguments) in invocations(&def.body) { + for (inner_pos, argument) in arguments.iter().enumerate() { + if !contains_word(argument, formal) { + continue; + } + if binders.contains(&inner) { + dir[pos] = true; + continue; + } + match state.get(&inner) { + None => dir[pos] = true, + Some(inner_state) if inner_pos >= inner_state.len() => dir[pos] = true, + Some(_) => pos_deps[pos].push((inner.clone(), inner_pos)), + } + } } } } - false } + + loop { + let mut changed = false; + for (name, pos_deps) in &deps { + let Some(dir) = direct.get(name) else { continue }; + let Some(cur) = state.get(name) else { continue }; + let mut next = cur.clone(); + for (pos, edges) in pos_deps.iter().enumerate() { + if !cur[pos] { + continue; + } + let keep = dir[pos] + || edges.iter().any(|(inner, ipos)| state.get(inner).is_some_and(|v| v[*ipos])); + if !keep { + next[pos] = false; + changed = true; + } + } + if let Some(slot) = state.get_mut(name) { + *slot = next; + } + } + if !changed { + break; + } + } + + let mut out: BTreeMap>> = BTreeMap::new(); + for name in binders { + if defs.contains_key(name) { + out.insert(name.clone(), None); + } + } + for (name, vec) in state { + out.insert(name, Some(vec)); + } + out } /// Whether a `` `define`` body holds a `bind` into `unit`; a body that @@ -188,30 +215,40 @@ fn invocations(text: &str) -> Vec<(String, Vec<&str>)> { let bytes = text.as_bytes(); let mut out = Vec::new(); let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'"' => i = skip_string(bytes, i + 1), + while let Some(&b) = bytes.get(i) { + match b { + b'"' => i = skip_string(text, i + 1), b'/' if bytes.get(i + 1) == Some(&b'/') => { - i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n) + i = bytes + .get(i..) + .and_then(|s| s.iter().position(|&b| b == b'\n')) + .map_or(bytes.len(), |n| i + n) } b'/' if bytes.get(i + 1) == Some(&b'*') => { - i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2) + i = text + .get(i + 2..) + .and_then(|s| s.find("*/")) + .map_or(bytes.len(), |n| i + 2 + n + 2) } // `` `" `` (stringify) and `` `` `` (paste) open nothing. b'`' if matches!(bytes.get(i + 1), Some(b'"' | b'`')) => i += 2, b'`' => { - let len = text[i + 1..] + let rest = text.get(i + 1..).unwrap_or_default(); + let len = rest .bytes() .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'$') .count(); - let name = &text[i + 1..i + 1 + len]; + let name = &rest[..len]; i += 1 + len; - let open = i + text[i..].len() - text[i..].trim_start().len(); + let tail = text.get(i..).unwrap_or_default(); + let open = i + tail.len() - tail.trim_start().len(); if !name.is_empty() && bytes.get(open) == Some(&b'(') { - out.push((name.to_string(), split_arguments(&text[open + 1..]).0)); + if let Some(args_text) = text.get(open + 1..) { + out.push((name.to_string(), split_arguments(args_text).0)); + } } } - _ => i += 1, + _ => i += text.get(i..).and_then(|s| s.chars().next()).map_or(1, char::len_utf8), } } out @@ -224,25 +261,35 @@ fn split_arguments(text: &str) -> (Vec<&str>, Vec) { let bytes = text.as_bytes(); let (mut arguments, mut starts) = (Vec::new(), vec![0]); let (mut depth, mut start, mut i) = (0usize, 0usize, 0usize); - while i < bytes.len() { - match bytes[i] { + while let Some(&b) = bytes.get(i) { + match b { b'"' => { - i = skip_string(bytes, i + 1); + i = skip_string(text, i + 1); continue; } - b'(' | b'[' | b'{' => depth += 1, + b'(' | b'[' | b'{' => { + depth += 1; + i += 1; + } b')' | b']' | b'}' if depth == 0 => break, - b')' | b']' | b'}' => depth -= 1, + b')' | b']' | b'}' => { + depth -= 1; + i += 1; + } b',' if depth == 0 => { - arguments.push(&text[start..i]); + if let Some(arg) = text.get(start..i) { + arguments.push(arg); + } start = i + 1; starts.push(start); + i += 1; } - _ => {} + _ => i += text.get(i..).and_then(|s| s.chars().next()).map_or(1, char::len_utf8), } - i += 1; } - arguments.push(&text[start..i.min(text.len())]); + if let Some(arg) = text.get(start..i.min(text.len())) { + arguments.push(arg); + } (arguments, starts) } @@ -323,6 +370,88 @@ mod tests { assert_eq!(argument_position(args, args.find('e').unwrap_or(0)), 2); assert_eq!(argument_position(args, args.find('g').unwrap_or(0)), 4); } + + #[test] + fn escaped_multibyte_utf8_in_macro_arguments_never_panics() { + let args = "\"\\é, x\", \"\\中, y\", /* 中 */ sig)"; + assert_eq!(argument_position(args, 0), 0); + assert_eq!(argument_position(args, args.find('y').unwrap_or(0)), 1); + assert_eq!(argument_position(args, args.find("sig").unwrap_or(0)), 2); + + let inv = invocations("`WRAP(\"\\é, x\", \"\\中, y\", z)"); + assert_eq!(inv, vec![("WRAP".to_string(), vec!["\"\\é, x\"", " \"\\中, y\"", " z"])]); + assert!(invocations("`WRAP(\"\\é").len() == 1); + } + + #[test] + fn mutually_recursive_binders_are_detected_regardless_of_key_order() { + let forward = defs(&[ + ("A", &["x"], "`B(x)"), + ("B", &["y"], "`A(y) `BIND_M"), + ("BIND_M", &[], "bind m chk u_chk ();"), + ("DEAD_P", &["x"], "`DEAD_Q(x)"), + ("DEAD_Q", &["y"], "`DEAD_P(y)"), + ]); + let reversed = defs(&[ + ("Z_BIND_M", &[], "bind m chk u_chk ();"), + ("Y_B", &["y"], "`X_A(y) `Z_BIND_M"), + ("X_A", &["x"], "`Y_B(x)"), + ]); + let cf = Carriers::of(&forward, "m"); + assert!(cf.binds("A") && cf.binds("B") && cf.binds("BIND_M")); + assert!(cf.carries("A", 0) && cf.carries("B", 0)); + assert!(!cf.binds("DEAD_P") && !cf.binds("DEAD_Q")); + + let cr = Carriers::of(&reversed, "m"); + assert!(cr.binds("X_A") && cr.binds("Y_B") && cr.binds("Z_BIND_M")); + assert!(cr.carries("X_A", 0) && cr.carries("Y_B", 0)); + } + + #[test] + fn mutually_recursive_formals_are_order_independent() { + let ab = defs(&[("A", &["a", "b"], "`B(b, a)"), ("B", &["p", "q"], "`A(p, 0)")]); + let xy = defs(&[("Y", &["a", "b"], "`X(b, a)"), ("X", &["p", "q"], "`Y(p, 0)")]); + let c1 = Carriers::of(&ab, "m"); + let c2 = Carriers::of(&xy, "m"); + assert!(!c1.carries("A", 0) && !c1.carries("A", 1)); + assert!(!c1.carries("B", 0) && !c1.carries("B", 1)); + assert!(!c2.carries("Y", 0) && !c2.carries("Y", 1)); + assert!(!c2.carries("X", 0) && !c2.carries("X", 1)); + + let cycle = defs(&[("CYC_A", &["x"], "`CYC_B(x)"), ("CYC_B", &["y"], "`CYC_A(y)")]); + let cc = Carriers::of(&cycle, "m"); + assert!(cc.carries("CYC_A", 0) && cc.carries("CYC_B", 0)); + } + + #[test] + fn qa_carry_three_cycle_and_utf8_backslash_arguments() { + let cyc3 = defs(&[ + ("M1", &["a", "b"], "`M2(b, a)"), + ("M2", &["p", "q"], "`M3(q, p)"), + ("M3", &["u", "v"], "u_m.u + v"), + ]); + let cyc3_rev = defs(&[ + ("Z3", &["u", "v"], "u_m.u + v"), + ("Z2", &["p", "q"], "`Z3(q, p)"), + ("Z1", &["a", "b"], "`Z2(b, a)"), + ]); + let c1 = Carriers::of(&cyc3, "m"); + let c2 = Carriers::of(&cyc3_rev, "m"); + assert!(c1.carries("M1", 0) && !c1.carries("M1", 1)); + assert!(!c1.carries("M2", 0) && c1.carries("M2", 1)); + assert!(c1.carries("M3", 0) && !c1.carries("M3", 1)); + assert!(c2.carries("Z1", 0) && !c2.carries("Z1", 1)); + assert!(!c2.carries("Z2", 0) && c2.carries("Z2", 1)); + assert!(c2.carries("Z3", 0) && !c2.carries("Z3", 1)); + + let args = "\"\\\\\", \"\\🚀, a\", \"line1\nline2, \\é\", sig)"; + assert_eq!(argument_position(args, 0), 0); + assert_eq!(argument_position(args, args.find("sig").unwrap_or(0)), 3); + let inv = invocations("`M(\"\\\\\", \"\\🚀, a\", \"\\"); + assert_eq!(inv.len(), 1); + assert_eq!(inv[0].0, "M"); + assert_eq!(inv[0].1.len(), 3); + } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/src/rename/home.rs b/crates/vlog_refactor/src/rename/home.rs index 60ae027..a73c460 100644 --- a/crates/vlog_refactor/src/rename/home.rs +++ b/crates/vlog_refactor/src/rename/home.rs @@ -153,11 +153,12 @@ fn includes_in(text: &str) -> Vec> { while let Some(hit) = text.get(from..).and_then(|s| s.find("`include")) { let after = from + hit + "`include".len(); from = after; + let Some(tail) = text.get(after..) else { continue }; // `` `includes`` or `` `include_dir`` is another word. - if text[after..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') { + if tail.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') { continue; } - let rest = text[after..].trim_start(); + let rest = tail.trim_start(); let close = match rest.chars().next() { Some('"') => '"', Some('<') => '>', @@ -166,8 +167,8 @@ fn includes_in(text: &str) -> Vec> { continue; } }; - match rest[1..].find(close) { - Some(end) => out.push(Some(&rest[1..1 + end])), + match rest.get(1..).and_then(|s| s.find(close).map(|end| &s[..end])) { + Some(path) => out.push(Some(path)), None => out.push(None), } } @@ -216,18 +217,26 @@ pub(super) fn macro_names(text: &str) -> Vec { let mut out = Vec::new(); let bytes = text.as_bytes(); let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'"' => i = skip_string(bytes, i + 1), + while let Some(&b) = bytes.get(i) { + match b { + b'"' => i = skip_string(text, i + 1), b'/' if bytes.get(i + 1) == Some(&b'/') => { - i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n) + i = bytes + .get(i..) + .and_then(|s| s.iter().position(|&b| b == b'\n')) + .map_or(bytes.len(), |n| i + n) } b'/' if bytes.get(i + 1) == Some(&b'*') => { - i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2) + i = text + .get(i + 2..) + .and_then(|s| s.find("*/")) + .map_or(bytes.len(), |n| i + 2 + n + 2) } b'`' => { - let name: String = text[i + 1..] - .chars() + let name: String = text + .get(i + 1..) + .into_iter() + .flat_map(|s| s.chars()) .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') .collect(); i += 1 + name.len(); @@ -235,24 +244,34 @@ pub(super) fn macro_names(text: &str) -> Vec { out.push(name); } } - _ => i += 1, + _ => i += utf8_char_len(text, i), } } out } /// The offset just past the string literal whose body starts at `i`. -pub(super) fn skip_string(bytes: &[u8], mut i: usize) -> usize { - while i < bytes.len() { - match bytes[i] { - b'\\' => i += 2, +pub(super) fn skip_string(text: &str, mut i: usize) -> usize { + let bytes = text.as_bytes(); + while let Some(&b) = bytes.get(i) { + match b { + b'\\' => { + let escaped = + text.get(i + 1..).and_then(|s| s.chars().next()).map_or(0, char::len_utf8); + i += 1 + escaped; + } b'"' => return i + 1, - _ => i += 1, + _ => i += utf8_char_len(text, i), } } bytes.len() } +/// Byte width of the UTF-8 character starting at `i` (falling back to 1 byte). +fn utf8_char_len(text: &str, i: usize) -> usize { + text.get(i..).and_then(|s| s.chars().next()).map_or(1, char::len_utf8) +} + #[cfg(test)] mod tests { use super::super::carry::MacroDef; @@ -316,6 +335,36 @@ mod tests { assert_eq!(names, vec!["A", "F"]); } + #[test] + fn escaped_multibyte_utf8_in_strings_never_panics_and_keeps_scanning() { + let names = + macro_names("x = `A; $display(\"\\é `NOPE\"); $display(\"\\中 `NOPE2\"); /* 中 */ `B"); + assert_eq!(names, vec!["A", "B"]); + assert!(macro_names("\"`X \\é").is_empty()); + assert!(macro_names("\"`X \\中").is_empty()); + assert_eq!(skip_string("\"\\é\" `OK", 1), "\"\\é\"".len()); + assert_eq!(skip_string("\"\\中\" `OK", 1), "\"\\中\"".len()); + assert_eq!(includes_in("// é\n`include \"a/b.svh\" // 中\n"), vec![Some("a/b.svh")]); + } + + #[test] + fn qa_skip_string_escaped_backslash_4byte_utf8_and_eof_backslash() { + assert_eq!(skip_string("\"\\\\\" `OK", 1), "\"\\\\\"".len()); + assert_eq!(skip_string("\"\\\\\\\" `NO", 1), "\"\\\\\\\" `NO".len()); + assert_eq!(skip_string("\"\\🚀\" `OK", 1), "\"\\🚀\"".len()); + assert_eq!(skip_string("\"\\", 1), "\"\\".len()); + assert_eq!( + macro_names("`A; $display(\"\\\\\" `B); $display(\"\\🚀 `NO\"); /* 🚀 */ `C"), + vec!["A", "B", "C"] + ); + assert!(macro_names("\"`X \\").is_empty()); + assert!(macro_names("\"`X \\🚀").is_empty()); + assert_eq!( + includes_in("// 🚀\n`include \"é/🚀.svh\"\n`include \"unterminated \\"), + vec![Some("é/🚀.svh"), None] + ); + } + #[test] fn invocations_are_followed_through_define_bodies() { let def = |body: &str| vec![MacroDef { params: Vec::new(), body: body.to_string() }]; diff --git a/crates/vlog_refactor/src/rename/mod.rs b/crates/vlog_refactor/src/rename/mod.rs index 3db2317..48eeca0 100644 --- a/crates/vlog_refactor/src/rename/mod.rs +++ b/crates/vlog_refactor/src/rename/mod.rs @@ -52,7 +52,7 @@ use vlog_parser::token::{is_keyword, TokenKind}; use vlog_parser::tokenize; use vlog_semantic::{ Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Surface, Symbol, - SymbolId, WorkspaceIndex, + SymbolId, SymbolKind, WorkspaceIndex, }; use crate::trace::RenameTrace; @@ -148,12 +148,55 @@ fn renameable_here( if declaration.name_span.is_empty() { return Err(unspelled(&declaration.name)); } - if declaration.scope == semantics.file_scope() && index.units(&declaration.name).len() > 1 { - return Err(ambiguous(&declaration.name)); + if let Some((unit, kind)) = enclosing_unit(semantics, declaration) { + if is_duplicate_unit(index, unit, kind) { + return Err(ambiguous(unit)); + } } Ok(()) } +/// The declaration's enclosing file-scope unit name and kind (or its own at file scope). +pub(super) fn enclosing_unit<'a>( + semantics: &'a Semantics, + declaration: &'a Symbol, +) -> Option<(&'a str, SymbolKind)> { + let file_scope = semantics.file_scope(); + if declaration.scope == file_scope { + return Some((declaration.name.as_str(), declaration.kind)); + } + let mut here = Some(declaration.scope); + while let Some(id) = here { + let current = semantics.scope(id)?; + if current.parent == Some(file_scope) { + return current + .owner + .and_then(|o| semantics.symbol(o)) + .filter(|s| { + s.scope == file_scope + && (s.kind.is_instantiable() + || matches!( + s.kind, + SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class + )) + }) + .map(|s| (s.name.as_str(), s.kind)); + } + here = current.parent; + } + None +} + +/// Whether `index.units(unit)` declares more than one unit of a matching kind. +fn is_duplicate_unit(index: &WorkspaceIndex, unit: &str, kind: SymbolKind) -> bool { + index + .units(unit) + .iter() + .filter(|def| (def.kind.is_instantiable() && kind.is_instantiable()) || def.kind == kind) + .count() + > 1 +} + /// The identifier a rename at `offset` would act on, read from one buffer's /// analysis alone: the name, with no opinion on whether it may be renamed. /// @@ -408,24 +451,24 @@ impl<'a> Scope<'a> { symbol: SymbolId, cursor: TextRange, ) -> Result { - let (name, name_span, at_file_scope) = { + let (name, name_span, unit) = { let Some(analysis) = self.analysis(file) else { return Err("the declaring file could not be analyzed.".to_string()); }; let Some(declaration) = analysis.semantics.symbol(symbol) else { return Err(NOTHING_HERE.to_string()); }; - ( - declaration.name.clone(), - declaration.name_span, - declaration.scope == analysis.semantics.file_scope(), - ) + let unit = enclosing_unit(&analysis.semantics, declaration) + .map(|(u, kind)| (u.to_string(), kind)); + (declaration.name.clone(), declaration.name_span, unit) }; if name_span.is_empty() { return Err(unspelled(&name)); } - if at_file_scope && self.index.units(&name).len() > 1 { - return Err(ambiguous(&name)); + if let Some((unit, kind)) = unit { + if is_duplicate_unit(&self.index, &unit, kind) { + return Err(ambiguous(&unit)); + } } Ok(Target { file, symbol, name, cursor }) } diff --git a/crates/vlog_refactor/src/rename/preflight.rs b/crates/vlog_refactor/src/rename/preflight.rs index d3d2b6b..c41a3c4 100644 --- a/crates/vlog_refactor/src/rename/preflight.rs +++ b/crates/vlog_refactor/src/rename/preflight.rs @@ -31,7 +31,9 @@ use vlog_semantic::{Resolution, Semantics, SymbolId}; -use super::{already_named, check_new_name, from_base, unresolved, unspelled, NOTHING_HERE}; +use super::{ + already_named, check_new_name, enclosing_unit, from_base, unresolved, unspelled, NOTHING_HERE, +}; /// The refusal `rename` would make for this cursor and this new name, when the /// request buffer alone is enough to know it — and `Ok(())` when it is not. @@ -73,10 +75,11 @@ fn declared_here(semantics: &Semantics, symbol: SymbolId, new_name: &str) -> Res if declaration.name_span.is_empty() { return Err(unspelled(&declaration.name)); } - // A file-scope unit is refused when the index holds its name more than - // once, and that count belongs to the slow road — so nothing after it may - // be decided here either, or a refusal would jump the ambiguity check. - if declaration.scope == semantics.file_scope() { + // A file-scope unit — and any declaration inside one — is refused when + // the index holds that unit's name more than once, and that count belongs + // to the slow road — so nothing after it may be decided here either, or + // a refusal would jump the ambiguity check. + if enclosing_unit(semantics, declaration).is_some() { return Ok(()); } if declaration.name == new_name { diff --git a/crates/vlog_refactor/tests/extract.rs b/crates/vlog_refactor/tests/extract.rs index e8fddf0..f9a210d 100644 --- a/crates/vlog_refactor/tests/extract.rs +++ b/crates/vlog_refactor/tests/extract.rs @@ -737,4 +737,44 @@ fn a_crossing_member_access_names_the_head_and_the_field_second() { assert!(said.contains("`s` is declared with a type written outside `m`"), "{said}"); } +#[test] +fn extraction_preserves_crlf_line_endings_in_same_file_and_new_file() { + let crlf = concat!( + "module m (\r\n", + " input logic [7:0] a,\r\n", + " input logic [7:0] b,\r\n", + " output logic [7:0] y\r\n", + ");\r\n", + " logic [7:0] s;\r\n", + " assign s = a + b;\r\n", + " assign y = s ^ 8'hFF;\r\n", + "endmodule\r\n", + ); + let (start, end) = at(crlf, "assign s = a + b;"); + + let same = extract_module(&files(crlf), Path::new(M), start, end, "adder", Home::SameFile) + .expect("extracts with SameFile"); + let same_after = applied(crlf, &same, M); + assert!(same_after.contains("\r\n\r\nmodule adder"), "{same_after:?}"); + let lone_lf: Vec<_> = same_after + .match_indices('\n') + .filter(|&(i, _)| i == 0 || same_after.as_bytes()[i - 1] != b'\r') + .collect(); + assert!( + lone_lf.is_empty(), + "lone LF found in same-file CRLF output at {lone_lf:?}:\n{same_after:?}" + ); + + let separate = extract_module(&files(crlf), Path::new(M), start, end, "adder", Home::NewFile) + .expect("extracts with NewFile"); + for file in [applied(crlf, &separate, M), applied(crlf, &separate, "/rtl/adder.sv")] { + assert!(file.contains("\r\n"), "{file:?}"); + let lone_lf: Vec<_> = file + .match_indices('\n') + .filter(|&(i, _)| i == 0 || file.as_bytes()[i - 1] != b'\r') + .collect(); + assert!(lone_lf.is_empty(), "lone LF found in CRLF output at {lone_lf:?}:\n{file:?}"); + } +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/tests/ports.rs b/crates/vlog_refactor/tests/ports.rs index 704c8ff..8de5316 100644 --- a/crates/vlog_refactor/tests/ports.rs +++ b/crates/vlog_refactor/tests/ports.rs @@ -376,6 +376,49 @@ fn a_port_still_used_in_the_body_is_refused() { assert!(message.contains("sub.sv:6"), "the line it is used on: {message}"); } +#[test] +fn a_same_file_connection_in_another_module_does_not_count_as_a_body_use() { + let both = concat!( + "module leaf (\n", + " input logic a,\n", + " input logic unused_b\n", + ");\n", + " wire out;\n", + " assign out = a;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .unused_b(y));\n", + "endmodule\n", + ); + let workspace = files(&[("/rtl/both.sv", both)]); + let edit = + remove_port(&workspace, Path::new("/rtl/both.sv"), at(both, "input logic unused_b") + 12) + .expect("another module's .unused_b connection in the same file is not a body use"); + let after = applied(&workspace, &edit, "/rtl/both.sv"); + assert!(!after.contains("unused_b"), "port declaration and connection removed:\n{after}"); + assert!(after.contains("leaf u_leaf (.a(x));"), "{after}"); + + let reversed = concat!( + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .unused_b(y));\n", + "endmodule\n", + "module leaf (\n", + " input logic a,\n", + " input logic unused_b\n", + ");\n", + " wire out;\n", + " assign out = a;\n", + "endmodule\n", + ); + let rev_ws = files(&[("/rtl/both.sv", reversed)]); + let rev_edit = + remove_port(&rev_ws, Path::new("/rtl/both.sv"), at(reversed, "input logic unused_b") + 12) + .expect("ordering before leaf also removes cleanly"); + assert!(applied(&rev_ws, &rev_edit, "/rtl/both.sv").contains("leaf u_leaf (.a(x));")); +} + #[test] fn a_positional_connection_anywhere_refuses_the_whole_removal() { let sub = "module sub (input a, input b);\nendmodule\n"; diff --git a/crates/vlog_refactor/tests/preflight_oracle.rs b/crates/vlog_refactor/tests/preflight_oracle.rs index 21c8f75..03ddd54 100644 --- a/crates/vlog_refactor/tests/preflight_oracle.rs +++ b/crates/vlog_refactor/tests/preflight_oracle.rs @@ -246,21 +246,28 @@ fn a_binds_connection_expressions_defer_rather_than_invent_a_refusal() { #[test] fn renaming_a_symbol_to_the_name_it_already_has_is_refused_from_the_buffer() { - let files = [("sub.sv", SUB), ("top.sv", TOP)]; - let sources = workspace(&files); - let path = PathBuf::from("sub.sv"); - let semantics = analyze(&parse_source_tolerant(SUB).0, SUB); - // `local_net` is a declaration inside the module — not at file scope, so - // no index question stands between the cursor and this refusal. - let at = SUB.find("local_net").expect("the declaration") as u32; - let fast = rename_preflight(&semantics, at, "local_net").expect_err("the same name"); - assert_eq!(fast, "`local_net` is the name it already has."); - assert_eq!(fast, rename(&sources, &path, at, "local_net").expect_err("the same name")); + // A declaration outside any file-scope unit (here inside a `$unit`-level + // function) has no enclosing unit ambiguity check standing between the + // cursor and `already_named`, so the buffer-only preflight takes it. + let unit_fn = "function automatic int helper(int x);\n int local_var;\n local_var = x;\n return local_var;\nendfunction\n"; + let fn_files = [("helper.sv", unit_fn)]; + let fn_sources = workspace(&fn_files); + let fn_path = PathBuf::from("helper.sv"); + let fn_semantics = analyze(&parse_source_tolerant(unit_fn).0, unit_fn); + let at_fn = unit_fn.find("local_var").expect("the local var") as u32; + let fast = rename_preflight(&fn_semantics, at_fn, "local_var").expect_err("the same name"); + assert_eq!(fast, "`local_var` is the name it already has."); + assert_eq!(fast, rename(&fn_sources, &fn_path, at_fn, "local_var").expect_err("the same name")); - // A file-scope unit's same-name refusal is the index's to reach, because - // the ambiguity check comes first. - let at = SUB.find("sub").expect("the module name") as u32; - assert!(rename_preflight(&semantics, at, "sub").is_ok(), "deferred, not taken"); + // Both a file-scope unit and a declaration inside one (`local_net` in + // `module sub`) check `enclosing_unit` ambiguity against the workspace + // index before `already_named`, so the buffer-only preflight defers both. + let semantics = analyze(&parse_source_tolerant(SUB).0, SUB); + let at_net = SUB.find("local_net").expect("the declaration") as u32; + assert!(rename_preflight(&semantics, at_net, "local_net").is_ok(), "deferred, not taken"); + + let at_unit = SUB.find("sub").expect("the module name") as u32; + assert!(rename_preflight(&semantics, at_unit, "sub").is_ok(), "deferred, not taken"); } #[test] diff --git a/crates/vlog_refactor/tests/qa_correctness_r1.rs b/crates/vlog_refactor/tests/qa_correctness_r1.rs new file mode 100644 index 0000000..81c04f5 --- /dev/null +++ b/crates/vlog_refactor/tests/qa_correctness_r1.rs @@ -0,0 +1,762 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! QA adversarial attacks for Round 1, Lane 1A (`refactor-correctness-r1`). + +use std::path::{Path, PathBuf}; + +use vlog_parser::parse_source_tolerant; +use vlog_refactor::{ + extract_module, port_offers, prepare_rename, prepare_rename_here, remove_port, rename, + rename_preflight, Home, PortOfferKind, +}; +use vlog_semantic::{analyze, resolve_external, WorkspaceIndex}; + +fn ws(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + entries.iter().map(|(p, t)| (PathBuf::from(p), (*t).to_string())).collect() +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +fn at_after(text: &str, prefix: &str, name: &str) -> u32 { + let base = text.find(prefix).expect("prefix present") + prefix.len(); + let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_'); + let bytes = text.as_bytes(); + let mut search = base; + while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) { + let start = search + hit; + let end = start + name.len(); + if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) { + return start as u32; + } + search = start + 1; + } + panic!("whole word `{name}` not found after `{prefix}`"); +} + +fn apply(text: &str, edits: &vlog_refactor::RefactorEdit, file: &str) -> String { + let mut out = text.to_string(); + let mut list = edits.edits_for(Path::new(file)).to_vec(); + list.sort_by_key(|e| (e.range.start, e.range.end)); + for edit in list.into_iter().rev() { + out.replace_range(edit.range.start as usize..edit.range.end as usize, &edit.new_text); + } + out +} + +fn assert_no_bare_lf(text: &str, label: &str) { + let bare: Vec = text + .match_indices('\n') + .filter(|&(i, _)| i == 0 || text.as_bytes()[i - 1] != b'\r') + .map(|(i, _)| i) + .collect(); + assert!(bare.is_empty(), "{label}: bare LF at byte offsets {bare:?} in:\n{text:?}"); +} + +fn assert_no_cr(text: &str, label: &str) { + assert!(!text.contains('\r'), "{label}: unexpected CR in:\n{text:?}"); +} + +// --------------------------------------------------------------------------- +// 1. UTF-8 string/escape scanning via rename macro-carry & home-set +// --------------------------------------------------------------------------- + +#[test] +fn qa_utf8_escaped_backslash_4byte_and_unterminated_backslash_do_not_panic() { + // Escaped backslash before closing quote (`"\\"`), 2-byte (`\é`), 4-byte (`\🚀`), + // non-ASCII comments near strings, and multi-line strings in macro args. + let defs = concat!( + "`define CALL(msg, sig) $display(msg); force u_m.sig = 1'b0;\n", + "`define UNUSED_AFTER(msg, sig) $display(msg); logic _keep_ = sig;\n", + ); + let top = concat!( + "// 🚀 non-ASCII comment\n", + "module top;\n", + " logic state_q;\n", + " initial begin\n", + " `CALL(\"\\\\\", state_q)\n", + " `CALL(\"\\é \\🚀 line1\n", + "line2, `FAKE\", state_q)\n", + " `CALL(\"\\\\🚀\\\\\" , state_q)\n", + " end\n", + "endmodule\n", + ); + let target = "module m; logic sig; endmodule\n"; + let files = ws(&[("/rtl/defs.svh", defs), ("/rtl/top.sv", top), ("/rtl/m.sv", target)]); + let edit = + rename(&files, Path::new("/rtl/top.sv"), at_after(top, "logic", "state_q"), "next_q") + .expect("utf8 macro invocations must not panic during warning scan"); + assert!(edit.warnings.iter().any(|w| w.contains("CALL")), "{:?}", edit.warnings); + + // Unterminated string ending with a lone backslash at EOF in a watched file. + let eof_bs = concat!("module broken_str;\n", " logic x;\n", " initial `CALL(\"state_q \\",); + let files_eof = ws(&[ + ("/rtl/defs.svh", defs), + ("/rtl/m.sv", "module m; logic state_q; assign state_q = 1'b0; endmodule\n"), + ("/rtl/broken.sv", eof_bs), + ]); + let m_text = &files_eof[1].1; + let res = + rename(&files_eof, Path::new("/rtl/m.sv"), at_after(m_text, "logic", "state_q"), "next_q"); + assert!(res.is_ok(), "unterminated backslash string at EOF must not panic: {res:?}"); +} + +// --------------------------------------------------------------------------- +// 2. SipHash / cycle determinism via macro-carry warnings +// --------------------------------------------------------------------------- + +#[test] +fn qa_macro_carry_three_cycle_and_reversed_order_are_deterministic() { + let chk = "module chk (input logic s);\nendmodule\n"; + let user_a = "module user;\n logic state_q;\n initial `A(state_q)\nendmodule\n"; + let defs_fwd = concat!( + "`define A(x) `B(x)\n", + "`define B(x) `C(x)\n", + "`define C(x) `A(x) `BIND_M\n", + "`define BIND_M bind m chk u_chk (.s(state_q));\n", + ); + let defs_rev = concat!( + "`define BIND_M bind m chk u_chk (.s(state_q));\n", + "`define C(x) `A(x) `BIND_M\n", + "`define B(x) `C(x)\n", + "`define A(x) `B(x)\n", + ); + let m_src = "module m;\n logic state_q;\n assign state_q = 1'b0;\nendmodule\n"; + for run in 0..10 { + let f1 = ws(&[ + ("/rtl/defs.svh", defs_fwd), + ("/rtl/chk.sv", chk), + ("/rtl/user.sv", user_a), + ("/rtl/m.sv", m_src), + ]); + let f2 = ws(&[ + ("/rtl/defs.svh", defs_rev), + ("/rtl/chk.sv", chk), + ("/rtl/user.sv", user_a), + ("/rtl/m.sv", m_src), + ]); + let w1 = rename(&f1, Path::new("/rtl/m.sv"), at_after(m_src, "logic", "state_q"), "next_q") + .expect("fwd") + .warnings; + let w2 = rename(&f2, Path::new("/rtl/m.sv"), at_after(m_src, "logic", "state_q"), "next_q") + .expect("rev") + .warnings; + assert!(w1.iter().any(|w| w.contains("user.sv:3")), "run {run} fwd: {w1:?}"); + assert!(w2.iter().any(|w| w.contains("user.sv:3")), "run {run} rev: {w2:?}"); + } +} + +// --------------------------------------------------------------------------- +// 3. Duplicate-unit member rename (#53) +// --------------------------------------------------------------------------- + +#[test] +fn qa_duplicate_unit_attacks_and_prepare_parity() { + // 3a. Same-named module `m` and package `m` must NOT collide. + let mod_m = "module m (input logic clk);\n logic sig;\n assign sig = clk;\nendmodule\n"; + let pkg_m = "package m;\n localparam int W = 8;\nendpackage\n"; + let both = ws(&[("/rtl/mod_m.sv", mod_m), ("/rtl/pkg_m.sv", pkg_m)]); + let mod_edit = + rename(&both, Path::new("/rtl/mod_m.sv"), at_after(mod_m, "logic", "sig"), "sig_n") + .expect("module `m` member must not collide with package `m`"); + assert!(apply(mod_m, &mod_edit, "/rtl/mod_m.sv").contains("sig_n")); + let pkg_edit = rename(&both, Path::new("/rtl/pkg_m.sv"), at_after(pkg_m, "int", "W"), "WIDTH") + .expect("package `m` member must not collide with module `m`"); + assert!(apply(pkg_m, &pkg_edit, "/rtl/pkg_m.sv").contains("WIDTH")); + + // 3b. Two `interface bus_if` files must refuse member/port/modport renames. + let bus = concat!( + "interface bus_if (input logic clk);\n", + " logic req;\n", + " modport mp (input req);\n", + "endinterface\n", + ); + let dup_if = ws(&[("/rtl/if_a.sv", bus), ("/rtl/if_b.sv", bus)]); + for (prefix, name) in [("input logic", "clk"), ("logic", "req"), ("modport", "mp")] { + let off = at_after(bus, prefix, name); + let err = rename(&dup_if, Path::new("/rtl/if_a.sv"), off, "renamed") + .expect_err("duplicate interface member must refuse"); + assert!(err.contains("`bus_if`") && err.contains("more than one"), "{err}"); + } + + // 3c. Nested generate block inside duplicated module + non-duplicated module in same file. + let mixed = concat!( + "module dup (input logic a);\n", + " generate\n", + " for (genvar i = 0; i < 2; i++) begin : g_outer\n", + " if (1) begin : g_inner\n", + " logic deep_sig;\n", + " end\n", + " end\n", + " endgenerate\n", + "endmodule\n", + "module unique_m (input logic u_in);\n", + " logic u_sig;\n", + " assign u_sig = u_in;\n", + "endmodule\n", + ); + let dup_only = "module dup (input logic a);\nendmodule\n"; + let mixed_ws = ws(&[("/rtl/mixed.sv", mixed), ("/rtl/dup2.sv", dup_only)]); + + for (prefix, name) in + [("genvar", "i"), ("begin :", "g_outer"), ("begin :", "g_inner"), ("logic", "deep_sig")] + { + let off = at_after(mixed, prefix, name); + let prep = prepare_rename(&mixed_ws, Path::new("/rtl/mixed.sv"), off) + .expect_err("nested generate inside dup must refuse prepare"); + let full = rename(&mixed_ws, Path::new("/rtl/mixed.sv"), off, "renamed") + .expect_err("nested generate inside dup must refuse rename"); + assert_eq!(prep, full); + assert!(prep.contains("`dup`") && prep.contains("more than one"), "{prep}"); + } + + // Non-duplicated module in the same file remains renameable. + let uniq_edit = rename( + &mixed_ws, + Path::new("/rtl/mixed.sv"), + at_after(mixed, "logic", "u_sig"), + "u_renamed", + ) + .expect("non-duplicated module in same file must still rename"); + assert!(apply(mixed, &uniq_edit, "/rtl/mixed.sv").contains("u_renamed")); + + // 3d. Byte-for-byte parity between `prepare_rename` and `prepare_rename_here` on mixed.sv! + let index = WorkspaceIndex::build(mixed_ws.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let semantics = analyze(&parse_source_tolerant(mixed).0, mixed); + let external = resolve_external(&semantics, &index); + for offset in 0..=mixed.len() as u32 { + let whole = prepare_rename(&mixed_ws, Path::new("/rtl/mixed.sv"), offset); + let here = prepare_rename_here(&semantics, &external, &index, offset); + match (&whole, &here) { + (Ok(w), Ok(h)) => assert_eq!(w, h, "at byte {offset}"), + (Err(w), Err(h)) => assert_eq!(w, h, "at byte {offset}"), + (Err(_), Ok(_)) => {} // allowed deferral + (Ok(w), Err(h)) => panic!("invented refusal at byte {offset}: whole={w:?} here={h:?}"), + } + } +} + +#[test] +fn qa_duplicate_typedef_and_class_and_module_interface_collision() { + // Module `bus` vs Interface `bus` share instantiable namespace. + let mod_bus = "module bus; logic sig; endmodule\n"; + let if_bus = "interface bus; logic sig; endinterface\n"; + let collision = ws(&[("/rtl/m.sv", mod_bus), ("/rtl/i.sv", if_bus)]); + let err = rename(&collision, Path::new("/rtl/m.sv"), at_after(mod_bus, "logic", "sig"), "s2") + .expect_err("module and interface with same name share namespace"); + assert!(err.contains("`bus`") && err.contains("more than one"), "{err}"); + + // Duplicate file-scope `typedef struct`. + let td = "typedef struct packed { logic f; } my_s_t;\n"; + let td_ws = ws(&[("/rtl/t1.sv", td), ("/rtl/t2.sv", td)]); + let err_td = rename(&td_ws, Path::new("/rtl/t1.sv"), at_after(td, "logic", "f"), "g") + .expect_err("duplicate typedef struct member must refuse"); + assert!(err_td.contains("`my_s_t`") && err_td.contains("more than one"), "{err_td}"); + + // Duplicate file-scope `class`. + let cls = "class item;\n int val;\nendclass\n"; + let cls_ws = ws(&[("/rtl/c1.sv", cls), ("/rtl/c2.sv", cls)]); + let err_cls = rename(&cls_ws, Path::new("/rtl/c1.sv"), at_after(cls, "int", "val"), "v2") + .expect_err("duplicate file-scope class member must refuse"); + assert!(err_cls.contains("`item`") && err_cls.contains("more than one"), "{err_cls}"); +} + +// --------------------------------------------------------------------------- +// 4. Port removal (#38) +// --------------------------------------------------------------------------- + +#[test] +fn qa_remove_port_same_file_body_use_positional_and_wildcard() { + // Same-file `.p(sig)` AND target module itself uses `p` -> must refuse! + let used_in_both = concat!( + "module leaf (\n", + " input logic a,\n", + " input logic p\n", + ");\n", + " wire out;\n", + " assign out = a & p;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .p(y));\n", + "endmodule\n", + ); + let w1 = ws(&[("/rtl/both.sv", used_in_both)]); + let p_off = at(used_in_both, "input logic p") + "input logic ".len() as u32; + let err = remove_port(&w1, Path::new("/rtl/both.sv"), p_off) + .expect_err("still used inside leaf body"); + assert!(err.contains("`p` is still used inside `leaf` at both.sv:6"), "{err}"); + + // Same-file positional connection -> must refuse! + let pos_same = concat!( + "module leaf (input logic a, input logic p);\n", + " wire out = a;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_pos (x, y);\n", + "endmodule\n", + ); + let w2 = ws(&[("/rtl/both.sv", pos_same)]); + let p_pos = at(pos_same, "input logic p") + "input logic ".len() as u32; + let err_pos = remove_port(&w2, Path::new("/rtl/both.sv"), p_pos) + .expect_err("positional connection must refuse"); + assert!(err_pos.contains("by position"), "{err_pos}"); + + // Same-file `.*` connection when `p` is unused in leaf -> succeeds with warning! + let wc_same = concat!( + "module leaf (input logic a, input logic p);\n", + " wire out = a;\n", + "endmodule\n", + "module top;\n", + " logic a, p;\n", + " leaf u_wc (.*);\n", + "endmodule\n", + ); + let w3 = ws(&[("/rtl/both.sv", wc_same)]); + let p_wc = at(wc_same, "input logic p") + "input logic ".len() as u32; + let ok_wc = remove_port(&w3, Path::new("/rtl/both.sv"), p_wc) + .expect("wildcard in same file with unused body port removes header and warns"); + assert!(!apply(wc_same, &ok_wc, "/rtl/both.sv").contains("input logic p")); + assert!(ok_wc.warnings.iter().any(|w| w.contains(".*")), "{:?}", ok_wc.warnings); + + // Non-ANSI port with same-file connection in another module. + let non_ansi = concat!( + "module leaf (a, unused_b);\n", + " input logic a;\n", + " input logic unused_b;\n", + " wire out = a;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .unused_b(y));\n", + "endmodule\n", + ); + let w4 = ws(&[("/rtl/both.sv", non_ansi)]); + let ok_na = remove_port(&w4, Path::new("/rtl/both.sv"), at(non_ansi, "unused_b);")) + .expect("non-ansi same-file connection in another module is not a body use"); + let after_na = apply(non_ansi, &ok_na, "/rtl/both.sv"); + assert!(!after_na.contains("unused_b"), "{after_na}"); + assert!(after_na.contains("leaf u_leaf (.a(x));"), "{after_na}"); + + // Nested module with same-named port in the same file. + let nested = concat!( + "module outer (input logic p);\n", + " module inner (input logic p);\n", + " wire w = p;\n", + " endmodule\n", + "endmodule\n", + ); + let w5 = ws(&[("/rtl/nested.sv", nested)]); + let p_outer = + at(nested, "module outer (input logic p)") + "module outer (input logic ".len() as u32; + let ok_nested = remove_port(&w5, Path::new("/rtl/nested.sv"), p_outer) + .expect("inner module's own port `p` must not block outer unused port `p`"); + let after_nested = apply(nested, &ok_nested, "/rtl/nested.sv"); + assert!(after_nested.contains("module outer ();"), "{after_nested}"); + assert!(after_nested.contains("module inner (input logic p);"), "{after_nested}"); +} + +#[test] +fn qa_remove_port_empty_body_module_with_default_expr_using_removed_port() { + // Module with NO body items (`module.items` empty), where port `b` has default `= a`. + // `find_module` returns the full `module ... endmodule` item span so `body_uses_in` + // covers header port defaults even when `module.items` is empty. + let empty_body = "module leaf (\n input logic a,\n input logic b = a\n);\nendmodule\n"; + let w = ws(&[("/rtl/leaf.sv", empty_body)]); + let off = at_after(empty_body, "input logic", "a"); + let res = remove_port(&w, Path::new("/rtl/leaf.sv"), off); + let offers = port_offers(&w, Path::new("/rtl/leaf.sv"), off); + assert!( + offers.is_empty() && res.as_ref().is_err_and(|e| e.contains("still used inside")), + "expected body_uses_in to detect `b = a` usage: offers={offers:?}, res={res:?}" + ); + + // With a sibling module in the same file, removing `a` still refuses (`b = a`), + // while removing `b` (unused in `leaf`, connected only in sibling `top`) succeeds. + let with_sibling = concat!( + "module leaf #(\n parameter int P = 1\n) (\n input logic [P-1:0] a,\n input logic [P-1:0] b = a\n);\nendmodule : leaf\n", + "module top;\n logic x, y;\n leaf u_leaf (.a(x), .b(y));\nendmodule\n", + ); + let ws_sib = ws(&[("/rtl/both.sv", with_sibling)]); + let off_a = at_after(with_sibling, "input logic [P-1:0]", "a"); + let res_a = remove_port(&ws_sib, Path::new("/rtl/both.sv"), off_a); + assert!( + port_offers(&ws_sib, Path::new("/rtl/both.sv"), off_a).is_empty() + && res_a.as_ref().is_err_and(|e| e.contains("still used inside `leaf` at both.sv:5")), + "expected `b = a` refusal in leaf: {res_a:?}" + ); + let off_b = at_after(with_sibling, "input logic [P-1:0]", "b"); + let offers_b = port_offers(&ws_sib, Path::new("/rtl/both.sv"), off_b); + assert_eq!(offers_b.len(), 1, "expected remove offer for unused `b`: {offers_b:?}"); + let ok_b = remove_port(&ws_sib, Path::new("/rtl/both.sv"), off_b) + .expect("sibling top's .b(y) connection must not block removing unused `b`"); + let after_b = apply(with_sibling, &ok_b, "/rtl/both.sv"); + assert!(after_b.contains("leaf u_leaf (.a(x));"), "{after_b}"); +} + +#[test] +fn qa_remove_port_non_ansi_param_default_and_sibling_before_target_edge_cases() { + // Sibling module BEFORE target `leaf`, and sibling ALSO declares a port named `a`. + // `body_uses_in` must bind to `leaf`'s port `a`, detect `b = a`, and ignore sibling `.b(y)`. + let sib_before = concat!( + "module top (input logic a);\n", + " logic y;\n", + " leaf u_leaf (.a(a), .b(y));\n", + "endmodule\n", + "module leaf #(\n", + " parameter int P = 8,\n", + " parameter int Q = P + 1\n", + ") (\n", + " input logic [Q-1:0] a,\n", + " input logic [Q-1:0] b = a\n", + ");\n", + "endmodule\n", + ); + let ws_before = ws(&[("/rtl/both.sv", sib_before)]); + let off_a = at_after(sib_before, "input logic [Q-1:0]", "a"); + let offers_a = port_offers(&ws_before, Path::new("/rtl/both.sv"), off_a); + let rem_a = remove_port(&ws_before, Path::new("/rtl/both.sv"), off_a); + assert!( + offers_a.is_empty() + && rem_a.as_ref().is_err_and(|e| e.contains("still used inside `leaf`")), + "expected leaf's `b = a` refusal even with sibling `top (input logic a)` before it: offers={offers_a:?}, rem={rem_a:?}" + ); + let off_b = at_after(sib_before, "input logic [Q-1:0]", "b"); + let offers_b = port_offers(&ws_before, Path::new("/rtl/both.sv"), off_b); + assert_eq!(offers_b.len(), 1, "expected remove offer for unused `b`: {offers_b:?}"); + assert!(offers_b[0].title.contains("1 instantiation"), "{offers_b:?}"); + let ok_b = remove_port(&ws_before, Path::new("/rtl/both.sv"), off_b) + .expect("unused `b` with sibling before `leaf` must succeed"); + let after_b = apply(sib_before, &ok_b, "/rtl/both.sv"); + assert!(after_b.contains("leaf u_leaf (.a(a));"), "{after_b}"); + + // Non-ANSI port list with default expression using another port + sibling instantiation. + let non_ansi_default = concat!( + "module leaf (a, b);\n", + " input logic a;\n", + " input logic b = a;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .b(y));\n", + "endmodule\n", + ); + let ws_na = ws(&[("/rtl/na.sv", non_ansi_default)]); + let na_a_hdr = at(non_ansi_default, "a, b);"); + let na_offers_a = port_offers(&ws_na, Path::new("/rtl/na.sv"), na_a_hdr); + let na_rem_a = remove_port(&ws_na, Path::new("/rtl/na.sv"), na_a_hdr); + assert!( + na_offers_a.is_empty() + && na_rem_a.as_ref().is_err_and(|e| e.contains("still used inside `leaf`")), + "non-ANSI `b = a` must block removing `a`: offers={na_offers_a:?}, rem={na_rem_a:?}" + ); + let na_b_hdr = at(non_ansi_default, "b);"); + let na_offers_b = port_offers(&ws_na, Path::new("/rtl/na.sv"), na_b_hdr); + assert!( + na_offers_b.iter().any(|o| o.kind == PortOfferKind::Remove), + "expected remove offer for non-ANSI unused `b`: {na_offers_b:?}" + ); + let na_ok_b = remove_port(&ws_na, Path::new("/rtl/na.sv"), na_b_hdr) + .expect("non-ANSI unused `b` must remove cleanly"); + let na_after_b = apply(non_ansi_default, &na_ok_b, "/rtl/na.sv"); + assert!(na_after_b.contains("module leaf (a);"), "{na_after_b}"); + assert!(na_after_b.contains("leaf u_leaf (.a(x));"), "{na_after_b}"); + + // Non-ANSI port list with shared declarator line (`input logic a, b;`) and sibling `.b(y)`. + let non_ansi_shared = concat!( + "module leaf (a, b);\n", + " input logic a, b;\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf u_leaf (.a(x), .b(y));\n", + "endmodule\n", + ); + let ws_shared = ws(&[("/rtl/shared.sv", non_ansi_shared)]); + let sh_b = at(non_ansi_shared, "b);"); + let sh_offers = port_offers(&ws_shared, Path::new("/rtl/shared.sv"), sh_b); + assert!( + sh_offers.iter().any(|o| o.kind == PortOfferKind::Remove), + "expected remove offer for shared non-ANSI `b`: {sh_offers:?}" + ); + let sh_ok = remove_port(&ws_shared, Path::new("/rtl/shared.sv"), sh_b).expect("removes b"); + let sh_after = apply(non_ansi_shared, &sh_ok, "/rtl/shared.sv"); + assert!(sh_after.contains("input logic a;"), "{sh_after}"); + assert!(sh_after.contains("leaf u_leaf (.a(x));"), "{sh_after}"); + + // Parameter named like a port in a sibling module + parameter default expression in target. + let param_sib = concat!( + "module other #(parameter int a = 1) (input logic x);\n", + " wire [a-1:0] w = x;\n", + "endmodule\n", + "module leaf #(parameter int P = 1, parameter int Q = P) (\n", + " input logic [Q-1:0] a,\n", + " input logic [Q-1:0] b\n", + ");\n", + "endmodule\n", + "module top;\n", + " logic x, y;\n", + " leaf #(.P(1)) u_leaf (.a(x), .b(y));\n", + "endmodule\n", + ); + let ws_param = ws(&[("/rtl/param_sib.sv", param_sib)]); + let pa = at_after(param_sib, "input logic [Q-1:0]", "a"); + let pa_offers = port_offers(&ws_param, Path::new("/rtl/param_sib.sv"), pa); + assert_eq!(pa_offers.len(), 1, "{pa_offers:?}"); + let pa_ok = remove_port(&ws_param, Path::new("/rtl/param_sib.sv"), pa) + .expect("sibling param `a` and sibling .a(x) must not block removing unused port `a`"); + assert!(apply(param_sib, &pa_ok, "/rtl/param_sib.sv").contains("leaf #(.P(1)) u_leaf (.b(y));")); +} + +// --------------------------------------------------------------------------- +// 5. CRLF preservation in extract (#39) +// --------------------------------------------------------------------------- + +#[test] +fn qa_extract_crlf_with_imports_params_ports_comments_and_no_trailing_eol() { + let pkg = "package my_pkg;\r\n typedef logic [7:0] byte_t;\r\nendpackage\r\n"; + let crlf_full = concat!( + "module top\r\n", + " import my_pkg::*;\r\n", + "#(\r\n", + " parameter int W = 8\r\n", + ") (\r\n", + " input byte_t a,\r\n", + " input byte_t b,\r\n", + " output logic [W-1:0] y\r\n", + ");\r\n", + " byte_t s;\r\n", + " // extract this comment\r\n", + " /* block\r\n", + " comment */\r\n", + " assign s = a + b + W[7:0];\r\n", + " assign y = s;\r\n", + "endmodule", // NO trailing CRLF! + ); + let start = at(crlf_full, "// extract this comment"); + let end = at(crlf_full, " assign y") - 2; // end of `assign s = ...;` before `\r\n` + let files = ws(&[("/rtl/pkg.sv", pkg), ("/rtl/top.sv", crlf_full)]); + + for home in [Home::SameFile, Home::NewFile] { + let edit = extract_module(&files, Path::new("/rtl/top.sv"), start, end, "sub_blk", home) + .expect("crlf full extract succeeds"); + for (path, _) in &edit.edits { + let base = if path == Path::new("/rtl/top.sv") { crlf_full } else { "" }; + let after = apply(base, &edit, path.to_str().unwrap()); + assert!(after.contains("\r\n"), "{path:?}: expected CRLF"); + assert_no_bare_lf(&after, &format!("{home:?} {path:?}")); + } + } + + // LF control must emit zero `\r`. + let lf = crlf_full.replace("\r\n", "\n"); + let lf_start = at(&lf, "// extract this comment"); + let lf_end = at(&lf, " assign y") - 1; + let lf_files = ws(&[("/rtl/pkg.sv", &pkg.replace("\r\n", "\n")), ("/rtl/top.sv", &lf)]); + for home in [Home::SameFile, Home::NewFile] { + let edit = + extract_module(&lf_files, Path::new("/rtl/top.sv"), lf_start, lf_end, "sub_blk", home) + .expect("lf full extract succeeds"); + for (path, _) in &edit.edits { + let base = if path == Path::new("/rtl/top.sv") { lf.as_str() } else { "" }; + let after = apply(base, &edit, path.to_str().unwrap()); + assert_no_cr(&after, &format!("LF {home:?} {path:?}")); + } + } +} + +#[test] +fn qa_extract_crlf_zero_ports_zero_params() { + let crlf_empty = + concat!("module top;\r\n", " wire a;\r\n", " assign a = 1'b1;\r\n", "endmodule\r\n",); + let start = at(crlf_empty, "wire a;"); + let end = at(crlf_empty, "endmodule") - 2; + let files = ws(&[("/rtl/top.sv", crlf_empty)]); + for home in [Home::SameFile, Home::NewFile] { + let edit = extract_module(&files, Path::new("/rtl/top.sv"), start, end, "inner_m", home) + .expect("zero-port extract succeeds"); + for (path, _) in &edit.edits { + let base = if path == Path::new("/rtl/top.sv") { crlf_empty } else { "" }; + let after = apply(base, &edit, path.to_str().unwrap()); + assert!(after.contains("\r\n"), "{path:?}"); + assert_no_bare_lf(&after, &format!("zero-port {home:?} {path:?}")); + } + } +} + +// --------------------------------------------------------------------------- +// 6. Preflight parity on duplicate-unit member (#53 handshake check) +// --------------------------------------------------------------------------- + +#[test] +fn qa_preflight_same_name_inside_duplicate_unit_matches_rename() { + let dup = "module dup (input logic clk);\n wire sig;\nendmodule\n"; + let files = ws(&[("/rtl/dup_a.sv", dup), ("/rtl/dup_b.sv", dup)]); + let off = at_after(dup, "wire", "sig"); + let sem = analyze(&parse_source_tolerant(dup).0, dup); + let fast = rename_preflight(&sem, off, "sig"); + let slow = rename(&files, Path::new("/rtl/dup_a.sv"), off, "sig"); + match (&fast, &slow) { + (Err(f), Err(s)) => assert_eq!(f, s, "preflight and rename must refuse in the same words"), + (Err(f), Ok(_)) => panic!("preflight invented refusal {f:?}"), + (Ok(()), _) => {} + } + assert!(fast.is_ok(), "preflight must defer same-name inside module to ambiguity check"); + assert!( + slow.as_ref().is_err_and(|e| e.contains("`dup`") && e.contains("more than one")), + "{slow:?}" + ); + + // Verify nested generate, interface, package, typedef struct, and class members + // all defer same-name rename_preflight rather than jumping `ambiguous(unit)`. + let nested = concat!( + "module dup;\n", + " generate if (1) begin : g\n", + " logic deep;\n", + " end endgenerate\n", + "endmodule\n", + ); + let dup_if = "interface bus_if (input logic clk); logic req; endinterface\n"; + let dup_pkg = "package pk; localparam int W = 8; endpackage\n"; + let dup_td = "typedef struct packed { logic f; } my_s_t;\n"; + let dup_cls = "class item; int val; endclass\n"; + for (src, prefix, name, unit) in [ + (nested, "logic", "deep", "dup"), + (dup_if, "logic", "req", "bus_if"), + (dup_pkg, "int", "W", "pk"), + (dup_td, "logic", "f", "my_s_t"), + (dup_cls, "int", "val", "item"), + ] { + let off = at_after(src, prefix, name); + let sem = analyze(&parse_source_tolerant(src).0, src); + let fast = rename_preflight(&sem, off, name); + assert!(fast.is_ok(), "preflight must defer `{name}` in `{unit}`: {fast:?}"); + let ws_dup = ws(&[("/rtl/a.sv", src), ("/rtl/b.sv", src)]); + let slow = rename(&ws_dup, Path::new("/rtl/a.sv"), off, name) + .expect_err("duplicate enclosing unit must refuse"); + assert!(slow.contains(&format!("`{unit}`")) && slow.contains("more than one"), "{slow}"); + } +} + +#[test] +fn qa_preflight_parity_sweep_unit_local_vs_duplicate_module_nested_members() { + use vlog_refactor::rename_name_at; + + // 1. `$unit`-level function local & arg renamed to themselves must refuse from buffer, + // while `$unit`-level var/localparam still never invent refusals across every byte. + let unit_src = concat!( + "logic u_var;\n", + "localparam int U_P = 4;\n", + "function automatic int u_fn(int u_arg);\n", + " int u_local;\n", + " u_local = u_arg + U_P;\n", + " return u_local;\n", + "endfunction\n", + ); + let unit_ws = ws(&[("/rtl/unit_fn.sv", unit_src)]); + let unit_sem = analyze(&parse_source_tolerant(unit_src).0, unit_src); + for (prefix, name) in [("int", "u_arg"), ("int", "u_local"), ("return", "u_local")] { + let off = at_after(unit_src, prefix, name); + let fast = rename_preflight(&unit_sem, off, name).expect_err("unit fn local/arg same name"); + let slow = + rename(&unit_ws, Path::new("/rtl/unit_fn.sv"), off, name).expect_err("slow same name"); + assert_eq!(fast, format!("`{name}` is the name it already has.")); + assert_eq!(fast, slow); + } + + // 2. Duplicated `module dup` with nested `generate`, `function`, `class` (plus unique `uniq`) + // — sweep every byte offset and new name (including the symbol's own name). + let dup_src = concat!( + "module dup (input logic clk);\n", + " generate if (1) begin : g\n", + " logic g_sig;\n", + " end endgenerate\n", + " function automatic int fn(int fn_arg);\n", + " int fn_loc;\n", + " fn_loc = fn_arg;\n", + " return fn_loc;\n", + " endfunction\n", + " class inner_c;\n", + " int c_field;\n", + " function int c_meth(int m_arg);\n", + " int m_loc;\n", + " m_loc = c_field + m_arg;\n", + " return m_loc;\n", + " endfunction\n", + " endclass\n", + "endmodule\n", + "module uniq;\n", + " function automatic int ok_fn(int ok_arg);\n", + " int ok_loc;\n", + " ok_loc = ok_arg;\n", + " return ok_loc;\n", + " endfunction\n", + "endmodule\n", + ); + let dup_other = "module dup (input logic clk);\nendmodule\n"; + let dup_ws = ws(&[("/rtl/dup_a.sv", dup_src), ("/rtl/dup_b.sv", dup_other)]); + let dup_sem = analyze(&parse_source_tolerant(dup_src).0, dup_src); + + // Explicit same-name checks inside `dup` for generate/function/class members. + for (prefix, name) in [ + ("begin :", "g"), + ("logic", "g_sig"), + ("int", "fn_arg"), + ("int", "fn_loc"), + ("return", "fn_loc"), + ("class", "inner_c"), + ("int", "c_field"), + ("int", "m_arg"), + ("int", "m_loc"), + ("m_loc =", "c_field"), + ] { + let off = at_after(dup_src, prefix, name); + let fast = rename_preflight(&dup_sem, off, name); + assert!(fast.is_ok(), "must defer same-name `{name}` inside dup: {fast:?}"); + let slow = rename(&dup_ws, Path::new("/rtl/dup_a.sv"), off, name) + .expect_err("dup member must refuse"); + assert!(slow.contains("`dup`") && slow.contains("more than one"), "{slow}"); + } + + // Full byte-by-byte oracle sweep on both files. + for (ws_ref, file, src, sem) in [ + (&unit_ws, "/rtl/unit_fn.sv", unit_src, &unit_sem), + (&dup_ws, "/rtl/dup_a.sv", dup_src, &dup_sem), + ] { + let index = WorkspaceIndex::build(ws_ref.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let external = resolve_external(sem, &index); + for offset in 0..=src.len() as u32 { + let prep_whole = prepare_rename(ws_ref, Path::new(file), offset); + let prep_here = prepare_rename_here(sem, &external, &index, offset); + match (&prep_whole, &prep_here) { + (Ok(w), Ok(h)) => assert_eq!(w, h, "{file}@{offset}"), + (Err(w), Err(h)) => assert_eq!(w, h, "{file}@{offset}"), + (Err(_), Ok(_)) => {} + (Ok(w), Err(h)) => { + panic!("{file}@{offset}: invented prepare refusal: {w:?} vs {h:?}") + } + } + + let here = rename_name_at(sem, offset); + let mut names = vec!["", "module", "1bad", "has space", "renamed_thing"]; + if let Some(n) = &here { + names.push(n.as_str()); + } + for new_name in names { + let fast = rename_preflight(sem, offset, new_name); + let slow = rename(ws_ref, Path::new(file), offset, new_name); + match (&fast, &slow) { + (Err(f), Err(s)) => assert_eq!(f, s, "{file}@{offset}->{new_name:?}"), + (Err(f), Ok(_)) => { + panic!("{file}@{offset}->{new_name:?}: preflight invented refusal {f:?}") + } + (Ok(()), _) => {} + } + } + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/tests/qa_rename_implicit.rs b/crates/vlog_refactor/tests/qa_rename_implicit.rs index 5bb7049..bc380f4 100644 --- a/crates/vlog_refactor/tests/qa_rename_implicit.rs +++ b/crates/vlog_refactor/tests/qa_rename_implicit.rs @@ -301,7 +301,7 @@ fn qa_a_port_rename_into_a_module_declared_twice_is_refused() { let top = "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n"; let files = [("leaf.sv", LEAF), ("leaf_copy.sv", LEAF), ("top.sv", top)]; let refusal = renamed(&files, "leaf.sv", "[7:0] ", "d", "din").expect_err("refused"); - assert!(refusal.contains("u_leaf"), "{refusal}"); + assert!(refusal.contains("`leaf`") && refusal.contains("more than one"), "{refusal}"); } #[test] diff --git a/crates/vlog_refactor/tests/rename.rs b/crates/vlog_refactor/tests/rename.rs index 51f8c44..cdf2912 100644 --- a/crates/vlog_refactor/tests/rename.rs +++ b/crates/vlog_refactor/tests/rename.rs @@ -1368,4 +1368,46 @@ fn a_file_whose_only_relationship_to_the_name_is_a_macro_argument_is_warned_abou ); } +#[test] +fn renaming_a_member_inside_a_duplicate_unit_refuses_while_distinct_packages_still_rename() { + const DUP_A: &str = concat!( + "module dup (input logic clk);\n", + " wire sig;\n", + " begin : blk\n", + " logic inner;\n", + " end\n", + "endmodule\n", + ); + const DUP_PKG: &str = "package dup_pkg;\n class item;\n int val;\n endclass\nendpackage\n"; + let dup_files = workspace(&[ + ("dup_a.sv", DUP_A), + ("dup_b.sv", DUP_A), + ("pkg_a.sv", DUP_PKG), + ("pkg_b.sv", DUP_PKG), + ]); + + for (prefix, name) in [("input logic", "clk"), ("wire", "sig"), ("logic", "inner")] { + let at_decl = at(DUP_A, prefix, name); + let prep = prepare_rename(&dup_files, &path("dup_a.sv"), at_decl) + .expect_err("duplicate module member must refuse prepare"); + assert!(prep.contains("`dup`") && prep.contains("more than one"), "{prep}"); + let msg = rename(&dup_files, &path("dup_a.sv"), at_decl, "renamed") + .expect_err("duplicate module member must refuse rename"); + assert_eq!(msg, prep); + } + + let pkg_at = at(DUP_PKG, "int", "val"); + let pkg_msg = rename(&dup_files, &path("pkg_a.sv"), pkg_at, "renamed") + .expect_err("duplicate package nested class member must refuse"); + assert!(pkg_msg.contains("`dup_pkg`") && pkg_msg.contains("more than one"), "{pkg_msg}"); + + // Control: distinct non-duplicated packages each defining `class item { int val; }` succeed. + const P1: &str = "package pkg1;\n class item;\n int val;\n endclass\nendpackage\n"; + const P2: &str = "package pkg2;\n class item;\n int val;\n endclass\nendpackage\n"; + let distinct = workspace(&[("p1.sv", P1), ("p2.sv", P2)]); + let edit = rename(&distinct, &path("p1.sv"), at(P1, "int", "val"), "next_val") + .expect("distinct non-duplicated packages must remain renameable"); + assert!(apply(P1, &edit, &path("p1.sv")).contains("int next_val;")); +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/tests/rename_macro_carry.rs b/crates/vlog_refactor/tests/rename_macro_carry.rs index 5d826a0..77a8a07 100644 --- a/crates/vlog_refactor/tests/rename_macro_carry.rs +++ b/crates/vlog_refactor/tests/rename_macro_carry.rs @@ -139,4 +139,30 @@ endmodule assert!(!said(&warnings, "other.sv", 3), "{warnings:#?}"); } +#[test] +fn mutually_recursive_binder_macros_deterministically_warn() { + let defs = concat!( + "`define A(sig) `B(sig)\n", + "`define B(sig) `A(sig) `BIND_M\n", + "`define BIND_M bind m chk u_chk (.s(state_q));\n", + ); + let chk = "module chk (input logic s);\nendmodule\n"; + let user = "module user;\n logic state_q;\n initial `A(state_q)\nendmodule\n"; + let warnings = warnings_of(&[("defs.svh", defs), ("chk.sv", chk), ("user.sv", user)]); + assert!(said(&warnings, "user.sv", 3), "{warnings:#?}"); +} + +#[test] +fn escaped_multibyte_utf8_strings_in_macros_and_modules_do_not_panic() { + let defs = "`define CALL(msg, sig) $display(msg); force u_m.sig = 1'b0;\n"; + let top = concat!( + "module top;\n", + " logic state_q;\n", + " initial `CALL(\"\\é \\中 `FAKE\", state_q)\n", + "endmodule\n", + ); + let warnings = warnings_of(&[("defs.svh", defs), ("top.sv", top)]); + assert!(said(&warnings, "top.sv", 3), "{warnings:#?}"); +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/docs/features/refactor-correctness-r1/README.md b/docs/features/refactor-correctness-r1/README.md new file mode 100644 index 0000000..0c854d0 --- /dev/null +++ b/docs/features/refactor-correctness-r1/README.md @@ -0,0 +1,148 @@ + + +# refactor-correctness-r1 + +## Goal + +Fix five correctness, panic, and determinism issues in `vlog_refactor`: +1. **UTF-8 char-boundary panic in `skip_string` & callers** (`rename/home.rs`, `rename/carry.rs`): advancing past a backslash escape in `"\\é"` or `"\\中"` with `i += 2` lands mid-codepoint and panics subsequent string slices. +2. **SipHash nondeterminism and cycle-memoization bug in `carry.rs`**: `HashMap`/`HashSet` iteration order combined with memoizing cycle-tainted `false` results in `Walk::is_binder` (and order-sensitive recursion in `Walk::formals_of`) produces non-deterministic carrier sets for mutually recursive macros. +3. **Duplicate-unit member rename ambiguity (`#53`)** (`rename/mod.rs`): `renameable_here` and `Scope::declaration` previously checked `index.units(&name).len() > 1` only for `file_scope` symbols; renaming a member/port/block declared inside a file-scope unit (`module`/`interface`/`package`/`class`/`typedef`) whose unit name appears more than once in `index.units` (matching kind) must refuse unambiguously with `ambiguous(unit_name)`. +4. **Cross-module same-file `.port(...)` false body-use hit (`#38`)** (`ports/remove.rs`): `body_uses_in` previously treated all `semantics.references_of(id)` in the file as body uses of the target module, including `.port(...)` connections on instances in another module in the same file. +5. **CRLF preservation in `extract` (`#39`)** (`extract/render.rs`, `extract/mod.rs`): preserve `\r\n` vs `\n` from the source file across the extracted module, replacement instantiation, and `\r\n\r\n` same-file insertion. + +## Assumptions + +- `Semantics::file_scope()` owns all units indexed by `WorkspaceIndex::units(name)` (`Module`, `Interface`, `Package`, `Typedef`, `Class`), matching `vlog_semantic/src/workspace/record.rs::is_unit`. +- Unit-kind matching treats `Module`/`Interface` (`is_instantiable()`) as sharing the instantiable namespace (matching `ports/find.rs:52`) while keeping `Package`, `Class`, and `Typedef` distinct by `SymbolKind`, so a `package pk` and `module pk` in the same workspace (`top_rooted_paths::qa_f1_*`) are not treated as duplicate declarations of one unit, and two non-duplicated packages `pkg1`/`pkg2` with identically named classes/members remain renameable. +- Source files using CRLF consistently contain `\r\n`; mixed line-ending files default to `\r\n` when any `\r\n` is present (matching `rename/layout.rs`), and instantiation line endings are normalized in `extract/render.rs` because `instantiate::InstantiationPlan::render_with` is outside this task's file ownership. + +## Handshakes + +- **`rename/preflight.rs` (`declared_here`)** (implemented in Round 1 Lane 1A QA-fix pass): + - Shares `super::enclosing_unit` with `Scope::declaration` (`rename/mod.rs`) so `declared_here` defers (`Ok(())`) before `already_named` whenever `enclosing_unit(semantics, declaration).is_some()` (both file-scope declarations and declarations inside file-scope units). This keeps `rename_preflight` one-directionally consistent with `rename` on duplicate-unit members (`qa_correctness_r1::qa_preflight_same_name_inside_duplicate_unit_matches_rename`). `crates/vlog_refactor/tests/preflight_oracle.rs::renaming_a_symbol_to_the_name_it_already_has_is_refused_from_the_buffer` was updated to test buffer-only `already_named` outside file-scope units (a `$unit` function local) and deferral inside file-scope units (`module sub`). +- **`lucisv_server/src/same_file.rs` (`renamed_here`)** (assigned to Lane 1B — untouched here): + - `same_file.rs:179-197` treats symbols with `symbol.scope != file_scope()` as eligible for single-file fast-path `prepareRename` when the workspace index is not consulted. Lane 1B owns updating `same_file.rs` for QA finding F2b so single-file `prepareRename` defers members inside file-scope units to match settled `prepare_rename_here`. +- **`lucisv_mcp/src/tools/find.rs` (`engine_refusal`)**: + - Translates `"which declaration this rename means"` to `"which declaration this position means"`. Reusing `ambiguous(enclosing_unit)` preserves exact parity across `rename::prepare_rename`, `rename::prepare_rename_here`, `Scope::declaration`, and `lucisv_mcp`'s `find_references`. +- **`crates/vlog_refactor/tests/qa_rename_implicit.rs` (`qa_a_port_rename_into_a_module_declared_twice_is_refused`)**: + - Previously, renaming a port inside duplicated `module leaf` passed `Scope::declaration` and failed downstream in `connections.rs` with ``"`u_leaf` at top.sv:2 connects with `.*` to `leaf`, which lucisv cannot read..."``. With `#53` fixed, `Scope::declaration` now refuses upfront with ``"`leaf` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."``; the test assertion was updated accordingly (while `rename_implicit::a_wildcard_into_a_module_declared_twice_is_refused`, which renames in `top.sv` rather than `leaf.sv`, still exercises the `u_leaf` wildcard refusal unchanged). +- **`crates/vlog_refactor/src/instantiate.rs`**: + - `InstantiationPlan::render_with` emits `\n`. `extract/render.rs::instantiation` converts emitted `\n` to `\r\n` when the source uses CRLF so `instantiate.rs` stays untouched. + +## Status / TODO + +- [x] Fix UTF-8 char-boundary handling in `rename/home.rs` and `rename/carry.rs` +- [x] Replace `HashMap`/`HashSet` and cycle-tainted memoization in `rename/carry.rs` with `BTreeMap`/`BTreeSet` + monotonic fixed-point computation +- [x] Refuse renames inside duplicated file-scope units in `rename/mod.rs` (`renameable_here` and `Scope::declaration`) +- [x] Filter `ports/remove.rs::body_uses_in` references to `module_span(module)` +- [x] Preserve source line endings (`\r\n` vs `\n`) in `extract/render.rs` and `extract/mod.rs` +- [x] Add/update regression tests in `crates/vlog_refactor/tests/` and inline unit tests +- [x] Fix QA F1 (`ports/remove.rs`, `ports/offer.rs`): pass `find_module`'s full `module ... endmodule` span into `body_uses_in` so empty-body modules check header port default expressions +- [x] Fix QA F2a (`rename/preflight.rs`, `rename/mod.rs`): share `enclosing_unit` in `declared_here` so same-name renames inside file-scope units defer to the ambiguity check +- [x] Pass formatting, clippy, full test suite, and author-stamp check + +## Work log + +- Changed `rename/home.rs::skip_string` to accept `&str` and step past escaped multi-byte UTF-8 characters (`1 + char::len_utf8`), and guarded string/slice indexing in `home.rs` (`includes_in`, `macro_names`, `skip_string`) and `carry.rs` (`invocations`, `split_arguments`) with `.get(..)` and UTF-8 character stepping. +- Changed `carry::Defs`, `Carriers::formals`, and `Carriers::binders` from `HashMap`/`HashSet` to `BTreeMap`/`BTreeSet`; replaced `Walk::is_binder` and `Walk::formals_of` with order-independent monotonic fixed-point loops (`find_binders` least fixed point and `compute_formals` greatest fixed point so cycles remain carried/`true`). +- Added `enclosing_unit` and `is_duplicate_unit` in `rename/mod.rs`, shared between `renameable_here` and `Scope::declaration`, refusing members/ports/blocks inside duplicated same-kind file-scope units with `ambiguous(unit)`. +- Filtered `ports/remove.rs::body_uses_in` references to `module_span(module)` so `.port(...)` connections in other modules within the same file are ignored. +- Threaded `line_ending(text)` (`\r\n` vs `\n`) through `extract/mod.rs` (`ensure_newline`, `module_text`, `instantiation`, and `{eol}{eol}{module_text}` same-file insertion) and `extract/render.rs` (`new_module`, `instantiation`). +- Added regression unit and integration tests in `rename/home.rs`, `rename/carry.rs`, `tests/rename_macro_carry.rs`, `tests/rename.rs`, `tests/ports.rs`, and `tests/extract.rs`, and updated `tests/qa_rename_implicit.rs`. +- Production non-blank non-comment line counts (`<= 600` limit): + - `crates/vlog_refactor/src/rename/home.rs`: 211 lines + - `crates/vlog_refactor/src/rename/carry.rs`: 233 lines + - `crates/vlog_refactor/src/rename/mod.rs`: 495 lines + - `crates/vlog_refactor/src/ports/remove.rs`: 288 lines + - `crates/vlog_refactor/src/extract/render.rs`: 322 lines + - `crates/vlog_refactor/src/extract/mod.rs`: 409 lines + +### 2026-11-26 — Round 1 Lane 1A QA-fix pass (F1 & F2a) + +- **QA F1 (`crates/vlog_refactor/src/ports/remove.rs`, `crates/vlog_refactor/src/ports/offer.rs`)**: Removed `module_span(module)` and updated `body_uses_in` to take `module_range: TextRange` directly from `find_module`'s `item.span` (which covers the entire `module ... endmodule` declaration including header ports and default expressions while excluding sibling modules in the same file). Updated both `plan_remove` (`ports/remove.rs`) and `removal` (`ports/offer.rs`) to pass that range. +- **QA F2a (`crates/vlog_refactor/src/rename/mod.rs`, `crates/vlog_refactor/src/rename/preflight.rs`)**: Promoted `enclosing_unit` to `pub(super) fn` in `rename/mod.rs` and updated `declared_here` in `rename/preflight.rs` to defer (`Ok(())`) whenever `enclosing_unit(semantics, declaration).is_some()`, matching `Scope::declaration`'s ambiguity-before-`already_named` ordering without duplicating logic. +- Updated `crates/vlog_refactor/tests/preflight_oracle.rs::renaming_a_symbol_to_the_name_it_already_has_is_refused_from_the_buffer` to verify `already_named` still refuses from buffer outside file-scope units (`$unit` function local) and defers for declarations inside file-scope units (`module sub`). +- Un-ignored and expanded `crates/vlog_refactor/tests/qa_correctness_r1.rs::qa_remove_port_empty_body_module_with_default_expr_using_removed_port` and `qa_preflight_same_name_inside_duplicate_unit_matches_rename`. +- Updated production non-blank non-comment line counts (`<= 600` limit): + - `crates/vlog_refactor/src/rename/home.rs`: 211 lines + - `crates/vlog_refactor/src/rename/carry.rs`: 233 lines + - `crates/vlog_refactor/src/rename/mod.rs`: 495 lines + - `crates/vlog_refactor/src/rename/preflight.rs`: 33 lines + - `crates/vlog_refactor/src/ports/remove.rs`: 283 lines + - `crates/vlog_refactor/src/ports/offer.rs`: 286 lines + - `crates/vlog_refactor/src/extract/render.rs`: 322 lines + - `crates/vlog_refactor/src/extract/mod.rs`: 409 lines + +## QA log + +### 2026-11-26 — QA agent: FAIL — core fixes 1/2/5 hold, two concrete findings on #38 (`module_span`) and #53 (`preflight` / `same_file` handshakes) + +**Verdict: FAIL.** Two concrete findings (F1 inside owned `ports/remove.rs`, F2 in the `#53` handshakes noted as untouched by DEV). Fixes 1 (UTF-8 `skip_string`), 2 (`carry.rs` determinism), and 5 (`extract` CRLF) survived every adversarial attack. + +#### Findings + +- **F1 (BLOCKING — `crates/vlog_refactor/src/ports/remove.rs:248-251`):** `module_span(module)` computes `end = module.items.last().map_or(module.name_span.end, |item| item.span.end)` and returns `TextRange::new(module.name_span.start, end.max(module.name_span.end))`. When `module.items` is empty (e.g., `module leaf (\n input logic a,\n input logic b = a\n);\nendmodule\n`), `module_span` covers only `leaf` (`name_span`), excluding the port header. As a result, `body_uses_in` (`ports/remove.rs:223-227`) fails to find port `a` (`module_range.contains(s.name_span.start)` is `false`) and returns `Vec::new()`: + - `port_offers` (`crates/vlog_refactor/src/ports/offer.rs:302`) falsely offers `"lucisv: remove port `a` (no instantiation in scope)"` despite `b = a` using `a`. + - `remove_port` bypasses the `"is still used inside ..."` refusal and fails later in `verify_splice` with `"removing port `a` from `leaf` would change what `a` means in leaf.sv; no edits were made."` instead of ``"`a` is still used inside `leaf` at leaf.sv:3; remove those uses first."``. + - Reproduction: `crates/vlog_refactor/tests/qa_correctness_r1.rs::qa_remove_port_empty_body_module_with_default_expr_using_removed_port` (`#[ignore = "QA finding 1..."]`; `find_module` at `ports/find.rs:95` already returns the full `item.span` covering `module ... endmodule`, which `ports/remove.rs:99` and `ports/offer.rs:298` currently discard). + +- **F2 (BLOCKING — `#53` parity breaks in `crates/vlog_refactor/src/rename/preflight.rs:79-81` and `crates/lucisv_server/src/same_file.rs:196`):** Both files were left untouched by DEV under strict file ownership and documented in `## Handshakes`, but `#53` breaks their invariants with concrete user-visible mismatches: + - **F2a (`crates/vlog_refactor/src/rename/preflight.rs:79-81`):** `declared_here` only skips `already_named` when `declaration.scope == semantics.file_scope()`. With `Scope::declaration` now rejecting members inside duplicated file-scope units before `already_named`, renaming a member `sig` to `"sig"` inside duplicated `module dup` returns `Err("`sig` is the name it already has.")` from `rename_preflight` while `rename` returns `Err("`dup` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.")`. Since `crates/lucisv_server/src/rename.rs:85` calls `rename_preflight` first, the LSP server returns the wrong refusal. + - Reproduction: `crates/vlog_refactor/tests/qa_correctness_r1.rs::qa_preflight_same_name_inside_duplicate_unit_matches_rename` (`#[ignore = "QA finding 2..."]`). + - **F2b (`crates/lucisv_server/src/same_file.rs:196`):** `renamed_here` only defers to the workspace index when `symbol.scope == doc.semantics.file_scope()`. With `prepare_rename_here` now reading `index.units(...)` for members inside file-scope units, an early/mid-scan `textDocument/prepareRename` (`ahead.rs`) on `logic d;` in `dup_b.sv` (`module dup; logic d; endmodule`) answers `Ok({"placeholder": "d", ...})` while the settled server refuses with `"lucisv: `dup` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."`. + - Reproduction: Adding `"dup_b.sv"` (already written in `shapes` at `crates/lucisv_server/src/server/tests/fast_actions_differential.rs:245`) to the loop at line 272 fails `early_answers_equal_settled_over_the_locality_shapes` with `differed=3` on `dup_b.sv` line 1 cols 8–9 (`lucisv_server` was immediately reverted so no unowned files remain modified). + +#### Verification Summary + +- **Diff / Ownership / Standards:** + - Modified/added files confined to `crates/vlog_refactor/` (6 prod files, 5 existing test files, new `tests/qa_correctness_r1.rs`) and `docs/features/refactor-correctness-r1/README.md`. + - Production non-blank, non-comment line counts before `mod tests`: `home.rs` 211, `carry.rs` 233, `rename/mod.rs` 495, `ports/remove.rs` 288, `extract/render.rs` 322, `extract/mod.rs` 409 (all `<= 600`). + - Zero `unwrap()`, `expect()`, `panic!`, or `unsafe` in modified production code. + - `python3 tools/stamp_author.py --check`: pass (`would stamp 0 files; left 249 untouched`). +- **Adversarial Checks (`crates/vlog_refactor/src/rename/{home,carry}.rs` + `crates/vlog_refactor/tests/qa_correctness_r1.rs`):** + - UTF-8 `skip_string` (`home.rs`, `carry.rs`): tested `"\\\\"`, `"\\\\\\"`, `"\\é"`, `"\\🚀"`, `"\\` at EOF, multi-line strings in `invocations`/`split_arguments`, and non-ASCII comments/identifiers near strings — all passed without panic. + - Determinism (`carry.rs`): tested 3-cycles (`M1 -> M2 -> M3 -> M1` with binder and cross-position forwarding), reversed key names (`Z3/Z2/Z1`), and reversed definition order across 10 iterations — identical deterministic carrier/warning behavior. + - Duplicate-unit member rename (`rename/mod.rs`): same-named `module m` + `package m` do not collide; two `interface bus_if` files refuse ports/signals/modports; `module bus` + `interface bus` collide; nested `generate`/`for`/`if` inside `dup` refuses; non-duplicated `unique_m` in the same file renames cleanly; duplicate file-scope `typedef struct` and `class` refuse; byte-for-byte `prepare_rename` vs `prepare_rename_here` parity holds on `mixed.sv`. + - `#38` (`ports/remove.rs`): same-file `.p(sig)` in another module + body use of `p` still refuses; same-file positional refuses; same-file `.*` warns; non-ANSI port and nested same-named port succeed; **fails** F1 on empty-body module with `b = a` port default. + - `#39` (`extract/render.rs`, `extract/mod.rs`): CRLF with imports + params + ports + `//` and `/* */` comments + no trailing EOL (`SameFile` & `NewFile`) and zero-port/zero-param CRLF emit zero bare `\n`; LF control emits zero `\r`. +- **Gates (post-final-edit):** + - `cargo fmt -p vlog_refactor -- --check`: pass. + - `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets -- -D warnings`: pass. + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_refactor --all-targets`: pass (`qa_correctness_r1`: 7 passed, 0 failed, 2 ignored for F1/F2a; full `vlog_refactor` suite green). + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_mcp --all-targets`: pass. + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets`: pass. + +### 2026-11-26 — QA re-check (post DEV fix pass): PASS (Lane 1A F1 & F2a resolved; F2b remains with Lane 1B) + +**Verdict: PASS.** Re-verified Round 1, Lane 1A after the DEV fix pass. Both Lane 1A findings (**F1** in `ports/remove.rs` & `ports/offer.rs`, **F2a** in `rename/preflight.rs` & `rename/mod.rs`) are fixed and survived expanded adversarial attacks; **F2b** (`crates/lucisv_server/src/same_file.rs`) remains tracked under Lane 1B per `## Handshakes`. + +#### Re-Verification Summary + +- **Diff / Ownership / Standards:** + - `git status` / `git diff`: only `crates/vlog_refactor/` (8 modified prod files, 6 modified test files, `tests/qa_correctness_r1.rs`) and `docs/features/refactor-correctness-r1/README.md` are modified/untracked. + - Non-blank, non-comment prod lines before `mod tests` (`<= 600`): `extract/mod.rs` 409, `extract/render.rs` 322, `ports/offer.rs` 286, `ports/remove.rs` 283, `rename/carry.rs` 234, `rename/home.rs` 212, `rename/mod.rs` 495, `rename/preflight.rs` 33. + - Zero `unwrap()`, `expect()`, `panic!`, or `unsafe` in modified production code. + - `python3 tools/stamp_author.py --check`: exit 0 (`would stamp 0 files; left 249 untouched`). +- **F1 Attack (`crates/vlog_refactor/src/ports/{remove,offer}.rs`):** + - `qa_correctness_r1::qa_remove_port_empty_body_module_with_default_expr_using_removed_port` runs un-ignored and passes. + - Added `qa_correctness_r1::qa_remove_port_non_ansi_param_default_and_sibling_before_target_edge_cases`: passes across sibling `module top (input logic a)` placed before `leaf` with parameter defaults `P = 8, Q = P + 1` and `b = a` (refuses `a` in `remove_port` & empty `port_offers`, offers & removes `b` while ignoring sibling `.b(y)` in body checks), non-ANSI `(a, b); input logic a; input logic b = a;` + sibling `.a(x), .b(y)`, shared non-ANSI `input logic a, b;` with `port_offers` (`PortOfferKind::Remove`), and sibling parameter `a` alongside target parameter default `Q = P`. +- **F2a Attack (`crates/vlog_refactor/src/rename/{preflight,mod}.rs`):** + - `qa_correctness_r1::qa_preflight_same_name_inside_duplicate_unit_matches_rename` runs un-ignored and passes; all 11 tests in `tests/preflight_oracle.rs` pass. + - Added `qa_correctness_r1::qa_preflight_parity_sweep_unit_local_vs_duplicate_module_nested_members`: passes for `$unit` function local/arg renamed to itself (immediate `already_named`), duplicated `module dup` nested `generate`/`function`/`class` members renamed to themselves (`rename_preflight` defers with `Ok(())` to `ambiguous("dup")`), and full byte-by-byte parity sweeps for `prepare_rename` vs `prepare_rename_here` and `rename_preflight` vs `rename` on both shapes. +- **Guarded Gates (post-final-code-edit):** + - `cargo fmt -p vlog_refactor -- --check`: pass. + - `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p vlog_refactor -p lucisv_server -p lucisv_mcp --all-targets -- -D warnings`: pass (0 warnings in crates). + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_refactor --all-targets`: pass (`qa_correctness_r1`: 11 passed, 0 failed, 0 ignored; `preflight_oracle`: 11 passed, 0 failed; total 765 passed, 0 failed, 6 pre-existing ignored across `corpus`/`opentitan_top_rooted`/`qa_rename_implicit`/`rename_bind`). + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_mcp --all-targets`: pass (388 passed, 0 failed, 4 pre-existing ignored). + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets`: pass (2139 passed, 0 failed, 52 pre-existing ignored). + +## Review + +### 2026-11-26 — Lead review: PASS (merged with Lane 1B in Round 1) + +- Inspected combined diff across `vlog_refactor` and `lucisv_server`; cross-lane handshake F2b (`same_file::renamed_here` + `dup_b.sv` differential check) landed cleanly in Lane 1B and passes together with Lane 1A on trunk. +- Removed stray duplicate `// Author:` line at line 3 of this README. +- Handshakes closed in `docs/topo.md`: `#38`, `#39`, `#53` (engine half). Full `tools/gates.sh` verified green on merged `master`. + + diff --git a/docs/features/server-ordering-r1/README.md b/docs/features/server-ordering-r1/README.md new file mode 100644 index 0000000..de29d78 --- /dev/null +++ b/docs/features/server-ordering-r1/README.md @@ -0,0 +1,137 @@ + + +# Server Ordering, Versioned Edits, and Startup Race Fixes (Round 1) + +## Goal + +Close four ordering and protocol-soundness bugs identified in `docs/topo.md` (`#53`, `#52`, `#61`, `#62`): + +1. **Topo #53 (Startup scan race for workspace-wide mutating requests)**: Hold `textDocument/rename`, `codeAction/resolve`, `workspace/executeCommand`, and `workspace/willRenameFiles` until an active background scan (`self.scanning == true`) finishes completely rather than letting them run mid-scan once `head_owed` clears, while preserving read-only `same_file` fast-action early answers and avoiding O(N) re-drain spinning across scan publishes. +2. **Topo #52 (Versioned `DocumentChanges` edits)**: Track client-announced `i32` buffer versions across `didOpen`, `didChange`, dirty flushes, `didSave`, `didClose`, and large-file reclassification; detect `workspace.workspaceEdit.documentChanges` in `ClientAbilities`; and emit deterministic, sorted `DocumentChanges::Edits` (`OptionalVersionedTextDocumentIdentifier { uri, version }`) in `rename.rs` and `ports.rs`, falling back to `WorkspaceEdit { changes: Some(...), .. }` when unsupported or when no edited buffer carries a version. +3. **Topo #61 (Stale `didChangeConfiguration` replay during staging)**: When `take_the_answer_out_of_held` plucks a pulled `Pending::Configuration` response during startup staging, drop any older `workspace/didChangeConfiguration` notifications sitting earlier in `self.held` so they cannot replay after staging ends and overwrite newer pulled settings, while retaining any pushes that arrived after the pull response. +4. **Topo #62 (Exact state-index oracle in `fast_actions_bursts`)**: Record the server's exact `applied_changes` counter whenever `answered_ahead` emits an early response and assert in `fast_actions_bursts.rs` both `applied >= required` (no skipped affecting state change) and `e == reference_at[applied]` against the single-message reference stream. + +## Assumptions + +- Read-only requests exempted via `same_file` / `viewport` (`answer_from_the_buffer`) remain eligible mid-scan whenever their own preconditions hold; only whole-workspace mutating requests (`textDocument/rename`, `codeAction/resolve`, `workspace/executeCommand`, `workspace/willRenameFiles`) must wait for `self.scanning == false`. +- Unopened on-disk files touched alongside an open versioned buffer in `DocumentChanges::Edits` carry `OptionalVersionedTextDocumentIdentifier { uri, version: None }`, matching LSP 3.16+ semantics (and existing `extract.rs` conventions). When no edited file has an attached version (for instance, direct workspace unit tests or closed-file commands) or when `document_changes` capability is false, `WorkspaceEdit::new(changes)` is used. + +## Handshakes + +- **`crates/lucisv_server/src/server/index.rs` (`waiting_for_this_scan`)**: Untouched per lane file ownership. Whole-scan mutators arriving during `self.scanning == true` are staged into `Server::after_scan` in `server/mod.rs` (checked alongside `held` in `must_wait`, `must_hold`, `ahead.rs::nothing_unapplied_for`, `ahead.rs::answer_ahead_mid_widen`, `Server::run`, and `server/tests/scan_ordering.rs::settle`) so `waiting_for_this_scan` does not re-drain and re-hold them on each intermediate scan file. A follow-up lane can fold `after_scan` into `index.rs` if desired. +- **`crates/lucisv_server/src/server/probe.rs` (`went_ahead`)**: Untouched per lane file ownership. Exact `applied_changes` recording at `answered_ahead` lives in `#[cfg(test)]` `server/ahead.rs::AHEAD_APPLIED` (`take_ahead_applied()`) paired with `#[cfg(test)] Server::applied_changes` incremented in `server/mod.rs`, `server/startup.rs`, and `server/notification.rs`. A follow-up lane can fold `AHEAD_APPLIED` into `probe::Probe`. +- **`crates/lucisv_server/src/state/buffers.rs` / `server/diagnostics.rs` / `server/large_file.rs`**: Untouched per lane file ownership. Because `Workspace::set_document` rebuilds `Document` without a version parameter, `Server::versions: HashMap` and `Server::sync_document_versions()` re-attach versions after dirty flushes, `didSave(text)`, `apply_settings`, and `take_the_answer_out_of_held`. +- **Remaining `WorkspaceEdit` producers (`imports.rs`, `instantiate.rs`, `extract.rs`, `inline_module.rs`, `code_action.rs`, `file_ops.rs`)**: Untouched beyond lane ownership. `rename.rs` and `ports.rs` now share `ports::encode_edit` and honor `ClientAbilities::document_changes`; follow-up lanes can pass `self.abilities.document_changes` and document versions to `imports`, `instantiate`, `extract`, `inline_module`, `code_action`, and `file_ops::will_rename`. +- **Cross-lane handshake F2b (`crates/lucisv_server/src/same_file.rs` + `server/tests/fast_actions_differential.rs`)**: Lane 1A fixed `#53` in `vlog_refactor::prepare_rename_here` to check `index.units(enclosing_unit)` for symbols inside a file-scope unit (`Module`/`Interface`/`Package`/`Typedef`/`Class`), not only `scope == file_scope`. Updated `same_file::renamed_here` to walk `Semantics` parent scopes up to `file_scope` and defer (`false`) whenever the symbol sits inside a file-scope unit, updated `same_file/tests.rs`, and added `"dup_b.sv"` to `fast_actions_differential::early_answers_equal_settled_over_the_locality_shapes` (passes both before and after Lane 1A merges). + +## Status / TODO + +- [x] Topo #53: Hold workspace-wide mutating requests across `self.scanning` via `after_scan` + `waits_for_whole_scan`. +- [x] Topo #52: Track `Document::version` atomically, parse `workspace.workspaceEdit.documentChanges`, and emit `DocumentChanges::Edits` in `rename.rs` and `ports.rs` via shared `ports::encode_edit` (including non-canonical client URIs and immediate version sync after `flush_dirty` / `flush_buffer`). +- [x] Topo #61: Drain superseded `workspace/didChangeConfiguration` notifications preceding plucked `Pending::Configuration` answers in `take_the_answer_out_of_held`. +- [x] Topo #62: Record exact `applied_changes` on early answers and tighten `fast_actions_bursts.rs` oracle to exact state equality (`e == reference_at[applied]` and `applied >= required`). +- [x] Cross-lane F2b: Align `same_file::renamed_here` with `vlog_refactor::prepare_rename_here` for symbols enclosed by file-scope units and cover `"dup_b.sv"` in `fast_actions_differential.rs`. +- [x] Add regression suite `crates/lucisv_server/src/server/tests/ordering_r1.rs` plus unit tests in `main.rs`, `rename.rs`, and `ports.rs`. + +## Work log + +- Added `AtomicI64` buffer `version` storage (`version()`, `set_version()`) on `Document` in `crates/lucisv_server/src/state/document.rs` without changing `Document: Sync` or existing constructors. +- Added `document_changes_support` in `crates/lucisv_server/src/main.rs` and `ClientAbilities::document_changes` in `crates/lucisv_server/src/server/mod.rs`. +- Added `Server::after_scan`, `Server::versions`, `must_wait_for`, `waits_for_whole_scan`, and `sync_document_versions` in `crates/lucisv_server/src/server/mod.rs`, updating `Server::run`, `process_batch`, `hold`, and `must_hold`. +- Updated `crates/lucisv_server/src/server/startup.rs` (`take_the_answer_out_of_held`) to drain older `DidChangeConfiguration` notifications prior to the last plucked `Pending::Configuration` response while keeping newer pushes intact; updated `crates/lucisv_server/src/server/tests/fast_actions_precondition.rs::what_staging_held_behind_a_push_is_not_released_ahead_of_it` so its test `push(1000)` arrives after `settings_answer(0)` rather than relying on the pre-#61 stale-replay bug. +- Updated `crates/lucisv_server/src/server/notification.rs` and `crates/lucisv_server/src/server/dispatch.rs` to record/sync document versions and dispatch `document_changes` capability to `rename::rename_traced_for` and `ports::{code_actions_for, resolve_for, execute_for}`. +- Extracted shared `ports::encode_edit` helper used by both `ports.rs` and `rename.rs`. +- Tightened `crates/lucisv_server/src/server/tests/fast_actions_bursts.rs` with `ahead::take_ahead_applied()` and `applied >= required` + exact state equality, and added regression tests in `crates/lucisv_server/src/server/tests/ordering_r1.rs`, `rename.rs`, `ports.rs`, and `main.rs`. + +### 2026-11-26 — QA fix pass + F2b handshake + +- **QA F1 (`crates/lucisv_server/src/ports.rs::encode_edit`)**: Matched open documents via `ws.open_documents()` (`doc.path.as_deref() == Some(path)`) instead of canonical `path_to_uri(path)` + `ws.document(&target)`, preserving the client's open URI (`file://localhost/...`, lowercase percent-encoding, etc.) and `doc.version()` across both `DocumentChanges::Edits` and unversioned `changes` maps. Added unit and integration tests in `ports.rs` and `ordering_r1.rs`. +- **QA F2 (`crates/lucisv_server/src/server/{notification,ahead}.rs`)**: Added `self.sync_document_versions()` immediately after `self.flush_dirty()` in `notification.rs` and `self.flush_buffer(&uri)` in `ahead.rs` so `Document::version()` remains `Some(v)` immediately after `didSave(text: None)`, `didClose(other)`, `didChangeWatchedFiles`, or mid-scan buffer flushes. Added regression test `qa_f2_document_version_survives_flush_dirty_and_flush_buffer_immediately` in `ordering_r1.rs`. +- **Cross-lane F2b (`crates/lucisv_server/src/same_file.rs`, `same_file/tests.rs`, `server/tests/fast_actions_differential.rs`)**: Updated `same_file::renamed_here` with `enclosed_by_unit` so `textDocument/prepareRename` defers (`false`) for symbols inside file-scope units (`Module`, `Interface`, `Package`, `Typedef`, `Class`), updated `same_file/tests.rs`, and added `"dup_b.sv"` to `early_answers_equal_settled_over_the_locality_shapes` in `fast_actions_differential.rs`. + +## QA log + +### 2026-11-26 — QA agent (Round 1, Lane 1B) + +**Verdict: FAIL** (two concrete Topo #52 bugs found; Topo #53, Topo #61, and Topo #62 passed all adversarial checks and live OpenTitan probing). + +#### Ownership, hygiene, and size checks + +- **File ownership (`git status` / `git diff --stat`)**: All DEV changes are inside the lane's allowed files (`main.rs`, `ports.rs`, `rename.rs`, `server/{mod,startup,dispatch,notification,ahead}.rs`, `state/document.rs`, `server/tests/{mod,fast_actions_bursts,fast_actions_precondition,scan_ordering,ordering_r1}.rs`, `docs/features/server-ordering-r1/README.md`). QA added 5 passing adversarial regression tests in `crates/lucisv_server/src/server/tests/ordering_r1.rs` (`qa_topo_53_*`, `qa_topo_52_full_version_lifecycle_*`, `qa_topo_61_attack_burst_*`). +- **Production line counts (non-blank, non-comment lines before `mod tests {`)**: All modified production files are `<= 600` lines (`dispatch.rs`: 522, `main.rs`: 400, `ports.rs`: 367, `server/mod.rs`: 311, `notification.rs`: 261, `ahead.rs`: 250, `startup.rs`: 192, `state/document.rs`: 135, `rename.rs`: 88). +- **Safety / author stamps**: `0` occurrences of `unwrap(`, `expect(`, `panic!`, or `unsafe` in modified production code. `python3 tools/stamp_author.py --check` exits `0`. + +#### Verification & adversarial attacks + +1. **Topo #53 (`after_scan` & `waits_for_whole_scan`) — PASS**: + - Inspected `Server::hold`, `must_wait`, `must_wait_for`, `must_hold`, `after_scan` drain in `Server::run`, `waiting_for_this_scan`, `nothing_unapplied_for`, and `answer_ahead_mid_widen`. `held` and `after_scan` remain mutually exclusive across `hold`, `answer_ahead_mid_widen`, and `run`, preserving arrival order on nested `process_batch` scans and avoiding O(N) re-drain spinning (`handed_back <= 1`). + - Added and passed QA tests in `ordering_r1.rs` covering: `$/cancelRequest` arriving in a later burst while `rename` sits in `after_scan`; `$/cancelRequest` in the same burst as `rename` while `head_owed == true` (transitioning `held -> after_scan`); incremental `didChange` behind `rename` in `after_scan` followed by a second incremental `didChange` and mid-scan `didSave` (`rescan_wanted = true`, two scan `end`s before `after_scan` drains). + - **Live OpenTitan 10-spawn probe** (`./tools/guard.sh -m 6 -t 600 -- cargo build --release -p lucisv_server` -> `target/release/lucisv-server --verbose` against `/Users/lucio/repo/opentitan`, `hw/top_englishbreakfast/ip/ast/rtl/adc.sv` line 81 col 42 `rst_adc_ni`, workspace scope with `persist: false` and scratch `/tmp` storage dirs): 5 startup-burst spawns + 5 mid-scan `$/progress` `report` spawns (`4044 files`) all logged `textDocument/rename HELD behind a rescan`, answered strictly after `$/progress` `end`, exited `0`, and returned **10/10 identical** deterministic refusal (`code: -32803`, ``"lucisv: `rst_adc_ni` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."``). `git -C /Users/lucio/repo/opentitan status --porcelain` remained empty. + +2. **Topo #52 (versioned `documentChanges`) — FAIL (2 findings)**: + - Passing lifecycle checks (`qa_topo_52_full_version_lifecycle_open_change_save_empty_change_rename_and_overlay` + `topo_52_session_tracks_versions_and_emits_versioned_document_changes`): `didOpen(v=1)` -> `didChange(v=2)` -> `didSave(None)` -> `didChange(v=3, contentChanges=[])` -> `watched` (`Document::refresh_overlay`) -> `rename` (mixed `Some(3)` and `None`, `changes` fallback when `document_changes=false`), eager `codeAction`, `codeAction/resolve`, `executeCommand` (`workspace/applyEdit`), `largeFile.threshold` reclassification, and `didClose` resetting version to `None` all pass for canonical `file:///` URIs. + - **Finding 1 (Medium/High — wire bug): `crates/lucisv_server/src/ports.rs:555-571` (`encode_edit`) drops document versions and emits unversioned `changes` (or `version: None`) for valid non-canonical `file:` URIs.** + - At `ports.rs:555`, `ws.text_of(path)` resolves open buffers via `d.path.as_deref() == Some(path)` (`state/buffers.rs:103`), whereas `ports.rs:570` computes `target = path_to_uri(path)` and looks up `ws.document(&target).and_then(Document::version)`. + - Whenever the client opened the file with a valid `file:` URI whose serialization differs from `path_to_uri(path)` — e.g. `file://localhost/...` (explicitly supported by `uri.rs:38`), lowercase percent-encoding such as `caf%c3%a9.sv` vs `path_to_uri`'s `%C3%A9`, or Windows VS Code's `file:///c%3A/...` vs `file:///C:/...` — `ws.document(&target)` returns `None`, silently losing the buffer's version (`Some(v)` -> `None`) and falling back to unversioned `changes` (and `target` also fails to echo the client's open URI). + - **Reproduction**: Open `caf%c3%a9.sv` (or `file://localhost//sub.sv`) at `version: 12` with `ClientAbilities { document_changes: true, ..Default::default() }`, then issue `textDocument/rename` on it (or cross-file from `top.sv`). `rename` returns `{"changes": ...}` (or `version: null` for `sub.sv` in cross-file `documentChanges`) instead of `documentChanges` with `version: 12`. + - **Finding 2 (Low/Medium — state invariant leak): `crates/lucisv_server/src/server/notification.rs:71` (`handle_notification` `flush_dirty`) and `crates/lucisv_server/src/server/ahead.rs:195` (`flush_buffer`) rebuild `Document` without re-attaching `self.versions`.** + - `notification.rs:71` runs `self.flush_dirty()` on non-`didChange` notifications such as `didSave` with `text: None` (the default because `main.rs:221` advertises `include_text: Some(false)`), `didClose` of another file, or `didChangeWatchedFiles`. `flush_dirty()` calls `set_document`, replacing the `Document` with `version = NO_VERSION` (`None`). Only `didSave(Some(text))` (`notification.rs:167`) and `apply_settings` (`notification.rs:366`) call `self.sync_document_versions()`. Similarly `ahead.rs:195` (`flush_buffer`) does not sync versions. + - Currently masked on LSP wire requests because `dispatch.rs:172` (`answer_request`) calls `self.sync_document_versions()` before `answer_flushed`, but `Document::version()` on `Workspace` is `None` immediately after `didSave(None)` until the next request or debounce timeout. + - **Reproduction**: `didOpen(uri, v=1)` -> `didChange(uri, v=2, text)` -> `didSave(uri)` (no `text` field). Immediately inspecting `session.server.workspace.document(&uri).unwrap().version()` returns `None` instead of `Some(2)`. + +3. **Topo #61 (`take_the_answer_out_of_held`) — PASS**: + - Tested attack burst `[didOpen, (optional lens), push(A: threshold=0), hover, settings_answer(B: threshold=100), push(C: threshold=4MiB)]` in `qa_topo_61_attack_burst_didopen_push_a_hover_answer_b_push_c`: `B` beats `A` (`hover` sees threshold=100 -> `Null`), `hover` is not dropped, `C` beats `B` once `held` drains (`threshold=4MiB`), and `applied_changes` matches exact applied state transitions (`2`/`3` at staging end, `+1` after `push(C)`). + +4. **Topo #62 (`fast_actions_bursts`) — PASS**: + - Inspected `fast_actions_bursts.rs:403-511`: `ahead_applied` records `self.applied_changes` at `answered_ahead` (`ahead.rs:237`) and asserts both `applied >= required` (prior reaching `can_reach` or config changes) and `e == reference_at[applied]`. + - Ran `fast_actions_bursts` (`1448 requests, 384 answered ahead (0 from a later state), 1280 settled comparisons`), 300-round `answers_given_ahead_equal_a_one_message_at_a_time_server_long_run` (`seed 7: 1313 requests, 400 answered ahead (0 from a later state), 1200 settled comparisons, 0 differ`), and `ordering_random` (`12 seeds × 10 rounds`, pass). + - Verified oracle sensitivity via temporary mutations (reverted immediately): subtracting 1 from `applied` failed immediately at `seed 1, round 0` (`6 answered at applied=1 ahead of reaching change 2`), and skipping `self.flush_buffer(&uri)` in `ahead.rs:195` failed at `seed 2, round 5` (`28 went ahead at applied=4 (required >= 4) with wrong state`). + +#### Full crate gates (worktree, after final edits) + +- `python3 tools/stamp_author.py --check` -> exit 0 +- `cargo fmt -p lucisv_server -- --check` -> exit 0 +- `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p lucisv_server --all-targets -- -D warnings` -> exit 0 +- `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets` -> `2,043` passed (`47` ignored) unit + `106` passed (`3` ignored) e2e + `3` grammar + `1` ifdef_folding + `0` passed (`2` ignored) opentitan_references; `0` failed + +### 2026-11-26 — QA re-check (Round 1, Lane 1B) + +**Verdict: PASS** (F1, F2, and cross-lane F2b all verified fixed; full crate gates green). + +#### Ownership, hygiene, and size checks + +- **File ownership (`git status` / `git diff --stat`)**: Only owned `crates/lucisv_server/` files (`main.rs`, `ports.rs`, `rename.rs`, `same_file.rs`, `same_file/tests.rs`, `server/{mod,startup,dispatch,notification,ahead}.rs`, `state/document.rs`, `server/tests/{mod,fast_actions_bursts,fast_actions_differential,fast_actions_precondition,ordering_r1,scan_ordering}.rs`) and `docs/features/server-ordering-r1/README.md` are modified or untracked. QA added 2 passing re-check regression tests (`qa_r2_f1_*`, `qa_r2_f2_*`) in `crates/lucisv_server/src/server/tests/ordering_r1.rs`. +- **Production line counts (non-blank, non-comment before inline `mod tests {`)**: All modified production files remain `<= 600` lines (`dispatch.rs`: 522, `main.rs`: 400, `ports.rs`: 374, `server/mod.rs`: 311, `notification.rs`: 262, `ahead.rs`: 251, `startup.rs`: 192, `state/document.rs`: 134, `same_file.rs`: 126, `rename.rs`: 88). +- **Safety / author stamps**: `0` occurrences of `unwrap(`, `expect(`, `panic!`, or `unsafe` in modified production code. `python3 tools/stamp_author.py --check` exits `0`. + +#### Re-verification & adversarial attack results + +1. **Attack F1 (`ports.rs::encode_edit`) — PASS**: + - Verified `ws.open_documents().find(|(_, doc)| doc.path.as_deref() == Some(path))` preserves client non-canonical URIs (`file://localhost/...` and lowercase percent-encoded `caf%c3%a9.sv`) and `doc.version()`, while closed files fall back to canonical `path_to_uri(path)` with `version: None`. + - Verified `qa_f1_non_canonical_client_uris_preserve_uri_and_version_in_edits` and QA-added `qa_r2_f1_multifile_rename_open_noncanonical_and_closed_doc_with_and_without_document_changes` pass: multi-file `textDocument/rename` touching one open non-canonical URI (`file://localhost/...` or `caf%c3%a9.sv`) plus one closed file (`version: null`) emits `documentChanges` when enabled and uses the client's open URI as the `changes` map key when `documentChanges` is disabled. + +2. **Attack F2 (`notification.rs` / `ahead.rs` version sync) — PASS**: + - Verified `qa_f2_document_version_survives_flush_dirty_and_flush_buffer_immediately` passes. + - Audited all `Document` reconstruction call sites across `server/` and `state/`: every `Server::set_document`, `flush_dirty`, `flush_buffer`, and `reclassify_large_buffers` caller (`notification.rs`, `ahead.rs`, `dispatch.rs`, `server/mod.rs`, `startup.rs`) immediately runs `record_document_version` or `sync_document_versions()`. + - Verified QA-added `qa_r2_f2_document_version_survives_reclassify_incremental_apply_changes_and_didsave_with_text` passes across incremental `apply_changes_at` + flush, `didSave(text: Some(...))`, and `reclassify_large_buffers` (`normal -> large -> normal`). + +3. **Attack F2b (`same_file.rs::renamed_here` + `fast_actions_differential.rs`) — PASS**: + - Verified `enclosed_by_unit` matches `vlog_semantic`'s 5 unit kinds (`Module`, `Interface`, `Package`, `Typedef`, `Class`) at `file_scope` and walks parent scopes so declarations/uses inside file-scope units wait for the index. + - Confirmed `"dup_b.sv"` runs in `fast_actions_differential::early_answers_equal_settled_over_the_locality_shapes` (`early=3378 waited=614 differed=0`), `same_file::tests::prepare_rename_waits_at_file_scope_inside_units_and_on_an_unresolved_use` passes, and `fast_actions_bursts::answers_given_ahead_equal_a_one_message_at_a_time_server` passes (`1448 requests, 284 answered ahead (0 from a later state), 1280 settled comparisons`). + +#### Full crate gates (worktree, after final edits) + +- `python3 tools/stamp_author.py --check` -> exit 0 +- `cargo fmt -p lucisv_server -- --check` -> exit 0 +- `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p lucisv_server --all-targets -- -D warnings` -> exit 0 +- `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets` -> `2,048` passed (`47` ignored) unit + `106` passed (`3` ignored) e2e + `3` grammar + `1` ifdef_folding + `0` passed (`2` ignored) opentitan_references; `0` failed + +## Review + +### 2026-11-26 — Lead review: PASS (merged with Lane 1A in Round 1) + +- Inspected combined diff across `lucisv_server` and verified `after_scan` exclusivity, non-canonical URI/version tracking in `ports::encode_edit`, immediate `sync_document_versions` after `flush_dirty`/`flush_buffer`, staging push draining (`#61`), exact `applied_changes` oracle (`#62`), and `same_file::renamed_here` parity (`F2b`) with Lane 1A's duplicate-unit check. +- Live 10-spawn OpenTitan `adc.sv:81` probe confirmed 10/10 deterministic refusal with `/Users/lucio/repo/opentitan` untouched. +- Handshakes closed in `docs/topo.md`: `#52`, `#53` (server half), `#61`, `#62`. Full `tools/gates.sh` verified green on merged `master`. + + diff --git a/docs/topo.md b/docs/topo.md index d208c53..ea832da 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -763,8 +763,8 @@ update the filing README(s) and this file. | 35 | **MCP-5 → `vlog_parser`:** lift the server's `expand.rs` (one-step macro expansion) into `vlog_parser::defines` as a pure move so `lucisv-mcp`'s `defines` can offer expansion — *moot since M7: `defines` folded into `find`, which lists a macro's definitions and no expansion* | mcp-navigation | vlog_parser | | 36 | **MCP-6 → `lucisv_server` (possible bug):** LSP `references` omits three real `aes` instantiations in the `*_pd_main.sv` tops (and their `.clk_i` connections) that `lucisv-mcp`'s whole-set answer lists; stable after a 30 s settle, not investigated | mcp-navigation | lucisv_server | | 37 | **MCP-7 → `vlog_refactor`:** a `find_references` variant taking `&dyn KnownFacts` (like `rename_traced_with`) so whole-set callers feed cached records instead of re-parsing 3 944 files (≈2 s per opentitan call today) | mcp-navigation | vlog_refactor | -| 38 | **MCP-8 → `vlog_refactor`:** false `remove_port` refusal when the only "use" of the port is a named connection from another module in the same file (`ports/remove.rs::body_uses_in`) | mcp-edit-tools | vlog_refactor | -| 39 | **MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`) | mcp-edit-tools | vlog_refactor | +| ~~38~~ | ~~**MCP-8 → `vlog_refactor`:** false `remove_port` refusal when the only "use" of the port is a named connection from another module in the same file (`ports/remove.rs::body_uses_in`)~~ — **closed 2026-11-26 by `refactor-correctness-r1` (Round 1):** `body_uses_in` takes `find_module`'s full `module ... endmodule` span (`item.span`) and filters references to that range. | mcp-edit-tools | ~~vlog_refactor~~ done | +| ~~39~~ | ~~**MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`)~~ — **closed 2026-11-26 by `refactor-correctness-r1` (Round 1):** `extract/mod.rs` and `extract/render.rs` detect source `\r\n` vs `\n` and preserve it across new-module, instantiation, and same-file insertion. | mcp-edit-tools | ~~vlog_refactor~~ done | | 40 | **MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; ~~`find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`)~~ — **second half answered 2026-09-30 by generate-label-rename (TODO §65.1, row 43)**; the batched `find_references` stays open | mcp-structural-edits | vlog_refactor, vlog_semantic | | 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter | | 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser | @@ -777,8 +777,8 @@ update the filing README(s) and this file. | 49 | **A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6) | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | vlog_semantic (index removal) / lucisv_server (`state/`) | | 50 | **An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6) | scan-ordering (QA-2) | lucisv_server (`state/scan.rs`, `server/index.rs`) | | 51 | **Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6) | localized-reindex (QA P3); scan-ordering | lucisv_server (`state/discover.rs`, `state/incremental.rs`) | -| 52 | **A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6) | scan-ordering (QA) | lucisv_server (`server/`, `rename.rs`) | -| 53 | **Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6) | scan-ordering (QA-7c) | vlog_refactor / lucisv_server (`module_select.rs`) — undiagnosed | +| ~~52~~ | ~~**A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `Document` tracks client `version: Option`, and `ports::encode_edit` (shared by `rename.rs` and `ports.rs`) emits versioned `DocumentChanges::Edits` preserving open client URIs when `workspace.workspaceEdit.documentChanges` is advertised. | scan-ordering (QA) | ~~lucisv_server (`server/`, `rename.rs`)~~ done | +| ~~53~~ | ~~**Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6)~~ — **closed 2026-11-26 by Round 1 (`refactor-correctness-r1` + `server-ordering-r1`):** `lucisv_server` holds workspace-wide mutating requests (`rename`, `codeAction/resolve`, `executeCommand`, `willRenameFiles`) in `after_scan` across `self.scanning`, and `vlog_refactor::rename` + `preflight` + `same_file::renamed_here` refuse members inside duplicated file-scope units; verified 10/10 deterministic on OpenTitan `adc.sv:81`. | scan-ordering (QA-7c) | ~~vlog_refactor / lucisv_server~~ done | | 54 | **`lucisv-mcp` re-reads a file with a future mtime on every call**, forever (67 ms against 7 ms per `find` on 4 000 files) — the racy rule never settles (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (`project/files.rs`) | | 55 | `crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70) | linux-test-portability (Round 2) | crates/lucisv (tests) | | 56 | `crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (tests) | @@ -786,8 +786,8 @@ update the filing README(s) and this file. | 58 | **The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) | | 59 | **A `range` answered during a rescan always counts as a guess** (`Viewport::guessed`) and costs one refresh at settle even when nothing changed (TODO §71 wave 7) | viewport-highlight (QA) | lucisv_server (`server/viewport.rs`) | | 60 | **An edit in one file that changes how another open file colours sends no refresh** (a package type renamed) — as before this lane (TODO §71 wave 7) | viewport-highlight | lucisv_server (`server/viewport.rs`) | -| 61 | **Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1) | fast-actions (QA) | lucisv_server (`server/startup.rs`) | -| 62 | **`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4) | fast-actions (QA) | lucisv_server (tests) | +| ~~61~~ | ~~**Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `take_the_answer_out_of_held` drains older `DidChangeConfiguration` pushes preceding the plucked pull answer while keeping newer pushes. | fast-actions (QA) | ~~lucisv_server (`server/startup.rs`)~~ done | +| ~~62~~ | ~~**`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `ahead::take_ahead_applied` records exact `applied_changes` and the oracle asserts `applied >= required` and `e == reference_at[applied]`. | fast-actions (QA) | ~~lucisv_server (tests)~~ done | | 63 | **Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8) | fast-actions (QA) | lucisv_server (`state/`, the index lane) | | 64 | **The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8) | fast-actions | undiagnosed (lucisv_server scan) | | 65 | **`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19) | topo refresh (draft discrepancy 10) | CI (lead) |