diff --git a/CLAUDE.md b/CLAUDE.md index eef27cf..11833ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -112,6 +112,27 @@ every non-test production module in the workspace is under 600 (`lexer.rs` `vlog_parser/src/parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs` 535, `lucisv_server/src/server/dispatch.rs` 522, `lucisv_server/src/state/discover.rs` 510). +Re-measured 2026-11-26 after Round 12 (`hygiene-splits-r12`, pure moves; same +rule): no production file exceeds 600. Top production files: +`lucisv/src/main.rs` 574, `vlog_parser/src/parser/module.rs` 568, +`parser/split.rs` 554, `parser/sva.rs` 542, `vlog_refactor/src/extract/flow.rs` +535, `parser/class.rs` 518, `parser/covergroup.rs` 517, +`lucisv_server/src/server/dispatch.rs` 515, `state/discover.rs` 515. The round +split `resolve.rs` (587 → 294; `resolve/member.rs` 196, `types.rs` 115), +`parser/item.rs` (589 → 322; `package.rs` 113, `generate.rs` 160), +`parser/instance.rs` (565 → 353; `connection.rs` 218), `format/stmt.rs` +(570 → 400; `case.rs` 94, `timing.rs` 89) and `lexer.rs` (→ 497; +`lexer/number.rs` 114, `define_params.rs` 105, `attach.rs` 54). The `lexer.rs` +540 above was a counting artifact: a `#[cfg(test)]` *field* at line 723 ended +the count 230 lines early, and the file was still 771. This measurement steps over a `#[cfg(test)]` +that is not the test module; counted that way +`vlog_refactor/src/rename/warnings.rs` is 521 (80 by the bare rule), +`rename/mod.rs` 494 and `lucisv_server/src/state/rescan.rs` 483. Test-only +files over 600 (declared under `#[cfg(test)]`, so not production): `perf.rs` +907 (reasoned), and the test modules the round moved out of their files in +`lucisv_server` — `nav/tests.rs` 1 926, `inline/tests.rs` 1 170, +`pairs/tests.rs` 1 009, `ports/tests.rs` 910 and nine more between 611 and 818. + ## Rust standards - `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]` diff --git a/crates/lucisv_server/src/completion/member.rs b/crates/lucisv_server/src/completion/member.rs index 12e2bf9..be25f2d 100644 --- a/crates/lucisv_server/src/completion/member.rs +++ b/crates/lucisv_server/src/completion/member.rs @@ -377,833 +377,6 @@ fn last_segment(path: &str) -> &str { } #[cfg(test)] -mod tests { - use super::*; - use crate::completion::harness::*; - use crate::completion::*; - - // ------------------------------------------------------------------ - // the member answer (2026-09-02) — after a `.` or a `::` - // ------------------------------------------------------------------ - - /// The buffer most of these ask against: a class chain, a struct, an - /// interface with a modport and a clocking block, and a handle for each. - const MEMBERS: &str = "\ -interface bus_if; - logic clk; - logic [7:0] data; - modport mp (input clk); - clocking cb @(posedge clk); - input data; - endclocking -endinterface - -typedef struct packed { logic [7:0] addr; logic vld; } hdr_t; - -class base_c; - bit from_base; -endclass - -class item_c extends base_c; - bit user_id; - bit feature1; - hdr_t hdr; - function void run(); - endfunction -endclass - -module top; - virtual bus_if vif; - item_c item; - item_c queue[4]; - hdr_t [3:0] hs; - hdr_t h; - initial begin - item. - end -endmodule -"; - - /// The names a member request against [`MEMBERS`] offers, **sorted** — - /// which is the order the client shows them in, because `sortText` is - /// ``. The array order is the cap's order and is pinned - /// separately by [`the_list_is_ordered_nearest_declaration_first`]. - fn member_labels(name: &str, spine: &str) -> Vec { - let mut found: Vec = - items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect(); - found.sort(); - found - } - - /// The whole response, for the tests that read more than the labels. - fn member_response(name: &str, spine: &str) -> Option { - let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n")); - let tree = Tree::new(name); - let (_tree, ws, uri, position) = opened(tree, &top, spine); - completions(&ws, &uri, position, true) - } - - #[test] - fn a_class_handle_lists_its_members_and_its_bases() { - assert_eq!( - member_labels("cls", "item."), - vec!["feature1", "from_base", "hdr", "run", "user_id"], - ); - } - - #[test] - fn the_member_answer_is_exclusive() { - let items = items(member_response("exclusive", "item.")); - // No keyword, no template, no project word — every item is a member, - // and every one of them is filed under the member tier. - for item in &items { - assert_eq!(tier(item), TIER_MEMBER, "{item:#?}"); - assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}"); - assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}"); - assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}"); - } - let found = labels(&items); - assert!(!found.contains(&"always_ff"), "no keywords"); - assert!(!found.contains(&"top"), "no index names"); - assert!(!found.contains(&"vif"), "not even what is visible at the cursor"); - } - - /// A member wins over a same-named local because the answer is exclusive: - /// the local is not a worse candidate here, it is not a candidate. - #[test] - fn a_local_of_the_same_name_is_not_offered_beside_the_member() { - let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n"); - let tree = Tree::new("shadow"); - let (_tree, ws, uri, position) = opened(tree, &top, "item."); - let items = items(completions(&ws, &uri, position, true)); - let user_id = find(&items, "user_id").expect("the member"); - assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE)); - assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1); - } - - #[test] - fn a_nested_struct_field_lists_the_inner_fields() { - assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]); - assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]); - } - - #[test] - fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() { - let found = member_labels("iface", "vif."); - for wanted in ["clk", "data", "mp", "cb"] { - assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}"); - } - } - - /// A clocking block's `type_name` is the interface enclosing it - /// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data` - /// resolve to the interface's own `data` declaration — correct - /// SystemVerilog, since a clocking block names a *view* of those signals - /// and declares nothing of its own. So the list after `vif.cb.` is the - /// interface's, exactly as the resolution is: one walk, one answer, wider - /// than the block's own item list and never wrong about a name. - #[test] - fn a_clocking_block_lists_the_enclosing_interfaces_signals() { - assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif.")); - assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string())); - } - - /// A **packed** array head is indexed away and names its element type's - /// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`. - #[test] - fn a_packed_array_head_is_indexed_away() { - assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]); - assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly"); - } - - /// An **unpacked** declarator answers nothing, and that is - /// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]` - /// names a container, not a value of `item_c`, so no `type_name` is - /// recorded and `q.size()` is an array method rather than a member - /// (`bind.rs::declare_typed`). Completion may not mint a type the - /// resolver refuses to mint — that would be the second resolver this - /// round exists to avoid. Filed as a follow-on in the feature README. - #[test] - fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() { - assert!(member_response("unpacked", "queue[0].").is_none()); - } - - /// The order of the `items` array is the order the cap keeps, and it is - /// **nearest declaration first**: a class's own members before its base's, - /// in declaration order within each. `sortText` still says the client - /// should draw them alphabetically. - #[test] - fn the_list_is_ordered_nearest_declaration_first() { - let items = items(member_response("order", "item.")); - assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]); - for item in &items { - assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str())); - } - } - - #[test] - fn this_and_super_answer_from_inside_a_method() { - let top = - MEMBERS.replace(" function void run();\n", " function void run();\n this.\n"); - let tree = Tree::new("this"); - let (_tree, ws, uri, position) = opened(tree, &top, " this."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]); - - let top = - MEMBERS.replace(" function void run();\n", " function void run();\n super.\n"); - let tree = Tree::new("super"); - let (_tree, ws, uri, position) = opened(tree, &top, " super."); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["from_base"], "super is the base and not the class itself"); - } - - #[test] - fn the_kind_and_the_detail_come_off_the_declaration() { - let items = items(member_response("detail", "item.")); - // In this buffer the declaration's own line is free, so that is the - // card — the same one tier 1 has always shown. - let hdr = find(&items, "hdr").expect("the struct-typed property"); - assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE)); - assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself"); - let run = find(&items, "run").expect("the method"); - assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION)); - assert_eq!(run.detail.as_deref(), Some("function void run();")); - // A method inserts its bare name: the parentheses and the arguments - // are the user's to write, and a completion that invented them would - // be guessing at the call. - assert_eq!(inserted(run), "run"); - assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - } - - /// The edit is an **empty** range at the cursor, so accepting an item - /// writes the member name after the dot and touches nothing before it. - #[test] - fn the_edit_is_empty_at_the_cursor_after_a_separator() { - let items = items(member_response("range", "item.")); - assert!(!items.is_empty()); - for item in &items { - let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { - panic!("a plain edit"); - }; - assert_eq!(edit.range.start, edit.range.end, "{item:#?}"); - assert_eq!(edit.new_text, item.label); - } - } - - /// And with characters typed after the dot it replaces exactly those. - #[test] - fn the_edit_replaces_exactly_what_was_typed_after_the_separator() { - let items = items(member_response("range2", "item.us")); - assert_eq!(labels(&items), vec!["user_id"]); - let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else { - panic!("a plain edit"); - }; - assert_eq!(edit.range.start.character + 2, edit.range.end.character); - } - - #[test] - fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() { - // One and two characters: a prefix, exactly as every other tier does - // below the floor. `fe` reaches `feature1` and not `from_base`. - assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]); - assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]); - // Three: a subsequence, so `fbs` reaches `from_base` — which no - // prefix match ever would. - assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]); - assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]); - } - - /// **The `isIncomplete` rule.** The request that matters — the one the - /// trigger character fires, with nothing typed yet — is complete, so VS - /// Code filters the whole member list client-side. A 1- or 2-character - /// answer is a prefix slice that the third keystroke would *widen*, so it - /// must say it is incomplete or the widening never reaches the client. - #[test] - fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() { - let incomplete = |name: &str, spine: &str| match member_response(name, spine) { - Some(CompletionResponse::List(list)) => list.is_incomplete, - other => panic!("a list, not {other:#?}"), - }; - assert!(!incomplete("inc0", "item."), "the whole list is the whole answer"); - assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character"); - assert!(incomplete("inc2", "item.fe")); - assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks"); - // Even a query nothing matches answers with a list, so the client is - // told to come back rather than left filtering an answer it has not - // got. - assert!(incomplete("inc4", "item.zz")); - let empty = items(member_response("inc5", "item.zz")); - assert!(empty.is_empty()); - } - - /// An **empty** answer is incomplete whatever was typed — including at - /// zero characters, where a non-empty list would be complete. QA finding - /// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not - /// reached the declaring file's directory yet answers empty for one - /// request and correctly for the next, and a *complete* emptiness would - /// be cached by the client until the user retyped the dot. - #[test] - fn an_empty_answer_always_asks_the_client_to_come_back() { - let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n"; - let tree = Tree::new("hollow"); - let (_tree, ws, uri, position) = opened(tree, top, " h."); - match completions(&ws, &uri, position, true) { - Some(CompletionResponse::List(list)) => { - assert!(list.items.is_empty(), "a class with no members"); - assert!(list.is_incomplete, "and the client is asked to come back"); - } - other => panic!("a list, not {other:#?}"), - } - // The same for a connection list whose module nothing declares. - let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n"; - let (_tree, ws, uri, position) = asking("hollowconn", top, " ."); - match completions(&ws, &uri, position, true) { - Some(CompletionResponse::List(list)) => { - assert!(list.items.is_empty()); - assert!(list.is_incomplete); - } - other => panic!("a list, not {other:#?}"), - } - } - - #[test] - fn an_unresolvable_head_answers_nothing_at_all() { - for (name, spine) in [ - ("nohead", "no_such_handle."), - ("call", "f()."), - ("nothing", "."), - ("space", "item ."), - ("untyped", "vif.clk."), - ] { - assert!( - member_response(name, spine).is_none(), - "{spine} must answer nothing, not a guess", - ); - } - } - - /// A lone `:` is a case item, a label or a ternary — not a separator. The - /// request there is the ordinary six-tier one it always was. - #[test] - fn a_lone_colon_falls_through_to_the_ordinary_tiers() { - let top = "module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n"; - let tree = Tree::new("colon"); - let (_tree, ws, uri, position) = opened(tree, top, "1: si"); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}"); - } - - #[test] - fn a_package_lists_its_members_after_a_scope_separator() { - let tree = Tree::new("pkg"); - tree.write( - "p.sv", - "package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n", - ); - let top = "module top;\n initial $display(other_pkg::);\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::"); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert!(found.contains(&"WIDTH"), "{found:?}"); - assert!(found.contains(&"cfg_t"), "{found:?}"); - assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}"); - } - - #[test] - fn a_package_this_file_declares_lists_its_members_too() { - let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n"; - let tree = Tree::new("pkg_local"); - let (_tree, ws, uri, position) = opened(tree, top, "p::"); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["W", "t_t"]); - } - - /// The cross-file half: an in-file class extending a class in another - /// file lists both halves, its own scope first. - #[test] - fn a_base_in_another_file_contributes_its_members() { - let tree = Tree::new("crossfile"); - tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n"); - let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " h."); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["local_field", "shared", "remote_field"]); - // The subclass's `shared` is the one offered — the same first-hit-wins - // rule a lookup applies. - let items = items(completions(&ws, &uri, position, true)); - let shared = find(&items, "shared").expect("the shadowed name"); - assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1); - assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE)); - } - - /// A class whose base the workspace does not declare at all: the chain - /// stops there, and everything known still lists. - #[test] - fn an_absent_base_stops_the_chain_without_losing_what_is_known() { - let tree = Tree::new("nobase"); - let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " h."); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["local_field"]); - } - - /// The other half of the detail rule: a member the *index* holds carries - /// no text, so its card is the kind label plus the declared type — the - /// most a table can say, and no file is read to say it. - #[test] - fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() { - let tree = Tree::new("xdetail"); - tree.write( - "remote.sv", - "class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n", - ); - let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " h."); - let items = items(completions(&ws, &uri, position, true)); - let typed = find(&items, "typed_field").expect("the typed property"); - assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t")); - let plain = find(&items, "plain_field").expect("the untyped property"); - assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add"); - } - - /// A type only another file declares: the whole list comes from the - /// index, inherited members included. - #[test] - fn a_handle_whose_type_is_another_files_lists_from_the_index() { - let tree = Tree::new("remote"); - tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n"); - tree.write( - "item.sv", - "class remote_item extends remote_base;\n bit own_field;\nendclass\n", - ); - let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " h."); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["inherited_field", "own_field"]); - } - - /// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the - /// index holds under the synthesized `reg2hw_t.ctrl` key. - #[test] - fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() { - let tree = Tree::new("reg2hw"); - tree.write( - "regs.sv", - "package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n", - ); - let top = "module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl."); - let answer = items(completions(&ws, &uri, position, true)); - let found = labels(&answer); - assert_eq!(found, vec!["q", "qe"]); - } - - // ------------------------------------------------------------------ - // the connection list (2026-09-02 rework) — `.` inside `sub u (…)` - // ------------------------------------------------------------------ - - /// A module in the buffer, so the in-file half is exercised without the - /// index. Three ports and two parameters, in a shape a user really types. - const WIRING: &str = "\ -module wiring_sub #( - parameter int WIDTH = 8, - parameter int DEPTH = 4 -) ( - input logic clk, - input logic [WIDTH-1:0] data, - output logic ready -); -endmodule - -module wiring_top; - logic clk; - wiring_sub u_sub ( - HOLE - ); -endmodule -"; - - /// A connection-list request against [`WIRING`], `HOLE` replaced by what - /// is typed. Sorted, like every other member list here. - fn wiring_labels(name: &str, hole: &str) -> Vec { - let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); - let tree = Tree::new(name); - let (_tree, ws, uri, position) = opened(tree, &top, hole); - let mut found: Vec = items(completions(&ws, &uri, position, true)) - .iter() - .map(|item| item.label.clone()) - .collect(); - found.sort(); - found - } - - /// **The regression this rework exists for.** `.cl` inside `sub u (` used - /// to get the 512-item whole-index dump; it now gets the port. - #[test] - fn a_dot_in_a_connection_list_lists_the_modules_ports() { - assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]); - assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]); - } - - /// The answer against [`WIRING`] in the order the client shows it — by - /// `sortText` — as `(label, marked connected)` pairs. - fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> { - let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); - let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole); - let mut found = items(completions(&ws, &uri, position, true)); - found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text)); - found - .into_iter() - .map(|item| { - let marked = item - .label_details - .as_ref() - .and_then(|d| d.description.as_deref()) - .is_some_and(|d| d == "connected"); - (item.label, marked) - }) - .collect() - } - - fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> { - list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect() - } - - #[test] - fn a_connection_list_answers_after_a_comma_and_across_a_newline() { - let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]); - assert_eq!(wiring_order("comma", ".clk(clk), ."), expected); - assert_eq!( - wiring_order("newline", ".clk(clk),\n ."), - expected, - "an indented continuation line is the ordinary way this is written", - ); - } - - /// Already-connected ports sort after the ones still to wire and say so - /// (`completion-ux`, 2026-11-17 — they used to be dropped): in a - /// sixty-port instantiation the ones still to wire are what the user is - /// looking for, but a port connected twice by mistake is findable. - #[test] - fn a_port_already_connected_is_offered_last_and_marked() { - assert_eq!( - wiring_order("taken", ".clk(clk), .data(d), ."), - pairs(&[("ready", false), ("clk", true), ("data", true)]), - "two written, one left, and the two after it", - ); - // …and the entry being *re-typed* is not marked, because the dot the - // cursor follows is the one that is skipped. - assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)])); - } - - #[test] - fn a_parameter_override_lists_the_parameters_not_the_ports() { - let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub ("); - let tree = Tree::new("params"); - let (_tree, ws, uri, position) = opened(tree, &top, "#(."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!(found, vec!["DEPTH", "WIDTH"]); - for item in &answer { - assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}"); - } - } - - /// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync` - /// derives its width with a header `localparam`, which is **not - /// overridable** — and until `vlog_semantic` learned - /// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here. - /// The keyword is sticky, so a continuation entry after `localparam` is - /// one too, and a body `localparam` is never a header entry at all. - #[test] - fn a_localparam_is_never_offered_as_an_override() { - let top = "\ -module fifo #( - parameter int Depth = 4, - localparam int DepthW = 3, - DepthX = 4, - parameter int Again = 1 -) ( - input logic clk -); - localparam int Body = 7; -endmodule - -module top; - fifo #(.) u_fifo (); -endmodule -"; - let tree = Tree::new("localparam"); - let (_tree, ws, uri, position) = opened(tree, top, "#(."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!( - found, - vec!["Again", "Depth"], - "only the two `parameter` entries may be overridden", - ); - for item in &answer { - assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}"); - } - } - - /// The same, for a module the **index** answers for — the half QA - /// actually hit, since `prim_fifo_sync` is instantiated from another file. - #[test] - fn a_localparam_in_another_file_is_not_offered_either() { - let tree = Tree::new("xlocalparam"); - tree.write( - "fifo.sv", - "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n", - ); - let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "#(."); - let answer = items(completions(&ws, &uri, position, true)); - assert_eq!(labels(&answer), vec!["Depth"]); - // …and the localparam is still *there* to be read hierarchically — - // the split changes what may be offered, never what exists. - assert!( - ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"), - "a localparam is still exported", - ); - } - - /// The completion list and the **ghost instantiation** must agree about - /// what is overridable: two answers to "which parameters may be - /// overridden" would eventually offer a name the skeleton omits. - /// `vlog_refactor::instantiation_plan` reads the AST keyword and always - /// did; this pins the two against each other. - #[test] - fn the_override_list_and_the_instantiation_plan_agree() { - let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n"; - let tree = Tree::new("planagree"); - tree.write("fifo.sv", fifo); - let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "#(."); - let mut offered = labels(&items(completions(&ws, &uri, position, true))) - .iter() - .map(|s| (*s).to_string()) - .collect::>(); - offered.sort(); - let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan"); - let mut planned: Vec = plan.params.iter().map(|p| p.name.clone()).collect(); - planned.sort(); - assert_eq!(offered, planned, "the popup and the skeleton name one set"); - } - - #[test] - fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() { - let top = WIRING.replace(" HOLE\n", " .\n"); - let tree = Tree::new("portitem"); - let (_tree, ws, uri, position) = opened(tree, &top, " ."); - let answer = items(completions(&ws, &uri, position, true)); - let data = find(&answer, "data").expect("the port"); - assert_eq!(data.kind, Some(CompletionItemKind::FIELD)); - // `.data(|)`: the parentheses come with it, the cursor inside - // (`completion-ux`, 2026-11-17). Nothing named `data` is visible in - // `wiring_top`, so the placeholder is empty… - assert_eq!(inserted(data), "data(${1})"); - assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET)); - // …while `clk` is, so it is pre-filled. - let clk = find(&answer, "clk").expect("the clock"); - assert_eq!(inserted(clk), "clk(${1:clk})"); - // The declaration line carries the direction and the width, which is - // the whole of what a connection list needs to know. - assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,")); - // Exclusive, like every other member answer. - for item in &answer { - assert_eq!(tier(item), TIER_MEMBER, "{item:#?}"); - } - } - - #[test] - fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() { - // A `(` already after the word: only the name is being re-edited. - let top = WIRING.replace(" HOLE\n", " .da(d)\n"); - let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da"); - let answer = items(completions(&ws, &uri, position, true)); - assert_eq!(inserted(find(&answer, "data").expect("the port")), "data"); - // A client without snippet support gets the name, as before. - let top = WIRING.replace(" HOLE\n", " .\n"); - let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " ."); - let answer = items(completions(&ws, &uri, position, false)); - let data = find(&answer, "data").expect("the port"); - assert_eq!(inserted(data), "data"); - assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - } - - #[test] - fn a_parameter_item_is_pre_filled_from_a_visible_parameter() { - let top = WIRING - .replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n") - .replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub ("); - let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(."); - let answer = items(completions(&ws, &uri, position, true)); - assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})"); - assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})"); - } - - /// A **non-ANSI** port list writes its directions in the module body, so - /// the header alone names the ports and the body types them. Both halves - /// bind a `Port`, so the list is the same. - #[test] - fn a_non_ansi_port_list_is_completed_too() { - let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n"; - let tree = Tree::new("nonansi"); - let (_tree, ws, uri, position) = opened(tree, top, " ."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!(found, vec!["a", "b"]); - } - - /// A module declared in another file: the ports come out of the index's - /// member table, which exports exactly ports and parameters. - #[test] - fn a_module_in_another_file_lists_its_ports_from_the_index() { - let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n"; - let (_tree, ws, uri, position) = asking("xconn", top, " ."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter"); - let clk = find(&answer, "clk").expect("a port"); - assert_eq!(clk.kind, Some(CompletionItemKind::FIELD)); - assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files"); - } - - /// **§49's completion decision, and its limit.** Behind `u_sub.` in an - /// *expression* the list is the module's **hierarchical** surface — its - /// nets, its variables and its instances as well as its ports and its - /// parameters — because that is what a hierarchical path may name and - /// exactly what the tail resolution will find, so every item offered is - /// an item hover and go-to-definition answer. Behind the `.` of a - /// **connection list** it is the connection surface and nothing more: - /// `.internal(w)` is not a legal connection, and an item the resolution - /// could not find is a wrong answer rather than a generous one. - #[test] - fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() { - const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n"; - let hierarchical = { - let tree = Tree::new("hiersurface_expr"); - tree.write("sub.sv", SUB); - tree.write("leaf.sv", "module leaf;\nendmodule\n"); - let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "= u_sub."); - let mut found = labels(&items(completions(&ws, &uri, position, true))) - .iter() - .map(|l| l.to_string()) - .collect::>(); - found.sort(); - found - }; - assert_eq!( - hierarchical, - vec!["clk", "counter", "internal", "u_leaf"], - "the port and the three hierarchical-only members" - ); - - let connection = { - let tree = Tree::new("hiersurface_conn"); - tree.write("sub.sv", SUB); - tree.write("leaf.sv", "module leaf;\nendmodule\n"); - let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " ."); - let mut found = labels(&items(completions(&ws, &uri, position, true))) - .iter() - .map(|l| l.to_string()) - .collect::>(); - found.sort(); - found - }; - assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged"); - } - - #[test] - fn an_interface_instance_lists_its_ports_too() { - let tree = Tree::new("ifaceconn"); - tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n"); - let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, " ."); - let answer = items(completions(&ws, &uri, position, true)); - let mut found = labels(&answer); - found.sort(); - assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals"); - } - - /// A module nothing declares has no ports to name. The answer is an - /// **empty list** — the same shape a resolved site with no matching - /// member gets, and for the same reason: the question was this one, and - /// the honest answer to it is nothing. Never the whole-index dump. - #[test] - fn a_module_the_workspace_does_not_declare_answers_nothing() { - let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n"; - let (_tree, ws, uri, position) = asking("unknownconn", top, " ."); - assert!(items(completions(&ws, &uri, position, true)).is_empty()); - } - - /// …and a `.` that is in no instantiation list at all answers `None`, - /// which is the other half of the same split: not "nothing to offer here" - /// but "this was not a question I can read". - #[test] - fn a_dot_outside_any_instantiation_list_answers_none() { - let top = "module top;\n initial begin\n (.\n end\nendmodule\n"; - let (_tree, ws, uri, position) = asking("looseconn", top, " (."); - assert!(completions(&ws, &uri, position, true).is_none()); - } - - /// A `.` inside a *connected expression* is not a connection: `.clk(` - /// opens a paren of its own, and what may be written there is an - /// expression. - #[test] - fn a_dot_inside_a_connected_expression_is_not_a_connection() { - let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n"); - let tree = Tree::new("nested"); - let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head."); - assert!(completions(&ws, &uri, position, true).is_none()); - } - - #[test] - fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() { - // One and two characters: a prefix. - assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]); - // Three: a subsequence, so `rdy` reaches `ready`. - assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]); - let incomplete = |name: &str, hole: &str| { - let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); - let tree = Tree::new(name); - let (_tree, ws, uri, position) = opened(tree, &top, hole); - match completions(&ws, &uri, position, true) { - Some(CompletionResponse::List(list)) => list.is_incomplete, - other => panic!("a list, not {other:#?}"), - } - }; - assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer"); - assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character"); - assert!(!incomplete("cinc3", ".rdy")); - } - - /// Nothing about an ordinary identifier request changed. - #[test] - fn a_plain_identifier_still_gets_every_tier() { - let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n"; - let (_tree, ws, uri, position) = asking("plain", top, "= sig"); - let items = items(completions(&ws, &uri, position, true)); - let found = labels(&items); - assert!(found.contains(&"sig_here"), "the scope tier: {found:?}"); - assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD)); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/completion/member/tests.rs b/crates/lucisv_server/src/completion/member/tests.rs new file mode 100644 index 0000000..321d75a --- /dev/null +++ b/crates/lucisv_server/src/completion/member/tests.rs @@ -0,0 +1,820 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::completion::harness::*; +use crate::completion::*; + +// ------------------------------------------------------------------ +// the member answer (2026-09-02) — after a `.` or a `::` +// ------------------------------------------------------------------ + +/// The buffer most of these ask against: a class chain, a struct, an +/// interface with a modport and a clocking block, and a handle for each. +const MEMBERS: &str = "\ +interface bus_if; + logic clk; + logic [7:0] data; + modport mp (input clk); + clocking cb @(posedge clk); + input data; + endclocking +endinterface + +typedef struct packed { logic [7:0] addr; logic vld; } hdr_t; + +class base_c; + bit from_base; +endclass + +class item_c extends base_c; + bit user_id; + bit feature1; + hdr_t hdr; + function void run(); + endfunction +endclass + +module top; + virtual bus_if vif; + item_c item; + item_c queue[4]; + hdr_t [3:0] hs; + hdr_t h; + initial begin + item. + end +endmodule +"; + +/// The names a member request against [`MEMBERS`] offers, **sorted** — +/// which is the order the client shows them in, because `sortText` is +/// ``. The array order is the cap's order and is pinned +/// separately by [`the_list_is_ordered_nearest_declaration_first`]. +fn member_labels(name: &str, spine: &str) -> Vec { + let mut found: Vec = + items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect(); + found.sort(); + found +} + +/// The whole response, for the tests that read more than the labels. +fn member_response(name: &str, spine: &str) -> Option { + let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n")); + let tree = Tree::new(name); + let (_tree, ws, uri, position) = opened(tree, &top, spine); + completions(&ws, &uri, position, true) +} + +#[test] +fn a_class_handle_lists_its_members_and_its_bases() { + assert_eq!( + member_labels("cls", "item."), + vec!["feature1", "from_base", "hdr", "run", "user_id"], + ); +} + +#[test] +fn the_member_answer_is_exclusive() { + let items = items(member_response("exclusive", "item.")); + // No keyword, no template, no project word — every item is a member, + // and every one of them is filed under the member tier. + for item in &items { + assert_eq!(tier(item), TIER_MEMBER, "{item:#?}"); + assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}"); + assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}"); + assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}"); + } + let found = labels(&items); + assert!(!found.contains(&"always_ff"), "no keywords"); + assert!(!found.contains(&"top"), "no index names"); + assert!(!found.contains(&"vif"), "not even what is visible at the cursor"); +} + +/// A member wins over a same-named local because the answer is exclusive: +/// the local is not a worse candidate here, it is not a candidate. +#[test] +fn a_local_of_the_same_name_is_not_offered_beside_the_member() { + let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n"); + let tree = Tree::new("shadow"); + let (_tree, ws, uri, position) = opened(tree, &top, "item."); + let items = items(completions(&ws, &uri, position, true)); + let user_id = find(&items, "user_id").expect("the member"); + assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE)); + assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1); +} + +#[test] +fn a_nested_struct_field_lists_the_inner_fields() { + assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]); + assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]); +} + +#[test] +fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() { + let found = member_labels("iface", "vif."); + for wanted in ["clk", "data", "mp", "cb"] { + assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}"); + } +} + +/// A clocking block's `type_name` is the interface enclosing it +/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data` +/// resolve to the interface's own `data` declaration — correct +/// SystemVerilog, since a clocking block names a *view* of those signals +/// and declares nothing of its own. So the list after `vif.cb.` is the +/// interface's, exactly as the resolution is: one walk, one answer, wider +/// than the block's own item list and never wrong about a name. +#[test] +fn a_clocking_block_lists_the_enclosing_interfaces_signals() { + assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif.")); + assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string())); +} + +/// A **packed** array head is indexed away and names its element type's +/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`. +#[test] +fn a_packed_array_head_is_indexed_away() { + assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]); + assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly"); +} + +/// An **unpacked** declarator answers nothing, and that is +/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]` +/// names a container, not a value of `item_c`, so no `type_name` is +/// recorded and `q.size()` is an array method rather than a member +/// (`bind.rs::declare_typed`). Completion may not mint a type the +/// resolver refuses to mint — that would be the second resolver this +/// round exists to avoid. Filed as a follow-on in the feature README. +#[test] +fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() { + assert!(member_response("unpacked", "queue[0].").is_none()); +} + +/// The order of the `items` array is the order the cap keeps, and it is +/// **nearest declaration first**: a class's own members before its base's, +/// in declaration order within each. `sortText` still says the client +/// should draw them alphabetically. +#[test] +fn the_list_is_ordered_nearest_declaration_first() { + let items = items(member_response("order", "item.")); + assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]); + for item in &items { + assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str())); + } +} + +#[test] +fn this_and_super_answer_from_inside_a_method() { + let top = MEMBERS.replace(" function void run();\n", " function void run();\n this.\n"); + let tree = Tree::new("this"); + let (_tree, ws, uri, position) = opened(tree, &top, " this."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]); + + let top = MEMBERS.replace(" function void run();\n", " function void run();\n super.\n"); + let tree = Tree::new("super"); + let (_tree, ws, uri, position) = opened(tree, &top, " super."); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["from_base"], "super is the base and not the class itself"); +} + +#[test] +fn the_kind_and_the_detail_come_off_the_declaration() { + let items = items(member_response("detail", "item.")); + // In this buffer the declaration's own line is free, so that is the + // card — the same one tier 1 has always shown. + let hdr = find(&items, "hdr").expect("the struct-typed property"); + assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE)); + assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself"); + let run = find(&items, "run").expect("the method"); + assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION)); + assert_eq!(run.detail.as_deref(), Some("function void run();")); + // A method inserts its bare name: the parentheses and the arguments + // are the user's to write, and a completion that invented them would + // be guessing at the call. + assert_eq!(inserted(run), "run"); + assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); +} + +/// The edit is an **empty** range at the cursor, so accepting an item +/// writes the member name after the dot and touches nothing before it. +#[test] +fn the_edit_is_empty_at_the_cursor_after_a_separator() { + let items = items(member_response("range", "item.")); + assert!(!items.is_empty()); + for item in &items { + let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + assert_eq!(edit.range.start, edit.range.end, "{item:#?}"); + assert_eq!(edit.new_text, item.label); + } +} + +/// And with characters typed after the dot it replaces exactly those. +#[test] +fn the_edit_replaces_exactly_what_was_typed_after_the_separator() { + let items = items(member_response("range2", "item.us")); + assert_eq!(labels(&items), vec!["user_id"]); + let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + assert_eq!(edit.range.start.character + 2, edit.range.end.character); +} + +#[test] +fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() { + // One and two characters: a prefix, exactly as every other tier does + // below the floor. `fe` reaches `feature1` and not `from_base`. + assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]); + assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]); + // Three: a subsequence, so `fbs` reaches `from_base` — which no + // prefix match ever would. + assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]); + assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]); +} + +/// **The `isIncomplete` rule.** The request that matters — the one the +/// trigger character fires, with nothing typed yet — is complete, so VS +/// Code filters the whole member list client-side. A 1- or 2-character +/// answer is a prefix slice that the third keystroke would *widen*, so it +/// must say it is incomplete or the widening never reaches the client. +#[test] +fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() { + let incomplete = |name: &str, spine: &str| match member_response(name, spine) { + Some(CompletionResponse::List(list)) => list.is_incomplete, + other => panic!("a list, not {other:#?}"), + }; + assert!(!incomplete("inc0", "item."), "the whole list is the whole answer"); + assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character"); + assert!(incomplete("inc2", "item.fe")); + assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks"); + // Even a query nothing matches answers with a list, so the client is + // told to come back rather than left filtering an answer it has not + // got. + assert!(incomplete("inc4", "item.zz")); + let empty = items(member_response("inc5", "item.zz")); + assert!(empty.is_empty()); +} + +/// An **empty** answer is incomplete whatever was typed — including at +/// zero characters, where a non-empty list would be complete. QA finding +/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not +/// reached the declaring file's directory yet answers empty for one +/// request and correctly for the next, and a *complete* emptiness would +/// be cached by the client until the user retyped the dot. +#[test] +fn an_empty_answer_always_asks_the_client_to_come_back() { + let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n"; + let tree = Tree::new("hollow"); + let (_tree, ws, uri, position) = opened(tree, top, " h."); + match completions(&ws, &uri, position, true) { + Some(CompletionResponse::List(list)) => { + assert!(list.items.is_empty(), "a class with no members"); + assert!(list.is_incomplete, "and the client is asked to come back"); + } + other => panic!("a list, not {other:#?}"), + } + // The same for a connection list whose module nothing declares. + let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n"; + let (_tree, ws, uri, position) = asking("hollowconn", top, " ."); + match completions(&ws, &uri, position, true) { + Some(CompletionResponse::List(list)) => { + assert!(list.items.is_empty()); + assert!(list.is_incomplete); + } + other => panic!("a list, not {other:#?}"), + } +} + +#[test] +fn an_unresolvable_head_answers_nothing_at_all() { + for (name, spine) in [ + ("nohead", "no_such_handle."), + ("call", "f()."), + ("nothing", "."), + ("space", "item ."), + ("untyped", "vif.clk."), + ] { + assert!(member_response(name, spine).is_none(), "{spine} must answer nothing, not a guess",); + } +} + +/// A lone `:` is a case item, a label or a ternary — not a separator. The +/// request there is the ordinary six-tier one it always was. +#[test] +fn a_lone_colon_falls_through_to_the_ordinary_tiers() { + let top = + "module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n"; + let tree = Tree::new("colon"); + let (_tree, ws, uri, position) = opened(tree, top, "1: si"); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}"); +} + +#[test] +fn a_package_lists_its_members_after_a_scope_separator() { + let tree = Tree::new("pkg"); + tree.write( + "p.sv", + "package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n", + ); + let top = "module top;\n initial $display(other_pkg::);\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::"); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert!(found.contains(&"WIDTH"), "{found:?}"); + assert!(found.contains(&"cfg_t"), "{found:?}"); + assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}"); +} + +#[test] +fn a_package_this_file_declares_lists_its_members_too() { + let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n"; + let tree = Tree::new("pkg_local"); + let (_tree, ws, uri, position) = opened(tree, top, "p::"); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["W", "t_t"]); +} + +/// The cross-file half: an in-file class extending a class in another +/// file lists both halves, its own scope first. +#[test] +fn a_base_in_another_file_contributes_its_members() { + let tree = Tree::new("crossfile"); + tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n"); + let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " h."); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["local_field", "shared", "remote_field"]); + // The subclass's `shared` is the one offered — the same first-hit-wins + // rule a lookup applies. + let items = items(completions(&ws, &uri, position, true)); + let shared = find(&items, "shared").expect("the shadowed name"); + assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1); + assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE)); +} + +/// A class whose base the workspace does not declare at all: the chain +/// stops there, and everything known still lists. +#[test] +fn an_absent_base_stops_the_chain_without_losing_what_is_known() { + let tree = Tree::new("nobase"); + let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " h."); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["local_field"]); +} + +/// The other half of the detail rule: a member the *index* holds carries +/// no text, so its card is the kind label plus the declared type — the +/// most a table can say, and no file is read to say it. +#[test] +fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() { + let tree = Tree::new("xdetail"); + tree.write( + "remote.sv", + "class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n", + ); + let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " h."); + let items = items(completions(&ws, &uri, position, true)); + let typed = find(&items, "typed_field").expect("the typed property"); + assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t")); + let plain = find(&items, "plain_field").expect("the untyped property"); + assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add"); +} + +/// A type only another file declares: the whole list comes from the +/// index, inherited members included. +#[test] +fn a_handle_whose_type_is_another_files_lists_from_the_index() { + let tree = Tree::new("remote"); + tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n"); + tree.write("item.sv", "class remote_item extends remote_base;\n bit own_field;\nendclass\n"); + let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " h."); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["inherited_field", "own_field"]); +} + +/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the +/// index holds under the synthesized `reg2hw_t.ctrl` key. +#[test] +fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() { + let tree = Tree::new("reg2hw"); + tree.write( + "regs.sv", + "package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n", + ); + let top = + "module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl."); + let answer = items(completions(&ws, &uri, position, true)); + let found = labels(&answer); + assert_eq!(found, vec!["q", "qe"]); +} + +// ------------------------------------------------------------------ +// the connection list (2026-09-02 rework) — `.` inside `sub u (…)` +// ------------------------------------------------------------------ + +/// A module in the buffer, so the in-file half is exercised without the +/// index. Three ports and two parameters, in a shape a user really types. +const WIRING: &str = "\ +module wiring_sub #( + parameter int WIDTH = 8, + parameter int DEPTH = 4 +) ( + input logic clk, + input logic [WIDTH-1:0] data, + output logic ready +); +endmodule + +module wiring_top; + logic clk; + wiring_sub u_sub ( + HOLE + ); +endmodule +"; + +/// A connection-list request against [`WIRING`], `HOLE` replaced by what +/// is typed. Sorted, like every other member list here. +fn wiring_labels(name: &str, hole: &str) -> Vec { + let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); + let tree = Tree::new(name); + let (_tree, ws, uri, position) = opened(tree, &top, hole); + let mut found: Vec = items(completions(&ws, &uri, position, true)) + .iter() + .map(|item| item.label.clone()) + .collect(); + found.sort(); + found +} + +/// **The regression this rework exists for.** `.cl` inside `sub u (` used +/// to get the 512-item whole-index dump; it now gets the port. +#[test] +fn a_dot_in_a_connection_list_lists_the_modules_ports() { + assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]); + assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]); +} + +/// The answer against [`WIRING`] in the order the client shows it — by +/// `sortText` — as `(label, marked connected)` pairs. +fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> { + let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); + let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole); + let mut found = items(completions(&ws, &uri, position, true)); + found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text)); + found + .into_iter() + .map(|item| { + let marked = item + .label_details + .as_ref() + .and_then(|d| d.description.as_deref()) + .is_some_and(|d| d == "connected"); + (item.label, marked) + }) + .collect() +} + +fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> { + list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect() +} + +#[test] +fn a_connection_list_answers_after_a_comma_and_across_a_newline() { + let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]); + assert_eq!(wiring_order("comma", ".clk(clk), ."), expected); + assert_eq!( + wiring_order("newline", ".clk(clk),\n ."), + expected, + "an indented continuation line is the ordinary way this is written", + ); +} + +/// Already-connected ports sort after the ones still to wire and say so +/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a +/// sixty-port instantiation the ones still to wire are what the user is +/// looking for, but a port connected twice by mistake is findable. +#[test] +fn a_port_already_connected_is_offered_last_and_marked() { + assert_eq!( + wiring_order("taken", ".clk(clk), .data(d), ."), + pairs(&[("ready", false), ("clk", true), ("data", true)]), + "two written, one left, and the two after it", + ); + // …and the entry being *re-typed* is not marked, because the dot the + // cursor follows is the one that is skipped. + assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)])); +} + +#[test] +fn a_parameter_override_lists_the_parameters_not_the_ports() { + let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub ("); + let tree = Tree::new("params"); + let (_tree, ws, uri, position) = opened(tree, &top, "#(."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["DEPTH", "WIDTH"]); + for item in &answer { + assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}"); + } +} + +/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync` +/// derives its width with a header `localparam`, which is **not +/// overridable** — and until `vlog_semantic` learned +/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here. +/// The keyword is sticky, so a continuation entry after `localparam` is +/// one too, and a body `localparam` is never a header entry at all. +#[test] +fn a_localparam_is_never_offered_as_an_override() { + let top = "\ +module fifo #( + parameter int Depth = 4, + localparam int DepthW = 3, + DepthX = 4, + parameter int Again = 1 +) ( + input logic clk +); + localparam int Body = 7; +endmodule + +module top; + fifo #(.) u_fifo (); +endmodule +"; + let tree = Tree::new("localparam"); + let (_tree, ws, uri, position) = opened(tree, top, "#(."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["Again", "Depth"], "only the two `parameter` entries may be overridden",); + for item in &answer { + assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}"); + } +} + +/// The same, for a module the **index** answers for — the half QA +/// actually hit, since `prim_fifo_sync` is instantiated from another file. +#[test] +fn a_localparam_in_another_file_is_not_offered_either() { + let tree = Tree::new("xlocalparam"); + tree.write( + "fifo.sv", + "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n", + ); + let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "#(."); + let answer = items(completions(&ws, &uri, position, true)); + assert_eq!(labels(&answer), vec!["Depth"]); + // …and the localparam is still *there* to be read hierarchically — + // the split changes what may be offered, never what exists. + assert!( + ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"), + "a localparam is still exported", + ); +} + +/// The completion list and the **ghost instantiation** must agree about +/// what is overridable: two answers to "which parameters may be +/// overridden" would eventually offer a name the skeleton omits. +/// `vlog_refactor::instantiation_plan` reads the AST keyword and always +/// did; this pins the two against each other. +#[test] +fn the_override_list_and_the_instantiation_plan_agree() { + let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n"; + let tree = Tree::new("planagree"); + tree.write("fifo.sv", fifo); + let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "#(."); + let mut offered = labels(&items(completions(&ws, &uri, position, true))) + .iter() + .map(|s| (*s).to_string()) + .collect::>(); + offered.sort(); + let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan"); + let mut planned: Vec = plan.params.iter().map(|p| p.name.clone()).collect(); + planned.sort(); + assert_eq!(offered, planned, "the popup and the skeleton name one set"); +} + +#[test] +fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() { + let top = WIRING.replace(" HOLE\n", " .\n"); + let tree = Tree::new("portitem"); + let (_tree, ws, uri, position) = opened(tree, &top, " ."); + let answer = items(completions(&ws, &uri, position, true)); + let data = find(&answer, "data").expect("the port"); + assert_eq!(data.kind, Some(CompletionItemKind::FIELD)); + // `.data(|)`: the parentheses come with it, the cursor inside + // (`completion-ux`, 2026-11-17). Nothing named `data` is visible in + // `wiring_top`, so the placeholder is empty… + assert_eq!(inserted(data), "data(${1})"); + assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET)); + // …while `clk` is, so it is pre-filled. + let clk = find(&answer, "clk").expect("the clock"); + assert_eq!(inserted(clk), "clk(${1:clk})"); + // The declaration line carries the direction and the width, which is + // the whole of what a connection list needs to know. + assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,")); + // Exclusive, like every other member answer. + for item in &answer { + assert_eq!(tier(item), TIER_MEMBER, "{item:#?}"); + } +} + +#[test] +fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() { + // A `(` already after the word: only the name is being re-edited. + let top = WIRING.replace(" HOLE\n", " .da(d)\n"); + let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da"); + let answer = items(completions(&ws, &uri, position, true)); + assert_eq!(inserted(find(&answer, "data").expect("the port")), "data"); + // A client without snippet support gets the name, as before. + let top = WIRING.replace(" HOLE\n", " .\n"); + let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " ."); + let answer = items(completions(&ws, &uri, position, false)); + let data = find(&answer, "data").expect("the port"); + assert_eq!(inserted(data), "data"); + assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); +} + +#[test] +fn a_parameter_item_is_pre_filled_from_a_visible_parameter() { + let top = WIRING + .replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n") + .replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub ("); + let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(."); + let answer = items(completions(&ws, &uri, position, true)); + assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})"); + assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})"); +} + +/// A **non-ANSI** port list writes its directions in the module body, so +/// the header alone names the ports and the body types them. Both halves +/// bind a `Port`, so the list is the same. +#[test] +fn a_non_ansi_port_list_is_completed_too() { + let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n"; + let tree = Tree::new("nonansi"); + let (_tree, ws, uri, position) = opened(tree, top, " ."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["a", "b"]); +} + +/// A module declared in another file: the ports come out of the index's +/// member table, which exports exactly ports and parameters. +#[test] +fn a_module_in_another_file_lists_its_ports_from_the_index() { + let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n"; + let (_tree, ws, uri, position) = asking("xconn", top, " ."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter"); + let clk = find(&answer, "clk").expect("a port"); + assert_eq!(clk.kind, Some(CompletionItemKind::FIELD)); + assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files"); +} + +/// **§49's completion decision, and its limit.** Behind `u_sub.` in an +/// *expression* the list is the module's **hierarchical** surface — its +/// nets, its variables and its instances as well as its ports and its +/// parameters — because that is what a hierarchical path may name and +/// exactly what the tail resolution will find, so every item offered is +/// an item hover and go-to-definition answer. Behind the `.` of a +/// **connection list** it is the connection surface and nothing more: +/// `.internal(w)` is not a legal connection, and an item the resolution +/// could not find is a wrong answer rather than a generous one. +#[test] +fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() { + const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n"; + let hierarchical = { + let tree = Tree::new("hiersurface_expr"); + tree.write("sub.sv", SUB); + tree.write("leaf.sv", "module leaf;\nendmodule\n"); + let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= u_sub."); + let mut found = labels(&items(completions(&ws, &uri, position, true))) + .iter() + .map(|l| l.to_string()) + .collect::>(); + found.sort(); + found + }; + assert_eq!( + hierarchical, + vec!["clk", "counter", "internal", "u_leaf"], + "the port and the three hierarchical-only members" + ); + + let connection = { + let tree = Tree::new("hiersurface_conn"); + tree.write("sub.sv", SUB); + tree.write("leaf.sv", "module leaf;\nendmodule\n"); + let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " ."); + let mut found = labels(&items(completions(&ws, &uri, position, true))) + .iter() + .map(|l| l.to_string()) + .collect::>(); + found.sort(); + found + }; + assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged"); +} + +#[test] +fn an_interface_instance_lists_its_ports_too() { + let tree = Tree::new("ifaceconn"); + tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n"); + let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, " ."); + let answer = items(completions(&ws, &uri, position, true)); + let mut found = labels(&answer); + found.sort(); + assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals"); +} + +/// A module nothing declares has no ports to name. The answer is an +/// **empty list** — the same shape a resolved site with no matching +/// member gets, and for the same reason: the question was this one, and +/// the honest answer to it is nothing. Never the whole-index dump. +#[test] +fn a_module_the_workspace_does_not_declare_answers_nothing() { + let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n"; + let (_tree, ws, uri, position) = asking("unknownconn", top, " ."); + assert!(items(completions(&ws, &uri, position, true)).is_empty()); +} + +/// …and a `.` that is in no instantiation list at all answers `None`, +/// which is the other half of the same split: not "nothing to offer here" +/// but "this was not a question I can read". +#[test] +fn a_dot_outside_any_instantiation_list_answers_none() { + let top = "module top;\n initial begin\n (.\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("looseconn", top, " (."); + assert!(completions(&ws, &uri, position, true).is_none()); +} + +/// A `.` inside a *connected expression* is not a connection: `.clk(` +/// opens a paren of its own, and what may be written there is an +/// expression. +#[test] +fn a_dot_inside_a_connected_expression_is_not_a_connection() { + let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n"); + let tree = Tree::new("nested"); + let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head."); + assert!(completions(&ws, &uri, position, true).is_none()); +} + +#[test] +fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() { + // One and two characters: a prefix. + assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]); + // Three: a subsequence, so `rdy` reaches `ready`. + assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]); + let incomplete = |name: &str, hole: &str| { + let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n")); + let tree = Tree::new(name); + let (_tree, ws, uri, position) = opened(tree, &top, hole); + match completions(&ws, &uri, position, true) { + Some(CompletionResponse::List(list)) => list.is_incomplete, + other => panic!("a list, not {other:#?}"), + } + }; + assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer"); + assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character"); + assert!(!incomplete("cinc3", ".rdy")); +} + +/// Nothing about an ordinary identifier request changed. +#[test] +fn a_plain_identifier_still_gets_every_tier() { + let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n"; + let (_tree, ws, uri, position) = asking("plain", top, "= sig"); + let items = items(completions(&ws, &uri, position, true)); + let found = labels(&items); + assert!(found.contains(&"sig_here"), "the scope tier: {found:?}"); + assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD)); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/completion/module.rs b/crates/lucisv_server/src/completion/module.rs index dd66332..a27f9fb 100644 --- a/crates/lucisv_server/src/completion/module.rs +++ b/crates/lucisv_server/src/completion/module.rs @@ -336,592 +336,6 @@ fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use crate::completion::harness::*; - use crate::completion::*; - use std::fs; - use std::path::PathBuf; - - /// Completion's own view of the three new kinds, and the detail card that - /// used to hard-code "module" over an interface — the C2 wrong answer - /// (`docs/features/interface-semantics/README.md`). - #[test] - fn an_interface_completes_as_an_interface() { - assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE); - assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE); - assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT); - - let index = vlog_semantic::WorkspaceIndex::build([ - (PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"), - (PathBuf::from("/rtl/sub.sv"), SUB), - ]); - assert!(module_detail(&index, "bus_if", None).starts_with("interface")); - assert!(module_detail(&index, "sub", None).starts_with("module")); - // The ghost-instantiation lookups reach an interface too. - assert_eq!( - nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()), - Some("/rtl/bus_if.sv".to_string()) - ); - } - - // ------------------------------------------------------------------ - // tier 0's header slice (2026-08-28) — it must change no answer - // ------------------------------------------------------------------ - - /// Every header shape the slice has to survive, as (file text, module). - /// - /// The list is the argument that the slice changes nothing: each entry is - /// planned both ways below and the two plans are compared field by field. - const SHAPES: &[(&str, &str)] = &[ - // The ordinary ANSI header, params and all. - (SUB, "sub"), - // No ports at all. - ("module bare;\nendmodule\n", "bare"), - // An empty port list. - ("module empty ();\n logic x;\nendmodule\n", "empty"), - // A package import written into the header: its `;` is not the - // header's, and a slice that stopped there would report no ports. - ( - "package p;\n localparam int W = 4;\nendpackage\n\ - module imported import p::*; #(\n parameter int W = 8\n) (\n \ - input logic clk,\n output logic [W-1:0] q\n);\n \ - assign q = '0;\nendmodule\n", - "imported", - ), - // Two imports, then a parameter list. - ( - "package p;\nendpackage\npackage q;\nendpackage\n\ - module twice import p::*; import q::*; (input logic a);\nendmodule\n", - "twice", - ), - // A **non-ANSI** port list: the directions live in the body, which is - // exactly what the slice drops. - ( - "module old (a, b);\n input wire [7:0] a;\n output reg b;\n \ - always @* b = |a;\nendmodule\n", - "old", - ), - // Non-ANSI with nothing declaring the ports at all. - ("module silent (a, b);\nendmodule\n", "silent"), - // A comment and an attribute inside the header. - ( - "module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \ - input logic clk\n);\nendmodule\n", - "noisy", - ), - // A lifetime qualifier. - ("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"), - // A second module in the same file, after the one being planned. - ( - "module first (input logic a);\nendmodule\n\ - module second (output logic b);\nendmodule\n", - "first", - ), - // …and before it, so the slice's prefix carries a whole module. - ( - "module first (input logic a);\nendmodule\n\ - module second (output logic b);\nendmodule\n", - "second", - ), - // A compiler directive between the name and the port list, which the - // whitelist refuses outright. - ("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"), - // A directive *inside* the port list, which carries a warning the two - // plans must both raise. - ( - "module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\ - `endif\n);\nendmodule\n", - "ifdefd", - ), - // An escaped identifier for the module and for a port. - ("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"), - // A header longer than the first rung of the window ladder. - (WIDE, "wide"), - // QA (performance wave Lane B, 2026-08-28): a genuine attribute - // instance, `(* ... *)`, right after the module name and before the - // parameter list — the one shape the "noisy" case above is commented - // as covering but does not (it has two comments, no attribute). - // **Finding, not a regression this round introduced**: a module with - // an attribute anywhere near its header is not indexed as a `Module` - // unit at all (see - // `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`), - // so this pins the safe side effect — `module_header` declines before - // its whitelist walk ever runs — rather than the whitelist's own - // handling of attributes, which this shape cannot reach. - ( - "module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \ - input logic clk\n);\nendmodule\n", - "attributed", - ), - // An attribute instance *inside* the port list, attached to one port. - // Same finding as `attributed`: not indexed, so not reached either. - ( - "module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\ - );\nendmodule\n", - "port_attributed", - ), - // A single import declaration naming several packages, comma - // separated (`import a::*, b::*;`) — one statement, not two, and the - // whitelist's `skip_to_semicolon` must not stop at the first `::`. - ( - "package p;\nendpackage\npackage q;\nendpackage\n\ - module chained import p::*, q::*; (input logic a);\nendmodule\n", - "chained", - ), - // A parameter default whose string literal carries the exact bytes - // the whitelist watches for — `;` and `)` — which must stay inside - // the `String` token and never be mistaken for header punctuation. - ( - "module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \ - input logic clk\n);\nendmodule\n", - "stringy", - ), - // CRLF line endings through the whole header. - ("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"), - ]; - - /// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb. - const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \ - input logic port_number_one_with_a_long_name,\n \ - input logic port_number_two_with_a_long_name,\n \ - input logic port_number_three_with_a_long_name,\n \ - input logic port_number_four_with_a_long_name,\n \ - input logic port_number_five_with_a_long_name,\n \ - output logic port_number_six_with_a_long_name\n);\n \ - assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n"; - - /// The whole argument for the slice: for every shape above, the plan built - /// from the header alone is the plan built from the whole file. Where it - /// would not be — a non-ANSI list, a header the whitelist refuses — the - /// guard in [`plan_for`] sends the question back to the whole file, so the - /// comparison holds there too. - #[test] - fn the_header_slice_plans_exactly_what_the_whole_file_plans() { - for (text, module) in SHAPES { - let path = PathBuf::from("/rtl/shape.sv"); - let index = WorkspaceIndex::build(vec![(path.clone(), *text)]); - let (tree, _) = vlog_parser::parse_source_tolerant(text); - let semantics = vlog_semantic::analyze(&tree, text); - let site = Site { semantics: &semantics, offset: 0 }; - let whole = vlog_refactor::instantiation_plan(module, text, Some(site)); - let ours = plan_for(&index, module, text, site); - assert_eq!(ours, whole, "{module}"); - } - } - - /// QA (performance wave Lane B, 2026-08-28): the equality above holds - /// trivially for a shape the whitelist declines — both sides parse the - /// whole file, so a wrong slice could hide behind that. These shapes must - /// actually slice, so the comparison exercises the whitelist walk it is - /// meant to pin: an `import a::*, b::*;` chain (one statement, several - /// packages — `skip_to_semicolon` must not stop at the first `::`), a - /// `;`/`)` sitting inside a string literal, and CRLF endings. - #[test] - fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() { - for module in ["chained", "stringy", "crlf", "twice", "imported"] { - let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES"); - let path = PathBuf::from("/rtl/shape.sv"); - let index = WorkspaceIndex::build(vec![(path, *text)]); - assert!( - module_header(&index, module, text).is_some(), - "{module}: expected the header to actually slice, not fall back whole-file" - ); - } - } - - /// QA finding (performance wave Lane B, 2026-08-28), not a regression that - /// round introduced: a module with an attribute instance (`(* ... *)`) - /// **between its name and its `#(`** is not indexed as a `Module` unit at - /// all. `WorkspaceIndex::units` comes back empty, so [`module_header`] - /// declines at the very first line (no `[def]` to anchor on) before the - /// whitelist walk ever runs, and completion's module tier — which sources - /// its candidate names from the same table — never offers the module in - /// the first place. That attribute sits inside no list, so no recovery - /// reaches it; it is still filed in `docs/features/completion-core/ - /// README.md`'s QA log. - /// - /// **The `port_attributed` half of the finding was fixed by header - /// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an - /// attribute on a *port* now costs that one port and nothing else — the - /// list keeps a `ListElem::Error` where `(* keep *) output logic q` was - /// written, and the module keeps its name, its other ports and its body, - /// so it is indexed and its header slices for real rather than by - /// whole-file fallback. That is the re-audit the old message asked for, - /// and it is the second half of this test; - /// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the - /// same shape from the other side. - #[test] - fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() { - let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES"); - let path = PathBuf::from("/rtl/shape.sv"); - let index = WorkspaceIndex::build(vec![(path, *text)]); - assert!( - index.units("attributed").is_empty(), - "if this starts finding a unit, module_header should be re-audited \ - for whether it now slices attributes correctly rather than by lucky fallback" - ); - assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on"); - } - - #[test] - fn an_attribute_on_a_port_costs_that_port_only() { - let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES"); - let path = PathBuf::from("/rtl/shape.sv"); - let index = WorkspaceIndex::build(vec![(path, *text)]); - assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port"); - let header = module_header(&index, "port_attributed", text).expect("a sliced header"); - assert!(header.starts_with("module port_attributed ("), "{header:?}"); - assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole"); - } - - /// The guard is not decoration: a non-ANSI module really does plan - /// differently off its header, and really is sent back to the whole file. - #[test] - fn a_non_ansi_port_list_is_planned_from_the_whole_file() { - let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n"; - let path = PathBuf::from("/rtl/old.sv"); - let index = WorkspaceIndex::build(vec![(path, text)]); - let header = module_header(&index, "old", text).expect("the header slices"); - let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan"); - assert!( - sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()), - "premise: the header alone knows nothing about these ports" - ); - let (tree, _) = vlog_parser::parse_source_tolerant(text); - let semantics = vlog_semantic::analyze(&tree, text); - let site = Site { semantics: &semantics, offset: 0 }; - let guarded = plan_for(&index, "old", text, site).expect("a plan"); - assert_eq!(guarded.ports[0].dir, "input"); - assert_eq!(guarded.ports[0].ty, "wire [7:0]"); - } - - /// The whole answer, pinned at the prefixes the hot path is worst at — the - /// empty one and a one-character one, where every tier is at its widest. - /// Tier 0 answers with names, so the pin spells out every module item's - /// label *and* the text it inserts, which is now the label again. - #[test] - fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() { - let tree = Tree::new("pinned"); - tree.write("sub.sv", SUB); - tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n"); - tree.write("submarine.sv", "module submarine ();\nendmodule\n"); - let (_tree, mut ws, uri, _) = - opened(tree, "module top;\n logic clk;\n \nendmodule\n", " "); - - // Nothing typed, then one character — the two widest requests there - // are. `top` is in the answer because the buffer declares it and the - // index holds it like any other module. - let mut answer = |typed: &str| { - let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n"); - ws.set_document(uri.clone(), text.clone()); - let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32 - + typed.len() as u32; - let doc = ws.document(&uri).expect("open"); - let position = doc.positions().position(offset); - items(completions(&ws, &uri, position, true)) - }; - for (typed, expected) in - [("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])] - { - let items = answer(typed); - let found: Vec<&str> = - skeletons(&items).iter().map(|item| item.label.as_str()).collect(); - assert_eq!(found, expected, "module items after typing {typed:?}"); - } - - // …and the exact text each of them inserts, which is the name and - // nothing else however many ports the module has. The instantiation is - // `inline.rs`'s business now. - let items = answer(""); - for name in ["sub", "alpha", "submarine"] { - let item = find(&items, name).expect("the module item"); - assert_eq!(inserted(item), name, "the popup inserts the name alone"); - assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - assert_eq!(item.insert_text_mode, None, "there is no indentation to keep"); - } - } - - /// A file edited on disk since the index last read it has moved every span - /// the index holds, so the slice must not take one on trust. - #[test] - fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() { - let text = - "module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n"; - let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]); - assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally"); - // The same index against a file whose text has shifted underneath it. - let moved = format!("// a line nobody told the index about\n{text}"); - assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there"); - } - - // ------------------------------------------------------------------ - // tier 0 — module names (level 1 of the instantiation wave, 2026-08-30) - // ------------------------------------------------------------------ - - #[test] - fn a_module_name_at_item_position_completes_to_the_name_alone() { - let top = "module top;\n logic clk;\n su\nendmodule\n"; - let (_tree, ws, uri, position) = asking("nameonly", top, " su"); - let items = items(completions(&ws, &uri, position, true)); - let modules = skeletons(&items); - assert_eq!(modules.len(), 1, "{items:#?}"); - let item = modules[0]; - assert_eq!(item.label, "sub"); - assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon"); - assert_eq!(item.detail.as_deref(), Some("module — sub.sv")); - assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest"); - assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show"); - } - - #[test] - fn the_snippet_flag_no_longer_changes_the_module_item() { - // The M4 fallback — a plain-text spelling of the skeleton for a client - // that never advertised `snippetSupport` — has nothing left to fall - // back from: the item is a word either way. - let top = "module top;\n logic clk;\n su\nendmodule\n"; - let (_tree, ws, uri, position) = asking("plain", top, " su"); - for snippets in [true, false] { - let items = items(completions(&ws, &uri, position, snippets)); - let item = skeletons(&items)[0]; - assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - assert_eq!(inserted(item), "sub", "snippets: {snippets}"); - } - } - - /// The whole point of level 1: the popup no longer reads the files it - /// offers names from. Proved by deleting the declaring file after the - /// index has been built — the old tier answered nothing at all here, - /// because every item needed that file's text. - #[test] - fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() { - let tree = Tree::new("noread"); - let sub = tree.write("sub.sv", SUB); - let (_tree, ws, uri, position) = - opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su"); - fs::remove_file(&sub).expect("remove the declaring file"); - let items = items(completions(&ws, &uri, position, true)); - assert_eq!( - skeletons(&items).iter().map(|item| item.label.as_str()).collect::>(), - ["sub"], - "the name comes from the index's table, not from the file: {items:#?}" - ); - } - - #[test] - fn the_edit_replaces_exactly_the_typed_word() { - let top = "module top;\n su\nendmodule\n"; - let (_tree, ws, uri, position) = asking("replace", top, " su"); - let items = items(completions(&ws, &uri, position, true)); - for item in &items { - let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { - panic!("a plain edit"); - }; - assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}"); - assert_eq!(edit.range.end, Position { line: 1, character: 4 }); - } - } - - #[test] - fn no_skeleton_is_offered_in_the_middle_of_an_expression() { - // The other tiers answer here — a name is a name wherever it is - // written — but a fifteen-line instantiation is not. - for (name, top, needle) in [ - ("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"), - ("decl", "module top;\n logic su\nendmodule\n", "logic su"), - ("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"), - ("header", "module top (su\n);\nendmodule\n", "top (su"), - ] { - let (_tree, ws, uri, position) = asking(name, top, needle); - let items = items(completions(&ws, &uri, position, true)); - assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}"); - } - } - - #[test] - fn no_skeleton_is_offered_inside_a_procedural_block() { - let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n"; - let (_tree, ws, uri, position) = asking("always", top, " su"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - - let top = "module top;\n initial begin\n su\n end\nendmodule\n"; - let (_tree, ws, uri, position) = asking("initial", top, " su"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - } - - #[test] - fn no_skeleton_is_offered_inside_a_function_or_a_class() { - let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n"; - let (_tree, ws, uri, position) = asking("function", top, " su"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - - let top = "package p;\n class c;\n su\n endclass\nendpackage\n"; - let (_tree, ws, uri, position) = asking("class", top, " su"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - } - - #[test] - fn a_generate_block_is_still_item_position() { - let top = "\ -module top; - for (genvar i = 0; i < 4; i++) begin : g - su - end -endmodule -"; - let (_tree, ws, uri, position) = asking("genfor", top, " su"); - assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}"); - - let top = "module top;\n generate\n su\n endgenerate\nendmodule\n"; - let (_tree, ws, uri, position) = asking("generate", top, " su"); - assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1); - } - - #[test] - fn no_skeleton_is_offered_outside_a_design_unit() { - let top = "su\nmodule top;\nendmodule\n"; - let (_tree, ws, uri, position) = asking("toplevel", top, "su"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - } - - #[test] - fn a_prefix_that_matches_no_module_offers_no_skeleton() { - let top = "module top;\n zzz\nendmodule\n"; - let (_tree, ws, uri, position) = asking("nomatch", top, " zzz"); - assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); - } - - #[test] - fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() { - // Until 2026-08-30 tier 0 skipped it: there is no single definition to - // build a *skeleton* from, and the skeleton was the item. A name needs - // no definition, so round 1 offered the name and left the detail - // blank. Round 2 (owner ruling, same day) makes the ghost choose a - // copy rather than decline, so the popup names the copy the ghost will - // read — `nearest_definition`'s answer, which for a buffer at the tree - // root is the lexicographically smaller path. - let tree = Tree::new("dup"); - tree.write("a.sv", "module dup ();\nendmodule\n"); - tree.write("b.sv", "module dup ();\nendmodule\n"); - let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du"); - let items = items(completions(&ws, &uri, position, true)); - let item = find(&items, "dup").expect("the name is still known"); - assert_eq!(tier(item), TIER_MODULE, "{items:#?}"); - assert_eq!(item.detail.as_deref(), Some("module — a.sv")); - } - - /// The nearest-definition chooser, at the level `inline.rs` consumes it. - /// - /// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling` - /// share `hw` and nothing more, and a byte-wise prefix would count the - /// `hw/top_` they spell alike and rank the copies by a coincidence. - #[test] - fn the_nearest_definition_is_the_one_sharing_the_most_path_components() { - let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv"); - let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv"); - let text = "module ast_dft ();\nendmodule\n"; - let index = - WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]); - - let asking = |from: &str| { - nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from))) - .expect("a definition") - .to_path_buf() - }; - assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey); - assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling); - // Near neither, and no path at all: the tie falls to the smaller path - // rather than to whatever the index happens to hold first. - assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling); - assert_eq!( - nearest_definition(&index, "ast_dft", None).expect("a definition"), - darjeeling.as_path() - ); - } - - /// QA round-2 finding, fixed at lead review: a copy in the asking - /// buffer's own directory and one in a subdirectory of it share the same - /// number of leading components with the buffer (its filename never - /// matches a directory), and the lexicographic tie-break alone could pick - /// the deeper, less related copy. The real shape is opentitan's 61-way - /// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv` - /// for a buffer in `rstmgr/dv`, even though `'r' < 't'`. - #[test] - fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() { - let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv"); - let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv"); - let text = "module tb ();\nendmodule\n"; - for sources in [ - vec![(sibling.clone(), text), (deeper.clone(), text)], - vec![(deeper.clone(), text), (sibling.clone(), text)], - ] { - let index = WorkspaceIndex::build(sources); - let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv"); - assert_eq!( - nearest_definition(&index, "tb", Some(&from)).expect("a definition"), - sibling.as_path(), - "the shallower copy is the nearer one" - ); - } - // …and depth only breaks a tie: a deeper copy that genuinely shares - // more of the asking path still wins. - let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]); - let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv"); - assert_eq!( - nearest_definition(&index, "tb", Some(&from)).expect("a definition"), - deeper.as_path(), - "sharing more components outranks being shallow" - ); - } - - /// The answer is a property of the paths, not of the order the index was - /// built in — which is what makes it the same answer twice in a row, and - /// the same answer in two editors. - #[test] - fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() { - let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv"); - let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv"); - let text = "module ast_dft ();\nendmodule\n"; - let forwards = - WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]); - let backwards = - WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]); - for index in [&forwards, &backwards] { - let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv"); - assert_eq!( - nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"), - earlgrey.as_path() - ); - assert_eq!( - nearest_definition(index, "ast_dft", None).expect("a definition"), - darjeeling.as_path() - ); - } - } - - /// A module only one file declares goes through the same chooser and comes - /// back with the file `vlog_refactor::module_definition` picks — the - /// equivalence that says round 2 widened the twice-declared case and moved - /// nothing else. - #[test] - fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() { - let path = PathBuf::from("/rtl/sub.sv"); - let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]); - let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition"); - assert_eq!(expected, path.as_path()); - for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] { - assert_eq!( - nearest_definition(&index, "sub", from.as_deref()).expect("a definition"), - expected, - "{from:?}" - ); - } - // And a name nothing declares is `None` here where it is an `Err` - // there — the same "no answer", spelled the way each caller reads it. - assert!(nearest_definition(&index, "nope", None).is_none()); - assert!(vlog_refactor::module_definition(&index, "nope").is_err()); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/completion/module/tests.rs b/crates/lucisv_server/src/completion/module/tests.rs new file mode 100644 index 0000000..225a286 --- /dev/null +++ b/crates/lucisv_server/src/completion/module/tests.rs @@ -0,0 +1,585 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::completion::harness::*; +use crate::completion::*; +use std::fs; +use std::path::PathBuf; + +/// Completion's own view of the three new kinds, and the detail card that +/// used to hard-code "module" over an interface — the C2 wrong answer +/// (`docs/features/interface-semantics/README.md`). +#[test] +fn an_interface_completes_as_an_interface() { + assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE); + assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE); + assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT); + + let index = vlog_semantic::WorkspaceIndex::build([ + (PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"), + (PathBuf::from("/rtl/sub.sv"), SUB), + ]); + assert!(module_detail(&index, "bus_if", None).starts_with("interface")); + assert!(module_detail(&index, "sub", None).starts_with("module")); + // The ghost-instantiation lookups reach an interface too. + assert_eq!( + nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()), + Some("/rtl/bus_if.sv".to_string()) + ); +} + +// ------------------------------------------------------------------ +// tier 0's header slice (2026-08-28) — it must change no answer +// ------------------------------------------------------------------ + +/// Every header shape the slice has to survive, as (file text, module). +/// +/// The list is the argument that the slice changes nothing: each entry is +/// planned both ways below and the two plans are compared field by field. +const SHAPES: &[(&str, &str)] = &[ + // The ordinary ANSI header, params and all. + (SUB, "sub"), + // No ports at all. + ("module bare;\nendmodule\n", "bare"), + // An empty port list. + ("module empty ();\n logic x;\nendmodule\n", "empty"), + // A package import written into the header: its `;` is not the + // header's, and a slice that stopped there would report no ports. + ( + "package p;\n localparam int W = 4;\nendpackage\n\ + module imported import p::*; #(\n parameter int W = 8\n) (\n \ + input logic clk,\n output logic [W-1:0] q\n);\n \ + assign q = '0;\nendmodule\n", + "imported", + ), + // Two imports, then a parameter list. + ( + "package p;\nendpackage\npackage q;\nendpackage\n\ + module twice import p::*; import q::*; (input logic a);\nendmodule\n", + "twice", + ), + // A **non-ANSI** port list: the directions live in the body, which is + // exactly what the slice drops. + ( + "module old (a, b);\n input wire [7:0] a;\n output reg b;\n \ + always @* b = |a;\nendmodule\n", + "old", + ), + // Non-ANSI with nothing declaring the ports at all. + ("module silent (a, b);\nendmodule\n", "silent"), + // A comment and an attribute inside the header. + ( + "module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \ + input logic clk\n);\nendmodule\n", + "noisy", + ), + // A lifetime qualifier. + ("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"), + // A second module in the same file, after the one being planned. + ( + "module first (input logic a);\nendmodule\n\ + module second (output logic b);\nendmodule\n", + "first", + ), + // …and before it, so the slice's prefix carries a whole module. + ( + "module first (input logic a);\nendmodule\n\ + module second (output logic b);\nendmodule\n", + "second", + ), + // A compiler directive between the name and the port list, which the + // whitelist refuses outright. + ("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"), + // A directive *inside* the port list, which carries a warning the two + // plans must both raise. + ( + "module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\ + `endif\n);\nendmodule\n", + "ifdefd", + ), + // An escaped identifier for the module and for a port. + ("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"), + // A header longer than the first rung of the window ladder. + (WIDE, "wide"), + // QA (performance wave Lane B, 2026-08-28): a genuine attribute + // instance, `(* ... *)`, right after the module name and before the + // parameter list — the one shape the "noisy" case above is commented + // as covering but does not (it has two comments, no attribute). + // **Finding, not a regression this round introduced**: a module with + // an attribute anywhere near its header is not indexed as a `Module` + // unit at all (see + // `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`), + // so this pins the safe side effect — `module_header` declines before + // its whitelist walk ever runs — rather than the whitelist's own + // handling of attributes, which this shape cannot reach. + ( + "module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \ + input logic clk\n);\nendmodule\n", + "attributed", + ), + // An attribute instance *inside* the port list, attached to one port. + // Same finding as `attributed`: not indexed, so not reached either. + ( + "module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\ + );\nendmodule\n", + "port_attributed", + ), + // A single import declaration naming several packages, comma + // separated (`import a::*, b::*;`) — one statement, not two, and the + // whitelist's `skip_to_semicolon` must not stop at the first `::`. + ( + "package p;\nendpackage\npackage q;\nendpackage\n\ + module chained import p::*, q::*; (input logic a);\nendmodule\n", + "chained", + ), + // A parameter default whose string literal carries the exact bytes + // the whitelist watches for — `;` and `)` — which must stay inside + // the `String` token and never be mistaken for header punctuation. + ( + "module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \ + input logic clk\n);\nendmodule\n", + "stringy", + ), + // CRLF line endings through the whole header. + ("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"), +]; + +/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb. +const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \ + input logic port_number_one_with_a_long_name,\n \ + input logic port_number_two_with_a_long_name,\n \ + input logic port_number_three_with_a_long_name,\n \ + input logic port_number_four_with_a_long_name,\n \ + input logic port_number_five_with_a_long_name,\n \ + output logic port_number_six_with_a_long_name\n);\n \ + assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n"; + +/// The whole argument for the slice: for every shape above, the plan built +/// from the header alone is the plan built from the whole file. Where it +/// would not be — a non-ANSI list, a header the whitelist refuses — the +/// guard in [`plan_for`] sends the question back to the whole file, so the +/// comparison holds there too. +#[test] +fn the_header_slice_plans_exactly_what_the_whole_file_plans() { + for (text, module) in SHAPES { + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path.clone(), *text)]); + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let semantics = vlog_semantic::analyze(&tree, text); + let site = Site { semantics: &semantics, offset: 0 }; + let whole = vlog_refactor::instantiation_plan(module, text, Some(site)); + let ours = plan_for(&index, module, text, site); + assert_eq!(ours, whole, "{module}"); + } +} + +/// QA (performance wave Lane B, 2026-08-28): the equality above holds +/// trivially for a shape the whitelist declines — both sides parse the +/// whole file, so a wrong slice could hide behind that. These shapes must +/// actually slice, so the comparison exercises the whitelist walk it is +/// meant to pin: an `import a::*, b::*;` chain (one statement, several +/// packages — `skip_to_semicolon` must not stop at the first `::`), a +/// `;`/`)` sitting inside a string literal, and CRLF endings. +#[test] +fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() { + for module in ["chained", "stringy", "crlf", "twice", "imported"] { + let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES"); + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path, *text)]); + assert!( + module_header(&index, module, text).is_some(), + "{module}: expected the header to actually slice, not fall back whole-file" + ); + } +} + +/// QA finding (performance wave Lane B, 2026-08-28), not a regression that +/// round introduced: a module with an attribute instance (`(* ... *)`) +/// **between its name and its `#(`** is not indexed as a `Module` unit at +/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`] +/// declines at the very first line (no `[def]` to anchor on) before the +/// whitelist walk ever runs, and completion's module tier — which sources +/// its candidate names from the same table — never offers the module in +/// the first place. That attribute sits inside no list, so no recovery +/// reaches it; it is still filed in `docs/features/completion-core/ +/// README.md`'s QA log. +/// +/// **The `port_attributed` half of the finding was fixed by header +/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an +/// attribute on a *port* now costs that one port and nothing else — the +/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was +/// written, and the module keeps its name, its other ports and its body, +/// so it is indexed and its header slices for real rather than by +/// whole-file fallback. That is the re-audit the old message asked for, +/// and it is the second half of this test; +/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the +/// same shape from the other side. +#[test] +fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() { + let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES"); + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path, *text)]); + assert!( + index.units("attributed").is_empty(), + "if this starts finding a unit, module_header should be re-audited \ + for whether it now slices attributes correctly rather than by lucky fallback" + ); + assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on"); +} + +#[test] +fn an_attribute_on_a_port_costs_that_port_only() { + let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES"); + let path = PathBuf::from("/rtl/shape.sv"); + let index = WorkspaceIndex::build(vec![(path, *text)]); + assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port"); + let header = module_header(&index, "port_attributed", text).expect("a sliced header"); + assert!(header.starts_with("module port_attributed ("), "{header:?}"); + assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole"); +} + +/// The guard is not decoration: a non-ANSI module really does plan +/// differently off its header, and really is sent back to the whole file. +#[test] +fn a_non_ansi_port_list_is_planned_from_the_whole_file() { + let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n"; + let path = PathBuf::from("/rtl/old.sv"); + let index = WorkspaceIndex::build(vec![(path, text)]); + let header = module_header(&index, "old", text).expect("the header slices"); + let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan"); + assert!( + sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()), + "premise: the header alone knows nothing about these ports" + ); + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let semantics = vlog_semantic::analyze(&tree, text); + let site = Site { semantics: &semantics, offset: 0 }; + let guarded = plan_for(&index, "old", text, site).expect("a plan"); + assert_eq!(guarded.ports[0].dir, "input"); + assert_eq!(guarded.ports[0].ty, "wire [7:0]"); +} + +/// The whole answer, pinned at the prefixes the hot path is worst at — the +/// empty one and a one-character one, where every tier is at its widest. +/// Tier 0 answers with names, so the pin spells out every module item's +/// label *and* the text it inserts, which is now the label again. +#[test] +fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() { + let tree = Tree::new("pinned"); + tree.write("sub.sv", SUB); + tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n"); + tree.write("submarine.sv", "module submarine ();\nendmodule\n"); + let (_tree, mut ws, uri, _) = opened(tree, "module top;\n logic clk;\n \nendmodule\n", " "); + + // Nothing typed, then one character — the two widest requests there + // are. `top` is in the answer because the buffer declares it and the + // index holds it like any other module. + let mut answer = |typed: &str| { + let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n"); + ws.set_document(uri.clone(), text.clone()); + let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32 + + typed.len() as u32; + let doc = ws.document(&uri).expect("open"); + let position = doc.positions().position(offset); + items(completions(&ws, &uri, position, true)) + }; + for (typed, expected) in + [("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])] + { + let items = answer(typed); + let found: Vec<&str> = skeletons(&items).iter().map(|item| item.label.as_str()).collect(); + assert_eq!(found, expected, "module items after typing {typed:?}"); + } + + // …and the exact text each of them inserts, which is the name and + // nothing else however many ports the module has. The instantiation is + // `inline.rs`'s business now. + let items = answer(""); + for name in ["sub", "alpha", "submarine"] { + let item = find(&items, name).expect("the module item"); + assert_eq!(inserted(item), name, "the popup inserts the name alone"); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); + assert_eq!(item.insert_text_mode, None, "there is no indentation to keep"); + } +} + +/// A file edited on disk since the index last read it has moved every span +/// the index holds, so the slice must not take one on trust. +#[test] +fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() { + let text = "module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n"; + let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]); + assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally"); + // The same index against a file whose text has shifted underneath it. + let moved = format!("// a line nobody told the index about\n{text}"); + assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there"); +} + +// ------------------------------------------------------------------ +// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30) +// ------------------------------------------------------------------ + +#[test] +fn a_module_name_at_item_position_completes_to_the_name_alone() { + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("nameonly", top, " su"); + let items = items(completions(&ws, &uri, position, true)); + let modules = skeletons(&items); + assert_eq!(modules.len(), 1, "{items:#?}"); + let item = modules[0]; + assert_eq!(item.label, "sub"); + assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon"); + assert_eq!(item.detail.as_deref(), Some("module — sub.sv")); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); + assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest"); + assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show"); +} + +#[test] +fn the_snippet_flag_no_longer_changes_the_module_item() { + // The M4 fallback — a plain-text spelling of the skeleton for a client + // that never advertised `snippetSupport` — has nothing left to fall + // back from: the item is a word either way. + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("plain", top, " su"); + for snippets in [true, false] { + let items = items(completions(&ws, &uri, position, snippets)); + let item = skeletons(&items)[0]; + assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); + assert_eq!(inserted(item), "sub", "snippets: {snippets}"); + } +} + +/// The whole point of level 1: the popup no longer reads the files it +/// offers names from. Proved by deleting the declaring file after the +/// index has been built — the old tier answered nothing at all here, +/// because every item needed that file's text. +#[test] +fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() { + let tree = Tree::new("noread"); + let sub = tree.write("sub.sv", SUB); + let (_tree, ws, uri, position) = + opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su"); + fs::remove_file(&sub).expect("remove the declaring file"); + let items = items(completions(&ws, &uri, position, true)); + assert_eq!( + skeletons(&items).iter().map(|item| item.label.as_str()).collect::>(), + ["sub"], + "the name comes from the index's table, not from the file: {items:#?}" + ); +} + +#[test] +fn the_edit_replaces_exactly_the_typed_word() { + let top = "module top;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("replace", top, " su"); + let items = items(completions(&ws, &uri, position, true)); + for item in &items { + let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}"); + assert_eq!(edit.range.end, Position { line: 1, character: 4 }); + } +} + +#[test] +fn no_skeleton_is_offered_in_the_middle_of_an_expression() { + // The other tiers answer here — a name is a name wherever it is + // written — but a fifteen-line instantiation is not. + for (name, top, needle) in [ + ("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"), + ("decl", "module top;\n logic su\nendmodule\n", "logic su"), + ("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"), + ("header", "module top (su\n);\nendmodule\n", "top (su"), + ] { + let (_tree, ws, uri, position) = asking(name, top, needle); + let items = items(completions(&ws, &uri, position, true)); + assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}"); + } +} + +#[test] +fn no_skeleton_is_offered_inside_a_procedural_block() { + let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("always", top, " su"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); + + let top = "module top;\n initial begin\n su\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("initial", top, " su"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); +} + +#[test] +fn no_skeleton_is_offered_inside_a_function_or_a_class() { + let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n"; + let (_tree, ws, uri, position) = asking("function", top, " su"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); + + let top = "package p;\n class c;\n su\n endclass\nendpackage\n"; + let (_tree, ws, uri, position) = asking("class", top, " su"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); +} + +#[test] +fn a_generate_block_is_still_item_position() { + let top = "\ +module top; + for (genvar i = 0; i < 4; i++) begin : g + su + end +endmodule +"; + let (_tree, ws, uri, position) = asking("genfor", top, " su"); + assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}"); + + let top = "module top;\n generate\n su\n endgenerate\nendmodule\n"; + let (_tree, ws, uri, position) = asking("generate", top, " su"); + assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1); +} + +#[test] +fn no_skeleton_is_offered_outside_a_design_unit() { + let top = "su\nmodule top;\nendmodule\n"; + let (_tree, ws, uri, position) = asking("toplevel", top, "su"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); +} + +#[test] +fn a_prefix_that_matches_no_module_offers_no_skeleton() { + let top = "module top;\n zzz\nendmodule\n"; + let (_tree, ws, uri, position) = asking("nomatch", top, " zzz"); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); +} + +#[test] +fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() { + // Until 2026-08-30 tier 0 skipped it: there is no single definition to + // build a *skeleton* from, and the skeleton was the item. A name needs + // no definition, so round 1 offered the name and left the detail + // blank. Round 2 (owner ruling, same day) makes the ghost choose a + // copy rather than decline, so the popup names the copy the ghost will + // read — `nearest_definition`'s answer, which for a buffer at the tree + // root is the lexicographically smaller path. + let tree = Tree::new("dup"); + tree.write("a.sv", "module dup ();\nendmodule\n"); + tree.write("b.sv", "module dup ();\nendmodule\n"); + let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du"); + let items = items(completions(&ws, &uri, position, true)); + let item = find(&items, "dup").expect("the name is still known"); + assert_eq!(tier(item), TIER_MODULE, "{items:#?}"); + assert_eq!(item.detail.as_deref(), Some("module — a.sv")); +} + +/// The nearest-definition chooser, at the level `inline.rs` consumes it. +/// +/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling` +/// share `hw` and nothing more, and a byte-wise prefix would count the +/// `hw/top_` they spell alike and rank the copies by a coincidence. +#[test] +fn the_nearest_definition_is_the_one_sharing_the_most_path_components() { + let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv"); + let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv"); + let text = "module ast_dft ();\nendmodule\n"; + let index = WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]); + + let asking = |from: &str| { + nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from))) + .expect("a definition") + .to_path_buf() + }; + assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey); + assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling); + // Near neither, and no path at all: the tie falls to the smaller path + // rather than to whatever the index happens to hold first. + assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling); + assert_eq!( + nearest_definition(&index, "ast_dft", None).expect("a definition"), + darjeeling.as_path() + ); +} + +/// QA round-2 finding, fixed at lead review: a copy in the asking +/// buffer's own directory and one in a subdirectory of it share the same +/// number of leading components with the buffer (its filename never +/// matches a directory), and the lexicographic tie-break alone could pick +/// the deeper, less related copy. The real shape is opentitan's 61-way +/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv` +/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`. +#[test] +fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() { + let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv"); + let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv"); + let text = "module tb ();\nendmodule\n"; + for sources in [ + vec![(sibling.clone(), text), (deeper.clone(), text)], + vec![(deeper.clone(), text), (sibling.clone(), text)], + ] { + let index = WorkspaceIndex::build(sources); + let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv"); + assert_eq!( + nearest_definition(&index, "tb", Some(&from)).expect("a definition"), + sibling.as_path(), + "the shallower copy is the nearer one" + ); + } + // …and depth only breaks a tie: a deeper copy that genuinely shares + // more of the asking path still wins. + let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]); + let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv"); + assert_eq!( + nearest_definition(&index, "tb", Some(&from)).expect("a definition"), + deeper.as_path(), + "sharing more components outranks being shallow" + ); +} + +/// The answer is a property of the paths, not of the order the index was +/// built in — which is what makes it the same answer twice in a row, and +/// the same answer in two editors. +#[test] +fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() { + let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv"); + let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv"); + let text = "module ast_dft ();\nendmodule\n"; + let forwards = + WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]); + let backwards = + WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]); + for index in [&forwards, &backwards] { + let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv"); + assert_eq!( + nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"), + earlgrey.as_path() + ); + assert_eq!( + nearest_definition(index, "ast_dft", None).expect("a definition"), + darjeeling.as_path() + ); + } +} + +/// A module only one file declares goes through the same chooser and comes +/// back with the file `vlog_refactor::module_definition` picks — the +/// equivalence that says round 2 widened the twice-declared case and moved +/// nothing else. +#[test] +fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() { + let path = PathBuf::from("/rtl/sub.sv"); + let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]); + let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition"); + assert_eq!(expected, path.as_path()); + for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] { + assert_eq!( + nearest_definition(&index, "sub", from.as_deref()).expect("a definition"), + expected, + "{from:?}" + ); + } + // And a name nothing declares is `None` here where it is an `Err` + // there — the same "no answer", spelled the way each caller reads it. + assert!(nearest_definition(&index, "nope", None).is_none()); + assert!(vlog_refactor::module_definition(&index, "nope").is_err()); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/completion/tiers.rs b/crates/lucisv_server/src/completion/tiers.rs index 4bd5b93..bcdc698 100644 --- a/crates/lucisv_server/src/completion/tiers.rs +++ b/crates/lucisv_server/src/completion/tiers.rs @@ -238,713 +238,6 @@ pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: O } #[cfg(test)] -mod tests { - use super::*; - use crate::completion::harness::*; - use crate::completion::*; - use crate::uri::path_to_uri; - - // ------------------------------------------------------------------ - // tier 3 — templates - // ------------------------------------------------------------------ - - /// Only the templates — tier 3. - fn template_labels(items: &[CompletionItem]) -> Vec<&str> { - items - .iter() - .filter(|item| tier(item) == TIER_TEMPLATE) - .map(|item| item.label.as_str()) - .collect() - } - - /// The items offered at `needle`'s end in a buffer named `file`. - fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec { - let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle); - items(completions(&ws, &uri, position, true)) - } - - #[test] - fn a_statement_template_expands_where_a_statement_may_be_written() { - let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; - let items = offering("stmt", "top.sv", top, " if"); - let item = find(&items, "if begin/end").expect("the if template"); - assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET)); - assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET)); - assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed"); - assert_eq!( - inserted(item), - "if (${1:cond}) begin\n $0\n end", - "the site's own indentation, the condition first and the body last" - ); - assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items)); - } - - #[test] - fn a_template_never_swallows_the_keyword_it_is_reached_by() { - // Dedup is by label, so the labels are prose on purpose: `if` the - // keyword and `if begin/end` the template are two items, in that - // order of specificity. - let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; - let items = offering("both", "top.sv", top, " if"); - let keyword = find(&items, "if").expect("the bare keyword"); - let template = find(&items, "if begin/end").expect("the template"); - assert_eq!(tier(keyword), TIER_KEYWORD); - assert_eq!(tier(template), TIER_TEMPLATE); - assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word"); - } - - #[test] - fn a_template_ranks_below_a_name_the_code_declares() { - let top = "\ -module top; - logic if_enable; - always_comb begin - if - end -endmodule -"; - let items = offering("rank", "top.sv", top, " if"); - let symbol = find(&items, "if_enable").expect("a declaration in scope"); - let template = find(&items, "if begin/end").expect("the template"); - assert_eq!(tier(symbol), TIER_SCOPE); - assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton"); - } - - #[test] - fn statement_templates_and_item_templates_swap_places_with_the_position() { - // One prefix, `i`, reaching `if` in one place and `initial` in the - // other — so this is the gate and not the filter. - let inside = offering( - "posstmt", - "top.sv", - "module top;\n always_comb begin\n i\n end\nendmodule\n", - " i", - ); - assert!(template_labels(&inside).contains(&"if begin/end")); - assert!( - !template_labels(&inside).contains(&"initial begin/end"), - "an initial block is not a statement: {:?}", - template_labels(&inside) - ); - - let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i"); - assert!(template_labels(&at_item).contains(&"initial begin/end")); - assert!( - !template_labels(&at_item).contains(&"if begin/end"), - "a bare if is not a module item: {:?}", - template_labels(&at_item) - ); - } - - #[test] - fn an_always_template_is_a_module_item_and_nothing_else() { - let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw"); - assert_eq!( - template_labels(&at_item), - ["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"], - "and `alw` finds every one of them" - ); - - let inside = offering( - "alwstmt", - "top.sv", - "module top;\n always_comb begin\n alw\n end\nendmodule\n", - " alw", - ); - assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside)); - } - - #[test] - fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() { - let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log"); - assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]); - - let inside = offering( - "declstmt", - "top.sv", - "module top;\n always_comb begin\n log\n end\nendmodule\n", - " log", - ); - assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]); - } - - #[test] - fn the_file_name_decides_which_dialect_is_offered() { - let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l"); - assert!(template_labels(&sv).contains(&"logic name;")); - assert!(template_labels(&sv).contains(&"localparam int NAME = 0;")); - - let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l"); - assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog"); - assert!(template_labels(&v).contains(&"localparam integer NAME = 0;")); - - let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r"); - assert_eq!(template_labels(®), ["reg name;", "reg [N:0] name;"]); - let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r"); - assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file"); - - let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw"); - assert_eq!( - template_labels(&always), - ["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"], - "and no always_ff, which a .v file's compiler would reject" - ); - } - - #[test] - fn an_else_template_follows_an_end_on_the_same_line() { - let top = "\ -module top; - always_comb begin - if (a) begin - end el - end -endmodule -"; - let items = offering("elsetail", "top.sv", top, "end el"); - assert_eq!(template_labels(&items), ["else if", "else begin/end"]); - assert_eq!( - inserted(find(&items, "else if").expect("the else-if template")), - "else if (${1:cond}) begin\n $0\n end" - ); - } - - #[test] - fn a_word_in_the_middle_of_a_line_starts_no_statement() { - // The other half of the same rule: `x = if` is an expression, not a - // place a template belongs — and the general tiers still answer there. - let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n"; - let items = offering("midline", "top.sv", top, "x = if"); - assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items)); - assert!(find(&items, "if").is_some(), "the keyword tier still answers"); - } - - #[test] - fn no_template_is_offered_where_a_statement_cannot_go() { - for (name, top, needle) in [ - // A generate block is item position, not statement position. - ("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"), - // A `case` arm wants `label:`, not a bare statement. - ( - "casearm", - "module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n", - " if", - ), - // Nothing at all is open here. - ("toplevel", "if\nmodule top;\nendmodule\n", "if"), - // A port list is not a statement, however much it starts a line. - ("ports", "module top (\n if\n);\nendmodule\n", " if"), - ] { - let items = offering(name, "top.sv", top, needle); - assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items)); - } - } - - #[test] - fn a_subprogram_body_is_statement_position() { - for (name, top, needle) in [ - ("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"), - ("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"), - ( - "fnbegin", - "module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n", - " if", - ), - ] { - let items = offering(name, "top.sv", top, needle); - assert!(template_labels(&items).contains(&"if begin/end"), "{name}"); - } - } - - #[test] - fn nothing_templated_is_offered_inside_a_comment() { - let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n"; - let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if"); - assert!(completions(&ws, &uri, position, true).is_none()); - } - - #[test] - fn a_client_without_snippet_support_gets_the_template_filled_in() { - let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; - let (_tree, ws, uri, position) = asking("tmplplain", top, " if"); - let items = items(completions(&ws, &uri, position, false)); - let item = find(&items, "if begin/end").expect("the if template"); - assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); - let text = inserted(item); - assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}"); - assert_eq!(text, "if (cond) begin\n\n end"); - let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n"); - assert!( - vlog_parser::parse_source_tolerant(&probe).1.is_empty(), - "the inserted text must parse: {text}" - ); - } - - /// The premise the probe above rests on, stated as a test: the probe is - /// *discriminating*. Header recovery (TODO §32) widened what a tolerant - /// parse can read, so the question "did this insertion parse?" is only - /// worth asking while text that does **not** parse still says so. - #[test] - fn the_insertion_probe_still_reports_text_that_does_not_parse() { - let broken = "if (cond begin\n\n end"; - let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n"); - assert!( - !vlog_parser::parse_source_tolerant(&probe).1.is_empty(), - "recovery must not make a broken insertion look clean: {probe}" - ); - } - - #[test] - fn a_templates_documentation_shows_what_it_expands_to() { - let top = "module top;\n alw\nendmodule\n"; - let items = offering("tmpldocs", "top.sv", top, " alw"); - let item = find(&items, "always_comb begin/end").expect("the always_comb template"); - let Some(Documentation::MarkupContent(docs)) = &item.documentation else { - panic!("markdown documentation"); - }; - // Fenced with the language id the extension's TextMate grammar is - // registered for, so the panel renders highlighted rather than grey. - assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value); - assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value); - assert_eq!(item.detail.as_deref(), Some("combinational block — template")); - } - - // ------------------------------------------------------------------ - // tier 4 — keywords - // ------------------------------------------------------------------ - - #[test] - - fn every_keyword_the_lexer_knows_is_offered() { - let top = "module top;\n assign x = alw\nendmodule\n"; - let (_tree, ws, uri, position) = asking("keyword", top, "= alw"); - let items = items(completions(&ws, &uri, position, true)); - let keywords: Vec<&str> = - items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); - assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]); - let always = find(&items, "always").expect("`always`"); - assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD)); - assert_eq!(inserted(always), "always"); - } - - #[test] - fn the_keyword_tier_is_exactly_the_lexers_list() { - let top = "module top;\n assign x = \nendmodule\n"; - let (_tree, ws, uri, position) = asking("allkeywords", top, "= "); - let items = items(completions(&ws, &uri, position, true)); - let offered: HashSet<&str> = - items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); - let known: HashSet<&str> = KEYWORDS.iter().copied().collect(); - assert_eq!(offered, known, "no keyword may be missing and none invented"); - } - - // ------------------------------------------------------------------ - // tiers, ordering and dedup - // ------------------------------------------------------------------ - - #[test] - fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() { - let tree = Tree::new("tiers"); - tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n"); - tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n"); - let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "= w"); - let items = items(completions(&ws, &uri, position, true)); - - assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE); - assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX); - assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD); - assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD); - - let scope = find(&items, "w_local").expect("in scope"); - let word = find(&items, "w_elsewhere").expect("a project word"); - assert!(scope.sort_text < word.sort_text, "the client sorts scope above words"); - } - - #[test] - fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() { - let tree = Tree::new("dedup"); - // The same name, declared here and used elsewhere in the project. - tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n"); - let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n"; - let (_tree, ws, uri, position) = opened(tree, top, "= shared"); - let items = items(completions(&ws, &uri, position, true)); - let hits: Vec<&CompletionItem> = - items.iter().filter(|i| i.label == "shared_name").collect(); - assert_eq!(hits.len(), 1, "{hits:#?}"); - assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins"); - assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it"); - } - - #[test] - fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() { - let top = "\ -module top #(parameter int WIDTH = 8) (input logic clk); - typedef logic [1:0] pair_t; - logic [WIDTH-1:0] data; - function int f(); return 0; endfunction - assign x = -endmodule -"; - let (_tree, ws, uri, position) = asking("kinds", top, "assign x ="); - let items = items(completions(&ws, &uri, position, true)); - let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind; - assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT)); - assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD)); - assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER)); - assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE)); - assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION)); - assert_eq!( - find(&items, "data").expect("data").detail.as_deref(), - Some("logic [WIDTH-1:0] data;"), - "the declaration as written" - ); - } - - #[test] - fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() { - // `inner` is declared in a block the cursor is not in, so it may only - // arrive as one of this file's declarations (tier 2, `completion-ux`) - // — never as a visible declaration. - let top = "\ -module top; - initial begin : b - integer inner_only; - end - initial begin - x = inner - end -endmodule -"; - let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner"); - let items = items(completions(&ws, &uri, position, true)); - let item = find(&items, "inner_only").expect("known as a declaration at least"); - assert_eq!(tier(item), TIER_DECLARED, "{item:#?}"); - } - - // ------------------------------------------------------------------ - // fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md - // ------------------------------------------------------------------ - - /// A workspace holding the name the whole round is about, a scatter to - /// rank it against, and a `ce…` name that only a prefix reaches. - fn typing(name: &str) -> (Tree, Workspace, Uri) { - let tree = Tree::new(name); - tree.write( - "ast.sv", - "module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\ - endmodule\n", - ); - let path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - (tree, ws, uri) - } - - /// The response to `typed`, written mid-expression in `top.sv` — the - /// position where no tier is position-gated off. - fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option { - let text = format!("module top;\n assign x = {typed}\nendmodule\n"); - ws.set_document(uri.clone(), text.clone()); - let offset = - (text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32; - let position = ws.document(uri).expect("open").positions().position(offset); - completions(ws, uri, position, true) - } - - /// The headline: three characters reach a name no prefix ever would. - #[test] - fn three_characters_reach_a_name_a_prefix_never_would() { - let (_tree, mut ws, uri) = typing("fuzzyhit"); - for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] { - let found = items(after_typing(&mut ws, &uri, typed)); - let item = find(&found, "clk_osc_en_q") - .unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found))); - assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project"); - assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted"); - } - } - - /// …and the edit still replaces exactly what was typed, which is the - /// whole reason a fuzzy hit is usable at all: `clkenq` becomes - /// `clk_osc_en_q`, not `clkenqclk_osc_en_q`. - #[test] - fn a_fuzzy_hit_replaces_exactly_the_typed_word() { - let (_tree, mut ws, uri) = typing("fuzzyedit"); - let found = items(after_typing(&mut ws, &uri, "clkenq")); - let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit"); - let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { - panic!("a plain edit"); - }; - // ` assign x = clkenq` — the word starts at column 13 and the cursor - // is at its end. - assert_eq!(edit.range.start, Position { line: 1, character: 13 }); - assert_eq!(edit.range.end, Position { line: 1, character: 19 }); - assert_eq!(edit.new_text, "clk_osc_en_q"); - assert_eq!(item.filter_text, None, "the client filters on the label, as it should"); - } - - /// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters - /// in order and must still not reach it. - #[test] - fn two_characters_match_by_prefix_and_nothing_else() { - let (_tree, mut ws, uri) = typing("fuzzyfloor"); - for typed in ["c", "ce"] { - let found = items(after_typing(&mut ws, &uri, typed)); - assert!(!found.is_empty(), "premise: {typed:?} answers something"); - for item in &found { - assert!( - starts_with_ignore_case(&item.label, typed), - "{:?} is not a prefix match for {typed:?}", - item.label - ); - } - } - // The discriminator, spelled out: `ce` would reach it if it were fuzzy - // (`c` at 0, `e` at 8), and `cen` — one character more — does. - let two = items(after_typing(&mut ws, &uri, "ce")); - assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two)); - assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two)); - let three = items(after_typing(&mut ws, &uri, "cen")); - assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three)); - } - - /// The 1- and 2-character answers, pinned against what they were before - /// fuzzy matching existed. The keyword tier is checked as a set rather - /// than listed, so adding a reserved word to the lexer does not break a - /// test about completion. - #[test] - fn the_short_answers_are_what_they_always_were() { - let (_tree, mut ws, uri) = typing("fuzzygolden"); - for (typed, expected) in [ - // `c` itself used to be in the list, because the buffer being - // typed in holds it as an `Ident` token. `completion-ux` - // (2026-11-17) dropped it on purpose: the buffer-word tier skips - // the token under the cursor, and offering the user their own - // half-word back is noise. - ("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]), - ("ce", vec!["celsius"]), - ] { - let found = items(after_typing(&mut ws, &uri, typed)); - let named: Vec<&str> = found - .iter() - .filter(|item| tier(item) != TIER_KEYWORD) - .map(|item| item.label.as_str()) - .collect(); - assert_eq!(named, expected, "the names {typed:?} answers with"); - let keywords: Vec<&str> = found - .iter() - .filter(|item| tier(item) == TIER_KEYWORD) - .map(|item| item.label.as_str()) - .collect(); - let expected_keywords: Vec<&str> = - KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect(); - assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with"); - } - } - - /// **The `isIncomplete` trap.** VS Code asks again on the next keystroke - /// only when the last answer said it was incomplete, so a complete - /// two-character answer would swallow the third keystroke and fuzzy would - /// never fire at all. - #[test] - fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() { - let (_tree, mut ws, uri) = typing("fuzzyincomplete"); - for typed in ["", "c", "ce"] { - let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else { - panic!("a completion list for {typed:?}"); - }; - assert!(list.is_incomplete, "{typed:?} must ask to be asked again"); - } - // From the floor up the ordinary rule stands: complete when the whole - // hit set fit, which is sound because appending a character can only - // ever shrink it. - let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else { - panic!("a completion list"); - }; - assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len()); - } - - /// A prefix match is the best subsequence match there is, and the list - /// says so — asserted on the order of the array, which is what the cap - /// cuts and what a client that does not re-rank shows. - #[test] - fn a_prefix_hit_outranks_a_scattered_one() { - let (_tree, mut ws, uri) = typing("fuzzyrank"); - let found = items(after_typing(&mut ws, &uri, "clk")); - let at = |label: &str| { - found - .iter() - .position(|item| item.label == label) - .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) - }; - assert!( - at("clk_osc_en_q") < at("c_l_k_scatter"), - "the prefix hit leads: {:?}", - labels(&found) - ); - } - - /// Scoring the boundaries is visible in the order, not only in the score: - /// a run that starts after an underscore beats the same letters buried - /// mid-word. - #[test] - fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() { - let tree = Tree::new("fuzzyboundary"); - tree.write( - "ast.sv", - "module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n", - ); - let path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - let found = items(after_typing(&mut ws, &uri, "ena")); - let at = |label: &str| { - found - .iter() - .position(|item| item.label == label) - .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) - }; - assert!( - at("osc_ena_ready") < at("xxenaxx_ready"), - "the boundary run leads: {:?}", - labels(&found) - ); - drop(tree); - } - - /// Dedup survives the change: a name two tiers can reach is offered once, - /// by the better tier, whichever way it was matched. - #[test] - fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() { - let tree = Tree::new("fuzzydedup"); - // The same name, declared in this buffer (tier 1) and used in the - // project (tier 5), reachable from `clkenq` by neither prefix. - tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n"); - let path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; - ws.set_document(uri.clone(), text.to_string()); - let offset = (text.find("= clkenq").expect("needle") + 8) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - let found = items(completions(&ws, &uri, position, true)); - let hits: Vec<&CompletionItem> = - found.iter().filter(|item| item.label == "clk_osc_en_q").collect(); - assert_eq!(hits.len(), 1, "{hits:#?}"); - assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word"); - assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE)); - drop(tree); - } - - /// The tiers that did **not** go fuzzy, pinned so the split is a decision - /// and not a drift: keywords, templates and macro names still match by - /// prefix, and the module tier still matches by substring. - #[test] - fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() { - let tree = Tree::new("fuzzyunchanged"); - tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n"); - tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n"); - let path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - - // Mid-expression: the macro name is offered bare by tier 2 and must - // not be reachable by subsequence, and neither is a keyword. - let found = items(after_typing(&mut ws, &uri, "clkenq")); - assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found)); - let found = items(after_typing(&mut ws, &uri, "alws")); - assert!(labels(&found).is_empty() || !labels(&found).contains(&"always")); - - // A backtick still answers by prefix only. - let text = "module top;\n assign x = `CLKENQ\nendmodule\n"; - ws.set_document(uri.clone(), text.to_string()); - let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way"); - - // …and the module tier is still a substring match, which is wider - // than a prefix and narrower than a subsequence. - let text = "module top;\n osc_en\nendmodule\n"; - ws.set_document(uri.clone(), text.to_string()); - let offset = (text.find("osc_en").expect("needle") + 6) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - let found = items(completions(&ws, &uri, position, true)); - let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect(); - assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it"); - drop(tree); - } - - /// Header recovery (TODO §32) pinned where completion meets it: with a - /// half-typed parameter *above* the cursor, the module still has a scope, - /// so [`visible_symbols`] still answers from it — the parameters and ports - /// already typed are offered inside the very header being edited. - /// - /// Before this round the broken header took the whole `Module` node with - /// it, the body re-parsed at file scope, and the scope chain covering this - /// offset held nothing at all. - #[test] - fn a_broken_header_still_completes_from_the_modules_scope() { - let top = "\ -module top #(parameter W = , parameter DEPTH = 4) ( - input logic clk_i, - output logic DE -); - logic w_local; -endmodule -"; - let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE"); - let found = items(completions(&ws, &uri, position, true)); - let item = find(&found, "DEPTH").expect("the parameter typed after the broken one"); - assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope"); - } - - /// The scope tier goes fuzzy too, with no mask table behind it — it is - /// the one tier computed per request. - #[test] - fn a_declaration_in_scope_is_reached_by_subsequence() { - let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; - let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq"); - let found = items(completions(&ws, &uri, position, true)); - let item = find(&found, "clk_osc_en_q").expect("the declaration"); - assert_eq!(tier(item), TIER_SCOPE); - assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;")); - } - - /// The index tier goes fuzzy too — a package member is reached the same - /// way a project word is. - #[test] - fn a_project_declaration_is_reached_by_subsequence() { - let tree = Tree::new("fuzzyindex"); - tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n"); - let path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - let found = items(after_typing(&mut ws, &uri, "clkenq")); - let item = find(&found, "CLK_OSC_EN_Q").expect("the package member"); - assert_eq!(tier(item), TIER_INDEX); - assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT)); - drop(tree); - } - - #[test] - fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() { - let tree = Tree::new("overlay"); - let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n"); - let top = "module top;\n assign x = ov\nendmodule\n"; - let (_tree, mut ws, uri, position) = opened(tree, top, "= ov"); - - let other_uri = path_to_uri(&other).expect("uri"); - ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string()); - ws.rebuild_index(); - let items = items(completions(&ws, &uri, position, true)); - assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items)); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/completion/tiers/tests.rs b/crates/lucisv_server/src/completion/tiers/tests.rs new file mode 100644 index 0000000..a879f5f --- /dev/null +++ b/crates/lucisv_server/src/completion/tiers/tests.rs @@ -0,0 +1,704 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::completion::harness::*; +use crate::completion::*; +use crate::uri::path_to_uri; + +// ------------------------------------------------------------------ +// tier 3 — templates +// ------------------------------------------------------------------ + +/// Only the templates — tier 3. +fn template_labels(items: &[CompletionItem]) -> Vec<&str> { + items + .iter() + .filter(|item| tier(item) == TIER_TEMPLATE) + .map(|item| item.label.as_str()) + .collect() +} + +/// The items offered at `needle`'s end in a buffer named `file`. +fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec { + let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle); + items(completions(&ws, &uri, position, true)) +} + +#[test] +fn a_statement_template_expands_where_a_statement_may_be_written() { + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let items = offering("stmt", "top.sv", top, " if"); + let item = find(&items, "if begin/end").expect("the if template"); + assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET)); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET)); + assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed"); + assert_eq!( + inserted(item), + "if (${1:cond}) begin\n $0\n end", + "the site's own indentation, the condition first and the body last" + ); + assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items)); +} + +#[test] +fn a_template_never_swallows_the_keyword_it_is_reached_by() { + // Dedup is by label, so the labels are prose on purpose: `if` the + // keyword and `if begin/end` the template are two items, in that + // order of specificity. + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let items = offering("both", "top.sv", top, " if"); + let keyword = find(&items, "if").expect("the bare keyword"); + let template = find(&items, "if begin/end").expect("the template"); + assert_eq!(tier(keyword), TIER_KEYWORD); + assert_eq!(tier(template), TIER_TEMPLATE); + assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word"); +} + +#[test] +fn a_template_ranks_below_a_name_the_code_declares() { + let top = "\ +module top; + logic if_enable; + always_comb begin + if + end +endmodule +"; + let items = offering("rank", "top.sv", top, " if"); + let symbol = find(&items, "if_enable").expect("a declaration in scope"); + let template = find(&items, "if begin/end").expect("the template"); + assert_eq!(tier(symbol), TIER_SCOPE); + assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton"); +} + +#[test] +fn statement_templates_and_item_templates_swap_places_with_the_position() { + // One prefix, `i`, reaching `if` in one place and `initial` in the + // other — so this is the gate and not the filter. + let inside = offering( + "posstmt", + "top.sv", + "module top;\n always_comb begin\n i\n end\nendmodule\n", + " i", + ); + assert!(template_labels(&inside).contains(&"if begin/end")); + assert!( + !template_labels(&inside).contains(&"initial begin/end"), + "an initial block is not a statement: {:?}", + template_labels(&inside) + ); + + let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i"); + assert!(template_labels(&at_item).contains(&"initial begin/end")); + assert!( + !template_labels(&at_item).contains(&"if begin/end"), + "a bare if is not a module item: {:?}", + template_labels(&at_item) + ); +} + +#[test] +fn an_always_template_is_a_module_item_and_nothing_else() { + let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw"); + assert_eq!( + template_labels(&at_item), + ["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"], + "and `alw` finds every one of them" + ); + + let inside = offering( + "alwstmt", + "top.sv", + "module top;\n always_comb begin\n alw\n end\nendmodule\n", + " alw", + ); + assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside)); +} + +#[test] +fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() { + let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log"); + assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]); + + let inside = offering( + "declstmt", + "top.sv", + "module top;\n always_comb begin\n log\n end\nendmodule\n", + " log", + ); + assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]); +} + +#[test] +fn the_file_name_decides_which_dialect_is_offered() { + let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l"); + assert!(template_labels(&sv).contains(&"logic name;")); + assert!(template_labels(&sv).contains(&"localparam int NAME = 0;")); + + let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l"); + assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog"); + assert!(template_labels(&v).contains(&"localparam integer NAME = 0;")); + + let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r"); + assert_eq!(template_labels(®), ["reg name;", "reg [N:0] name;"]); + let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r"); + assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file"); + + let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw"); + assert_eq!( + template_labels(&always), + ["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"], + "and no always_ff, which a .v file's compiler would reject" + ); +} + +#[test] +fn an_else_template_follows_an_end_on_the_same_line() { + let top = "\ +module top; + always_comb begin + if (a) begin + end el + end +endmodule +"; + let items = offering("elsetail", "top.sv", top, "end el"); + assert_eq!(template_labels(&items), ["else if", "else begin/end"]); + assert_eq!( + inserted(find(&items, "else if").expect("the else-if template")), + "else if (${1:cond}) begin\n $0\n end" + ); +} + +#[test] +fn a_word_in_the_middle_of_a_line_starts_no_statement() { + // The other half of the same rule: `x = if` is an expression, not a + // place a template belongs — and the general tiers still answer there. + let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n"; + let items = offering("midline", "top.sv", top, "x = if"); + assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items)); + assert!(find(&items, "if").is_some(), "the keyword tier still answers"); +} + +#[test] +fn no_template_is_offered_where_a_statement_cannot_go() { + for (name, top, needle) in [ + // A generate block is item position, not statement position. + ("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"), + // A `case` arm wants `label:`, not a bare statement. + ( + "casearm", + "module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n", + " if", + ), + // Nothing at all is open here. + ("toplevel", "if\nmodule top;\nendmodule\n", "if"), + // A port list is not a statement, however much it starts a line. + ("ports", "module top (\n if\n);\nendmodule\n", " if"), + ] { + let items = offering(name, "top.sv", top, needle); + assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items)); + } +} + +#[test] +fn a_subprogram_body_is_statement_position() { + for (name, top, needle) in [ + ("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"), + ("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"), + ( + "fnbegin", + "module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n", + " if", + ), + ] { + let items = offering(name, "top.sv", top, needle); + assert!(template_labels(&items).contains(&"if begin/end"), "{name}"); + } +} + +#[test] +fn nothing_templated_is_offered_inside_a_comment() { + let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if"); + assert!(completions(&ws, &uri, position, true).is_none()); +} + +#[test] +fn a_client_without_snippet_support_gets_the_template_filled_in() { + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("tmplplain", top, " if"); + let items = items(completions(&ws, &uri, position, false)); + let item = find(&items, "if begin/end").expect("the if template"); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); + let text = inserted(item); + assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}"); + assert_eq!(text, "if (cond) begin\n\n end"); + let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n"); + assert!( + vlog_parser::parse_source_tolerant(&probe).1.is_empty(), + "the inserted text must parse: {text}" + ); +} + +/// The premise the probe above rests on, stated as a test: the probe is +/// *discriminating*. Header recovery (TODO §32) widened what a tolerant +/// parse can read, so the question "did this insertion parse?" is only +/// worth asking while text that does **not** parse still says so. +#[test] +fn the_insertion_probe_still_reports_text_that_does_not_parse() { + let broken = "if (cond begin\n\n end"; + let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n"); + assert!( + !vlog_parser::parse_source_tolerant(&probe).1.is_empty(), + "recovery must not make a broken insertion look clean: {probe}" + ); +} + +#[test] +fn a_templates_documentation_shows_what_it_expands_to() { + let top = "module top;\n alw\nendmodule\n"; + let items = offering("tmpldocs", "top.sv", top, " alw"); + let item = find(&items, "always_comb begin/end").expect("the always_comb template"); + let Some(Documentation::MarkupContent(docs)) = &item.documentation else { + panic!("markdown documentation"); + }; + // Fenced with the language id the extension's TextMate grammar is + // registered for, so the panel renders highlighted rather than grey. + assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value); + assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value); + assert_eq!(item.detail.as_deref(), Some("combinational block — template")); +} + +// ------------------------------------------------------------------ +// tier 4 — keywords +// ------------------------------------------------------------------ + +#[test] + +fn every_keyword_the_lexer_knows_is_offered() { + let top = "module top;\n assign x = alw\nendmodule\n"; + let (_tree, ws, uri, position) = asking("keyword", top, "= alw"); + let items = items(completions(&ws, &uri, position, true)); + let keywords: Vec<&str> = + items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); + assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]); + let always = find(&items, "always").expect("`always`"); + assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD)); + assert_eq!(inserted(always), "always"); +} + +#[test] +fn the_keyword_tier_is_exactly_the_lexers_list() { + let top = "module top;\n assign x = \nendmodule\n"; + let (_tree, ws, uri, position) = asking("allkeywords", top, "= "); + let items = items(completions(&ws, &uri, position, true)); + let offered: HashSet<&str> = + items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); + let known: HashSet<&str> = KEYWORDS.iter().copied().collect(); + assert_eq!(offered, known, "no keyword may be missing and none invented"); +} + +// ------------------------------------------------------------------ +// tiers, ordering and dedup +// ------------------------------------------------------------------ + +#[test] +fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() { + let tree = Tree::new("tiers"); + tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n"); + tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n"); + let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= w"); + let items = items(completions(&ws, &uri, position, true)); + + assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE); + assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX); + assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD); + assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD); + + let scope = find(&items, "w_local").expect("in scope"); + let word = find(&items, "w_elsewhere").expect("a project word"); + assert!(scope.sort_text < word.sort_text, "the client sorts scope above words"); +} + +#[test] +fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() { + let tree = Tree::new("dedup"); + // The same name, declared here and used elsewhere in the project. + tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n"); + let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= shared"); + let items = items(completions(&ws, &uri, position, true)); + let hits: Vec<&CompletionItem> = items.iter().filter(|i| i.label == "shared_name").collect(); + assert_eq!(hits.len(), 1, "{hits:#?}"); + assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins"); + assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it"); +} + +#[test] +fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() { + let top = "\ +module top #(parameter int WIDTH = 8) (input logic clk); + typedef logic [1:0] pair_t; + logic [WIDTH-1:0] data; + function int f(); return 0; endfunction + assign x = +endmodule +"; + let (_tree, ws, uri, position) = asking("kinds", top, "assign x ="); + let items = items(completions(&ws, &uri, position, true)); + let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind; + assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT)); + assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD)); + assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER)); + assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE)); + assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION)); + assert_eq!( + find(&items, "data").expect("data").detail.as_deref(), + Some("logic [WIDTH-1:0] data;"), + "the declaration as written" + ); +} + +#[test] +fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() { + // `inner` is declared in a block the cursor is not in, so it may only + // arrive as one of this file's declarations (tier 2, `completion-ux`) + // — never as a visible declaration. + let top = "\ +module top; + initial begin : b + integer inner_only; + end + initial begin + x = inner + end +endmodule +"; + let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner"); + let items = items(completions(&ws, &uri, position, true)); + let item = find(&items, "inner_only").expect("known as a declaration at least"); + assert_eq!(tier(item), TIER_DECLARED, "{item:#?}"); +} + +// ------------------------------------------------------------------ +// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md +// ------------------------------------------------------------------ + +/// A workspace holding the name the whole round is about, a scatter to +/// rank it against, and a `ce…` name that only a prefix reaches. +fn typing(name: &str) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + tree.write( + "ast.sv", + "module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\ + endmodule\n", + ); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + (tree, ws, uri) +} + +/// The response to `typed`, written mid-expression in `top.sv` — the +/// position where no tier is position-gated off. +fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option { + let text = format!("module top;\n assign x = {typed}\nendmodule\n"); + ws.set_document(uri.clone(), text.clone()); + let offset = (text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32; + let position = ws.document(uri).expect("open").positions().position(offset); + completions(ws, uri, position, true) +} + +/// The headline: three characters reach a name no prefix ever would. +#[test] +fn three_characters_reach_a_name_a_prefix_never_would() { + let (_tree, mut ws, uri) = typing("fuzzyhit"); + for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] { + let found = items(after_typing(&mut ws, &uri, typed)); + let item = find(&found, "clk_osc_en_q") + .unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found))); + assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project"); + assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted"); + } +} + +/// …and the edit still replaces exactly what was typed, which is the +/// whole reason a fuzzy hit is usable at all: `clkenq` becomes +/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`. +#[test] +fn a_fuzzy_hit_replaces_exactly_the_typed_word() { + let (_tree, mut ws, uri) = typing("fuzzyedit"); + let found = items(after_typing(&mut ws, &uri, "clkenq")); + let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit"); + let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + // ` assign x = clkenq` — the word starts at column 13 and the cursor + // is at its end. + assert_eq!(edit.range.start, Position { line: 1, character: 13 }); + assert_eq!(edit.range.end, Position { line: 1, character: 19 }); + assert_eq!(edit.new_text, "clk_osc_en_q"); + assert_eq!(item.filter_text, None, "the client filters on the label, as it should"); +} + +/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters +/// in order and must still not reach it. +#[test] +fn two_characters_match_by_prefix_and_nothing_else() { + let (_tree, mut ws, uri) = typing("fuzzyfloor"); + for typed in ["c", "ce"] { + let found = items(after_typing(&mut ws, &uri, typed)); + assert!(!found.is_empty(), "premise: {typed:?} answers something"); + for item in &found { + assert!( + starts_with_ignore_case(&item.label, typed), + "{:?} is not a prefix match for {typed:?}", + item.label + ); + } + } + // The discriminator, spelled out: `ce` would reach it if it were fuzzy + // (`c` at 0, `e` at 8), and `cen` — one character more — does. + let two = items(after_typing(&mut ws, &uri, "ce")); + assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two)); + assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two)); + let three = items(after_typing(&mut ws, &uri, "cen")); + assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three)); +} + +/// The 1- and 2-character answers, pinned against what they were before +/// fuzzy matching existed. The keyword tier is checked as a set rather +/// than listed, so adding a reserved word to the lexer does not break a +/// test about completion. +#[test] +fn the_short_answers_are_what_they_always_were() { + let (_tree, mut ws, uri) = typing("fuzzygolden"); + for (typed, expected) in [ + // `c` itself used to be in the list, because the buffer being + // typed in holds it as an `Ident` token. `completion-ux` + // (2026-11-17) dropped it on purpose: the buffer-word tier skips + // the token under the cursor, and offering the user their own + // half-word back is noise. + ("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]), + ("ce", vec!["celsius"]), + ] { + let found = items(after_typing(&mut ws, &uri, typed)); + let named: Vec<&str> = found + .iter() + .filter(|item| tier(item) != TIER_KEYWORD) + .map(|item| item.label.as_str()) + .collect(); + assert_eq!(named, expected, "the names {typed:?} answers with"); + let keywords: Vec<&str> = found + .iter() + .filter(|item| tier(item) == TIER_KEYWORD) + .map(|item| item.label.as_str()) + .collect(); + let expected_keywords: Vec<&str> = + KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect(); + assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with"); + } +} + +/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke +/// only when the last answer said it was incomplete, so a complete +/// two-character answer would swallow the third keystroke and fuzzy would +/// never fire at all. +#[test] +fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() { + let (_tree, mut ws, uri) = typing("fuzzyincomplete"); + for typed in ["", "c", "ce"] { + let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else { + panic!("a completion list for {typed:?}"); + }; + assert!(list.is_incomplete, "{typed:?} must ask to be asked again"); + } + // From the floor up the ordinary rule stands: complete when the whole + // hit set fit, which is sound because appending a character can only + // ever shrink it. + let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else { + panic!("a completion list"); + }; + assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len()); +} + +/// A prefix match is the best subsequence match there is, and the list +/// says so — asserted on the order of the array, which is what the cap +/// cuts and what a client that does not re-rank shows. +#[test] +fn a_prefix_hit_outranks_a_scattered_one() { + let (_tree, mut ws, uri) = typing("fuzzyrank"); + let found = items(after_typing(&mut ws, &uri, "clk")); + let at = |label: &str| { + found + .iter() + .position(|item| item.label == label) + .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) + }; + assert!(at("clk_osc_en_q") < at("c_l_k_scatter"), "the prefix hit leads: {:?}", labels(&found)); +} + +/// Scoring the boundaries is visible in the order, not only in the score: +/// a run that starts after an underscore beats the same letters buried +/// mid-word. +#[test] +fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() { + let tree = Tree::new("fuzzyboundary"); + tree.write( + "ast.sv", + "module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n", + ); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let found = items(after_typing(&mut ws, &uri, "ena")); + let at = |label: &str| { + found + .iter() + .position(|item| item.label == label) + .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) + }; + assert!( + at("osc_ena_ready") < at("xxenaxx_ready"), + "the boundary run leads: {:?}", + labels(&found) + ); + drop(tree); +} + +/// Dedup survives the change: a name two tiers can reach is offered once, +/// by the better tier, whichever way it was matched. +#[test] +fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() { + let tree = Tree::new("fuzzydedup"); + // The same name, declared in this buffer (tier 1) and used in the + // project (tier 5), reachable from `clkenq` by neither prefix. + tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("= clkenq").expect("needle") + 8) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let found = items(completions(&ws, &uri, position, true)); + let hits: Vec<&CompletionItem> = + found.iter().filter(|item| item.label == "clk_osc_en_q").collect(); + assert_eq!(hits.len(), 1, "{hits:#?}"); + assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word"); + assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE)); + drop(tree); +} + +/// The tiers that did **not** go fuzzy, pinned so the split is a decision +/// and not a drift: keywords, templates and macro names still match by +/// prefix, and the module tier still matches by substring. +#[test] +fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() { + let tree = Tree::new("fuzzyunchanged"); + tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n"); + tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + + // Mid-expression: the macro name is offered bare by tier 2 and must + // not be reachable by subsequence, and neither is a keyword. + let found = items(after_typing(&mut ws, &uri, "clkenq")); + assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found)); + let found = items(after_typing(&mut ws, &uri, "alws")); + assert!(labels(&found).is_empty() || !labels(&found).contains(&"always")); + + // A backtick still answers by prefix only. + let text = "module top;\n assign x = `CLKENQ\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way"); + + // …and the module tier is still a substring match, which is wider + // than a prefix and narrower than a subsequence. + let text = "module top;\n osc_en\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("osc_en").expect("needle") + 6) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let found = items(completions(&ws, &uri, position, true)); + let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect(); + assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it"); + drop(tree); +} + +/// Header recovery (TODO §32) pinned where completion meets it: with a +/// half-typed parameter *above* the cursor, the module still has a scope, +/// so [`visible_symbols`] still answers from it — the parameters and ports +/// already typed are offered inside the very header being edited. +/// +/// Before this round the broken header took the whole `Module` node with +/// it, the body re-parsed at file scope, and the scope chain covering this +/// offset held nothing at all. +#[test] +fn a_broken_header_still_completes_from_the_modules_scope() { + let top = "\ +module top #(parameter W = , parameter DEPTH = 4) ( + input logic clk_i, + output logic DE +); + logic w_local; +endmodule +"; + let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE"); + let found = items(completions(&ws, &uri, position, true)); + let item = find(&found, "DEPTH").expect("the parameter typed after the broken one"); + assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope"); +} + +/// The scope tier goes fuzzy too, with no mask table behind it — it is +/// the one tier computed per request. +#[test] +fn a_declaration_in_scope_is_reached_by_subsequence() { + let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; + let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq"); + let found = items(completions(&ws, &uri, position, true)); + let item = find(&found, "clk_osc_en_q").expect("the declaration"); + assert_eq!(tier(item), TIER_SCOPE); + assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;")); +} + +/// The index tier goes fuzzy too — a package member is reached the same +/// way a project word is. +#[test] +fn a_project_declaration_is_reached_by_subsequence() { + let tree = Tree::new("fuzzyindex"); + tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let found = items(after_typing(&mut ws, &uri, "clkenq")); + let item = find(&found, "CLK_OSC_EN_Q").expect("the package member"); + assert_eq!(tier(item), TIER_INDEX); + assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT)); + drop(tree); +} + +#[test] +fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() { + let tree = Tree::new("overlay"); + let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n"); + let top = "module top;\n assign x = ov\nendmodule\n"; + let (_tree, mut ws, uri, position) = opened(tree, top, "= ov"); + + let other_uri = path_to_uri(&other).expect("uri"); + ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string()); + ws.rebuild_index(); + let items = items(completions(&ws, &uri, position, true)); + assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items)); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/file_ops.rs b/crates/lucisv_server/src/file_ops.rs index d3fbbd0..8cc6bd8 100644 --- a/crates/lucisv_server/src/file_ops.rs +++ b/crates/lucisv_server/src/file_ops.rs @@ -491,1181 +491,6 @@ fn path_of(uri: &str) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use std::fs; - - /// A scratch tree, removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_file_ops_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).expect("parent"); - } - fs::write(&path, text).expect("write"); - path - } - - /// The workspace this tree's `files.f` governs, with nothing open. - fn workspace(&self) -> Workspace { - let mut ws = Workspace::default(); - if self.path.join("files.f").is_file() { - ws.set_client_settings(crate::settings::ClientSettings { - filelist: Some(self.path.join("files.f").display().to_string()), - ..Default::default() - }); - } - ws.open_whole_workspace(vec![self.path.clone()]); - ws - } - - fn rename(&self, from: &str, to: &str) -> FileRename { - FileRename { - old_uri: uri_of(&self.path.join(from)), - new_uri: uri_of(&self.path.join(to)), - } - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - fn uri_of(path: &Path) -> String { - path_to_uri(path).expect("uri").as_str().to_string() - } - - /// The sufficiency property [`will_rename`]'s narrowed sweep rests on, - /// asserted directly over whatever tree the caller built: every in-scope - /// file the sweep no longer reads writes no `` `include`` this workspace - /// can resolve, so its turn in the loop could only ever have `continue`d. - /// - /// Checked as the complement rather than as an equality because it is the - /// complement that could hide a lost edit: an extra file in the set costs - /// a read, a missing one costs an `` `include`` left pointing at nothing. - fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) { - let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); - let graph = ws.includes(); - let mut skipped = 0usize; - for (path, text) in ws.sources() { - if read.contains(&path) { - continue; - } - skipped += 1; - for include in scan(&text) { - assert!( - graph.resolve(Some(&path), &include).is_none(), - "{} was skipped but its `include \"{}\"` resolves", - path.display(), - include.target - ); - } - } - assert!(skipped > 0, "the tree must actually exercise the narrowing"); - } - - /// The one file the rewrite touches, as (uri, the new path spellings). - fn only_file(rewrite: &Rewrite) -> (String, Vec) { - let edit = rewrite.edit.as_ref().expect("an edit"); - let changes = edit.changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 1, "expected one file, got {changes:#?}"); - let (uri, edits) = changes.iter().next().expect("one"); - (uri.as_str().to_string(), edits.iter().map(|e| e.new_text.clone()).collect()) - } - - /// Apply a rewrite to `text` the way a client would, so the test reads the - /// file the user would end up with. - fn applied(text: &str, rewrite: &Rewrite, uri: &str) -> String { - let edit = rewrite.edit.as_ref().expect("an edit"); - let changes = edit.changes.as_ref().expect("changes"); - let (_, edits) = changes - .iter() - .find(|(key, _)| key.as_str() == uri) - .unwrap_or_else(|| panic!("no edits for {uri} in {changes:#?}")); - let index = LineIndex::new(text); - let positions = Positions::new(text, &index); - // Back to front, so an earlier edit's offsets stay valid. - let mut ranges: Vec<(TextRange, String)> = edits - .iter() - .map(|edit| { - let start = positions.offset(edit.range.start); - let end = positions.offset(edit.range.end); - (TextRange::new(start, end), edit.new_text.clone()) - }) - .collect(); - ranges.sort_by_key(|(range, _)| std::cmp::Reverse(range.start)); - let mut out = text.to_string(); - for (range, new_text) in ranges { - out.replace_range(range.as_range(), &new_text); - } - out - } - - /// A wide workspace where almost nothing includes anything — the shape a - /// real one has, and the reason the sweep no longer reads all of it. The - /// answer must be the one the whole-workspace sweep gave, and the property - /// above must hold over the same tree. - #[test] - fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() { - let tree = Tree::new("narrowed"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); - let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n"); - // Twenty files with no `include at all, plus two whose includes name - // nothing on disk — both kinds are files the sweep may skip. - for n in 0..20 { - let rel = format!("rtl/quiet{n}.sv"); - tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n")); - list.push_str(&format!("{rel}\n")); - } - for n in 0..2 { - let rel = format!("rtl/dangling{n}.sv"); - tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n")); - list.push_str(&format!("{rel}\n")); - } - tree.write("files.f", &list); - let ws = tree.workspace(); - - assert_eq!(ws.sources().len(), 24, "the whole scope"); - assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands"); - nothing_skipped_has_an_include_to_rewrite(&ws); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - } - - /// An `` `include`` typed into a buffer and not yet saved is in no edge the - /// graph holds — the graph is rebuilt on save. The buffer is in the sweep - /// whatever the graph says, which is what keeps that include rewritten. - #[test] - fn an_unsaved_include_is_still_rewritten() { - let tree = Tree::new("unsaved_include"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "module t;\nendmodule\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let mut ws = tree.workspace(); - assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include"); - - let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n"; - ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string()); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - assert_eq!( - applied(buffered, &rewrite, &uri_of(&top)), - "`include \"widths.svh\"\nmodule t;\nendmodule\n" - ); - } - - /// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must - /// narrow to `a.svh` (its *direct* includer, via `includers()`), and must - /// **not** narrow away a file that includes `a.svh` but never spells - /// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of - /// the file that moves, so a third-order includer has nothing to rewrite - /// either way, but it must still not be mistaken for a candidate (which - /// would cost a read, not a corruption, but is worth pinning). - #[test] - fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() { - let tree = Tree::new("chain"); - tree.write("rtl/b.svh", "`define W 8\n"); - let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n"); - let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n"); - tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n"); - let ws = tree.workspace(); - - let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); - assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}"); - assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}"); - nothing_skipped_has_an_include_to_rewrite(&ws); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - // Only a.svh's own `include \"b.svh\"` line changes; c.sv's - // `include \"a.svh\"` is untouched because a.svh itself did not move. - assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()])); - } - - /// QA, 2026-08-28 attack: an include spelled with different letter case - /// than the file actually has on disk (`` `include "DEFS.svh"`` against a - /// real `defs.svh`) — legal and silently resolved on the common - /// case-insensitive filesystems (confirmed case-insensitive in this test - /// environment). `IncludeGraph::found`/`found_as_if` resolve through the - /// filesystem's own `Path::is_file`, so the includer still lands in `raw` - /// (keyed by the *includer's* path, not the target's spelling) and - /// therefore in `includers()`/`include_sources()` — the narrowing must not - /// accidentally depend on the include's target spelling matching the - /// disk's. - /// - /// Only a case-insensitive filesystem (macOS, Windows by default) resolves - /// the mismatched spelling at all; on a case-sensitive one (Linux) there - /// is no include to narrow in, so the test checks which it is on and stops - /// there, saying so. - #[test] - fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() { - let tree = Tree::new("case_mismatch"); - tree.write("rtl/defs.svh", "`define W 8\n"); - if !tree.path.join("rtl/DEFS.svh").is_file() { - eprintln!("skipped: this filesystem is case-sensitive; `DEFS.svh` names no file"); - return; - } - let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); - assert!( - read.contains(&top), - "top.sv's case-mismatched include still resolves and must narrow in: {read:?}" - ); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - } - - #[test] - fn a_same_directory_rename_keeps_the_bare_form() { - let tree = Tree::new("samedir"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - - let text = fs::read_to_string(&top).expect("read"); - assert_eq!( - applied(&text, &rewrite, &uri_of(&top)), - "`include \"widths.svh\"\nmodule t;\nendmodule\n", - "the delimiters, the backtick and the rest of the file are untouched" - ); - } - - /// Renaming a file that is open **on the large-file fast path** - /// (`docs/features/large-file-mode/README.md`). The renamed file's own - /// `` `include``s (it has none here — a netlist would not) are out of - /// `will_rename`'s sweep because `Workspace::sources()` already leaves a - /// fast-path buffer out entirely; what this pins is the other half: an - /// **unrelated** small file's include *of* the large file still resolves - /// and still gets rewritten, because resolution walks the filesystem - /// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list - /// the fast-path buffer was excluded from. - #[test] - fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() { - let tree = Tree::new("largerename"); - let net = tree.write("rtl/net.v", "module net;\nendmodule\n"); - let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n"); - tree.write("files.f", "rtl/top.sv\nrtl/net.v\n"); - let mut ws = tree.workspace(); - ws.set_client_settings(crate::settings::ClientSettings { - filelist: Some(tree.path.join("files.f").display().to_string()), - large_file_threshold: 10, - ..Default::default() - }); - let net_uri = path_to_uri(&net).expect("uri"); - // Padded past the 10-byte test threshold, so it opens on the fast path. - ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20))); - assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path"); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()])); - } - - #[test] - fn a_cross_directory_rename_re_spells_through_an_incdir() { - let tree = Tree::new("crossdir"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\n"); - fs::create_dir_all(tree.path.join("inc")).expect("mkdir"); - let ws = tree.workspace(); - - // Into a directory the filelist already names as an include path, with - // a new name: still the bare form, because the incdir rung reaches it - // — the shortest suffix that resolves, not the path from the includer. - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - - // And the same move keeping the name needs no edit at all: the line - // already reads correctly once the incdir rung answers it. - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/defs.svh")]); - assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - } - - #[test] - fn a_move_no_include_path_reaches_is_left_alone_and_reported() { - let tree = Tree::new("unreachable"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl/top.sv", "`include \n"); - // The angled form resolves against incdirs only, so `far/` — which is - // no include path — cannot be spelled from here at all. - tree.write("files.f", "+incdir+rtl\nrtl/top.sv\n"); - fs::create_dir_all(tree.path.join("far")).expect("mkdir"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "far/defs.svh")]); - assert!(rewrite.edit.is_none(), "no edit at all: {:?}", rewrite.edit); - assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); - let warning = &rewrite.warnings[0]; - assert!(warning.contains("top.sv:1"), "{warning}"); - assert!(warning.contains("`include "), "{warning}"); - assert!(warning.contains("left unchanged"), "{warning}"); - assert!(warning.contains("far/defs.svh"), "the new location is named: {warning}"); - } - - #[test] - fn every_include_of_one_renamed_file_is_rewritten_across_the_workspace() { - let tree = Tree::new("everywhere"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let a = tree.write("rtl/a.sv", "`include \"defs.svh\"\n`include \"defs.svh\"\n"); - let b = tree.write("rtl/b.sv", "module b;\nendmodule\n`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/a.sv\nrtl/b.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = rewrite.edit.as_ref().expect("edit").changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 2, "both files: {changes:#?}"); - let for_a = changes.iter().find(|(uri, _)| uri.as_str() == uri_of(&a)).expect("a.sv"); - assert_eq!(for_a.1.len(), 2, "both includes in the one file"); - - let text = fs::read_to_string(&b).expect("read"); - assert_eq!( - applied(&text, &rewrite, &uri_of(&b)), - "module b;\nendmodule\n`include \"widths.svh\"\n" - ); - } - - #[test] - fn an_include_of_a_different_file_with_the_same_name_is_untouched() { - // The whole reason this resolves rather than matching text: two - // `defs.svh` in one workspace, and only the one that is renamed moves. - let tree = Tree::new("samename"); - tree.write("a/defs.svh", "`define W 1\n"); - tree.write("b/defs.svh", "`define W 2\n"); - let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); - tree.write("b/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "a/top.sv\na/defs.svh\nb/top.sv\nb/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let (uri, spellings) = only_file(&rewrite); - assert_eq!(uri, uri_of(&top_a), "only the file whose target moved"); - assert_eq!(spellings, vec!["widths.svh".to_string()]); - } - - #[test] - fn several_renames_in_one_request_answer_one_edit() { - let tree = Tree::new("batch"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl/ports.svh", "`define P 2\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n`include \"ports.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\nrtl/ports.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename( - &ws, - &[ - tree.rename("rtl/defs.svh", "rtl/widths.svh"), - tree.rename("rtl/ports.svh", "rtl/pins.svh"), - ], - ); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let text = fs::read_to_string(&top).expect("read"); - assert_eq!( - applied(&text, &rewrite, &uri_of(&top)), - "`include \"widths.svh\"\n`include \"pins.svh\"\n" - ); - } - - #[test] - fn a_batch_that_carries_includer_and_included_together_writes_nothing() { - // Both land in the same new directory, so the own-directory rung still - // answers `defs.svh` and the line is already right. - let tree = Tree::new("moveboth"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - fs::create_dir_all(tree.path.join("src")).expect("mkdir"); - let ws = tree.workspace(); - - let rewrite = will_rename( - &ws, - &[tree.rename("rtl/top.sv", "src/top.sv"), tree.rename("rtl/defs.svh", "src/defs.svh")], - ); - assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - } - - #[test] - fn a_file_that_moves_away_from_its_own_headers_is_re_spelled_too() { - // The other half of the same rule: an include breaks when the file it - // is *written in* moves, because the own-directory rung moves with it. - // The answer is computed from where that file will be, and addressed - // to the URI it has now. - let tree = Tree::new("includermoves"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - fs::create_dir_all(tree.path.join("src")).expect("mkdir"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "src/top.sv")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let (uri, spellings) = only_file(&rewrite); - assert_eq!(uri, uri_of(&top), "addressed by the URI it has now"); - assert_eq!(spellings, vec!["../rtl/defs.svh".to_string()]); - } - - #[test] - fn every_source_extension_is_swept_and_nothing_else_is() { - let tree = Tree::new("extensions"); - tree.write("rtl/defs.vh", "`define W 8\n"); - let top = tree.write("rtl/top.v", "`include \"defs.vh\"\n"); - tree.write("notes.md", "not a source file\n"); - tree.write("files.f", "rtl/top.v\nrtl/defs.vh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.vh", "rtl/widths.vh")]); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.vh".to_string()])); - - // A file this server has no opinion about is answered with nothing — - // no edit, no warning, no sweep. - let rewrite = will_rename(&ws, &[tree.rename("notes.md", "NOTES.md")]); - assert!(rewrite.edit.is_none()); - assert!(rewrite.warnings.is_empty()); - } - - #[test] - fn a_directory_rename_moves_every_include_that_reached_into_it() { - // LSP names only the folder; the paths inside it move with it, which - // is the same prefix rewrite a file rename is. - let tree = Tree::new("directory"); - tree.write("inc/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"../inc/defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\ninc/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let text = fs::read_to_string(&top).expect("read"); - assert_eq!( - applied(&text, &rewrite, &uri_of(&top)), - "`include \"../headers/defs.svh\"\n", - "relative to the includer, which is the rung it resolved on before" - ); - } - - #[test] - fn a_renamed_include_directory_falls_back_to_a_relative_spelling() { - // Moving the directory a `+incdir+` names leaves the *filelist* stale, - // and this server does not edit filelists. What it can do is keep the - // source compiling: the own-directory rung is there in every tool, so - // the bare include becomes a relative one rather than staying broken. - // The `+incdir+` is then unused for this header — that is the user's - // to fix, and the file at least still resolves in the meantime. - let tree = Tree::new("incdirmoved"); - tree.write("inc/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "+incdir+inc\nrtl/top.sv\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["../headers/defs.svh".to_string()])); - } - - #[test] - fn an_unopened_file_is_swept_too() { - // Includes live in files nobody has opened; the sweep reads them off - // disk through `sources()`, exactly as the index does. - let tree = Tree::new("unopened"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - assert!(ws.open_uris().is_empty(), "the premise: nothing open"); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - } - - #[test] - fn an_unsaved_buffer_is_swept_from_its_own_text() { - let tree = Tree::new("buffer"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "module t;\nendmodule\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let mut ws = tree.workspace(); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), "`include \"defs.svh\"\nmodule t;\nendmodule\n".to_string()); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); - } - - #[test] - fn a_rename_that_moves_nothing_answers_nothing() { - let tree = Tree::new("noop"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - // The same path twice is not a move. - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/defs.svh")]); - assert!(rewrite.edit.is_none()); - assert!(rewrite.warnings.is_empty()); - - // Nor is renaming a file nothing includes. - let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "rtl/toplevel.sv")]); - assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); - assert!(rewrite.warnings.is_empty()); - } - - #[test] - fn a_move_between_two_incdirs_that_keeps_the_spelling_produces_no_edit() { - // Both directories are include paths and the name does not change, so - // the include already reads correctly; an edit here would be noise in - // the user's diff. - let tree = Tree::new("noopmove"); - tree.write("a/defs.svh", "`define W 8\n"); - tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "+incdir+a\n+incdir+b\nrtl/top.sv\n"); - fs::create_dir_all(tree.path.join("b")).expect("mkdir"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "b/defs.svh")]); - assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - } - - #[test] - fn the_edit_covers_the_path_token_and_not_one_byte_more() { - // Check (a), structurally: the range an edit carries is the bytes - // between the delimiters, so no answer this module can compute is able - // to disturb the backtick, the quotes, or a trailing comment. - let tree = Tree::new("token"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", " `include \"defs.svh\" // widths\nmodule t;\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - let text = fs::read_to_string(&top).expect("read"); - assert_eq!( - applied(&text, &rewrite, &uri_of(&top)), - " `include \"widths.svh\" // widths\nmodule t;\n", - "indent and trailing comment intact" - ); - let include = scan(&text).into_iter().next().expect("one"); - assert_eq!( - &text[path_token(&include).as_range()], - "defs.svh", - "no delimiters in the range" - ); - } - - #[test] - fn a_line_that_stops_being_one_include_is_never_written() { - // Check (c), attacked: a spelling carrying the closing delimiter would - // scan as a *different* include, and a spelling carrying a newline - // would leave a second line behind. Both are refused at the line the - // edit would produce, before anything is emitted. - let text = "`include \"defs.svh\"\n"; - let include = scan(text).into_iter().next().expect("one"); - assert_eq!(rewritten_line(text, &include, "widths.svh"), "`include \"widths.svh\""); - - let broken = rewritten_line(text, &include, "a\".svh"); - let found = scan(&broken); - assert_eq!(found.len(), 1, "{broken:?}"); - assert_ne!(found[0].target, "a\".svh", "the closing quote moved: {broken:?}"); - - let split = rewritten_line(text, &include, "a\nb.svh"); - assert!(!one_include_directive(&split), "two lines is not one directive: {split:?}"); - } - - #[test] - fn a_real_include_line_lexes_as_exactly_one_directive() { - assert!(one_include_directive("`include \"defs.svh\"")); - assert!(one_include_directive(" `include // a comment")); - assert!(one_include_directive("`include\"defs.svh\""), "no space, as the lexer allows"); - assert!(!one_include_directive("`define W 8"), "another directive entirely"); - assert!(!one_include_directive("wire a; `include \"defs.svh\""), "not alone on its line"); - } - - #[test] - fn a_spelling_that_would_resolve_somewhere_else_is_not_written() { - // Check (b), attacked: `defs.svh` is the shortest suffix of the new - // location, but a file of that name already sits beside the includer - // and wins the search — so that candidate resolves to the *wrong* - // file and is refused. The longer, correct spelling is written. - let tree = Tree::new("shadow"); - tree.write("rtl/defs.svh", "`define W 1\n"); - tree.write("inc/old.svh", "`define W 2\n"); - let top = tree.write("rtl/top.sv", "`include \"../inc/old.svh\"\n"); - tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\ninc/old.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("inc/old.svh", "inc/defs.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let text = fs::read_to_string(&top).expect("read"); - let applied = applied(&text, &rewrite, &uri_of(&top)); - assert_eq!( - applied, "`include \"../inc/defs.svh\"\n", - "the bare `defs.svh` would have resolved to rtl/defs.svh instead" - ); - } - - #[test] - fn the_capability_names_the_operations_this_server_answers() { - // Pinned as JSON: this is what goes on the wire, and a client sends - // these requests only where the filters say so. - let value = serde_json::to_value(file_operations()).expect("json"); - assert_eq!( - value, - serde_json::json!({ - "willRename": { "filters": [ - { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, - { "scheme": "file", "pattern": { "glob": "**", "matches": "folder" } }, - ] }, - "didRename": { "filters": [ - { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, - ] }, - "didDelete": { "filters": [ - { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, - ] }, - }), - "{value:#?}" - ); - } - - #[test] - fn a_notification_is_filtered_the_way_a_watched_file_event_is() { - let filelist = PathBuf::from("/p/files.f"); - let rename = |old: &str, new: &str| FileRename { - old_uri: uri_of(Path::new(old)), - new_uri: uri_of(Path::new(new)), - }; - let paths = renamed(&[rename("/p/a.sv", "/p/b.sv")]); - assert_eq!(paths.len(), 2, "both ends: {paths:?}"); - assert!(touches_scope(&paths, None)); - - assert!(!touches_scope(&renamed(&[rename("/p/a.md", "/p/b.md")]), None)); - // A file *becoming* a source file counts, exactly as a watcher's - // create event would. - assert!(touches_scope(&renamed(&[rename("/p/a.md", "/p/b.sv")]), None)); - - let deleting = |path: &str| FileDelete { uri: uri_of(Path::new(path)) }; - assert!(touches_scope(&deleted(&[deleting("/p/a.sv")]), None)); - assert!(!touches_scope(&deleted(&[deleting("/p/notes.txt")]), None)); - assert!(touches_scope(&deleted(&[deleting("/p/files.f")]), Some(&filelist))); - assert!(!touches_scope(&deleted(&[deleting("/p/other.f")]), Some(&filelist))); - assert!(!touches_scope(&[], None), "and an empty notification"); - } - - #[test] - fn a_non_file_uri_is_dropped_rather_than_guessed_at() { - let rename = FileRename { - old_uri: "untitled:Untitled-1".to_string(), - new_uri: "untitled:Untitled-2".to_string(), - }; - assert!(renamed(std::slice::from_ref(&rename)).is_empty()); - assert!(Moves::announced(&[rename]).0.is_empty()); - } - - #[test] - fn the_filesystem_a_rename_leaves_behind_answers_both_ends() { - let tree = Tree::new("moves"); - let here = tree.write("a.sv", "module a;\nendmodule\n"); - let moves = Moves(vec![(here.clone(), tree.path.join("b.sv"))]); - assert!(!moves.is_file(&here), "gone from where it was"); - assert!(moves.is_file(&tree.path.join("b.sv")), "and present where it goes"); - assert!(!moves.is_file(&tree.path.join("c.sv")), "an unrelated path is still absent"); - - // A swap leaves both files existing, as it does on disk. - let other = tree.write("b.sv", "module b;\nendmodule\n"); - let moves = Moves(vec![(here.clone(), other.clone()), (other.clone(), here.clone())]); - assert!(moves.is_file(&here) && moves.is_file(&other), "both, after the swap"); - } - - #[test] - fn a_relative_spelling_climbs_out_and_back_down() { - assert_eq!( - relative_spelling(Path::new("/p/rtl"), Path::new("/p/inc/defs.svh")).as_deref(), - Some("../inc/defs.svh") - ); - assert_eq!( - relative_spelling(Path::new("/p/rtl"), Path::new("/p/rtl/defs.svh")).as_deref(), - Some("defs.svh"), - "no climb needed" - ); - assert_eq!( - relative_spelling(Path::new("/p/a/b"), Path::new("/q/defs.svh")).as_deref(), - Some("../../../q/defs.svh"), - "the root is shared, so a spelling exists" - ); - assert_eq!(relative_spelling(Path::new("p/rtl"), Path::new("/q/defs.svh")), None); - } - - /// Order-of-magnitude perf check, not run as part of the ordinary suite: - /// timing assertions in a shared runner are flaky by nature. Run with - /// `cargo test --release -p lucisv_server --bin lucisv-server file_ops::tests::perf - /// -- --ignored --nocapture`. - mod perf { - use super::*; - - #[test] - #[ignore] - fn one_rename_sweeps_the_whole_corpus_in_milliseconds() { - // What a `willRenameFiles` costs: `sources()` re-reads every - // in-scope file, then one substring test each and the resolver for - // the few that include anything. Once per user gesture, and the - // same read the index rebuild already pays on every save. - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![root.clone()]); - let files = ws.index().files().len(); - assert!(files > 500, "the corpus is checked in: got {files}"); - let rename = FileRename { - old_uri: uri_of(&root.join("nothing_includes_this.svh")), - new_uri: uri_of(&root.join("moved.svh")), - }; - let start = std::time::Instant::now(); - let rewrite = will_rename(&ws, &[rename]); - eprintln!( - "perf: willRenameFiles over {files} corpus files in {:?} ({} warnings)", - start.elapsed(), - rewrite.warnings.len() - ); - } - } - - /// QA (file-operations, 2026-08-27): the attack surfaces the lead - /// specifically asked to hit before this rewrites-your-files feature - /// ships. Every test here either confirms the dev's claim or records what - /// actually happens; findings are written up in - /// `docs/features/file-operations/README.md`'s QA log, not here. - mod qa_2026_08_27_attacks { - use super::*; - use std::fs; - - /// Attack #1 (shadowing): the including file's own directory beats every - /// `+incdir+`. Two `defs.svh`, one reached by an own-dir rung and one only - /// by an `+incdir+` rung — renaming the incdir one must never touch the - /// include that resolves to the own-dir one, and vice versa. This is a - /// stronger shape than the dev's own same-name test (which uses two - /// separate directories with no incdir in play at all): here one of the - /// two spellings would *also* resolve to the incdir file if resolution - /// ever fell back to name-matching instead of the real search order. - #[test] - fn a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed() { - let tree = Tree::new("qa_shadow_incdir"); - tree.write("a/defs.svh", "`define W 1\n"); // own-dir winner for top_a - tree.write("inc/defs.svh", "`define W 2\n"); // incdir winner for top_b - let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); - let top_b = tree.write("b/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "+incdir+inc\na/top.sv\na/defs.svh\nb/top.sv\ninc/defs.svh\n"); - let ws = tree.workspace(); - - // Rename the incdir file: only top_b's include (which resolves to it) - // may be touched. - let rewrite = will_rename(&ws, &[tree.rename("inc/defs.svh", "inc/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 1, "only top_b: {changes:#?}"); - assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri"))); - assert!( - !changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri")), - "top_a resolves to a/defs.svh, which did not move: {changes:#?}" - ); - - // Rename the own-dir file: only top_a's include may be touched. - let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 1, "only top_a: {changes:#?}"); - assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri"))); - assert!( - !changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri")), - "top_b resolves to inc/defs.svh, which did not move: {changes:#?}" - ); - } - - /// Attack #4 (directory renames by prefix): `Moves` maps by path - /// *component* prefix, not string prefix. `rtl_extra/x.svh` must not be - /// claimed by a `rtl` → `rtl2` directory rename just because the string - /// "rtl" is a textual prefix of "rtl_extra". - /// - /// Both headers are referenced from a *sibling* directory (not from - /// inside the directory that moves), so renaming `rtl` actually forces - /// an edit — unlike moving a whole directory of includer-and-included - /// together, which is a no-op (`a_batch_that_carries_includer_and_\ - /// included_together_writes_nothing`) and would not have exercised the - /// prefix logic at all. - #[test] - fn a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix() { - let tree = Tree::new("qa_prefix"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl_extra/defs.svh", "`define W 9\n"); - let top = tree.write("outside/top.sv", "`include \"../rtl/defs.svh\"\n"); - let extra_top = tree.write("outside2/top2.sv", "`include \"../rtl_extra/defs.svh\"\n"); - tree.write( - "files.f", - "outside/top.sv\nrtl/defs.svh\noutside2/top2.sv\nrtl_extra/defs.svh\n", - ); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl", "rtl2")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 1, "only outside/top.sv, never top2.sv: {changes:#?}"); - let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; - assert_eq!(edit[0].new_text, "../rtl2/defs.svh"); - assert!( - !changes.contains_key(&Uri::from_str(&uri_of(&extra_top)).expect("uri")), - "a string-prefix match would wrongly touch rtl_extra: {changes:#?}" - ); - - // And the `Moves` primitive itself, directly: this is what a naive - // string-prefix implementation would get wrong. - let moves = Moves(vec![(tree.path.join("rtl"), tree.path.join("rtl2"))]); - assert_eq!( - moves.after(&tree.path.join("rtl/defs.svh")), - Some(tree.path.join("rtl2/defs.svh")) - ); - assert_eq!(moves.after(&tree.path.join("rtl_extra/defs.svh")), None); - } - - /// Attack #4b: a directory rename and a rename of a file inside that same - /// directory, both named in one batch. LSP says a folder rename carries - /// only the folder's own URI ("not its children"), so a spec-compliant - /// client never actually sends this — but nothing stops a client from - /// doing it anyway, and `Moves::after` takes the *first* matching entry - /// (`find_map`), so the two rules do not compound: whichever rename is - /// listed first in `params.files` decides that path's destination, and - /// the other entry is silently shadowed for any path under the directory. - /// Recorded here as a characterization, not asserted as "correct" — see - /// the QA log for the recommendation. - #[test] - fn a_directory_rename_and_a_file_rename_inside_it_do_not_compound() { - let tree = Tree::new("qa_nested_batch"); - tree.write("rtl/defs.svh", "`define W 8\n"); - tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - // The directory rename is listed first: `top.sv`'s explicit rename - // entry is never consulted for its own path. - let dir_first = Moves::announced(&[ - tree.rename("rtl", "rtl2"), - tree.rename("rtl/top.sv", "rtl/toplevel.sv"), - ]); - assert_eq!( - dir_first.after(&tree.path.join("rtl/top.sv")), - Some(tree.path.join("rtl2/top.sv")), - "the directory rule wins when listed first, not `toplevel.sv`" - ); - - // Reversed order: the file's own entry wins, and the directory rule - // no longer has a say over that one path. - let file_first = Moves::announced(&[ - tree.rename("rtl/top.sv", "rtl/toplevel.sv"), - tree.rename("rtl", "rtl2"), - ]); - assert_eq!( - file_first.after(&tree.path.join("rtl/top.sv")), - Some(tree.path.join("rtl/toplevel.sv")), - "order-dependent: whichever entry comes first claims the path" - ); - - // Either way, whatever `will_rename` writes is still checked against - // whichever model `Moves` produced (survives's check (c)), so no - // wrong-target edit escapes — the model can be surprising, but the - // output is never corrupt. - let rewrite = will_rename( - &ws, - &[tree.rename("rtl", "rtl2"), tree.rename("rtl/top.sv", "rtl/toplevel.sv")], - ); - if let Some(edit) = &rewrite.edit { - for edits in edit.changes.as_ref().expect("changes").values() { - for e in edits { - assert!(!e.new_text.contains('"'), "never a corrupt spelling: {e:?}"); - } - } - } - } - - /// Attack #5 (batch semantics): file A includes file B, and both move to - /// directories at different depths in the same batch. The right spelling - /// only falls out if *both* moves are consulted for the same resolution — - /// modeling just one of the two gives a spelling that is textually - /// different from the right answer, which is what makes this a real test - /// rather than a coincidence (some shapes of this scenario answer the - /// same text whichever move is dropped; this one does not). - #[test] - fn a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled() { - let tree = Tree::new("qa_both_moves"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - fs::create_dir_all(tree.path.join("deep/nested")).expect("mkdir"); - fs::create_dir_all(tree.path.join("other")).expect("mkdir"); - let ws = tree.workspace(); - - let rewrite = will_rename( - &ws, - &[ - tree.rename("rtl/top.sv", "deep/nested/top.sv"), - tree.rename("rtl/defs.svh", "other/defs.svh"), - ], - ); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - let edits = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; - assert_eq!( - edits[0].new_text, "../../other/defs.svh", - "wrong if only one of the two moves were modeled: dropping the \ - includer's own move gives \"../other/defs.svh\" (one `..` short), \ - dropping the included file's move gives \"../../rtl/defs.svh\" \ - (the old directory): {edits:#?}" - ); - } - - /// Attack #2b (check (b), adversarially): a rename to a filename that - /// itself contains the delimiter character. POSIX allows `"` in a - /// filename, so this is a real, if perverse, input — not something the - /// server can refuse at the door. If the only candidate spelling embeds a - /// literal `"`, writing it would prematurely close the string and change - /// what the rest of the line means; `survives`'s re-scan must catch this - /// and refuse it. Hard invariant #1 (never corrupt) is what is actually - /// at stake here, not just this feature's own warning volume. - #[test] - fn a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written() { - let tree = Tree::new("qa_quote_name"); - // No incdir, no other spelling available: this is the *only* shape a - // quoted include of this file can take, forcing the bad candidate to - // be the one and only one tried. - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let weird = tree.rename("rtl/defs.svh", "rtl/de\"fs.svh"); - let rewrite = will_rename(&ws, &[weird]); - - // Never a written edit that could corrupt the line: either no edit at - // all, or (if the checks pass some other way) a spelling that still - // scans as one clean include. - if let Some(edit) = &rewrite.edit { - let changes = edit.changes.as_ref().expect("changes"); - if let Some(edits) = changes.get(&Uri::from_str(&uri_of(&top)).expect("uri")) { - for e in edits { - let line = format!("`include \"{}\"", e.new_text); - let found = scan(&line); - assert_eq!(found.len(), 1, "must still scan as one include: {line:?}"); - assert_eq!( - found[0].target, e.new_text, - "must not truncate at an embedded quote" - ); - } - } - } else { - // The expected outcome: no legal quoted spelling exists (the - // literal name cannot be written between quotes at all), so the - // include is left alone and the user is warned, never guessed at. - assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); - assert!(rewrite.warnings[0].contains("left unchanged"), "{}", rewrite.warnings[0]); - } - // Either way, the file on disk was never touched by this call — the - // module returns edits, it does not write files itself. - assert_eq!(fs::read_to_string(&top).expect("read"), "`include \"defs.svh\"\n"); - } - - /// Attack #2c: a rename target with a plain space and one with non-ASCII - /// text. Neither character is a delimiter or a newline, so both are legal - /// inside a quoted `` `include`` and the rewrite should succeed cleanly — - /// this is the "total, correct" half of the lead's question, as opposed - /// to the quote case above, which is "refused, with a warning." - #[test] - fn a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly() { - let tree = Tree::new("qa_space_unicode"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/new defs.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - assert_eq!( - changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, - "new defs.svh" - ); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/défs.svh")]); - assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - assert_eq!( - changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, - "défs.svh" - ); - } - - /// Attack #2a: tabs in the indentation and a trailing block comment, not - /// just the line comment the dev's own test uses. The edit's byte range - /// must still cover exactly the path token. - #[test] - fn the_edit_range_is_exact_with_tab_indentation_and_a_block_comment() { - let tree = Tree::new("qa_tabs"); - tree.write("rtl/defs.svh", "`define W 8\n"); - let text = "\t\t`include \"defs.svh\" /* widths */\nmodule t;\n"; - let top = tree.write("rtl/top.sv", text); - tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); - let ws = tree.workspace(); - - let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); - let changes = - rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); - let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0]; - // Decode the LSP range back to a byte offset the way a client would, - // and check it names exactly the eight bytes of `defs.svh`. - let index = LineIndex::new(text); - let positions = Positions::new(text, &index); - let start = positions.offset(edit.range.start); - let end = positions.offset(edit.range.end); - assert_eq!(&text[start as usize..end as usize], "defs.svh", "{edit:?}"); - assert_eq!(edit.new_text, "widths.svh"); - } - - /// Corpus-scale probe: a real header with real fan-out, swept twice for - /// determinism. `prim_assert.sv` is included (own-directory rung, no - /// filelist needed) by 87 sibling files under - /// `ibex/vendor/lowrisc_ip/ip/prim/rtl/` — a renamed-file candidate that - /// actually exercises the "everywhere" path at scale, not a corpus file - /// picked at random that happens to include nothing. - /// - /// Every produced edit is checked against the post-rename filesystem - /// this module itself would use to verify a write (`resolve_as_if` - /// through `Moves`), and no file outside the 87 known includers may be - /// touched. - #[test] - fn a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - let target_dir = root.join("ibex/vendor/lowrisc_ip/ip/prim/rtl"); - let old = target_dir.join("prim_assert.sv"); - // Skipped when `corpus/` is not checked out, like every other - // corpus test in this crate — asserting its presence panicked any - // environment (a bare CI checkout, `act`) that never fetched it. - if !old.is_file() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let new = target_dir.join("prim_assert_renamed.sv"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![root.clone()]); - let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) }; - - let run = || { - let rewrite = will_rename(&ws, std::slice::from_ref(&rename)); - let changes = rewrite - .edit - .expect("87 known includers, so an edit is expected") - .changes - .expect("changes"); - (changes, rewrite.warnings) - }; - - let (first, warnings_first) = run(); - let (second, warnings_second) = run(); - assert_eq!( - first.len(), - second.len(), - "the same sweep run twice must touch the same number of files" - ); - assert_eq!(warnings_first.len(), warnings_second.len(), "and warn the same amount"); - - // Every touched file is genuinely an includer of the old target, - // and every edit's new spelling resolves to the new location once - // the rename this module models has happened — the same check - // `survives` runs before it will ever write a spelling, run again - // here from outside the module as an independent cross-check. - // - // Built through `Moves::announced`, not by hand: its entries are - // normalized (`path_of`), and comparing a normalized candidate - // against a hand-built, unnormalized `(old, new)` pair silently - // fails to match at all (`Path::strip_prefix`/`==` are - // component-wise, and a literal `..` is a different component - // from the directory it resolves to) — the same class of mismatch - // the fix above addresses, on the test's own side this time. - let moves = Moves::announced(std::slice::from_ref(&rename)); - let graph = ws.includes(); - let mut touched_dirs = std::collections::HashSet::new(); - for (uri, edits) in &first { - let path = uri_to_path(uri).expect("a file: URI"); - touched_dirs.insert(path.parent().map(Path::to_path_buf)); - let text = fs::read_to_string(&path).expect("read the real corpus file"); - for edit in edits { - assert_eq!(edit.new_text, "prim_assert_renamed.sv", "{edit:?}"); - // Not the include as it was written — that names the *old* - // spelling, which correctly no longer resolves once the - // rename has happened (that is exactly why an edit was - // needed). What must resolve is the *written* spelling, - // the same thing `survives` checks before this module - // ever emits it. - let original = scan(&text) - .into_iter() - .find(|inc| inc.target == "prim_assert.sv") - .expect("the include this edit was computed for"); - let written = Include { target: edit.new_text.clone(), ..original }; - let resolved = - graph.resolve_as_if(Some(&path), &written, &|p| moves.is_file(p)); - // `resolve_as_if` always folds `.`/`..` out of its answer - // (`normalize`), even when fed an unfolded `root` the way - // this test's own `CARGO_MANIFEST_DIR`-relative one is — - // so the expected side is folded here too. - assert_eq!(resolved, Some(normalize(&new)), "{path:?}: {edit:?}"); - } - } - // Every touched file really is one of the 87 known includers' - // directory — nothing outside it was swept in by this rename. - assert_eq!( - touched_dirs.len(), - 1, - "every includer of this own-dir-resolved header lives in one \ - directory; touching any other is a false positive: {touched_dirs:?}" - ); - assert_eq!(touched_dirs.into_iter().next().unwrap(), Some(target_dir)); - } - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/file_ops/tests.rs b/crates/lucisv_server/src/file_ops/tests.rs new file mode 100644 index 0000000..0a4ab68 --- /dev/null +++ b/crates/lucisv_server/src/file_ops/tests.rs @@ -0,0 +1,1160 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use std::fs; + +/// A scratch tree, removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_file_ops_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("parent"); + } + fs::write(&path, text).expect("write"); + path + } + + /// The workspace this tree's `files.f` governs, with nothing open. + fn workspace(&self) -> Workspace { + let mut ws = Workspace::default(); + if self.path.join("files.f").is_file() { + ws.set_client_settings(crate::settings::ClientSettings { + filelist: Some(self.path.join("files.f").display().to_string()), + ..Default::default() + }); + } + ws.open_whole_workspace(vec![self.path.clone()]); + ws + } + + fn rename(&self, from: &str, to: &str) -> FileRename { + FileRename { old_uri: uri_of(&self.path.join(from)), new_uri: uri_of(&self.path.join(to)) } + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn uri_of(path: &Path) -> String { + path_to_uri(path).expect("uri").as_str().to_string() +} + +/// The sufficiency property [`will_rename`]'s narrowed sweep rests on, +/// asserted directly over whatever tree the caller built: every in-scope +/// file the sweep no longer reads writes no `` `include`` this workspace +/// can resolve, so its turn in the loop could only ever have `continue`d. +/// +/// Checked as the complement rather than as an equality because it is the +/// complement that could hide a lost edit: an extra file in the set costs +/// a read, a missing one costs an `` `include`` left pointing at nothing. +fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) { + let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); + let graph = ws.includes(); + let mut skipped = 0usize; + for (path, text) in ws.sources() { + if read.contains(&path) { + continue; + } + skipped += 1; + for include in scan(&text) { + assert!( + graph.resolve(Some(&path), &include).is_none(), + "{} was skipped but its `include \"{}\"` resolves", + path.display(), + include.target + ); + } + } + assert!(skipped > 0, "the tree must actually exercise the narrowing"); +} + +/// The one file the rewrite touches, as (uri, the new path spellings). +fn only_file(rewrite: &Rewrite) -> (String, Vec) { + let edit = rewrite.edit.as_ref().expect("an edit"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "expected one file, got {changes:#?}"); + let (uri, edits) = changes.iter().next().expect("one"); + (uri.as_str().to_string(), edits.iter().map(|e| e.new_text.clone()).collect()) +} + +/// Apply a rewrite to `text` the way a client would, so the test reads the +/// file the user would end up with. +fn applied(text: &str, rewrite: &Rewrite, uri: &str) -> String { + let edit = rewrite.edit.as_ref().expect("an edit"); + let changes = edit.changes.as_ref().expect("changes"); + let (_, edits) = changes + .iter() + .find(|(key, _)| key.as_str() == uri) + .unwrap_or_else(|| panic!("no edits for {uri} in {changes:#?}")); + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + // Back to front, so an earlier edit's offsets stay valid. + let mut ranges: Vec<(TextRange, String)> = edits + .iter() + .map(|edit| { + let start = positions.offset(edit.range.start); + let end = positions.offset(edit.range.end); + (TextRange::new(start, end), edit.new_text.clone()) + }) + .collect(); + ranges.sort_by_key(|(range, _)| std::cmp::Reverse(range.start)); + let mut out = text.to_string(); + for (range, new_text) in ranges { + out.replace_range(range.as_range(), &new_text); + } + out +} + +/// A wide workspace where almost nothing includes anything — the shape a +/// real one has, and the reason the sweep no longer reads all of it. The +/// answer must be the one the whole-workspace sweep gave, and the property +/// above must hold over the same tree. +#[test] +fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() { + let tree = Tree::new("narrowed"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); + let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n"); + // Twenty files with no `include at all, plus two whose includes name + // nothing on disk — both kinds are files the sweep may skip. + for n in 0..20 { + let rel = format!("rtl/quiet{n}.sv"); + tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n")); + list.push_str(&format!("{rel}\n")); + } + for n in 0..2 { + let rel = format!("rtl/dangling{n}.sv"); + tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n")); + list.push_str(&format!("{rel}\n")); + } + tree.write("files.f", &list); + let ws = tree.workspace(); + + assert_eq!(ws.sources().len(), 24, "the whole scope"); + assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands"); + nothing_skipped_has_an_include_to_rewrite(&ws); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); +} + +/// An `` `include`` typed into a buffer and not yet saved is in no edge the +/// graph holds — the graph is rebuilt on save. The buffer is in the sweep +/// whatever the graph says, which is what keeps that include rewritten. +#[test] +fn an_unsaved_include_is_still_rewritten() { + let tree = Tree::new("unsaved_include"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "module t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let mut ws = tree.workspace(); + assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include"); + + let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n"; + ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string()); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + assert_eq!( + applied(buffered, &rewrite, &uri_of(&top)), + "`include \"widths.svh\"\nmodule t;\nendmodule\n" + ); +} + +/// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must +/// narrow to `a.svh` (its *direct* includer, via `includers()`), and must +/// **not** narrow away a file that includes `a.svh` but never spells +/// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of +/// the file that moves, so a third-order includer has nothing to rewrite +/// either way, but it must still not be mistaken for a candidate (which +/// would cost a read, not a corruption, but is worth pinning). +#[test] +fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() { + let tree = Tree::new("chain"); + tree.write("rtl/b.svh", "`define W 8\n"); + let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n"); + let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n"); + tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n"); + let ws = tree.workspace(); + + let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); + assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}"); + assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}"); + nothing_skipped_has_an_include_to_rewrite(&ws); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + // Only a.svh's own `include \"b.svh\"` line changes; c.sv's + // `include \"a.svh\"` is untouched because a.svh itself did not move. + assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()])); +} + +/// QA, 2026-08-28 attack: an include spelled with different letter case +/// than the file actually has on disk (`` `include "DEFS.svh"`` against a +/// real `defs.svh`) — legal and silently resolved on the common +/// case-insensitive filesystems (confirmed case-insensitive in this test +/// environment). `IncludeGraph::found`/`found_as_if` resolve through the +/// filesystem's own `Path::is_file`, so the includer still lands in `raw` +/// (keyed by the *includer's* path, not the target's spelling) and +/// therefore in `includers()`/`include_sources()` — the narrowing must not +/// accidentally depend on the include's target spelling matching the +/// disk's. +/// +/// Only a case-insensitive filesystem (macOS, Windows by default) resolves +/// the mismatched spelling at all; on a case-sensitive one (Linux) there +/// is no include to narrow in, so the test checks which it is on and stops +/// there, saying so. +#[test] +fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() { + let tree = Tree::new("case_mismatch"); + tree.write("rtl/defs.svh", "`define W 8\n"); + if !tree.path.join("rtl/DEFS.svh").is_file() { + eprintln!("skipped: this filesystem is case-sensitive; `DEFS.svh` names no file"); + return; + } + let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let read: Vec = ws.include_sources().into_iter().map(|(path, _)| path).collect(); + assert!( + read.contains(&top), + "top.sv's case-mismatched include still resolves and must narrow in: {read:?}" + ); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); +} + +#[test] +fn a_same_directory_rename_keeps_the_bare_form() { + let tree = Tree::new("samedir"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"widths.svh\"\nmodule t;\nendmodule\n", + "the delimiters, the backtick and the rest of the file are untouched" + ); +} + +/// Renaming a file that is open **on the large-file fast path** +/// (`docs/features/large-file-mode/README.md`). The renamed file's own +/// `` `include``s (it has none here — a netlist would not) are out of +/// `will_rename`'s sweep because `Workspace::sources()` already leaves a +/// fast-path buffer out entirely; what this pins is the other half: an +/// **unrelated** small file's include *of* the large file still resolves +/// and still gets rewritten, because resolution walks the filesystem +/// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list +/// the fast-path buffer was excluded from. +#[test] +fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() { + let tree = Tree::new("largerename"); + let net = tree.write("rtl/net.v", "module net;\nendmodule\n"); + let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/net.v\n"); + let mut ws = tree.workspace(); + ws.set_client_settings(crate::settings::ClientSettings { + filelist: Some(tree.path.join("files.f").display().to_string()), + large_file_threshold: 10, + ..Default::default() + }); + let net_uri = path_to_uri(&net).expect("uri"); + // Padded past the 10-byte test threshold, so it opens on the fast path. + ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20))); + assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path"); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()])); +} + +#[test] +fn a_cross_directory_rename_re_spells_through_an_incdir() { + let tree = Tree::new("crossdir"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("inc")).expect("mkdir"); + let ws = tree.workspace(); + + // Into a directory the filelist already names as an include path, with + // a new name: still the bare form, because the incdir rung reaches it + // — the shortest suffix that resolves, not the path from the includer. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); + + // And the same move keeping the name needs no edit at all: the line + // already reads correctly once the incdir rung answers it. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "inc/defs.svh")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); +} + +#[test] +fn a_move_no_include_path_reaches_is_left_alone_and_reported() { + let tree = Tree::new("unreachable"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \n"); + // The angled form resolves against incdirs only, so `far/` — which is + // no include path — cannot be spelled from here at all. + tree.write("files.f", "+incdir+rtl\nrtl/top.sv\n"); + fs::create_dir_all(tree.path.join("far")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "far/defs.svh")]); + assert!(rewrite.edit.is_none(), "no edit at all: {:?}", rewrite.edit); + assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); + let warning = &rewrite.warnings[0]; + assert!(warning.contains("top.sv:1"), "{warning}"); + assert!(warning.contains("`include "), "{warning}"); + assert!(warning.contains("left unchanged"), "{warning}"); + assert!(warning.contains("far/defs.svh"), "the new location is named: {warning}"); +} + +#[test] +fn every_include_of_one_renamed_file_is_rewritten_across_the_workspace() { + let tree = Tree::new("everywhere"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let a = tree.write("rtl/a.sv", "`include \"defs.svh\"\n`include \"defs.svh\"\n"); + let b = tree.write("rtl/b.sv", "module b;\nendmodule\n`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/a.sv\nrtl/b.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 2, "both files: {changes:#?}"); + let for_a = changes.iter().find(|(uri, _)| uri.as_str() == uri_of(&a)).expect("a.sv"); + assert_eq!(for_a.1.len(), 2, "both includes in the one file"); + + let text = fs::read_to_string(&b).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&b)), + "module b;\nendmodule\n`include \"widths.svh\"\n" + ); +} + +#[test] +fn an_include_of_a_different_file_with_the_same_name_is_untouched() { + // The whole reason this resolves rather than matching text: two + // `defs.svh` in one workspace, and only the one that is renamed moves. + let tree = Tree::new("samename"); + tree.write("a/defs.svh", "`define W 1\n"); + tree.write("b/defs.svh", "`define W 2\n"); + let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); + tree.write("b/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "a/top.sv\na/defs.svh\nb/top.sv\nb/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let (uri, spellings) = only_file(&rewrite); + assert_eq!(uri, uri_of(&top_a), "only the file whose target moved"); + assert_eq!(spellings, vec!["widths.svh".to_string()]); +} + +#[test] +fn several_renames_in_one_request_answer_one_edit() { + let tree = Tree::new("batch"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/ports.svh", "`define P 2\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n`include \"ports.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\nrtl/ports.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[ + tree.rename("rtl/defs.svh", "rtl/widths.svh"), + tree.rename("rtl/ports.svh", "rtl/pins.svh"), + ], + ); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"widths.svh\"\n`include \"pins.svh\"\n" + ); +} + +#[test] +fn a_batch_that_carries_includer_and_included_together_writes_nothing() { + // Both land in the same new directory, so the own-directory rung still + // answers `defs.svh` and the line is already right. + let tree = Tree::new("moveboth"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("src")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[tree.rename("rtl/top.sv", "src/top.sv"), tree.rename("rtl/defs.svh", "src/defs.svh")], + ); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); +} + +#[test] +fn a_file_that_moves_away_from_its_own_headers_is_re_spelled_too() { + // The other half of the same rule: an include breaks when the file it + // is *written in* moves, because the own-directory rung moves with it. + // The answer is computed from where that file will be, and addressed + // to the URI it has now. + let tree = Tree::new("includermoves"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("src")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "src/top.sv")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let (uri, spellings) = only_file(&rewrite); + assert_eq!(uri, uri_of(&top), "addressed by the URI it has now"); + assert_eq!(spellings, vec!["../rtl/defs.svh".to_string()]); +} + +#[test] +fn every_source_extension_is_swept_and_nothing_else_is() { + let tree = Tree::new("extensions"); + tree.write("rtl/defs.vh", "`define W 8\n"); + let top = tree.write("rtl/top.v", "`include \"defs.vh\"\n"); + tree.write("notes.md", "not a source file\n"); + tree.write("files.f", "rtl/top.v\nrtl/defs.vh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.vh", "rtl/widths.vh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.vh".to_string()])); + + // A file this server has no opinion about is answered with nothing — + // no edit, no warning, no sweep. + let rewrite = will_rename(&ws, &[tree.rename("notes.md", "NOTES.md")]); + assert!(rewrite.edit.is_none()); + assert!(rewrite.warnings.is_empty()); +} + +#[test] +fn a_directory_rename_moves_every_include_that_reached_into_it() { + // LSP names only the folder; the paths inside it move with it, which + // is the same prefix rewrite a file rename is. + let tree = Tree::new("directory"); + tree.write("inc/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"../inc/defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\ninc/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + "`include \"../headers/defs.svh\"\n", + "relative to the includer, which is the rung it resolved on before" + ); +} + +#[test] +fn a_renamed_include_directory_falls_back_to_a_relative_spelling() { + // Moving the directory a `+incdir+` names leaves the *filelist* stale, + // and this server does not edit filelists. What it can do is keep the + // source compiling: the own-directory rung is there in every tool, so + // the bare include becomes a relative one rather than staying broken. + // The `+incdir+` is then unused for this header — that is the user's + // to fix, and the file at least still resolves in the meantime. + let tree = Tree::new("incdirmoved"); + tree.write("inc/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc", "headers")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["../headers/defs.svh".to_string()])); +} + +#[test] +fn an_unopened_file_is_swept_too() { + // Includes live in files nobody has opened; the sweep reads them off + // disk through `sources()`, exactly as the index does. + let tree = Tree::new("unopened"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + assert!(ws.open_uris().is_empty(), "the premise: nothing open"); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); +} + +#[test] +fn an_unsaved_buffer_is_swept_from_its_own_text() { + let tree = Tree::new("buffer"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "module t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let mut ws = tree.workspace(); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), "`include \"defs.svh\"\nmodule t;\nendmodule\n".to_string()); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()])); +} + +#[test] +fn a_rename_that_moves_nothing_answers_nothing() { + let tree = Tree::new("noop"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + // The same path twice is not a move. + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/defs.svh")]); + assert!(rewrite.edit.is_none()); + assert!(rewrite.warnings.is_empty()); + + // Nor is renaming a file nothing includes. + let rewrite = will_rename(&ws, &[tree.rename("rtl/top.sv", "rtl/toplevel.sv")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty()); +} + +#[test] +fn a_move_between_two_incdirs_that_keeps_the_spelling_produces_no_edit() { + // Both directories are include paths and the name does not change, so + // the include already reads correctly; an edit here would be noise in + // the user's diff. + let tree = Tree::new("noopmove"); + tree.write("a/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+a\n+incdir+b\nrtl/top.sv\n"); + fs::create_dir_all(tree.path.join("b")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "b/defs.svh")]); + assert!(rewrite.edit.is_none(), "{:?}", rewrite.edit); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); +} + +#[test] +fn the_edit_covers_the_path_token_and_not_one_byte_more() { + // Check (a), structurally: the range an edit carries is the bytes + // between the delimiters, so no answer this module can compute is able + // to disturb the backtick, the quotes, or a trailing comment. + let tree = Tree::new("token"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", " `include \"defs.svh\" // widths\nmodule t;\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + let text = fs::read_to_string(&top).expect("read"); + assert_eq!( + applied(&text, &rewrite, &uri_of(&top)), + " `include \"widths.svh\" // widths\nmodule t;\n", + "indent and trailing comment intact" + ); + let include = scan(&text).into_iter().next().expect("one"); + assert_eq!(&text[path_token(&include).as_range()], "defs.svh", "no delimiters in the range"); +} + +#[test] +fn a_line_that_stops_being_one_include_is_never_written() { + // Check (c), attacked: a spelling carrying the closing delimiter would + // scan as a *different* include, and a spelling carrying a newline + // would leave a second line behind. Both are refused at the line the + // edit would produce, before anything is emitted. + let text = "`include \"defs.svh\"\n"; + let include = scan(text).into_iter().next().expect("one"); + assert_eq!(rewritten_line(text, &include, "widths.svh"), "`include \"widths.svh\""); + + let broken = rewritten_line(text, &include, "a\".svh"); + let found = scan(&broken); + assert_eq!(found.len(), 1, "{broken:?}"); + assert_ne!(found[0].target, "a\".svh", "the closing quote moved: {broken:?}"); + + let split = rewritten_line(text, &include, "a\nb.svh"); + assert!(!one_include_directive(&split), "two lines is not one directive: {split:?}"); +} + +#[test] +fn a_real_include_line_lexes_as_exactly_one_directive() { + assert!(one_include_directive("`include \"defs.svh\"")); + assert!(one_include_directive(" `include // a comment")); + assert!(one_include_directive("`include\"defs.svh\""), "no space, as the lexer allows"); + assert!(!one_include_directive("`define W 8"), "another directive entirely"); + assert!(!one_include_directive("wire a; `include \"defs.svh\""), "not alone on its line"); +} + +#[test] +fn a_spelling_that_would_resolve_somewhere_else_is_not_written() { + // Check (b), attacked: `defs.svh` is the shortest suffix of the new + // location, but a file of that name already sits beside the includer + // and wins the search — so that candidate resolves to the *wrong* + // file and is refused. The longer, correct spelling is written. + let tree = Tree::new("shadow"); + tree.write("rtl/defs.svh", "`define W 1\n"); + tree.write("inc/old.svh", "`define W 2\n"); + let top = tree.write("rtl/top.sv", "`include \"../inc/old.svh\"\n"); + tree.write("files.f", "+incdir+inc\nrtl/top.sv\nrtl/defs.svh\ninc/old.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("inc/old.svh", "inc/defs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let text = fs::read_to_string(&top).expect("read"); + let applied = applied(&text, &rewrite, &uri_of(&top)); + assert_eq!( + applied, "`include \"../inc/defs.svh\"\n", + "the bare `defs.svh` would have resolved to rtl/defs.svh instead" + ); +} + +#[test] +fn the_capability_names_the_operations_this_server_answers() { + // Pinned as JSON: this is what goes on the wire, and a client sends + // these requests only where the filters say so. + let value = serde_json::to_value(file_operations()).expect("json"); + assert_eq!( + value, + serde_json::json!({ + "willRename": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + { "scheme": "file", "pattern": { "glob": "**", "matches": "folder" } }, + ] }, + "didRename": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + ] }, + "didDelete": { "filters": [ + { "scheme": "file", "pattern": { "glob": "**/*.{v,vh,sv,svh}", "matches": "file" } }, + ] }, + }), + "{value:#?}" + ); +} + +#[test] +fn a_notification_is_filtered_the_way_a_watched_file_event_is() { + let filelist = PathBuf::from("/p/files.f"); + let rename = |old: &str, new: &str| FileRename { + old_uri: uri_of(Path::new(old)), + new_uri: uri_of(Path::new(new)), + }; + let paths = renamed(&[rename("/p/a.sv", "/p/b.sv")]); + assert_eq!(paths.len(), 2, "both ends: {paths:?}"); + assert!(touches_scope(&paths, None)); + + assert!(!touches_scope(&renamed(&[rename("/p/a.md", "/p/b.md")]), None)); + // A file *becoming* a source file counts, exactly as a watcher's + // create event would. + assert!(touches_scope(&renamed(&[rename("/p/a.md", "/p/b.sv")]), None)); + + let deleting = |path: &str| FileDelete { uri: uri_of(Path::new(path)) }; + assert!(touches_scope(&deleted(&[deleting("/p/a.sv")]), None)); + assert!(!touches_scope(&deleted(&[deleting("/p/notes.txt")]), None)); + assert!(touches_scope(&deleted(&[deleting("/p/files.f")]), Some(&filelist))); + assert!(!touches_scope(&deleted(&[deleting("/p/other.f")]), Some(&filelist))); + assert!(!touches_scope(&[], None), "and an empty notification"); +} + +#[test] +fn a_non_file_uri_is_dropped_rather_than_guessed_at() { + let rename = FileRename { + old_uri: "untitled:Untitled-1".to_string(), + new_uri: "untitled:Untitled-2".to_string(), + }; + assert!(renamed(std::slice::from_ref(&rename)).is_empty()); + assert!(Moves::announced(&[rename]).0.is_empty()); +} + +#[test] +fn the_filesystem_a_rename_leaves_behind_answers_both_ends() { + let tree = Tree::new("moves"); + let here = tree.write("a.sv", "module a;\nendmodule\n"); + let moves = Moves(vec![(here.clone(), tree.path.join("b.sv"))]); + assert!(!moves.is_file(&here), "gone from where it was"); + assert!(moves.is_file(&tree.path.join("b.sv")), "and present where it goes"); + assert!(!moves.is_file(&tree.path.join("c.sv")), "an unrelated path is still absent"); + + // A swap leaves both files existing, as it does on disk. + let other = tree.write("b.sv", "module b;\nendmodule\n"); + let moves = Moves(vec![(here.clone(), other.clone()), (other.clone(), here.clone())]); + assert!(moves.is_file(&here) && moves.is_file(&other), "both, after the swap"); +} + +#[test] +fn a_relative_spelling_climbs_out_and_back_down() { + assert_eq!( + relative_spelling(Path::new("/p/rtl"), Path::new("/p/inc/defs.svh")).as_deref(), + Some("../inc/defs.svh") + ); + assert_eq!( + relative_spelling(Path::new("/p/rtl"), Path::new("/p/rtl/defs.svh")).as_deref(), + Some("defs.svh"), + "no climb needed" + ); + assert_eq!( + relative_spelling(Path::new("/p/a/b"), Path::new("/q/defs.svh")).as_deref(), + Some("../../../q/defs.svh"), + "the root is shared, so a spelling exists" + ); + assert_eq!(relative_spelling(Path::new("p/rtl"), Path::new("/q/defs.svh")), None); +} + +/// Order-of-magnitude perf check, not run as part of the ordinary suite: +/// timing assertions in a shared runner are flaky by nature. Run with +/// `cargo test --release -p lucisv_server --bin lucisv-server file_ops::tests::perf +/// -- --ignored --nocapture`. +mod perf { + use super::*; + + #[test] + #[ignore = "perf probe over corpus/, timing printed not asserted; see the `perf` doc"] + fn one_rename_sweeps_the_whole_corpus_in_milliseconds() { + // What a `willRenameFiles` costs: `sources()` re-reads every + // in-scope file, then one substring test each and the resolver for + // the few that include anything. Once per user gesture, and the + // same read the index rebuild already pays on every save. + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![root.clone()]); + let files = ws.index().files().len(); + assert!(files > 500, "the corpus is checked in: got {files}"); + let rename = FileRename { + old_uri: uri_of(&root.join("nothing_includes_this.svh")), + new_uri: uri_of(&root.join("moved.svh")), + }; + let start = std::time::Instant::now(); + let rewrite = will_rename(&ws, &[rename]); + eprintln!( + "perf: willRenameFiles over {files} corpus files in {:?} ({} warnings)", + start.elapsed(), + rewrite.warnings.len() + ); + } +} + +/// QA (file-operations, 2026-08-27): the attack surfaces the lead +/// specifically asked to hit before this rewrites-your-files feature +/// ships. Every test here either confirms the dev's claim or records what +/// actually happens; findings are written up in +/// `docs/features/file-operations/README.md`'s QA log, not here. +mod qa_2026_08_27_attacks { + use super::*; + use std::fs; + + /// Attack #1 (shadowing): the including file's own directory beats every + /// `+incdir+`. Two `defs.svh`, one reached by an own-dir rung and one only + /// by an `+incdir+` rung — renaming the incdir one must never touch the + /// include that resolves to the own-dir one, and vice versa. This is a + /// stronger shape than the dev's own same-name test (which uses two + /// separate directories with no incdir in play at all): here one of the + /// two spellings would *also* resolve to the incdir file if resolution + /// ever fell back to name-matching instead of the real search order. + #[test] + fn a_shadow_between_an_own_dir_file_and_an_incdir_file_is_never_crossed() { + let tree = Tree::new("qa_shadow_incdir"); + tree.write("a/defs.svh", "`define W 1\n"); // own-dir winner for top_a + tree.write("inc/defs.svh", "`define W 2\n"); // incdir winner for top_b + let top_a = tree.write("a/top.sv", "`include \"defs.svh\"\n"); + let top_b = tree.write("b/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "+incdir+inc\na/top.sv\na/defs.svh\nb/top.sv\ninc/defs.svh\n"); + let ws = tree.workspace(); + + // Rename the incdir file: only top_b's include (which resolves to it) + // may be touched. + let rewrite = will_rename(&ws, &[tree.rename("inc/defs.svh", "inc/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only top_b: {changes:#?}"); + assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri"))); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri")), + "top_a resolves to a/defs.svh, which did not move: {changes:#?}" + ); + + // Rename the own-dir file: only top_a's include may be touched. + let rewrite = will_rename(&ws, &[tree.rename("a/defs.svh", "a/widths.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only top_a: {changes:#?}"); + assert!(changes.contains_key(&Uri::from_str(&uri_of(&top_a)).expect("uri"))); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&top_b)).expect("uri")), + "top_b resolves to inc/defs.svh, which did not move: {changes:#?}" + ); + } + + /// Attack #4 (directory renames by prefix): `Moves` maps by path + /// *component* prefix, not string prefix. `rtl_extra/x.svh` must not be + /// claimed by a `rtl` → `rtl2` directory rename just because the string + /// "rtl" is a textual prefix of "rtl_extra". + /// + /// Both headers are referenced from a *sibling* directory (not from + /// inside the directory that moves), so renaming `rtl` actually forces + /// an edit — unlike moving a whole directory of includer-and-included + /// together, which is a no-op (`a_batch_that_carries_includer_and_\ + /// included_together_writes_nothing`) and would not have exercised the + /// prefix logic at all. + #[test] + fn a_directory_rename_does_not_claim_a_sibling_with_a_shared_string_prefix() { + let tree = Tree::new("qa_prefix"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl_extra/defs.svh", "`define W 9\n"); + let top = tree.write("outside/top.sv", "`include \"../rtl/defs.svh\"\n"); + let extra_top = tree.write("outside2/top2.sv", "`include \"../rtl_extra/defs.svh\"\n"); + tree.write( + "files.f", + "outside/top.sv\nrtl/defs.svh\noutside2/top2.sv\nrtl_extra/defs.svh\n", + ); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl", "rtl2")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only outside/top.sv, never top2.sv: {changes:#?}"); + let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; + assert_eq!(edit[0].new_text, "../rtl2/defs.svh"); + assert!( + !changes.contains_key(&Uri::from_str(&uri_of(&extra_top)).expect("uri")), + "a string-prefix match would wrongly touch rtl_extra: {changes:#?}" + ); + + // And the `Moves` primitive itself, directly: this is what a naive + // string-prefix implementation would get wrong. + let moves = Moves(vec![(tree.path.join("rtl"), tree.path.join("rtl2"))]); + assert_eq!( + moves.after(&tree.path.join("rtl/defs.svh")), + Some(tree.path.join("rtl2/defs.svh")) + ); + assert_eq!(moves.after(&tree.path.join("rtl_extra/defs.svh")), None); + } + + /// Attack #4b: a directory rename and a rename of a file inside that same + /// directory, both named in one batch. LSP says a folder rename carries + /// only the folder's own URI ("not its children"), so a spec-compliant + /// client never actually sends this — but nothing stops a client from + /// doing it anyway, and `Moves::after` takes the *first* matching entry + /// (`find_map`), so the two rules do not compound: whichever rename is + /// listed first in `params.files` decides that path's destination, and + /// the other entry is silently shadowed for any path under the directory. + /// Recorded here as a characterization, not asserted as "correct" — see + /// the QA log for the recommendation. + #[test] + fn a_directory_rename_and_a_file_rename_inside_it_do_not_compound() { + let tree = Tree::new("qa_nested_batch"); + tree.write("rtl/defs.svh", "`define W 8\n"); + tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + // The directory rename is listed first: `top.sv`'s explicit rename + // entry is never consulted for its own path. + let dir_first = Moves::announced(&[ + tree.rename("rtl", "rtl2"), + tree.rename("rtl/top.sv", "rtl/toplevel.sv"), + ]); + assert_eq!( + dir_first.after(&tree.path.join("rtl/top.sv")), + Some(tree.path.join("rtl2/top.sv")), + "the directory rule wins when listed first, not `toplevel.sv`" + ); + + // Reversed order: the file's own entry wins, and the directory rule + // no longer has a say over that one path. + let file_first = Moves::announced(&[ + tree.rename("rtl/top.sv", "rtl/toplevel.sv"), + tree.rename("rtl", "rtl2"), + ]); + assert_eq!( + file_first.after(&tree.path.join("rtl/top.sv")), + Some(tree.path.join("rtl/toplevel.sv")), + "order-dependent: whichever entry comes first claims the path" + ); + + // Either way, whatever `will_rename` writes is still checked against + // whichever model `Moves` produced (survives's check (c)), so no + // wrong-target edit escapes — the model can be surprising, but the + // output is never corrupt. + let rewrite = will_rename( + &ws, + &[tree.rename("rtl", "rtl2"), tree.rename("rtl/top.sv", "rtl/toplevel.sv")], + ); + if let Some(edit) = &rewrite.edit { + for edits in edit.changes.as_ref().expect("changes").values() { + for e in edits { + assert!(!e.new_text.contains('"'), "never a corrupt spelling: {e:?}"); + } + } + } + } + + /// Attack #5 (batch semantics): file A includes file B, and both move to + /// directories at different depths in the same batch. The right spelling + /// only falls out if *both* moves are consulted for the same resolution — + /// modeling just one of the two gives a spelling that is textually + /// different from the right answer, which is what makes this a real test + /// rather than a coincidence (some shapes of this scenario answer the + /// same text whichever move is dropped; this one does not). + #[test] + fn a_batch_where_both_the_includer_and_the_included_move_needs_both_moves_modeled() { + let tree = Tree::new("qa_both_moves"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + fs::create_dir_all(tree.path.join("deep/nested")).expect("mkdir"); + fs::create_dir_all(tree.path.join("other")).expect("mkdir"); + let ws = tree.workspace(); + + let rewrite = will_rename( + &ws, + &[ + tree.rename("rtl/top.sv", "deep/nested/top.sv"), + tree.rename("rtl/defs.svh", "other/defs.svh"), + ], + ); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + let edits = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")]; + assert_eq!( + edits[0].new_text, "../../other/defs.svh", + "wrong if only one of the two moves were modeled: dropping the \ + includer's own move gives \"../other/defs.svh\" (one `..` short), \ + dropping the included file's move gives \"../../rtl/defs.svh\" \ + (the old directory): {edits:#?}" + ); + } + + /// Attack #2b (check (b), adversarially): a rename to a filename that + /// itself contains the delimiter character. POSIX allows `"` in a + /// filename, so this is a real, if perverse, input — not something the + /// server can refuse at the door. If the only candidate spelling embeds a + /// literal `"`, writing it would prematurely close the string and change + /// what the rest of the line means; `survives`'s re-scan must catch this + /// and refuse it. Hard invariant #1 (never corrupt) is what is actually + /// at stake here, not just this feature's own warning volume. + #[test] + fn a_rename_target_whose_name_contains_the_quote_delimiter_is_refused_not_written() { + let tree = Tree::new("qa_quote_name"); + // No incdir, no other spelling available: this is the *only* shape a + // quoted include of this file can take, forcing the bad candidate to + // be the one and only one tried. + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let weird = tree.rename("rtl/defs.svh", "rtl/de\"fs.svh"); + let rewrite = will_rename(&ws, &[weird]); + + // Never a written edit that could corrupt the line: either no edit at + // all, or (if the checks pass some other way) a spelling that still + // scans as one clean include. + if let Some(edit) = &rewrite.edit { + let changes = edit.changes.as_ref().expect("changes"); + if let Some(edits) = changes.get(&Uri::from_str(&uri_of(&top)).expect("uri")) { + for e in edits { + let line = format!("`include \"{}\"", e.new_text); + let found = scan(&line); + assert_eq!(found.len(), 1, "must still scan as one include: {line:?}"); + assert_eq!( + found[0].target, e.new_text, + "must not truncate at an embedded quote" + ); + } + } + } else { + // The expected outcome: no legal quoted spelling exists (the + // literal name cannot be written between quotes at all), so the + // include is left alone and the user is warned, never guessed at. + assert_eq!(rewrite.warnings.len(), 1, "{:?}", rewrite.warnings); + assert!(rewrite.warnings[0].contains("left unchanged"), "{}", rewrite.warnings[0]); + } + // Either way, the file on disk was never touched by this call — the + // module returns edits, it does not write files itself. + assert_eq!(fs::read_to_string(&top).expect("read"), "`include \"defs.svh\"\n"); + } + + /// Attack #2c: a rename target with a plain space and one with non-ASCII + /// text. Neither character is a delimiter or a newline, so both are legal + /// inside a quoted `` `include`` and the rewrite should succeed cleanly — + /// this is the "total, correct" half of the lead's question, as opposed + /// to the quote case above, which is "refused, with a warning." + #[test] + fn a_rename_to_a_name_with_a_space_or_non_ascii_text_is_written_correctly() { + let tree = Tree::new("qa_space_unicode"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n"); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/new defs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!( + changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, + "new defs.svh" + ); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/défs.svh")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + assert_eq!(changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0].new_text, "défs.svh"); + } + + /// Attack #2a: tabs in the indentation and a trailing block comment, not + /// just the line comment the dev's own test uses. The edit's byte range + /// must still cover exactly the path token. + #[test] + fn the_edit_range_is_exact_with_tab_indentation_and_a_block_comment() { + let tree = Tree::new("qa_tabs"); + tree.write("rtl/defs.svh", "`define W 8\n"); + let text = "\t\t`include \"defs.svh\" /* widths */\nmodule t;\n"; + let top = tree.write("rtl/top.sv", text); + tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n"); + let ws = tree.workspace(); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]); + let changes = rewrite.edit.as_ref().expect("an edit").changes.as_ref().expect("changes"); + let edit = &changes[&Uri::from_str(&uri_of(&top)).expect("uri")][0]; + // Decode the LSP range back to a byte offset the way a client would, + // and check it names exactly the eight bytes of `defs.svh`. + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let start = positions.offset(edit.range.start); + let end = positions.offset(edit.range.end); + assert_eq!(&text[start as usize..end as usize], "defs.svh", "{edit:?}"); + assert_eq!(edit.new_text, "widths.svh"); + } + + /// Corpus-scale probe: a real header with real fan-out, swept twice for + /// determinism. `prim_assert.sv` is included (own-directory rung, no + /// filelist needed) by 87 sibling files under + /// `ibex/vendor/lowrisc_ip/ip/prim/rtl/` — a renamed-file candidate that + /// actually exercises the "everywhere" path at scale, not a corpus file + /// picked at random that happens to include nothing. + /// + /// Every produced edit is checked against the post-rename filesystem + /// this module itself would use to verify a write (`resolve_as_if` + /// through `Moves`), and no file outside the 87 known includers may be + /// touched. + #[test] + fn a_real_corpus_header_with_wide_fan_out_is_swept_correctly_and_deterministically() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + let target_dir = root.join("ibex/vendor/lowrisc_ip/ip/prim/rtl"); + let old = target_dir.join("prim_assert.sv"); + // Skipped when `corpus/` is not checked out, like every other + // corpus test in this crate — asserting its presence panicked any + // environment (a bare CI checkout, `act`) that never fetched it. + if !old.is_file() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let new = target_dir.join("prim_assert_renamed.sv"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![root.clone()]); + let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) }; + + let run = || { + let rewrite = will_rename(&ws, std::slice::from_ref(&rename)); + let changes = rewrite + .edit + .expect("87 known includers, so an edit is expected") + .changes + .expect("changes"); + (changes, rewrite.warnings) + }; + + let (first, warnings_first) = run(); + let (second, warnings_second) = run(); + assert_eq!( + first.len(), + second.len(), + "the same sweep run twice must touch the same number of files" + ); + assert_eq!(warnings_first.len(), warnings_second.len(), "and warn the same amount"); + + // Every touched file is genuinely an includer of the old target, + // and every edit's new spelling resolves to the new location once + // the rename this module models has happened — the same check + // `survives` runs before it will ever write a spelling, run again + // here from outside the module as an independent cross-check. + // + // Built through `Moves::announced`, not by hand: its entries are + // normalized (`path_of`), and comparing a normalized candidate + // against a hand-built, unnormalized `(old, new)` pair silently + // fails to match at all (`Path::strip_prefix`/`==` are + // component-wise, and a literal `..` is a different component + // from the directory it resolves to) — the same class of mismatch + // the fix above addresses, on the test's own side this time. + let moves = Moves::announced(std::slice::from_ref(&rename)); + let graph = ws.includes(); + let mut touched_dirs = std::collections::HashSet::new(); + for (uri, edits) in &first { + let path = uri_to_path(uri).expect("a file: URI"); + touched_dirs.insert(path.parent().map(Path::to_path_buf)); + let text = fs::read_to_string(&path).expect("read the real corpus file"); + for edit in edits { + assert_eq!(edit.new_text, "prim_assert_renamed.sv", "{edit:?}"); + // Not the include as it was written — that names the *old* + // spelling, which correctly no longer resolves once the + // rename has happened (that is exactly why an edit was + // needed). What must resolve is the *written* spelling, + // the same thing `survives` checks before this module + // ever emits it. + let original = scan(&text) + .into_iter() + .find(|inc| inc.target == "prim_assert.sv") + .expect("the include this edit was computed for"); + let written = Include { target: edit.new_text.clone(), ..original }; + let resolved = graph.resolve_as_if(Some(&path), &written, &|p| moves.is_file(p)); + // `resolve_as_if` always folds `.`/`..` out of its answer + // (`normalize`), even when fed an unfolded `root` the way + // this test's own `CARGO_MANIFEST_DIR`-relative one is — + // so the expected side is folded here too. + assert_eq!(resolved, Some(normalize(&new)), "{path:?}: {edit:?}"); + } + } + // Every touched file really is one of the 87 known includers' + // directory — nothing outside it was swept in by this rename. + assert_eq!( + touched_dirs.len(), + 1, + "every includer of this own-dir-resolved header lives in one \ + directory; touching any other is a false positive: {touched_dirs:?}" + ); + assert_eq!(touched_dirs.into_iter().next().unwrap(), Some(target_dir)); + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/format.rs b/crates/lucisv_server/src/format.rs index e94a7b8..6410bbe 100644 --- a/crates/lucisv_server/src/format.rs +++ b/crates/lucisv_server/src/format.rs @@ -301,754 +301,6 @@ fn overrides_from_file(file: &FileConfig) -> StyleOverrides { } #[cfg(test)] -mod tests { - use super::*; - use crate::settings::ClientSettings; - use crate::state::Workspace; - use lsp_types::{Position, Uri}; - use std::path::PathBuf; - use std::str::FromStr; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn document(text: &str) -> (Workspace, Uri) { - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - (ws, uri) - } - - fn options(tab_size: u32, insert_spaces: bool) -> FormattingOptions { - FormattingOptions { tab_size, insert_spaces, ..Default::default() } - } - - /// No `lucisv.*` settings pushed — what every test predating them assumes. - fn none() -> ClientSettings { - ClientSettings::default() - } - - /// The settings a buffer resolves to, with nothing pushed by the client. - fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings { - settings_with(ws, uri, &none(), options) - } - - /// The settings a buffer resolves to against a given pushed configuration. - fn settings_with( - ws: &Workspace, - uri: &Uri, - client: &ClientSettings, - options: &FormattingOptions, - ) -> Settings { - settings_for(ws.document(uri).expect("open"), client, options) - } - - fn edit_of( - ws: &Workspace, - uri: &Uri, - options: &FormattingOptions, - ) -> Result, String> { - edit_with(ws, uri, &none(), options) - } - - fn edit_with( - ws: &Workspace, - uri: &Uri, - client: &ClientSettings, - options: &FormattingOptions, - ) -> Result, String> { - let doc = ws.document(uri).expect("open"); - formatting(doc, &settings_for(doc, client, options).config) - } - - /// A scratch directory holding a `lucisv.toml` and one source file, so - /// discovery runs against a real tree. Removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(config: &str) -> Tree { - static COUNTER: AtomicUsize = AtomicUsize::new(0); - let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let path = - std::env::temp_dir().join(format!("lucisv_server_fmt_{}_{n}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).expect("temp dir"); - // A `.git` marker stops discovery here, so a `lucisv.toml` in a real - // ancestor of the temp dir can never leak into these tests. - std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git"); - std::fs::write(path.join("lucisv.toml"), config).expect("write config"); - Tree { path } - } - - /// An open buffer for `m.sv` inside this tree. - fn document(&self, text: &str) -> (Workspace, Uri) { - let file = self.path.join("m.sv"); - std::fs::write(&file, text).expect("write source"); - let uri = crate::uri::path_to_uri(&file).expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - (ws, uri) - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.path); - } - } - - #[test] - fn an_unformatted_buffer_gets_one_whole_document_edit() { - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); - assert_eq!(edit.range.start.line, 0); - assert_eq!(edit.range.start.character, 0); - assert_eq!(edit.range.end.line, 3, "one past the last line"); - assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn an_already_formatted_buffer_gets_no_edit() { - let (ws, uri) = document("module m;\n wire a;\nendmodule\n"); - assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None); - } - - #[test] - fn a_sane_tab_size_becomes_the_indent_width() { - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let edit = edit_of(&ws, &uri, &options(4, true)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn hard_tabs_and_absurd_widths_fall_back_to_the_default() { - let nothing = FileConfig::default(); - assert_eq!( - config_from(¬hing, &none(), &options(4, false)).indent_width, - 2, - "hard tabs ignored" - ); - assert_eq!( - config_from(¬hing, &none(), &options(40, true)).indent_width, - 2, - "out of range ignored" - ); - assert_eq!( - config_from(¬hing, &none(), &options(0, true)).indent_width, - 2, - "zero ignored" - ); - assert_eq!( - config_from(¬hing, &none(), &options(8, true)).indent_width, - 8, - "the top of the range" - ); - } - - #[test] - fn a_line_length_is_never_taken_from_the_client() { - let config = config_from(&FileConfig::default(), &none(), &options(4, true)); - assert_eq!(config.max_width, Config::default().max_width); - } - - #[test] - fn a_config_file_beats_the_editors_tab_size() { - // The precedence decision, pinned: `tab_size` is the editor's default - // unless the user changed it, and a checked-in `lucisv.toml` is always - // deliberate. See `settings_for`. - let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() }; - let config = config_from(&file, &none(), &options(2, true)); - assert_eq!(config.indent_width, 4, "lucisv.toml wins over tab_size"); - assert_eq!(config.max_width, 120, "line-length has no client analog at all"); - // Where the config is silent the tab size still beats the default. - let only_width = FileConfig { line_length: Some(120), ..Default::default() }; - assert_eq!(config_from(&only_width, &none(), &options(3, true)).indent_width, 3); - } - - #[test] - fn a_lucisv_toml_governs_the_buffer_it_sits_above() { - let tree = Tree::new("indent = 4\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - // The client asks for 2, the config says 4: the config wins. - let settings = settings(&ws, &uri, &options(2, true)); - assert_eq!(settings.config.indent_width, 4); - assert_eq!(settings.problem, None); - let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn a_broken_lucisv_toml_reports_a_problem_and_formats_with_defaults() { - let tree = Tree::new("indent = 4\nbogus = 1\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - let settings = settings(&ws, &uri, &options(2, true)); - let problem = settings.problem.expect("a broken config must be reported"); - assert!(problem.contains("unknown key `bogus`"), "{problem}"); - assert!(problem.contains("lucisv.toml:2"), "the message names file and line: {problem}"); - // Nothing from the broken file is used, not even the key that parsed. - assert_eq!(settings.config.indent_width, Config::default().indent_width); - // And the buffer is still formatted: an editor must not hard-fail on a - // config typo the way the CLI's exit 2 does. - let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn a_lint_fixs_indent_comes_from_the_config_or_the_built_in_default() { - // A code action has no `tabSize` to consider, so a quick fix that - // writes spaces where a tab was gets the buffer's own `lucisv.toml`. - let tree = Tree::new("indent = 4\n"); - let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); - let doc = ws.document(&uri).expect("open"); - assert_eq!(indent_width(doc.path.as_deref(), &none()), 4); - assert_eq!( - indent_width(None, &none()), - Config::default().indent_width, - "an untitled buffer" - ); - } - - #[test] - fn a_broken_config_leaves_the_lint_fix_on_the_default_indent_and_says_nothing() { - let tree = Tree::new("indent = 4\nbogus = 1\n"); - let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); - let doc = ws.document(&uri).expect("open"); - assert_eq!(indent_width(doc.path.as_deref(), &none()), Config::default().indent_width); - } - - #[test] - fn an_untitled_buffer_has_no_directory_to_discover_from() { - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string()); - let settings = settings(&ws, &uri, &options(4, true)); - assert_eq!(settings.problem, None); - assert_eq!(settings.config.indent_width, 4, "the tab size is all there is"); - } - - // ------------------------------------------------------------------ - // the precedence ladder, one rung at a time - // ------------------------------------------------------------------ - - /// `lucisv.*` settings as a client would push them. - fn pushed(line_length: Option, indent: Option) -> ClientSettings { - ClientSettings { line_length, indent, ..Default::default() } - } - - #[test] - fn rung_1_a_config_file_beats_a_pushed_setting() { - // The whole reason the ladder is in this order: a checked-in - // `lucisv.toml` is the project speaking, and format-on-save must agree - // with what `lucisv --check` does in CI. - let tree = Tree::new("indent = 4\nline-length = 120\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - let client = pushed(Some(80), Some(8)); - let settings = settings_with(&ws, &uri, &client, &options(2, true)); - assert_eq!(settings.config.indent_width, 4, "lucisv.toml wins"); - assert_eq!(settings.config.max_width, 120, "for line-length too"); - let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats"); - assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn rung_2_a_pushed_setting_beats_the_editors_tab_size() { - // `tabSize` arrives on every request whether the user chose it or - // not; `lucisv.indent` was typed on purpose. - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let client = pushed(None, Some(4)); - let settings = settings_with(&ws, &uri, &client, &options(2, true)); - assert_eq!(settings.config.indent_width, 4); - let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats"); - assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n"); - } - - #[test] - fn rung_3_the_tab_size_still_beats_the_default_where_nothing_was_pushed() { - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - // Pushed settings that say nothing about indent leave rung 3 in charge. - let client = pushed(Some(120), None); - let settings = settings_with(&ws, &uri, &client, &options(3, true)); - assert_eq!(settings.config.indent_width, 3, "the tab size"); - assert_eq!(settings.config.max_width, 120, "and the pushed width"); - } - - #[test] - fn rung_4_the_default_applies_when_every_rung_above_is_silent() { - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - // Hard tabs, so even the tab size is not a usable signal. - let settings = settings_with(&ws, &uri, &none(), &options(4, false)); - assert_eq!(settings.config.indent_width, Config::default().indent_width); - assert_eq!(settings.config.max_width, Config::default().max_width); - } - - /// The `[format]` keys climb the same ladder — with no rung 3, since the - /// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` > - /// the built-in default, which is off (TODO §54.3). - #[test] - fn a_format_key_climbs_the_ladder_from_off() { - let uvm = |on: Option| ClientSettings { uvm_utils_indent: on, ..Default::default() }; - // Rung 4: nobody asked, so the key never fires. - let (ws, uri) = document("module m;\nendmodule\n"); - assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent); - // Rung 2: the editor setting is the only thing that spoke. - assert!( - settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent - ); - // Rung 1: `lucisv.toml` outranks the editor, in both directions. - let on = Tree::new("[format]\nuvm-utils-indent = true\n"); - let (ws, uri) = on.document("module m;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true)); - assert_eq!(settings.problem, None); - assert!(settings.config.uvm_utils_indent, "lucisv.toml wins"); - let off = Tree::new("[format]\nuvm-utils-indent = false\n"); - let (ws, uri) = off.document("module m;\nendmodule\n"); - assert!( - !settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent - ); - // A config that names other keys is silent about this one, so the - // editor setting still answers for it. - let other = Tree::new("indent = 4\n"); - let (ws, uri) = other.document("module m;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)); - assert_eq!(settings.config.indent_width, 4); - assert!(settings.config.uvm_utils_indent); - } - - /// The style climbs rungs 1, 2 and 4, supplies the starting indent and - /// width, and — once someone actually chose one — outranks `tabSize`. - #[test] - fn a_style_sets_the_starting_values_and_outranks_tab_size() { - let styled = |name| ClientSettings { style: Some(name), ..Default::default() }; - let (ws, uri) = document("module m;\nendmodule\n"); - let config = |client: &ClientSettings, tab| { - settings_with(&ws, &uri, client, &options(tab, true)).config - }; - // No style, and `lucisv` — what VS Code sends by default — are the - // same thing: `tabSize` is the indent, exactly as before styles. - assert_eq!((config(&none(), 4).indent_width, config(&none(), 4).style), (4, style::LUCISV)); - assert_eq!(config(&styled("lucisv"), 4).indent_width, 4); - // A chosen style outranks `tabSize`... - let google = config(&styled("google"), 4); - assert_eq!((google.style, google.indent_width, google.max_width), (style::GOOGLE, 2, 100)); - // ...but not an explicit `lucisv.indent`, and the width stays the style's. - let both = - ClientSettings { style: Some("microsoft"), indent: Some(2), ..Default::default() }; - let microsoft = config(&both, 8); - assert_eq!((microsoft.indent_width, microsoft.max_width), (2, 120)); - // A misspelt editor value never got this far: it is dropped on arrival. - assert_eq!( - crate::settings::from_payload(&serde_json::json!({ - "lucisv": { "format": { "style": "gogle" } } - })) - .style, - None - ); - } - - #[test] - fn lucisv_toml_names_the_style_over_the_editor() { - let styled = |name| ClientSettings { style: Some(name), ..Default::default() }; - let nxp = Tree::new("[format]\nstyle = \"nxp\"\n"); - let (ws, uri) = nxp.document("module m;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &styled("microsoft"), &options(4, true)); - assert_eq!(settings.problem, None); - let c = settings.config; - assert_eq!((c.style, c.indent_width, c.max_width), (style::NXP, 2, 80)); - // The project's `lucisv` beats the editor's `google`, and with it the - // editor's `tabSize` is back in play. - let plain = Tree::new("[format]\nstyle = \"lucisv\"\n"); - let (ws, uri) = plain.document("module m;\nendmodule\n"); - let c = settings_with(&ws, &uri, &styled("google"), &options(4, true)).config; - assert_eq!((c.style, c.indent_width), (style::LUCISV, 4)); - // The lint-fix width follows the style too, below the explicit keys. - let ansi = Tree::new("[format]\nstyle = \"ansi\"\n"); - let path = ansi.path.join("m.sv"); - assert_eq!(indent_width(Some(&path), &none()), 4); - assert_eq!(indent_width(None, &styled("microsoft")), 4); - let pushed = ClientSettings { indent: Some(3), ..styled("microsoft") }; - assert_eq!(indent_width(Some(&path), &pushed), 3); - // A bad name in `lucisv.toml` is the config problem every bad key is. - let bad = Tree::new("[format]\nstyle = \"gogle\"\n"); - let (ws, uri) = bad.document("module m;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &none(), &options(2, true)); - let problem = settings.problem.expect("a problem"); - assert!(problem.contains("unknown style `gogle`"), "{problem}"); - assert_eq!(settings.config.style, style::LUCISV); - } - - #[test] - fn each_key_climbs_the_ladder_independently() { - // A `lucisv.toml` naming only `indent` must not also claim the width: - // the pushed `lineLength` is still the best answer for that key. - let tree = Tree::new("indent = 4\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true)); - assert_eq!(settings.config.indent_width, 4, "config wins the key it names"); - assert_eq!(settings.config.max_width, 60, "and is silent about the other"); - } - - #[test] - fn a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config() { - // The protocol has no line-length option at all, so before - // `lucisv.lineLength` a config-less project could not narrow its lines - // from the editor. This is the new capability, at the level that - // actually reflows text. - let long = "module m;\n assign a = bbbbbbbbbbbb + cccccccccccc + dddddddddddd + eeeeeeeeeeee;\nendmodule\n"; - let (ws, uri) = document(long); - assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None, "fits at 100"); - let edit = edit_with(&ws, &uri, &pushed(Some(40), None), &options(2, true)) - .expect("formats") - .expect("40 columns must reflow it"); - assert!(edit.new_text.lines().count() > long.lines().count(), "{}", edit.new_text); - } - - #[test] - fn an_untitled_buffer_honours_pushed_settings() { - // It has no directory to discover a `lucisv.toml` from, so rung 2 is the - // highest rung it has — and before this feature it had only `tabSize`. - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string()); - let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(4)), &options(2, true)); - assert_eq!(settings.problem, None); - assert_eq!(settings.config.indent_width, 4, "pushed indent beats the tab size"); - assert_eq!(settings.config.max_width, 60); - } - - #[test] - fn a_lint_fix_climbs_the_same_ladder_without_rung_3() { - // A code action has no `tabSize`, so `lucisv.indent` is the only thing - // under a `lucisv.toml` here. - let tree = Tree::new("indent = 4\n"); - let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); - let doc = ws.document(&uri).expect("open"); - assert_eq!(indent_width(doc.path.as_deref(), &pushed(None, Some(8))), 4, "config wins"); - assert_eq!(indent_width(None, &pushed(None, Some(8))), 8, "untitled: the pushed value"); - assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default"); - } - - #[test] - fn a_request_without_options_climbs_the_same_ladder_without_rung_3() { - // What `willSaveWaitUntil` resolves to: the protocol sends no - // `FormattingOptions` with it, so the editor's tab size is simply not - // one of the inputs. - let tree = Tree::new("indent = 4\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - let doc = ws.document(&uri).expect("open"); - let settings = settings_without_editor_options(doc, &pushed(None, Some(8))); - assert_eq!(settings.config.indent_width, 4, "the config still wins"); - assert_eq!(settings.problem, None); - - // With no config, the pushed setting is the highest rung there is. - let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let doc = ws.document(&uri).expect("open"); - let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8))); - assert_eq!(settings.config.indent_width, 8); - assert_eq!(settings.config.max_width, 60); - // And with nothing pushed either, the built-in default — never a - // guess from an option that was not sent. - let settings = settings_without_editor_options(doc, &none()); - assert_eq!(settings.config.indent_width, Config::default().indent_width); - assert_eq!(settings.config.max_width, Config::default().max_width); - } - - #[test] - fn a_broken_config_leaves_the_pushed_settings_in_charge() { - // Nothing from a broken `lucisv.toml` is used, so the next rung down is - // the one that answers — which is now the pushed settings, not the - // built-in default. - let tree = Tree::new("indent = 4\nbogus = 1\n"); - let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); - let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true)); - assert!(settings.problem.is_some(), "the user is still told"); - assert_eq!(settings.config.indent_width, 8); - assert_eq!(settings.config.max_width, 60); - } - - /// Three items, one per line, so a range's reach is visible line by line. - const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n"; - - fn at(start_line: u32, start_char: u32, end_line: u32, end_char: u32) -> Range { - Range { - start: Position { line: start_line, character: start_char }, - end: Position { line: end_line, character: end_char }, - } - } - - fn ranged(text: &str, range: Range) -> Result, String> { - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - range_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, range) - } - - #[test] - fn a_range_formats_only_the_lines_it_covers() { - // A cursor sitting on line 2 (0-based line 1) with nothing selected. - let edit = ranged(THREE, at(1, 4, 1, 4)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); - // And the reply is still one whole-document edit. - assert_eq!(edit.range.start, Position { line: 0, character: 0 }); - assert_eq!(edit.range.end.line, 4); - } - - #[test] - fn a_selection_ending_at_the_start_of_a_line_stops_before_it() { - // "Select these two lines" in an editor ends at line 3, character 0. - let edit = ranged(THREE, at(1, 0, 3, 0)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); - // One line only, ending where it began. - let edit = ranged(THREE, at(2, 0, 3, 0)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); - } - - #[test] - fn a_range_over_nothing_formattable_produces_no_edit() { - // Line 4 is `endmodule`, already written the way the formatter writes - // it, so there is nothing to send. - assert_eq!(ranged(THREE, at(3, 0, 3, 9)).expect("formats"), None); - } - - #[test] - fn a_range_whose_end_is_past_the_document_still_answers() { - let edit = ranged(THREE, at(0, 0, 99, 0)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); - } - - #[test] - fn a_range_over_multi_byte_content_lands_on_the_right_lines() { - // The character columns are UTF-16 units; only the *lines* reach the - // engine, so the emoji line must not shift which item is formatted. - let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"; - let edit = ranged(text, at(2, 0, 2, 11)).expect("formats").expect("changed"); - assert_eq!( - edit.new_text, - "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n" - ); - assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped"); - } - - /// A file indented four spaces with a `case` nested in an `always`: the - /// shape VS Code's "Format Selection" most often sends. - const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n"; - - #[test] - fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() { - let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed"); - assert_eq!( - edit.new_text, - "module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n" - ); - } - - #[test] - fn a_tab_indented_selection_keeps_its_tabs() { - let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n"; - let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed"); - assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n"); - } - - #[test] - fn a_parse_error_outside_the_selection_does_not_block_it() { - let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n"; - let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed"); - assert_eq!( - edit.new_text, - "module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n" - ); - // Inside it, the request is refused with a message to read. - let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse"); - assert!(message.contains("syntax error"), "{message}"); - } - - #[test] - fn an_unparsable_buffer_produces_no_range_edit_either() { - // Range formatting cannot rescue broken input; the strict parse still - // has to succeed. - let message = - ranged("module m;\n wire ;\nendmodule\n", at(0, 0, 0, 9)).expect_err("must refuse"); - assert!(!message.is_empty(), "the user needs something to read"); - } - - #[test] - fn an_unparsable_buffer_produces_no_edit() { - let (ws, uri) = document("module m;\n wire ;\nendmodule\n"); - let message = edit_of(&ws, &uri, &options(2, true)).expect_err("must refuse"); - assert!(!message.is_empty(), "the user needs something to read"); - } - - // ------------------------------------------------------------------ - // `rangesFormatting` — the union of the ranges, on the one engine - // ------------------------------------------------------------------ - - /// Four items, one per line, so two disjoint ranges can reach two of them - /// and leave the ones between untouched. - const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; - - fn multi(text: &str, ranges: &[Range]) -> Result, String> { - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges) - } - - /// The `new_text` a multi-range request answers with, or `None`. - fn multi_text(text: &str, ranges: &[Range]) -> Option { - multi(text, ranges).expect("formats").map(|edit| edit.new_text) - } - - #[test] - fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() { - // Lines 2 and 4 selected, line 3 not: `b` keeps its bytes. - let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed"); - assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); - } - - #[test] - fn a_multi_range_answer_is_the_union_of_the_single_range_answers() { - // The contract, stated as an equality rather than as a re-spelled - // expectation: where two ranges do not interact, asking for both at - // once is asking for each and taking both results. Line 2 formatted - // alone, then line 4 formatted on *that* text, must be byte-identical - // to one request naming both. - let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text; - let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text; - let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed"); - assert_eq!(both, second); - } - - #[test] - fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() { - // `LineRanges::new` sorts and merges, and this asserts it through the - // answer rather than restating the arithmetic. All four spellings name - // lines 2 and 3. - let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed"); - assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); - for (spelling, ranges) in [ - ("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]), - ("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]), - ("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]), - ("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]), - ] { - assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}"); - } - } - - #[test] - fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() { - // A client with no selections must not get a popup. `LineRanges::new` - // refuses an empty list — that refusal is the CLI's (`--lines ''` is a - // typo), and it is answered before the engine here. - assert_eq!(multi(FOUR, &[]).expect("never an error"), None); - } - - #[test] - fn one_range_over_the_whole_buffer_is_the_whole_file_format() { - let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed"); - assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); - // And so is every line named separately, which is the same union. - let each: Vec = (0..5).map(|line| at(line, 0, line, 11)).collect(); - assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str())); - } - - #[test] - fn a_one_element_multi_range_request_is_the_single_range_request() { - // `range_formatting` is *defined* as this call, so the two can never - // drift — but the equality is what a client relies on, so it is - // asserted rather than argued. - for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] { - assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}"); - } - } - - #[test] - fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() { - // No partial output on either path (CLAUDE.md invariant #1), and the - // same message: both are one `format_selection` call away from the engine. - let broken = "module m;\n wire ;\nendmodule\n"; - let one = ranged(broken, at(0, 0, 0, 9)); - let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]); - assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways"); - assert_eq!(one, many, "byte-identical refusals, message included"); - } - - #[test] - fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() { - // Idempotency through the new path: format lines 2 and 4, then ask for - // exactly the same two ranges on the answer — nothing left to do. - let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)]; - let once = multi_text(FOUR, &ranges).expect("changed"); - assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say"); - } - - #[test] - fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() { - let clean = "module m;\n wire a;\n wire b;\nendmodule\n"; - assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None); - } - - #[test] - fn multi_byte_content_survives_a_multi_range_format_too() { - // The columns are UTF-16 units and only the lines reach the engine, so - // an emoji two lines up must not shift which items are laid out. - let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"; - let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed"); - assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"); - assert!(out.contains("é ✓ 🎉"), "comments are never dropped"); - } - - #[test] - fn the_line_conversion_is_the_one_rangeformatting_always_used() { - // Pinned directly, because both requests now share it: a cursor names - // its own line; an end at character 0 of a *later* line stops one line - // short; an end at character 0 on the start line does not. - assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor"); - assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines"); - assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line"); - assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line"); - assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer"); - // And it never produces a span `LineRanges` would refuse: line 0 is - // impossible (1-based), and `last` can never fall below `first`. - assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line"); - assert_eq!( - lines_of(at(u32::MAX, 0, u32::MAX, 0)), - (u32::MAX, u32::MAX), - "a saturating add, not an overflow" - ); - } - - #[test] - fn multi_byte_content_survives_formatting() { - let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n"); - let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); - assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped"); - // The replaced range must cover the whole document in UTF-16 terms. - assert_eq!(edit.range.end.line, 4); - } - - #[test] - fn selective_format_overrides_respect_toml_over_editor_over_style() { - let tree = Tree::new( - "[format]\nstyle = \"google\"\nbegin = \"own-line\"\nconnection-align-min = 0\n", - ); - let (ws, uri) = tree.document( - "module m (input logic a, input logic b);\n always_comb if (a) begin x = 1; end\n sub #(.A(1), .LONGER(2)) u (.clk(clk), .data_in(d));\nendmodule\n", - ); - let client = ClientSettings { - style: Some("lucisv"), - format_begin: Some("same-line"), - format_alignment: Some("always"), - format_connection_align_min: Some(1), - ..Default::default() - }; - let resolved = settings_with(&ws, &uri, &client, &options(2, true)); - assert_eq!(resolved.config.style.name, "google"); - assert_eq!(resolved.config.style.begin, Placement::OwnLine); - assert_eq!(resolved.config.style.alignment, Alignment::Always); - assert_eq!(resolved.config.style.connection_align_min, 0); - - let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("ok").expect("edit"); - assert!(edit.new_text.contains(" if (a)\n begin\n"), "{}", edit.new_text); - assert!(edit.new_text.contains(" .LONGER(2)\n"), "{}", edit.new_text); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/format/tests.rs b/crates/lucisv_server/src/format/tests.rs new file mode 100644 index 0000000..5509059 --- /dev/null +++ b/crates/lucisv_server/src/format/tests.rs @@ -0,0 +1,733 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::settings::ClientSettings; +use crate::state::Workspace; +use lsp_types::{Position, Uri}; +use std::path::PathBuf; +use std::str::FromStr; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn document(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) +} + +fn options(tab_size: u32, insert_spaces: bool) -> FormattingOptions { + FormattingOptions { tab_size, insert_spaces, ..Default::default() } +} + +/// No `lucisv.*` settings pushed — what every test predating them assumes. +fn none() -> ClientSettings { + ClientSettings::default() +} + +/// The settings a buffer resolves to, with nothing pushed by the client. +fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings { + settings_with(ws, uri, &none(), options) +} + +/// The settings a buffer resolves to against a given pushed configuration. +fn settings_with( + ws: &Workspace, + uri: &Uri, + client: &ClientSettings, + options: &FormattingOptions, +) -> Settings { + settings_for(ws.document(uri).expect("open"), client, options) +} + +fn edit_of( + ws: &Workspace, + uri: &Uri, + options: &FormattingOptions, +) -> Result, String> { + edit_with(ws, uri, &none(), options) +} + +fn edit_with( + ws: &Workspace, + uri: &Uri, + client: &ClientSettings, + options: &FormattingOptions, +) -> Result, String> { + let doc = ws.document(uri).expect("open"); + formatting(doc, &settings_for(doc, client, options).config) +} + +/// A scratch directory holding a `lucisv.toml` and one source file, so +/// discovery runs against a real tree. Removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(config: &str) -> Tree { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("lucisv_server_fmt_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + // A `.git` marker stops discovery here, so a `lucisv.toml` in a real + // ancestor of the temp dir can never leak into these tests. + std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git"); + std::fs::write(path.join("lucisv.toml"), config).expect("write config"); + Tree { path } + } + + /// An open buffer for `m.sv` inside this tree. + fn document(&self, text: &str) -> (Workspace, Uri) { + let file = self.path.join("m.sv"); + std::fs::write(&file, text).expect("write source"); + let uri = crate::uri::path_to_uri(&file).expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +#[test] +fn an_unformatted_buffer_gets_one_whole_document_edit() { + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert_eq!(edit.range.start.line, 0); + assert_eq!(edit.range.start.character, 0); + assert_eq!(edit.range.end.line, 3, "one past the last line"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn an_already_formatted_buffer_gets_no_edit() { + let (ws, uri) = document("module m;\n wire a;\nendmodule\n"); + assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None); +} + +#[test] +fn a_sane_tab_size_becomes_the_indent_width() { + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + let edit = edit_of(&ws, &uri, &options(4, true)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn hard_tabs_and_absurd_widths_fall_back_to_the_default() { + let nothing = FileConfig::default(); + assert_eq!( + config_from(¬hing, &none(), &options(4, false)).indent_width, + 2, + "hard tabs ignored" + ); + assert_eq!( + config_from(¬hing, &none(), &options(40, true)).indent_width, + 2, + "out of range ignored" + ); + assert_eq!(config_from(¬hing, &none(), &options(0, true)).indent_width, 2, "zero ignored"); + assert_eq!( + config_from(¬hing, &none(), &options(8, true)).indent_width, + 8, + "the top of the range" + ); +} + +#[test] +fn a_line_length_is_never_taken_from_the_client() { + let config = config_from(&FileConfig::default(), &none(), &options(4, true)); + assert_eq!(config.max_width, Config::default().max_width); +} + +#[test] +fn a_config_file_beats_the_editors_tab_size() { + // The precedence decision, pinned: `tab_size` is the editor's default + // unless the user changed it, and a checked-in `lucisv.toml` is always + // deliberate. See `settings_for`. + let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() }; + let config = config_from(&file, &none(), &options(2, true)); + assert_eq!(config.indent_width, 4, "lucisv.toml wins over tab_size"); + assert_eq!(config.max_width, 120, "line-length has no client analog at all"); + // Where the config is silent the tab size still beats the default. + let only_width = FileConfig { line_length: Some(120), ..Default::default() }; + assert_eq!(config_from(&only_width, &none(), &options(3, true)).indent_width, 3); +} + +#[test] +fn a_lucisv_toml_governs_the_buffer_it_sits_above() { + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + // The client asks for 2, the config says 4: the config wins. + let settings = settings(&ws, &uri, &options(2, true)); + assert_eq!(settings.config.indent_width, 4); + assert_eq!(settings.problem, None); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn a_broken_lucisv_toml_reports_a_problem_and_formats_with_defaults() { + let tree = Tree::new("indent = 4\nbogus = 1\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let settings = settings(&ws, &uri, &options(2, true)); + let problem = settings.problem.expect("a broken config must be reported"); + assert!(problem.contains("unknown key `bogus`"), "{problem}"); + assert!(problem.contains("lucisv.toml:2"), "the message names file and line: {problem}"); + // Nothing from the broken file is used, not even the key that parsed. + assert_eq!(settings.config.indent_width, Config::default().indent_width); + // And the buffer is still formatted: an editor must not hard-fail on a + // config typo the way the CLI's exit 2 does. + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn a_lint_fixs_indent_comes_from_the_config_or_the_built_in_default() { + // A code action has no `tabSize` to consider, so a quick fix that + // writes spaces where a tab was gets the buffer's own `lucisv.toml`. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + assert_eq!(indent_width(doc.path.as_deref(), &none()), 4); + assert_eq!(indent_width(None, &none()), Config::default().indent_width, "an untitled buffer"); +} + +#[test] +fn a_broken_config_leaves_the_lint_fix_on_the_default_indent_and_says_nothing() { + let tree = Tree::new("indent = 4\nbogus = 1\n"); + let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + assert_eq!(indent_width(doc.path.as_deref(), &none()), Config::default().indent_width); +} + +#[test] +fn an_untitled_buffer_has_no_directory_to_discover_from() { + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string()); + let settings = settings(&ws, &uri, &options(4, true)); + assert_eq!(settings.problem, None); + assert_eq!(settings.config.indent_width, 4, "the tab size is all there is"); +} + +// ------------------------------------------------------------------ +// the precedence ladder, one rung at a time +// ------------------------------------------------------------------ + +/// `lucisv.*` settings as a client would push them. +fn pushed(line_length: Option, indent: Option) -> ClientSettings { + ClientSettings { line_length, indent, ..Default::default() } +} + +#[test] +fn rung_1_a_config_file_beats_a_pushed_setting() { + // The whole reason the ladder is in this order: a checked-in + // `lucisv.toml` is the project speaking, and format-on-save must agree + // with what `lucisv --check` does in CI. + let tree = Tree::new("indent = 4\nline-length = 120\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let client = pushed(Some(80), Some(8)); + let settings = settings_with(&ws, &uri, &client, &options(2, true)); + assert_eq!(settings.config.indent_width, 4, "lucisv.toml wins"); + assert_eq!(settings.config.max_width, 120, "for line-length too"); + let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats"); + assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn rung_2_a_pushed_setting_beats_the_editors_tab_size() { + // `tabSize` arrives on every request whether the user chose it or + // not; `lucisv.indent` was typed on purpose. + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + let client = pushed(None, Some(4)); + let settings = settings_with(&ws, &uri, &client, &options(2, true)); + assert_eq!(settings.config.indent_width, 4); + let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats"); + assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n"); +} + +#[test] +fn rung_3_the_tab_size_still_beats_the_default_where_nothing_was_pushed() { + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + // Pushed settings that say nothing about indent leave rung 3 in charge. + let client = pushed(Some(120), None); + let settings = settings_with(&ws, &uri, &client, &options(3, true)); + assert_eq!(settings.config.indent_width, 3, "the tab size"); + assert_eq!(settings.config.max_width, 120, "and the pushed width"); +} + +#[test] +fn rung_4_the_default_applies_when_every_rung_above_is_silent() { + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + // Hard tabs, so even the tab size is not a usable signal. + let settings = settings_with(&ws, &uri, &none(), &options(4, false)); + assert_eq!(settings.config.indent_width, Config::default().indent_width); + assert_eq!(settings.config.max_width, Config::default().max_width); +} + +/// The `[format]` keys climb the same ladder — with no rung 3, since the +/// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` > +/// the built-in default, which is off (TODO §54.3). +#[test] +fn a_format_key_climbs_the_ladder_from_off() { + let uvm = |on: Option| ClientSettings { uvm_utils_indent: on, ..Default::default() }; + // Rung 4: nobody asked, so the key never fires. + let (ws, uri) = document("module m;\nendmodule\n"); + assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent); + // Rung 2: the editor setting is the only thing that spoke. + assert!(settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent); + // Rung 1: `lucisv.toml` outranks the editor, in both directions. + let on = Tree::new("[format]\nuvm-utils-indent = true\n"); + let (ws, uri) = on.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true)); + assert_eq!(settings.problem, None); + assert!(settings.config.uvm_utils_indent, "lucisv.toml wins"); + let off = Tree::new("[format]\nuvm-utils-indent = false\n"); + let (ws, uri) = off.document("module m;\nendmodule\n"); + assert!(!settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent); + // A config that names other keys is silent about this one, so the + // editor setting still answers for it. + let other = Tree::new("indent = 4\n"); + let (ws, uri) = other.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)); + assert_eq!(settings.config.indent_width, 4); + assert!(settings.config.uvm_utils_indent); +} + +/// The style climbs rungs 1, 2 and 4, supplies the starting indent and +/// width, and — once someone actually chose one — outranks `tabSize`. +#[test] +fn a_style_sets_the_starting_values_and_outranks_tab_size() { + let styled = |name| ClientSettings { style: Some(name), ..Default::default() }; + let (ws, uri) = document("module m;\nendmodule\n"); + let config = + |client: &ClientSettings, tab| settings_with(&ws, &uri, client, &options(tab, true)).config; + // No style, and `lucisv` — what VS Code sends by default — are the + // same thing: `tabSize` is the indent, exactly as before styles. + assert_eq!((config(&none(), 4).indent_width, config(&none(), 4).style), (4, style::LUCISV)); + assert_eq!(config(&styled("lucisv"), 4).indent_width, 4); + // A chosen style outranks `tabSize`... + let google = config(&styled("google"), 4); + assert_eq!((google.style, google.indent_width, google.max_width), (style::GOOGLE, 2, 100)); + // ...but not an explicit `lucisv.indent`, and the width stays the style's. + let both = ClientSettings { style: Some("microsoft"), indent: Some(2), ..Default::default() }; + let microsoft = config(&both, 8); + assert_eq!((microsoft.indent_width, microsoft.max_width), (2, 120)); + // A misspelt editor value never got this far: it is dropped on arrival. + assert_eq!( + crate::settings::from_payload(&serde_json::json!({ + "lucisv": { "format": { "style": "gogle" } } + })) + .style, + None + ); +} + +#[test] +fn lucisv_toml_names_the_style_over_the_editor() { + let styled = |name| ClientSettings { style: Some(name), ..Default::default() }; + let nxp = Tree::new("[format]\nstyle = \"nxp\"\n"); + let (ws, uri) = nxp.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &styled("microsoft"), &options(4, true)); + assert_eq!(settings.problem, None); + let c = settings.config; + assert_eq!((c.style, c.indent_width, c.max_width), (style::NXP, 2, 80)); + // The project's `lucisv` beats the editor's `google`, and with it the + // editor's `tabSize` is back in play. + let plain = Tree::new("[format]\nstyle = \"lucisv\"\n"); + let (ws, uri) = plain.document("module m;\nendmodule\n"); + let c = settings_with(&ws, &uri, &styled("google"), &options(4, true)).config; + assert_eq!((c.style, c.indent_width), (style::LUCISV, 4)); + // The lint-fix width follows the style too, below the explicit keys. + let ansi = Tree::new("[format]\nstyle = \"ansi\"\n"); + let path = ansi.path.join("m.sv"); + assert_eq!(indent_width(Some(&path), &none()), 4); + assert_eq!(indent_width(None, &styled("microsoft")), 4); + let pushed = ClientSettings { indent: Some(3), ..styled("microsoft") }; + assert_eq!(indent_width(Some(&path), &pushed), 3); + // A bad name in `lucisv.toml` is the config problem every bad key is. + let bad = Tree::new("[format]\nstyle = \"gogle\"\n"); + let (ws, uri) = bad.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &none(), &options(2, true)); + let problem = settings.problem.expect("a problem"); + assert!(problem.contains("unknown style `gogle`"), "{problem}"); + assert_eq!(settings.config.style, style::LUCISV); +} + +#[test] +fn each_key_climbs_the_ladder_independently() { + // A `lucisv.toml` naming only `indent` must not also claim the width: + // the pushed `lineLength` is still the best answer for that key. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true)); + assert_eq!(settings.config.indent_width, 4, "config wins the key it names"); + assert_eq!(settings.config.max_width, 60, "and is silent about the other"); +} + +#[test] +fn a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config() { + // The protocol has no line-length option at all, so before + // `lucisv.lineLength` a config-less project could not narrow its lines + // from the editor. This is the new capability, at the level that + // actually reflows text. + let long = "module m;\n assign a = bbbbbbbbbbbb + cccccccccccc + dddddddddddd + eeeeeeeeeeee;\nendmodule\n"; + let (ws, uri) = document(long); + assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None, "fits at 100"); + let edit = edit_with(&ws, &uri, &pushed(Some(40), None), &options(2, true)) + .expect("formats") + .expect("40 columns must reflow it"); + assert!(edit.new_text.lines().count() > long.lines().count(), "{}", edit.new_text); +} + +#[test] +fn an_untitled_buffer_honours_pushed_settings() { + // It has no directory to discover a `lucisv.toml` from, so rung 2 is the + // highest rung it has — and before this feature it had only `tabSize`. + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string()); + let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(4)), &options(2, true)); + assert_eq!(settings.problem, None); + assert_eq!(settings.config.indent_width, 4, "pushed indent beats the tab size"); + assert_eq!(settings.config.max_width, 60); +} + +#[test] +fn a_lint_fix_climbs_the_same_ladder_without_rung_3() { + // A code action has no `tabSize`, so `lucisv.indent` is the only thing + // under a `lucisv.toml` here. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + assert_eq!(indent_width(doc.path.as_deref(), &pushed(None, Some(8))), 4, "config wins"); + assert_eq!(indent_width(None, &pushed(None, Some(8))), 8, "untitled: the pushed value"); + assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default"); +} + +#[test] +fn a_request_without_options_climbs_the_same_ladder_without_rung_3() { + // What `willSaveWaitUntil` resolves to: the protocol sends no + // `FormattingOptions` with it, so the editor's tab size is simply not + // one of the inputs. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let settings = settings_without_editor_options(doc, &pushed(None, Some(8))); + assert_eq!(settings.config.indent_width, 4, "the config still wins"); + assert_eq!(settings.problem, None); + + // With no config, the pushed setting is the highest rung there is. + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8))); + assert_eq!(settings.config.indent_width, 8); + assert_eq!(settings.config.max_width, 60); + // And with nothing pushed either, the built-in default — never a + // guess from an option that was not sent. + let settings = settings_without_editor_options(doc, &none()); + assert_eq!(settings.config.indent_width, Config::default().indent_width); + assert_eq!(settings.config.max_width, Config::default().max_width); +} + +#[test] +fn a_broken_config_leaves_the_pushed_settings_in_charge() { + // Nothing from a broken `lucisv.toml` is used, so the next rung down is + // the one that answers — which is now the pushed settings, not the + // built-in default. + let tree = Tree::new("indent = 4\nbogus = 1\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true)); + assert!(settings.problem.is_some(), "the user is still told"); + assert_eq!(settings.config.indent_width, 8); + assert_eq!(settings.config.max_width, 60); +} + +/// Three items, one per line, so a range's reach is visible line by line. +const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n"; + +fn at(start_line: u32, start_char: u32, end_line: u32, end_char: u32) -> Range { + Range { + start: Position { line: start_line, character: start_char }, + end: Position { line: end_line, character: end_char }, + } +} + +fn ranged(text: &str, range: Range) -> Result, String> { + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + range_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, range) +} + +#[test] +fn a_range_formats_only_the_lines_it_covers() { + // A cursor sitting on line 2 (0-based line 1) with nothing selected. + let edit = ranged(THREE, at(1, 4, 1, 4)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); + // And the reply is still one whole-document edit. + assert_eq!(edit.range.start, Position { line: 0, character: 0 }); + assert_eq!(edit.range.end.line, 4); +} + +#[test] +fn a_selection_ending_at_the_start_of_a_line_stops_before_it() { + // "Select these two lines" in an editor ends at line 3, character 0. + let edit = ranged(THREE, at(1, 0, 3, 0)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); + // One line only, ending where it began. + let edit = ranged(THREE, at(2, 0, 3, 0)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); +} + +#[test] +fn a_range_over_nothing_formattable_produces_no_edit() { + // Line 4 is `endmodule`, already written the way the formatter writes + // it, so there is nothing to send. + assert_eq!(ranged(THREE, at(3, 0, 3, 9)).expect("formats"), None); +} + +#[test] +fn a_range_whose_end_is_past_the_document_still_answers() { + let edit = ranged(THREE, at(0, 0, 99, 0)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); +} + +#[test] +fn a_range_over_multi_byte_content_lands_on_the_right_lines() { + // The character columns are UTF-16 units; only the *lines* reach the + // engine, so the emoji line must not shift which item is formatted. + let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"; + let edit = ranged(text, at(2, 0, 2, 11)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"); + assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped"); +} + +/// A file indented four spaces with a `case` nested in an `always`: the +/// shape VS Code's "Format Selection" most often sends. +const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n"; + +#[test] +fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() { + let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed"); + assert_eq!( + edit.new_text, + "module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n" + ); +} + +#[test] +fn a_tab_indented_selection_keeps_its_tabs() { + let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n"; + let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n"); +} + +#[test] +fn a_parse_error_outside_the_selection_does_not_block_it() { + let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n"; + let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed"); + assert_eq!( + edit.new_text, + "module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n" + ); + // Inside it, the request is refused with a message to read. + let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse"); + assert!(message.contains("syntax error"), "{message}"); +} + +#[test] +fn an_unparsable_buffer_produces_no_range_edit_either() { + // Range formatting cannot rescue broken input; the strict parse still + // has to succeed. + let message = + ranged("module m;\n wire ;\nendmodule\n", at(0, 0, 0, 9)).expect_err("must refuse"); + assert!(!message.is_empty(), "the user needs something to read"); +} + +#[test] +fn an_unparsable_buffer_produces_no_edit() { + let (ws, uri) = document("module m;\n wire ;\nendmodule\n"); + let message = edit_of(&ws, &uri, &options(2, true)).expect_err("must refuse"); + assert!(!message.is_empty(), "the user needs something to read"); +} + +// ------------------------------------------------------------------ +// `rangesFormatting` — the union of the ranges, on the one engine +// ------------------------------------------------------------------ + +/// Four items, one per line, so two disjoint ranges can reach two of them +/// and leave the ones between untouched. +const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; + +fn multi(text: &str, ranges: &[Range]) -> Result, String> { + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges) +} + +/// The `new_text` a multi-range request answers with, or `None`. +fn multi_text(text: &str, ranges: &[Range]) -> Option { + multi(text, ranges).expect("formats").map(|edit| edit.new_text) +} + +#[test] +fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() { + // Lines 2 and 4 selected, line 3 not: `b` keeps its bytes. + let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed"); + assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); +} + +#[test] +fn a_multi_range_answer_is_the_union_of_the_single_range_answers() { + // The contract, stated as an equality rather than as a re-spelled + // expectation: where two ranges do not interact, asking for both at + // once is asking for each and taking both results. Line 2 formatted + // alone, then line 4 formatted on *that* text, must be byte-identical + // to one request naming both. + let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text; + let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text; + let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed"); + assert_eq!(both, second); +} + +#[test] +fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() { + // `LineRanges::new` sorts and merges, and this asserts it through the + // answer rather than restating the arithmetic. All four spellings name + // lines 2 and 3. + let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed"); + assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); + for (spelling, ranges) in [ + ("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]), + ("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]), + ("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]), + ("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]), + ] { + assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}"); + } +} + +#[test] +fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() { + // A client with no selections must not get a popup. `LineRanges::new` + // refuses an empty list — that refusal is the CLI's (`--lines ''` is a + // typo), and it is answered before the engine here. + assert_eq!(multi(FOUR, &[]).expect("never an error"), None); +} + +#[test] +fn one_range_over_the_whole_buffer_is_the_whole_file_format() { + let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed"); + assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"); + // And so is every line named separately, which is the same union. + let each: Vec = (0..5).map(|line| at(line, 0, line, 11)).collect(); + assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str())); +} + +#[test] +fn a_one_element_multi_range_request_is_the_single_range_request() { + // `range_formatting` is *defined* as this call, so the two can never + // drift — but the equality is what a client relies on, so it is + // asserted rather than argued. + for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] { + assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}"); + } +} + +#[test] +fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() { + // No partial output on either path (CLAUDE.md invariant #1), and the + // same message: both are one `format_selection` call away from the engine. + let broken = "module m;\n wire ;\nendmodule\n"; + let one = ranged(broken, at(0, 0, 0, 9)); + let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]); + assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways"); + assert_eq!(one, many, "byte-identical refusals, message included"); +} + +#[test] +fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() { + // Idempotency through the new path: format lines 2 and 4, then ask for + // exactly the same two ranges on the answer — nothing left to do. + let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)]; + let once = multi_text(FOUR, &ranges).expect("changed"); + assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say"); +} + +#[test] +fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() { + let clean = "module m;\n wire a;\n wire b;\nendmodule\n"; + assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None); +} + +#[test] +fn multi_byte_content_survives_a_multi_range_format_too() { + // The columns are UTF-16 units and only the lines reach the engine, so + // an emoji two lines up must not shift which items are laid out. + let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"; + let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed"); + assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"); + assert!(out.contains("é ✓ 🎉"), "comments are never dropped"); +} + +#[test] +fn the_line_conversion_is_the_one_rangeformatting_always_used() { + // Pinned directly, because both requests now share it: a cursor names + // its own line; an end at character 0 of a *later* line stops one line + // short; an end at character 0 on the start line does not. + assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor"); + assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines"); + assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line"); + assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line"); + assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer"); + // And it never produces a span `LineRanges` would refuse: line 0 is + // impossible (1-based), and `last` can never fall below `first`. + assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line"); + assert_eq!( + lines_of(at(u32::MAX, 0, u32::MAX, 0)), + (u32::MAX, u32::MAX), + "a saturating add, not an overflow" + ); +} + +#[test] +fn multi_byte_content_survives_formatting() { + let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n"); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped"); + // The replaced range must cover the whole document in UTF-16 terms. + assert_eq!(edit.range.end.line, 4); +} + +#[test] +fn selective_format_overrides_respect_toml_over_editor_over_style() { + let tree = + Tree::new("[format]\nstyle = \"google\"\nbegin = \"own-line\"\nconnection-align-min = 0\n"); + let (ws, uri) = tree.document( + "module m (input logic a, input logic b);\n always_comb if (a) begin x = 1; end\n sub #(.A(1), .LONGER(2)) u (.clk(clk), .data_in(d));\nendmodule\n", + ); + let client = ClientSettings { + style: Some("lucisv"), + format_begin: Some("same-line"), + format_alignment: Some("always"), + format_connection_align_min: Some(1), + ..Default::default() + }; + let resolved = settings_with(&ws, &uri, &client, &options(2, true)); + assert_eq!(resolved.config.style.name, "google"); + assert_eq!(resolved.config.style.begin, Placement::OwnLine); + assert_eq!(resolved.config.style.alignment, Alignment::Always); + assert_eq!(resolved.config.style.connection_align_min, 0); + + let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("ok").expect("edit"); + assert!(edit.new_text.contains(" if (a)\n begin\n"), "{}", edit.new_text); + assert!(edit.new_text.contains(" .LONGER(2)\n"), "{}", edit.new_text); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hierarchy.rs b/crates/lucisv_server/src/hierarchy.rs index ca91de2..0b3953b 100644 --- a/crates/lucisv_server/src/hierarchy.rs +++ b/crates/lucisv_server/src/hierarchy.rs @@ -343,787 +343,6 @@ fn key(range: Range) -> (u32, u32) { } #[cfg(test)] -mod tests { - use super::*; - use crate::uri::path_to_uri; - use std::fs; - use std::path::PathBuf; - - /// A scratch workspace root, removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_hierarchy_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - /// A workspace over `files`, with the first of them opened as a buffer. - fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { - let tree = Tree::new(name); - let mut first = None; - for (rel, text) in files { - let path = tree.write(rel, text); - if first.is_none() { - first = Some((path, *text)); - } - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let (path, text) = first.expect("at least one file"); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - (tree, ws, uri) - } - - /// The byte offset of the first occurrence of `needle`. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - /// An item as `(name, file name, selection line)`. - fn shape(item: &CallHierarchyItem) -> (String, String, u32) { - ( - item.name.clone(), - item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), - item.selection_range.start.line, - ) - } - - /// The lines every `fromRanges` entry starts on. - fn lines(ranges: &[Range]) -> Vec { - ranges.iter().map(|r| r.start.line).collect() - } - - const SUB: &str = "module sub (input logic clk);\nendmodule\n"; - const TOP: &str = "\ -module top; - sub u_a (.clk(1'b0)); - sub u_b (.clk(1'b1)); -endmodule -"; - const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; - - /// The three-file workspace of the cross-file tests, `top.sv` open. - fn three(name: &str) -> (Tree, Workspace, Uri) { - workspace(name, &[("top.sv", TOP), ("sub.sv", SUB), ("other.sv", OTHER)]) - } - - // ------------------------------------------------------------------ - // prepare - // ------------------------------------------------------------------ - - #[test] - fn the_cursor_on_a_declaration_prepares_that_module() { - let (_tree, ws, uri) = workspace("decl", &[("sub.sv", SUB)]); - let items = prepare(&ws, &uri, at(SUB, "sub")).expect("a module"); - assert_eq!(items.len(), 1); - assert_eq!(shape(&items[0]), ("sub".to_string(), "sub.sv".to_string(), 0)); - assert_eq!(items[0].kind, SymbolKind::MODULE); - assert_eq!(items[0].selection_range.start.character, 7, "the name, not the keyword"); - assert_eq!(items[0].range.start.character, 0, "the whole declaration"); - assert_eq!(items[0].range.end.line, 1, "through `endmodule`"); - } - - /// An interface is instantiated exactly as a module is, so the call - /// hierarchy still finds its declaration from an instantiation site - /// (`docs/features/interface-semantics/README.md`). - #[test] - fn the_cursor_on_an_interface_instantiation_prepares_the_interface() { - const IFACE: &str = "interface bus_if;\nendinterface\n"; - const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]); - let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface"); - assert_eq!(items.len(), 1); - assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0)); - } - - #[test] - fn the_cursor_on_an_instantiation_prepares_the_module_it_names() { - let (_tree, ws, uri) = three("inst"); - let items = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("a module"); - assert_eq!(items.len(), 1); - assert_eq!( - shape(&items[0]), - ("sub".to_string(), "sub.sv".to_string(), 0), - "the declaration in the other file, not the instantiation" - ); - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): the `module` - /// keyword and a connected expression are inside `top` and prepare it, - /// and an instance name stands for the instantiated module. Only a - /// position no module encloses still prepares nothing. - #[test] - fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() { - let (_tree, ws, uri) = three("none"); - let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0; - assert_eq!(name(0), "top", "the `module` keyword is inside `top`"); - assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module"); - assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`"); - let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]); - assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module"); - } - - #[test] - fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { - // Where a double-click and an end-of-word motion leave it. - let (_tree, ws, uri) = workspace("edge", &[("sub.sv", SUB)]); - assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some()); - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): no item for - /// `nope`, which nothing declares, but the module the cursor is inside. - #[test] - fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() { - let top = "module top;\n nope u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]); - let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module"); - assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0)); - } - - #[test] - fn a_module_two_files_declare_prepares_both_rather_than_guessing() { - let top = "module top;\n dup u1 ();\nendmodule\n"; - let dup = "module dup;\nendmodule\n"; - let (_tree, ws, uri) = workspace("dup", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); - let items = prepare(&ws, &uri, at(top, "dup")).expect("both"); - let names: Vec = items.iter().map(|i| shape(i).1).collect(); - assert_eq!(names, ["a.sv", "b.sv"], "every declaration, as definition does"); - } - - // ------------------------------------------------------------------ - // incoming - // ------------------------------------------------------------------ - - #[test] - fn incoming_calls_name_every_instantiating_module_once() { - let (_tree, ws, uri) = three("incoming"); - let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!( - calls.iter().map(|c| shape(&c.from)).collect::>(), - [ - ("other".to_string(), "other.sv".to_string(), 0), - ("top".to_string(), "top.sv".to_string(), 0), - ], - "one call per instantiating module, sorted by file" - ); - assert_eq!(lines(&calls[0].from_ranges), [1], "other.sv instantiates once"); - assert_eq!(lines(&calls[1].from_ranges), [1, 2], "top.sv twice, in one call"); - assert_eq!( - calls[1].from_ranges[0].start.character, 2, - "the range is the module name of the instantiation" - ); - assert_eq!(calls[1].from_ranges[0].end.character, 5); - } - - #[test] - fn a_module_nobody_instantiates_has_no_incoming_calls() { - let (_tree, ws, uri) = three("leaf"); - let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); - assert!(incoming(&ws, &root).is_empty(), "nothing instantiates the top"); - } - - #[test] - fn incoming_calls_reach_generate_regions_bind_and_instance_arrays() { - let top = "\ -module top; - generate - for (genvar i = 0; i < 4; i++) begin : g - sub u1 (.clk(1'b0)); - end - endgenerate - sub u2 [3:0] (.clk(1'b0)); - bind top sub u3 (.clk(1'b0)); -endmodule -"; - let (_tree, ws, uri) = workspace("shapes", &[("top.sv", top), ("sub.sv", SUB)]); - let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!(calls.len(), 1, "one caller: {calls:#?}"); - assert_eq!(lines(&calls[0].from_ranges), [3, 6, 7], "generate, array and bind"); - } - - #[test] - fn an_ordered_connection_list_is_found_like_any_other() { - // The walk matches the module *name*; how the ports are connected has - // nothing to do with it. - let top = "module top;\n sub u1 (clk);\nendmodule\n"; - let (_tree, ws, uri) = workspace("ordered", &[("top.sv", top), ("sub.sv", SUB)]); - let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!(calls.len(), 1); - assert_eq!(lines(&calls[0].from_ranges), [1]); - } - - #[test] - fn a_self_instantiating_module_is_its_own_caller_and_does_not_hang() { - let top = "module top;\n top u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("selfcall", &[("top.sv", top)]); - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!(calls.len(), 1); - assert_eq!(shape(&calls[0].from), ("top".to_string(), "top.sv".to_string(), 0)); - assert_eq!(lines(&calls[0].from_ranges), [1]); - // And the other direction of the same edge, one hop only. - let out = outgoing(&ws, &root); - assert_eq!(out.len(), 1); - assert_eq!(shape(&out[0].to), ("top".to_string(), "top.sv".to_string(), 0)); - } - - #[test] - fn a_module_instantiated_only_outside_the_index_scope_has_no_callers() { - // The scope ladder decides which files exist; a file the configured - // filelist omits is not searched, exactly as references are not. - let tree = Tree::new("scope"); - tree.write("sub.sv", SUB); - tree.write("top.sv", TOP); - tree.write("files.f", "sub.sv\n"); - tree.write("lucisv.toml", "filelist = \"files.f\"\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - - let root = prepare(&ws, &sub_uri, at(SUB, "sub")).expect("sub")[0].clone(); - assert!(incoming(&ws, &root).is_empty(), "top.sv is out of scope"); - } - - #[test] - fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() { - // Superseded this round (incremental-index, 2026-08-27): - // `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the - // census reading `Workspace::sources()` on every request, so a - // keystroke in *another* buffer moved the count before anything - // rebuilt. The census is the index's edge table now, and an index is - // only ever as of its last build or update — which does fold every - // open buffer in, so a save (or any other rescan trigger) makes the - // edit count. The rule the test pins is the new one, from both sides. - let (tree, mut ws, uri) = three("unsaved"); - let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); - assert_eq!(incoming(&ws, &root).len(), 2, "premise"); - - let fresh = tree.path.join("other.sv"); - let other_uri = path_to_uri(&fresh).expect("uri"); - ws.set_document(other_uri, "module other;\nendmodule\n".to_string()); - assert_eq!( - incoming(&ws, &root).len(), - 2, - "the buffer alone does not move the census — the index has not seen it" - ); - // What a save does, and what the incremental path does with it. - assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough"); - assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation"); - } - - // ------------------------------------------------------------------ - // outgoing - // ------------------------------------------------------------------ - - #[test] - fn outgoing_calls_name_every_distinct_instantiated_module_once() { - let top = "\ -module top; - sub u_a (.clk(1'b0)); - other_sub u_b (); - sub u_c (.clk(1'b1)); - nope u_d (); -endmodule -"; - let other_sub = "module other_sub;\nendmodule\n"; - let (_tree, ws, uri) = - workspace("outgoing", &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)]); - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - let calls = outgoing(&ws, &root); - assert_eq!( - calls.iter().map(|c| shape(&c.to)).collect::>(), - [ - ("sub".to_string(), "sub.sv".to_string(), 0), - ("other_sub".to_string(), "other_sub.sv".to_string(), 0), - ], - "distinct modules in source order; `nope` is declared nowhere and is skipped" - ); - assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, in one call"); - assert_eq!(lines(&calls[1].from_ranges), [2]); - } - - #[test] - fn an_ambiguous_target_is_skipped_rather_than_guessed() { - let top = "module top;\n dup u1 ();\nendmodule\n"; - let dup = "module dup;\nendmodule\n"; - let (_tree, ws, uri) = - workspace("outambig", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - assert!(outgoing(&ws, &root).is_empty(), "two `dup`s, so neither is claimed"); - } - - #[test] - fn outgoing_calls_reach_generate_regions_and_bind() { - let top = "\ -module top; - generate - if (1) begin : g - sub u1 (.clk(1'b0)); - end else begin - sub u2 (.clk(1'b1)); - end - endgenerate - bind top sub u3 (.clk(1'b0)); -endmodule -"; - let (_tree, ws, uri) = workspace("outshapes", &[("top.sv", top), ("sub.sv", SUB)]); - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - let calls = outgoing(&ws, &root); - assert_eq!(calls.len(), 1); - assert_eq!(lines(&calls[0].from_ranges), [3, 5, 8], "both arms and the bind"); - } - - #[test] - fn a_leaf_module_instantiates_nothing() { - let (_tree, ws, uri) = three("outleaf"); - let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); - assert!(outgoing(&ws, &root).is_empty()); - } - - #[test] - fn one_modules_calls_are_never_its_neighbours_in_the_same_file() { - // Two modules in one file. Each answers with its own instantiations, - // which means the item is matched by the name span `prepare` handed - // back and not by "the first module in the file". - let top = "\ -module top; - sub u1 (.clk(1'b0)); -endmodule - -module neighbour; - other_sub u2 (); -endmodule -"; - let other_sub = "module other_sub;\nendmodule\n"; - let (_tree, ws, uri) = workspace( - "neighbour", - &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)], - ); - let names = |item: &CallHierarchyItem| -> Vec { - outgoing(&ws, item).iter().map(|c| c.to.name.clone()).collect() - }; - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - assert_eq!(names(&root), ["sub"]); - let other = - prepare(&ws, &uri, at(top, "module neighbour") + 7).expect("neighbour")[0].clone(); - assert_eq!(names(&other), ["other_sub"]); - } - - #[test] - fn an_item_naming_a_file_that_is_gone_answers_with_no_calls() { - let (tree, ws, uri) = three("missing"); - let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); - assert_eq!(outgoing(&ws, &root).len(), 1, "premise"); - let mut stale = root.clone(); - stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); - assert!(outgoing(&ws, &stale).is_empty(), "no file, no calls, no panic"); - let mut renamed = root; - renamed.name = "no_such_module".to_string(); - assert!(outgoing(&ws, &renamed).is_empty(), "a name the file does not declare"); - } - - #[test] - fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { - let top = "module top; // é 🎉\n sub /* é */ u1 (.clk(1'b0));\nendmodule\n"; - let (_tree, ws, uri) = workspace("utf16", &[("top.sv", top), ("sub.sv", SUB)]); - let root = prepare(&ws, &uri, at(top, "sub /*")).expect("sub")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!(calls.len(), 1); - assert_eq!( - (calls[0].from_ranges[0].start.character, calls[0].from_ranges[0].end.character), - (2, 5), - "the `sub` of the instantiation, in UTF-16 units" - ); - } - - #[test] - fn a_nameless_item_reads_no_files_at_all() { - // A malformed item from a client: the prefilter matches every file for - // an empty name, so without the guard this would read and parse the - // whole workspace to find nothing. - let (_tree, ws, uri) = three("nameless"); - let mut nameless = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); - nameless.name = String::new(); - assert!(incoming(&ws, &nameless).is_empty()); - assert!(outgoing(&ws, &nameless).is_empty()); - } - - #[test] - fn an_unopened_document_prepares_nothing() { - let ws = Workspace::default(); - let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri"); - assert!(prepare(&ws, &uri, 0).is_none()); - } - - #[test] - fn an_untitled_buffer_prepares_from_itself() { - // No path, so no index entry — but the declaration is right there in - // the buffer, and its own hierarchy root is a fair answer. - use std::str::FromStr; - let text = "module scratch;\nendmodule\n"; - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own module"); - assert_eq!(items[0].name, "scratch"); - assert_eq!(items[0].uri, uri); - assert!(outgoing(&ws, &items[0]).is_empty(), "and it instantiates nothing"); - } - - #[test] - fn a_buffer_that_does_not_parse_invents_no_calls() { - // Whatever the tolerant parse recovered from an unclosed connection - // list, nothing may panic and no edge may be invented — the assertion - // is deliberately on survival, so a change in recovery is not a - // failure here. - let broken = "module top;\n sub u1 (\n"; - let (_tree, ws, uri) = workspace("broken", &[("top.sv", broken), ("sub.sv", SUB)]); - if let Some(items) = prepare(&ws, &uri, at(broken, "module top") + 7) { - for call in outgoing(&ws, &items[0]) { - assert_eq!(call.to.name, "sub", "only a module really written there"); - } - } - } - - // ------------------------------------------------------------------ - // QA (2026-08-25) — break-it fixtures not in the dev's own suite; see - // docs/features/hierarchy/README.md's QA log for the full findings - // ------------------------------------------------------------------ - - #[test] - fn qa_bind_owner_is_the_module_containing_the_directive_not_the_bind_target() { - // `bind top chk u_chk ();` written inside `module harness` in a THIRD - // file. If the owner were the bind's target (`top`) rather than the - // module the directive is textually inside, this would misattribute. - let top = "module top;\nendmodule\n"; - let chk = "module chk;\nendmodule\n"; - let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n"; - let (_tree, ws, uri) = workspace( - "qa_bind_elsewhere2", - &[("chk.sv", chk), ("top.sv", top), ("harness.sv", harness)], - ); - let root = prepare(&ws, &uri, at(chk, "chk")).expect("chk module")[0].clone(); - let calls = incoming(&ws, &root); - assert_eq!(calls.len(), 1, "one caller of chk: {calls:#?}"); - assert_eq!( - shape(&calls[0].from), - ("harness".to_string(), "harness.sv".to_string(), 0), - "owner is the module containing the `bind` directive, not `top`" - ); - } - - #[test] - fn qa_prefilter_over_admits_but_walk_rejects_a_comment_only_mention() { - // `widget` appears ONLY in a comment in b.sv. The substring prefilter - // will admit b.sv for parsing, but the walk must not report it as a - // caller since no real instantiation exists there. - let a = "module widget;\nendmodule\n"; - let b = "module b;\n // this file mentions widget only in a comment\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_prefilter", &[("a.sv", a), ("b.sv", b)]); - let root = prepare(&ws, &uri, at(a, "widget")).expect("widget")[0].clone(); - let calls = incoming(&ws, &root); - assert!(calls.is_empty(), "comment-only mention must not be a caller: {calls:#?}"); - } - - #[test] - fn qa_instantiation_in_a_package_does_not_crash() { - // Illegal-ish SystemVerilog (a package body instantiating a module), - // reachable through the tolerant parser. Must not panic. - let text = "package p;\n sub u1 ();\nendpackage\nmodule sub;\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_pkg_inst", &[("p.sv", text)]); - let root = prepare(&ws, &uri, at(text, "module sub") + 7).expect("sub")[0].clone(); - let _ = incoming(&ws, &root); - // No assertion on the exact answer — the assertion is on survival. - } - - #[test] - fn qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme() { - // The parser does not evaluate `ifdef`/`else`: both arms become - // ordinary `Instantiation` items in source order (confirmed against - // `vlog_parser::parser::parse_item_kind`). So `outgoing(top)` reports - // BOTH `sub_a` and `sub_b`, even though only one is ever really built. - // Unlike `inlay.rs` (which treats an `ifdef`-carrying list as an - // uncertainty and stays silent, see docs/features/inlay-hints — - // "ifdef" QA finding), this feature's README documents no `ifdef` - // policy at all. The answer is arguably the honest one — lucisv cannot - // know which arm is live, and showing both is not a *wrong* single - // claim the way a mis-ordered port hint would be — but it should be - // stated as an Assumption rather than left silent. See QA log. - let text = "\ -module top; -`ifdef CFG_A - sub_a u1 (); -`else - sub_b u1 (); -`endif -endmodule -"; - let sub_a = "module sub_a;\nendmodule\n"; - let sub_b = "module sub_b;\nendmodule\n"; - let (_tree, ws, uri) = - workspace("qa_ifdef", &[("top.sv", text), ("sub_a.sv", sub_a), ("sub_b.sv", sub_b)]); - let root = prepare(&ws, &uri, at(text, "module top") + 7).expect("top")[0].clone(); - let calls = outgoing(&ws, &root); - let names: Vec = calls.iter().map(|c| c.to.name.clone()).collect(); - assert_eq!(names, ["sub_a", "sub_b"], "both `ifdef` arms end up as real calls: {calls:#?}"); - } - - #[test] - fn qa_outgoing_ambiguous_does_not_leak_fromranges_into_resolved_entries() { - let top = "\ -module top; - sub u1 (); - dup u2 (); - sub u3 (); -endmodule -"; - let sub = "module sub;\nendmodule\n"; - let dup = "module dup;\nendmodule\n"; - let (_tree, ws, uri) = workspace( - "qa_no_leak", - &[("top.sv", top), ("sub.sv", sub), ("a.sv", dup), ("b.sv", dup)], - ); - let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); - let calls = outgoing(&ws, &root); - eprintln!("QA no-leak outgoing calls: {calls:#?}"); - assert_eq!(calls.len(), 1, "only `sub` resolves; `dup` is skipped: {calls:#?}"); - assert_eq!(calls[0].to.name, "sub"); - assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, dup's line 2 absent"); - } - - #[test] - fn qa_outgoing_nested_module_declaration_boundary() { - // The dev's pinned fixture shape from instantiations.rs, driven - // through the public API: a nested `module` the parser recovers as a - // sibling. `outer`'s outgoing calls must not include `sub`, which - // belongs to `inner`. - let text = "\ -module outer; - module inner; - sub u1 (); - endmodule -endmodule -"; - let sub = "module sub;\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_nested", &[("text.sv", text), ("sub.sv", sub)]); - let outer = prepare(&ws, &uri, at(text, "module outer") + 7).expect("outer")[0].clone(); - let inner = prepare(&ws, &uri, at(text, "module inner") + 7).expect("inner")[0].clone(); - let outer_calls = outgoing(&ws, &outer); - let inner_calls = outgoing(&ws, &inner); - assert!(outer_calls.is_empty(), "`sub` belongs to `inner`, not `outer`: {outer_calls:#?}"); - assert_eq!(inner_calls.len(), 1, "inner claims `sub`: {inner_calls:#?}"); - assert_eq!(inner_calls[0].to.name, "sub"); - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a - /// string inside `top` prepares `top` — never the `sub` its text spells. - #[test] - fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() { - let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]); - let comment_offset = at(text, "// sub"); - let string_offset = at(text, "\"sub\"") + 1; - let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0; - assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment"); - assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal"); - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target - /// is still not read as a module name, but the cursor is inside the - /// module the `bind` is written in, and that is what it prepares. The - /// fixture moves the `bind` into `harness` so the two cannot coincide. - #[test] - fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() { - let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n"; - let top = "module top;\nendmodule\n"; - let chk = "module chk;\nendmodule\n"; - let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)]; - let (_tree, ws, uri) = workspace("qa_bind_target2", &files); - let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module"); - assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`"); - } - - /// The M11 QA pin, kept for its history: the answer it pinned is the - /// enclosing module now, which in this fixture is `top` itself. - #[test] - fn qa_prepare_on_a_bind_target_module_name_was_null() { - // `bind top chk u_chk ();` — cursor on `top`, the bind's *target* - // module. `top` is a real, declared module and a genuine reference to - // it, but neither `declarations()` (which only sees `module ...` - // headers) nor `sites()` (whose span for a bind is `chk`'s, the - // instantiated module) covers this text, so `prepare` answers `null`. - // That fails safe rather than corrupting anything, but it is a - // completeness gap: undocumented and untested by the dev, and a user - // right-clicking the bind target gets no hierarchy where one plainly - // exists. See QA log. - let top = "module top;\n bind top chk u_chk ();\nendmodule\n"; - let chk = "module chk;\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]); - let target_offset = at(top, "bind top") + 5; - let items = prepare(&ws, &uri, target_offset).expect("the enclosing module"); - assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in"); - } - - #[test] - fn qa_cycle_a_to_b_to_a_two_hops_no_hang() { - let a = "module a;\n b u1 ();\nendmodule\n"; - let b = "module b;\n a u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_cycle", &[("a.sv", a), ("b.sv", b)]); - let root_a = prepare(&ws, &uri, at(a, "module a") + 7).expect("a")[0].clone(); - let out_a = outgoing(&ws, &root_a); - assert_eq!(out_a.len(), 1, "a -> b: {out_a:#?}"); - assert_eq!(out_a[0].to.name, "b"); - let hop2 = out_a[0].to.clone(); - let out_b = outgoing(&ws, &hop2); - assert_eq!(out_b.len(), 1, "b -> a: {out_b:#?}"); - assert_eq!(out_b[0].to.name, "a"); - // And incoming mirrors it. - let in_b = incoming(&ws, &hop2); - assert_eq!(in_b.len(), 1, "b's only caller is a: {in_b:#?}"); - assert_eq!(in_b[0].from.name, "a"); - } - - #[test] - fn qa_consistency_incoming_x_matches_outgoing_parent_of_x() { - let (_tree, ws, uri) = three("qa_consistency"); - let sub_root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); - let incoming_calls = incoming(&ws, &sub_root); - for call in &incoming_calls { - let parent_calls = outgoing(&ws, &call.from); - let matching = parent_calls.iter().find(|c| c.to.name == "sub"); - let matching = matching.unwrap_or_else(|| { - panic!( - "outgoing({}) has no `sub` entry, but incoming(sub) has one from it", - call.from.name - ) - }); - let mut incoming_ranges: Vec<(u32, u32)> = - call.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); - let mut outgoing_ranges: Vec<(u32, u32)> = - matching.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); - incoming_ranges.sort(); - outgoing_ranges.sort(); - assert_eq!( - incoming_ranges, outgoing_ranges, - "incoming(sub) from {} disagrees with outgoing({}) on fromRanges", - call.from.name, call.from.name - ); - } - assert_eq!(incoming_calls.len(), 2, "premise: two callers (top, other)"); - } - - #[test] - #[ignore] - fn qa_perf_worst_case_common_word_module_name() { - // A single-letter module name used to be the worst case there was: it - // is a substring of nearly every file, so the prefilter over - // `Workspace::sources()` admitted nearly everything. There is no - // prefilter and no walk since 2026-08-27 — the census is a lookup in - // the index's edge table, and a name nothing instantiates is an empty - // slice — so this probe is kept for what it now measures: that the - // shape which used to be the worst case is not a case at all. - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let item = CallHierarchyItem { - name: "d".to_string(), - kind: SymbolKind::MODULE, - tags: None, - detail: None, - uri: path_to_uri(&std::path::PathBuf::from("/dev/null")).expect("uri"), - range: Range::default(), - selection_range: Range::default(), - data: None, - }; - let started = std::time::Instant::now(); - let calls = incoming(&ws, &item); - let elapsed = started.elapsed(); - eprintln!( - "QA worst-case prefilter ('d' as module name): {} files, {} calls, {:?}", - ws.index().files().len(), - calls.len(), - elapsed - ); - } - - // ------------------------------------------------------------------ - // the performance claim, measured - // ------------------------------------------------------------------ - - /// What "who instantiates this?" costs over the real corpus, for a module - /// instantiated all over it. Skipped when `corpus/` is not checked out - /// (`tools/corpus_fetch.sh`), like the other corpus tests. - /// - /// The budget is deliberately loose — a debug build on a loaded machine is - /// the worst case this ever runs in — and exists to catch an order-of- - /// magnitude regression, not to pin a number. The numbers themselves are - /// in `docs/features/hierarchy/README.md`. - #[test] - fn incoming_calls_over_the_whole_corpus_stay_in_budget() { - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let declaring = - corpus.join("ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_flop_2sync.sv"); - let Ok(text) = fs::read_to_string(&declaring) else { - eprintln!("prim_flop_2sync.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&declaring).expect("uri"); - ws.set_document(uri.clone(), text.clone()); - let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7) - .expect("the declaration")[0] - .clone(); - - // Warm, then the worst of three. - let _ = incoming(&ws, &root); - let mut worst = std::time::Duration::ZERO; - let mut callers = 0; - for _ in 0..3 { - let started = std::time::Instant::now(); - let calls = incoming(&ws, &root); - worst = worst.max(started.elapsed()); - callers = calls.len(); - } - eprintln!( - "corpus: {} files, incomingCalls for prim_flop_2sync: {callers} callers, worst {worst:?}", - ws.index().files().len(), - ); - assert!(callers > 5, "the corpus really does instantiate it: {callers}"); - assert!(worst < std::time::Duration::from_millis(1500), "incomingCalls cost {worst:?}"); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hierarchy/tests.rs b/crates/lucisv_server/src/hierarchy/tests.rs new file mode 100644 index 0000000..b1cfaee --- /dev/null +++ b/crates/lucisv_server/src/hierarchy/tests.rs @@ -0,0 +1,777 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use std::fs; +use std::path::PathBuf; + +/// A scratch workspace root, removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_hierarchy_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +/// A workspace over `files`, with the first of them opened as a buffer. +fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + let mut first = None; + for (rel, text) in files { + let path = tree.write(rel, text); + if first.is_none() { + first = Some((path, *text)); + } + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let (path, text) = first.expect("at least one file"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + (tree, ws, uri) +} + +/// The byte offset of the first occurrence of `needle`. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// An item as `(name, file name, selection line)`. +fn shape(item: &CallHierarchyItem) -> (String, String, u32) { + ( + item.name.clone(), + item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + item.selection_range.start.line, + ) +} + +/// The lines every `fromRanges` entry starts on. +fn lines(ranges: &[Range]) -> Vec { + ranges.iter().map(|r| r.start.line).collect() +} + +const SUB: &str = "module sub (input logic clk);\nendmodule\n"; +const TOP: &str = "\ +module top; + sub u_a (.clk(1'b0)); + sub u_b (.clk(1'b1)); +endmodule +"; +const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + +/// The three-file workspace of the cross-file tests, `top.sv` open. +fn three(name: &str) -> (Tree, Workspace, Uri) { + workspace(name, &[("top.sv", TOP), ("sub.sv", SUB), ("other.sv", OTHER)]) +} + +// ------------------------------------------------------------------ +// prepare +// ------------------------------------------------------------------ + +#[test] +fn the_cursor_on_a_declaration_prepares_that_module() { + let (_tree, ws, uri) = workspace("decl", &[("sub.sv", SUB)]); + let items = prepare(&ws, &uri, at(SUB, "sub")).expect("a module"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]), ("sub".to_string(), "sub.sv".to_string(), 0)); + assert_eq!(items[0].kind, SymbolKind::MODULE); + assert_eq!(items[0].selection_range.start.character, 7, "the name, not the keyword"); + assert_eq!(items[0].range.start.character, 0, "the whole declaration"); + assert_eq!(items[0].range.end.line, 1, "through `endmodule`"); +} + +/// An interface is instantiated exactly as a module is, so the call +/// hierarchy still finds its declaration from an instantiation site +/// (`docs/features/interface-semantics/README.md`). +#[test] +fn the_cursor_on_an_interface_instantiation_prepares_the_interface() { + const IFACE: &str = "interface bus_if;\nendinterface\n"; + const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]); + let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0)); +} + +#[test] +fn the_cursor_on_an_instantiation_prepares_the_module_it_names() { + let (_tree, ws, uri) = three("inst"); + let items = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("a module"); + assert_eq!(items.len(), 1); + assert_eq!( + shape(&items[0]), + ("sub".to_string(), "sub.sv".to_string(), 0), + "the declaration in the other file, not the instantiation" + ); +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): the `module` +/// keyword and a connected expression are inside `top` and prepare it, +/// and an instance name stands for the instantiated module. Only a +/// position no module encloses still prepares nothing. +#[test] +fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() { + let (_tree, ws, uri) = three("none"); + let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0; + assert_eq!(name(0), "top", "the `module` keyword is inside `top`"); + assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module"); + assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`"); + let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]); + assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module"); +} + +#[test] +fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { + // Where a double-click and an end-of-word motion leave it. + let (_tree, ws, uri) = workspace("edge", &[("sub.sv", SUB)]); + assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some()); +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): no item for +/// `nope`, which nothing declares, but the module the cursor is inside. +#[test] +fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() { + let top = "module top;\n nope u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]); + let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module"); + assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0)); +} + +#[test] +fn a_module_two_files_declare_prepares_both_rather_than_guessing() { + let top = "module top;\n dup u1 ();\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = workspace("dup", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); + let items = prepare(&ws, &uri, at(top, "dup")).expect("both"); + let names: Vec = items.iter().map(|i| shape(i).1).collect(); + assert_eq!(names, ["a.sv", "b.sv"], "every declaration, as definition does"); +} + +// ------------------------------------------------------------------ +// incoming +// ------------------------------------------------------------------ + +#[test] +fn incoming_calls_name_every_instantiating_module_once() { + let (_tree, ws, uri) = three("incoming"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!( + calls.iter().map(|c| shape(&c.from)).collect::>(), + [ + ("other".to_string(), "other.sv".to_string(), 0), + ("top".to_string(), "top.sv".to_string(), 0), + ], + "one call per instantiating module, sorted by file" + ); + assert_eq!(lines(&calls[0].from_ranges), [1], "other.sv instantiates once"); + assert_eq!(lines(&calls[1].from_ranges), [1, 2], "top.sv twice, in one call"); + assert_eq!( + calls[1].from_ranges[0].start.character, 2, + "the range is the module name of the instantiation" + ); + assert_eq!(calls[1].from_ranges[0].end.character, 5); +} + +#[test] +fn a_module_nobody_instantiates_has_no_incoming_calls() { + let (_tree, ws, uri) = three("leaf"); + let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); + assert!(incoming(&ws, &root).is_empty(), "nothing instantiates the top"); +} + +#[test] +fn incoming_calls_reach_generate_regions_bind_and_instance_arrays() { + let top = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (.clk(1'b0)); + end + endgenerate + sub u2 [3:0] (.clk(1'b0)); + bind top sub u3 (.clk(1'b0)); +endmodule +"; + let (_tree, ws, uri) = workspace("shapes", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1, "one caller: {calls:#?}"); + assert_eq!(lines(&calls[0].from_ranges), [3, 6, 7], "generate, array and bind"); +} + +#[test] +fn an_ordered_connection_list_is_found_like_any_other() { + // The walk matches the module *name*; how the ports are connected has + // nothing to do with it. + let top = "module top;\n sub u1 (clk);\nendmodule\n"; + let (_tree, ws, uri) = workspace("ordered", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub u1")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(lines(&calls[0].from_ranges), [1]); +} + +#[test] +fn a_self_instantiating_module_is_its_own_caller_and_does_not_hang() { + let top = "module top;\n top u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("selfcall", &[("top.sv", top)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(shape(&calls[0].from), ("top".to_string(), "top.sv".to_string(), 0)); + assert_eq!(lines(&calls[0].from_ranges), [1]); + // And the other direction of the same edge, one hop only. + let out = outgoing(&ws, &root); + assert_eq!(out.len(), 1); + assert_eq!(shape(&out[0].to), ("top".to_string(), "top.sv".to_string(), 0)); +} + +#[test] +fn a_module_instantiated_only_outside_the_index_scope_has_no_callers() { + // The scope ladder decides which files exist; a file the configured + // filelist omits is not searched, exactly as references are not. + let tree = Tree::new("scope"); + tree.write("sub.sv", SUB); + tree.write("top.sv", TOP); + tree.write("files.f", "sub.sv\n"); + tree.write("lucisv.toml", "filelist = \"files.f\"\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let root = prepare(&ws, &sub_uri, at(SUB, "sub")).expect("sub")[0].clone(); + assert!(incoming(&ws, &root).is_empty(), "top.sv is out of scope"); +} + +#[test] +fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() { + // Superseded this round (incremental-index, 2026-08-27): + // `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the + // census reading `Workspace::sources()` on every request, so a + // keystroke in *another* buffer moved the count before anything + // rebuilt. The census is the index's edge table now, and an index is + // only ever as of its last build or update — which does fold every + // open buffer in, so a save (or any other rescan trigger) makes the + // edit count. The rule the test pins is the new one, from both sides. + let (tree, mut ws, uri) = three("unsaved"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + assert_eq!(incoming(&ws, &root).len(), 2, "premise"); + + let fresh = tree.path.join("other.sv"); + let other_uri = path_to_uri(&fresh).expect("uri"); + ws.set_document(other_uri, "module other;\nendmodule\n".to_string()); + assert_eq!( + incoming(&ws, &root).len(), + 2, + "the buffer alone does not move the census — the index has not seen it" + ); + // What a save does, and what the incremental path does with it. + assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough"); + assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation"); +} + +// ------------------------------------------------------------------ +// outgoing +// ------------------------------------------------------------------ + +#[test] +fn outgoing_calls_name_every_distinct_instantiated_module_once() { + let top = "\ +module top; + sub u_a (.clk(1'b0)); + other_sub u_b (); + sub u_c (.clk(1'b1)); + nope u_d (); +endmodule +"; + let other_sub = "module other_sub;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("outgoing", &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + assert_eq!( + calls.iter().map(|c| shape(&c.to)).collect::>(), + [ + ("sub".to_string(), "sub.sv".to_string(), 0), + ("other_sub".to_string(), "other_sub.sv".to_string(), 0), + ], + "distinct modules in source order; `nope` is declared nowhere and is skipped" + ); + assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, in one call"); + assert_eq!(lines(&calls[1].from_ranges), [2]); +} + +#[test] +fn an_ambiguous_target_is_skipped_rather_than_guessed() { + let top = "module top;\n dup u1 ();\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = workspace("outambig", &[("top.sv", top), ("a.sv", dup), ("b.sv", dup)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + assert!(outgoing(&ws, &root).is_empty(), "two `dup`s, so neither is claimed"); +} + +#[test] +fn outgoing_calls_reach_generate_regions_and_bind() { + let top = "\ +module top; + generate + if (1) begin : g + sub u1 (.clk(1'b0)); + end else begin + sub u2 (.clk(1'b1)); + end + endgenerate + bind top sub u3 (.clk(1'b0)); +endmodule +"; + let (_tree, ws, uri) = workspace("outshapes", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!(lines(&calls[0].from_ranges), [3, 5, 8], "both arms and the bind"); +} + +#[test] +fn a_leaf_module_instantiates_nothing() { + let (_tree, ws, uri) = three("outleaf"); + let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + assert!(outgoing(&ws, &root).is_empty()); +} + +#[test] +fn one_modules_calls_are_never_its_neighbours_in_the_same_file() { + // Two modules in one file. Each answers with its own instantiations, + // which means the item is matched by the name span `prepare` handed + // back and not by "the first module in the file". + let top = "\ +module top; + sub u1 (.clk(1'b0)); +endmodule + +module neighbour; + other_sub u2 (); +endmodule +"; + let other_sub = "module other_sub;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("neighbour", &[("top.sv", top), ("sub.sv", SUB), ("other_sub.sv", other_sub)]); + let names = |item: &CallHierarchyItem| -> Vec { + outgoing(&ws, item).iter().map(|c| c.to.name.clone()).collect() + }; + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + assert_eq!(names(&root), ["sub"]); + let other = prepare(&ws, &uri, at(top, "module neighbour") + 7).expect("neighbour")[0].clone(); + assert_eq!(names(&other), ["other_sub"]); +} + +#[test] +fn an_item_naming_a_file_that_is_gone_answers_with_no_calls() { + let (tree, ws, uri) = three("missing"); + let root = prepare(&ws, &uri, at(TOP, "module top") + 7).expect("top")[0].clone(); + assert_eq!(outgoing(&ws, &root).len(), 1, "premise"); + let mut stale = root.clone(); + stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); + assert!(outgoing(&ws, &stale).is_empty(), "no file, no calls, no panic"); + let mut renamed = root; + renamed.name = "no_such_module".to_string(); + assert!(outgoing(&ws, &renamed).is_empty(), "a name the file does not declare"); +} + +#[test] +fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { + let top = "module top; // é 🎉\n sub /* é */ u1 (.clk(1'b0));\nendmodule\n"; + let (_tree, ws, uri) = workspace("utf16", &[("top.sv", top), ("sub.sv", SUB)]); + let root = prepare(&ws, &uri, at(top, "sub /*")).expect("sub")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1); + assert_eq!( + (calls[0].from_ranges[0].start.character, calls[0].from_ranges[0].end.character), + (2, 5), + "the `sub` of the instantiation, in UTF-16 units" + ); +} + +#[test] +fn a_nameless_item_reads_no_files_at_all() { + // A malformed item from a client: the prefilter matches every file for + // an empty name, so without the guard this would read and parse the + // whole workspace to find nothing. + let (_tree, ws, uri) = three("nameless"); + let mut nameless = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + nameless.name = String::new(); + assert!(incoming(&ws, &nameless).is_empty()); + assert!(outgoing(&ws, &nameless).is_empty()); +} + +#[test] +fn an_unopened_document_prepares_nothing() { + let ws = Workspace::default(); + let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri"); + assert!(prepare(&ws, &uri, 0).is_none()); +} + +#[test] +fn an_untitled_buffer_prepares_from_itself() { + // No path, so no index entry — but the declaration is right there in + // the buffer, and its own hierarchy root is a fair answer. + use std::str::FromStr; + let text = "module scratch;\nendmodule\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own module"); + assert_eq!(items[0].name, "scratch"); + assert_eq!(items[0].uri, uri); + assert!(outgoing(&ws, &items[0]).is_empty(), "and it instantiates nothing"); +} + +#[test] +fn a_buffer_that_does_not_parse_invents_no_calls() { + // Whatever the tolerant parse recovered from an unclosed connection + // list, nothing may panic and no edge may be invented — the assertion + // is deliberately on survival, so a change in recovery is not a + // failure here. + let broken = "module top;\n sub u1 (\n"; + let (_tree, ws, uri) = workspace("broken", &[("top.sv", broken), ("sub.sv", SUB)]); + if let Some(items) = prepare(&ws, &uri, at(broken, "module top") + 7) { + for call in outgoing(&ws, &items[0]) { + assert_eq!(call.to.name, "sub", "only a module really written there"); + } + } +} + +// ------------------------------------------------------------------ +// QA (2026-08-25) — break-it fixtures not in the dev's own suite; see +// docs/features/hierarchy/README.md's QA log for the full findings +// ------------------------------------------------------------------ + +#[test] +fn qa_bind_owner_is_the_module_containing_the_directive_not_the_bind_target() { + // `bind top chk u_chk ();` written inside `module harness` in a THIRD + // file. If the owner were the bind's target (`top`) rather than the + // module the directive is textually inside, this would misattribute. + let top = "module top;\nendmodule\n"; + let chk = "module chk;\nendmodule\n"; + let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n"; + let (_tree, ws, uri) = workspace( + "qa_bind_elsewhere2", + &[("chk.sv", chk), ("top.sv", top), ("harness.sv", harness)], + ); + let root = prepare(&ws, &uri, at(chk, "chk")).expect("chk module")[0].clone(); + let calls = incoming(&ws, &root); + assert_eq!(calls.len(), 1, "one caller of chk: {calls:#?}"); + assert_eq!( + shape(&calls[0].from), + ("harness".to_string(), "harness.sv".to_string(), 0), + "owner is the module containing the `bind` directive, not `top`" + ); +} + +#[test] +fn qa_prefilter_over_admits_but_walk_rejects_a_comment_only_mention() { + // `widget` appears ONLY in a comment in b.sv. The substring prefilter + // will admit b.sv for parsing, but the walk must not report it as a + // caller since no real instantiation exists there. + let a = "module widget;\nendmodule\n"; + let b = "module b;\n // this file mentions widget only in a comment\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_prefilter", &[("a.sv", a), ("b.sv", b)]); + let root = prepare(&ws, &uri, at(a, "widget")).expect("widget")[0].clone(); + let calls = incoming(&ws, &root); + assert!(calls.is_empty(), "comment-only mention must not be a caller: {calls:#?}"); +} + +#[test] +fn qa_instantiation_in_a_package_does_not_crash() { + // Illegal-ish SystemVerilog (a package body instantiating a module), + // reachable through the tolerant parser. Must not panic. + let text = "package p;\n sub u1 ();\nendpackage\nmodule sub;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_pkg_inst", &[("p.sv", text)]); + let root = prepare(&ws, &uri, at(text, "module sub") + 7).expect("sub")[0].clone(); + let _ = incoming(&ws, &root); + // No assertion on the exact answer — the assertion is on survival. +} + +#[test] +fn qa_ifdef_instantiation_both_arms_are_reported_undisclosed_in_the_readme() { + // The parser does not evaluate `ifdef`/`else`: both arms become + // ordinary `Instantiation` items in source order (confirmed against + // `vlog_parser::parser::parse_item_kind`). So `outgoing(top)` reports + // BOTH `sub_a` and `sub_b`, even though only one is ever really built. + // Unlike `inlay.rs` (which treats an `ifdef`-carrying list as an + // uncertainty and stays silent, see docs/features/inlay-hints — + // "ifdef" QA finding), this feature's README documents no `ifdef` + // policy at all. The answer is arguably the honest one — lucisv cannot + // know which arm is live, and showing both is not a *wrong* single + // claim the way a mis-ordered port hint would be — but it should be + // stated as an Assumption rather than left silent. See QA log. + let text = "\ +module top; +`ifdef CFG_A + sub_a u1 (); +`else + sub_b u1 (); +`endif +endmodule +"; + let sub_a = "module sub_a;\nendmodule\n"; + let sub_b = "module sub_b;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("qa_ifdef", &[("top.sv", text), ("sub_a.sv", sub_a), ("sub_b.sv", sub_b)]); + let root = prepare(&ws, &uri, at(text, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + let names: Vec = calls.iter().map(|c| c.to.name.clone()).collect(); + assert_eq!(names, ["sub_a", "sub_b"], "both `ifdef` arms end up as real calls: {calls:#?}"); +} + +#[test] +fn qa_outgoing_ambiguous_does_not_leak_fromranges_into_resolved_entries() { + let top = "\ +module top; + sub u1 (); + dup u2 (); + sub u3 (); +endmodule +"; + let sub = "module sub;\nendmodule\n"; + let dup = "module dup;\nendmodule\n"; + let (_tree, ws, uri) = + workspace("qa_no_leak", &[("top.sv", top), ("sub.sv", sub), ("a.sv", dup), ("b.sv", dup)]); + let root = prepare(&ws, &uri, at(top, "module top") + 7).expect("top")[0].clone(); + let calls = outgoing(&ws, &root); + eprintln!("QA no-leak outgoing calls: {calls:#?}"); + assert_eq!(calls.len(), 1, "only `sub` resolves; `dup` is skipped: {calls:#?}"); + assert_eq!(calls[0].to.name, "sub"); + assert_eq!(lines(&calls[0].from_ranges), [1, 3], "both `sub` sites, dup's line 2 absent"); +} + +#[test] +fn qa_outgoing_nested_module_declaration_boundary() { + // The dev's pinned fixture shape from instantiations.rs, driven + // through the public API: a nested `module` the parser recovers as a + // sibling. `outer`'s outgoing calls must not include `sub`, which + // belongs to `inner`. + let text = "\ +module outer; + module inner; + sub u1 (); + endmodule +endmodule +"; + let sub = "module sub;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_nested", &[("text.sv", text), ("sub.sv", sub)]); + let outer = prepare(&ws, &uri, at(text, "module outer") + 7).expect("outer")[0].clone(); + let inner = prepare(&ws, &uri, at(text, "module inner") + 7).expect("inner")[0].clone(); + let outer_calls = outgoing(&ws, &outer); + let inner_calls = outgoing(&ws, &inner); + assert!(outer_calls.is_empty(), "`sub` belongs to `inner`, not `outer`: {outer_calls:#?}"); + assert_eq!(inner_calls.len(), 1, "inner claims `sub`: {inner_calls:#?}"); + assert_eq!(inner_calls[0].to.name, "sub"); +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a +/// string inside `top` prepares `top` — never the `sub` its text spells. +#[test] +fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() { + let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]); + let comment_offset = at(text, "// sub"); + let string_offset = at(text, "\"sub\"") + 1; + let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0; + assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment"); + assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal"); +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target +/// is still not read as a module name, but the cursor is inside the +/// module the `bind` is written in, and that is what it prepares. The +/// fixture moves the `bind` into `harness` so the two cannot coincide. +#[test] +fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() { + let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n"; + let top = "module top;\nendmodule\n"; + let chk = "module chk;\nendmodule\n"; + let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)]; + let (_tree, ws, uri) = workspace("qa_bind_target2", &files); + let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module"); + assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`"); +} + +/// The M11 QA pin, kept for its history: the answer it pinned is the +/// enclosing module now, which in this fixture is `top` itself. +#[test] +fn qa_prepare_on_a_bind_target_module_name_was_null() { + // `bind top chk u_chk ();` — cursor on `top`, the bind's *target* + // module. `top` is a real, declared module and a genuine reference to + // it, but neither `declarations()` (which only sees `module ...` + // headers) nor `sites()` (whose span for a bind is `chk`'s, the + // instantiated module) covers this text, so `prepare` answers `null`. + // That fails safe rather than corrupting anything, but it is a + // completeness gap: undocumented and untested by the dev, and a user + // right-clicking the bind target gets no hierarchy where one plainly + // exists. See QA log. + let top = "module top;\n bind top chk u_chk ();\nendmodule\n"; + let chk = "module chk;\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]); + let target_offset = at(top, "bind top") + 5; + let items = prepare(&ws, &uri, target_offset).expect("the enclosing module"); + assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in"); +} + +#[test] +fn qa_cycle_a_to_b_to_a_two_hops_no_hang() { + let a = "module a;\n b u1 ();\nendmodule\n"; + let b = "module b;\n a u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_cycle", &[("a.sv", a), ("b.sv", b)]); + let root_a = prepare(&ws, &uri, at(a, "module a") + 7).expect("a")[0].clone(); + let out_a = outgoing(&ws, &root_a); + assert_eq!(out_a.len(), 1, "a -> b: {out_a:#?}"); + assert_eq!(out_a[0].to.name, "b"); + let hop2 = out_a[0].to.clone(); + let out_b = outgoing(&ws, &hop2); + assert_eq!(out_b.len(), 1, "b -> a: {out_b:#?}"); + assert_eq!(out_b[0].to.name, "a"); + // And incoming mirrors it. + let in_b = incoming(&ws, &hop2); + assert_eq!(in_b.len(), 1, "b's only caller is a: {in_b:#?}"); + assert_eq!(in_b[0].from.name, "a"); +} + +#[test] +fn qa_consistency_incoming_x_matches_outgoing_parent_of_x() { + let (_tree, ws, uri) = three("qa_consistency"); + let sub_root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone(); + let incoming_calls = incoming(&ws, &sub_root); + for call in &incoming_calls { + let parent_calls = outgoing(&ws, &call.from); + let matching = parent_calls.iter().find(|c| c.to.name == "sub"); + let matching = matching.unwrap_or_else(|| { + panic!( + "outgoing({}) has no `sub` entry, but incoming(sub) has one from it", + call.from.name + ) + }); + let mut incoming_ranges: Vec<(u32, u32)> = + call.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); + let mut outgoing_ranges: Vec<(u32, u32)> = + matching.from_ranges.iter().map(|r| (r.start.line, r.start.character)).collect(); + incoming_ranges.sort(); + outgoing_ranges.sort(); + assert_eq!( + incoming_ranges, outgoing_ranges, + "incoming(sub) from {} disagrees with outgoing({}) on fromRanges", + call.from.name, call.from.name + ); + } + assert_eq!(incoming_calls.len(), 2, "premise: two callers (top, other)"); +} + +#[test] +#[ignore = "perf measurement over corpus/, printed not asserted; run with --ignored --nocapture"] +fn qa_perf_worst_case_common_word_module_name() { + // A single-letter module name used to be the worst case there was: it + // is a substring of nearly every file, so the prefilter over + // `Workspace::sources()` admitted nearly everything. There is no + // prefilter and no walk since 2026-08-27 — the census is a lookup in + // the index's edge table, and a name nothing instantiates is an empty + // slice — so this probe is kept for what it now measures: that the + // shape which used to be the worst case is not a case at all. + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let item = CallHierarchyItem { + name: "d".to_string(), + kind: SymbolKind::MODULE, + tags: None, + detail: None, + uri: path_to_uri(&std::path::PathBuf::from("/dev/null")).expect("uri"), + range: Range::default(), + selection_range: Range::default(), + data: None, + }; + let started = std::time::Instant::now(); + let calls = incoming(&ws, &item); + let elapsed = started.elapsed(); + eprintln!( + "QA worst-case prefilter ('d' as module name): {} files, {} calls, {:?}", + ws.index().files().len(), + calls.len(), + elapsed + ); +} + +// ------------------------------------------------------------------ +// the performance claim, measured +// ------------------------------------------------------------------ + +/// What "who instantiates this?" costs over the real corpus, for a module +/// instantiated all over it. Skipped when `corpus/` is not checked out +/// (`tools/corpus_fetch.sh`), like the other corpus tests. +/// +/// The budget is deliberately loose — a debug build on a loaded machine is +/// the worst case this ever runs in — and exists to catch an order-of- +/// magnitude regression, not to pin a number. The numbers themselves are +/// in `docs/features/hierarchy/README.md`. +#[test] +fn incoming_calls_over_the_whole_corpus_stay_in_budget() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let declaring = corpus.join("ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_flop_2sync.sv"); + let Ok(text) = fs::read_to_string(&declaring) else { + eprintln!("prim_flop_2sync.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&declaring).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7) + .expect("the declaration")[0] + .clone(); + + // Warm, then the worst of three. + let _ = incoming(&ws, &root); + let mut worst = std::time::Duration::ZERO; + let mut callers = 0; + for _ in 0..3 { + let started = std::time::Instant::now(); + let calls = incoming(&ws, &root); + worst = worst.max(started.elapsed()); + callers = calls.len(); + } + eprintln!( + "corpus: {} files, incomingCalls for prim_flop_2sync: {callers} callers, worst {worst:?}", + ws.index().files().len(), + ); + assert!(callers > 5, "the corpus really does instantiate it: {callers}"); + assert!(worst < std::time::Duration::from_millis(1500), "incomingCalls cost {worst:?}"); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index ea44107..27468b1 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -532,1385 +532,18 @@ fn markdown(doc: &Document, value: String, span: TextRange) -> Hover { } #[cfg(test)] -mod tests { - use super::*; - use crate::uri::path_to_uri; - use std::fs; - use std::path::PathBuf; - use std::str::FromStr; - - fn document(text: &str) -> (Workspace, Uri) { - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - (ws, uri) - } - - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - fn text_of(hover: &Hover) -> String { - match &hover.contents { - HoverContents::Markup(m) => m.value.clone(), - other => panic!("expected markup, got {other:?}"), - } - } - - fn temp_dir(tag: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("lucisv_server_hover_{tag}_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("temp dir"); - dir - } - - #[test] - fn hovering_a_macro_usage_shows_its_body() { - let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n"; - let (ws, uri) = document(text); - let hover = hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover"); - let body = text_of(&hover); - // The fence tag is load-bearing: it is the language id the extension - // registers its TextMate grammar for, and the only reason a hover card - // renders highlighted. Pinned here so a rename cannot pass silently. - assert!(body.contains("```systemverilog\n`define WIDTH 8\n```"), "got {body}"); - } - - #[test] - fn hovering_a_function_like_macro_shows_its_signature() { - let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(1, 2);\nendmodule\n"; - let (ws, uri) = document(text); - let hover = hover(&ws, &uri, at(text, "`MAX(1")).expect("hover"); - let body = text_of(&hover); - assert!(body.contains("`define MAX(a, b)"), "got {body}"); - assert!(body.contains("? (a) : (b)"), "got {body}"); - } - - #[test] - fn hovering_a_call_shows_what_it_expands_to_in_one_step() { - let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p, q+1);\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover")); - // The definition stays, and the expansion is added under it — same - // fence tag, since that is what colours a hover card (0.4.1). - assert!(body.contains("```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```")); - assert!( - body.contains("**expands to**\n\n```systemverilog\n((p) > (q+1) ? (p) : (q+1))\n```"), - "got {body}" - ); - assert!(!body.contains("one step:"), "nothing left unexpanded here: got {body}"); - } - - #[test] - fn a_plain_object_like_macro_gets_no_second_section() { - // Its expansion *is* its body, which the card already shows. - let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover")); - assert!(!body.contains("expands to"), "got {body}"); - } - - #[test] - fn an_object_like_macro_that_calls_another_shows_where_one_step_stopped() { - let text = - "`define BASE 4\n`define W `BASE + 1\nmodule m;\n wire [`W-1:0] a;\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "[`W-") + 1).expect("hover")); - assert!(body.contains("**expands to**\n\n```systemverilog\n`BASE + 1\n```"), "got {body}"); - assert!(body.contains("*one step: a nested macro use is left as written*"), "got {body}"); - assert!(!body.contains("`define BASE 4"), "one step, not two: got {body}"); - } - - #[test] - fn a_call_whose_argument_count_is_wrong_keeps_todays_card_and_guesses_nothing() { - let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p);\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover")); - assert!(body.contains("`define MAX(a, b)"), "the card is unchanged: got {body}"); - assert!(!body.contains("expands to"), "got {body}"); - } - - #[test] - fn an_argument_may_carry_commas_and_strings_of_its_own() { - let text = "`define SHOW(a, b) $display(a, b)\nmodule m;\n initial `SHOW(\"x, y\", f(1, 2));\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "`SHOW(\"")).expect("hover")); - assert!( - body.contains("```systemverilog\n$display(\"x, y\", f(1, 2))\n```"), - "the commas inside the string and the call did not split it: got {body}" - ); - } - - #[test] - fn a_long_body_is_truncated_with_a_note() { - let filler = "z".repeat(crate::expand::CAP + 100); - let text = - format!("`define BIG(a) a + {filler}\nmodule m;\n wire x = `BIG(1);\nendmodule\n"); - let (ws, uri) = document(&text); - let body = text_of(&hover(&ws, &uri, at(&text, "`BIG(1")).expect("hover")); - assert!( - body.contains(" …\n```"), - "cut with an ellipsis: got {}", - &body[..200.min(body.len())] - ); - assert!( - body.contains(&format!("*truncated at {} characters*", crate::expand::CAP)), - "and says so" - ); - } - - #[test] - fn the_expansion_follows_the_definition_the_card_narrowed_to() { - // M10's include narrowing picks `a.svh`; the expansion must be that - // definition's, not the other file's. - let text = "`include \"a.svh\"\nmodule top;\n wire x = `M(7);\nendmodule\n"; - let (dir, ws, uri) = included( - "expandreach", - &[ - ("a.svh", "`define M(x) x + 1\n"), - ("b.svh", "`define M(x) x + 2\n"), - ("top.sv", text), - ], - ); - let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover")); - assert!(body.contains("a.svh:1"), "got {body}"); - assert!(body.contains("**expands to**\n\n```systemverilog\n7 + 1\n```"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn several_candidate_definitions_expand_nothing() { - let text = "module top;\n wire x = `M(7);\nendmodule\n"; - let (dir, ws, uri) = included( - "expandambiguous", - &[ - ("a.svh", "`define M(x) x + 1\n"), - ("b.svh", "`define M(x) x + 2\n"), - ("top.sv", text), - ], - ); - let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover")); - assert!(body.contains("is defined 2 times"), "got {body}"); - assert!(!body.contains("expands to"), "no winner to expand: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_undefined_macro_says_so_rather_than_returning_nothing() { - let text = "module m;\n wire x = `NOPE;\nendmodule\n"; - let (ws, uri) = document(text); - let hover = hover(&ws, &uri, at(text, "`NOPE")).expect("hover"); - assert!(text_of(&hover).contains("no definition found")); - } - - #[test] - fn a_workspace_define_is_found_when_this_file_does_not_define_it() { - let dir = temp_dir("define"); - fs::write(dir.join("defs.svh"), "`define WIDTH 8\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n wire [`WIDTH-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let hover = hover(&ws, &uri, at(top_text, "`WIDTH")).expect("hover"); - let body = text_of(&hover); - assert!(body.contains("`define WIDTH 8"), "got {body}"); - assert!(body.contains("defs.svh:1"), "the file and line: got {body}"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn several_workspace_definitions_are_all_listed() { - let dir = temp_dir("dupdefine"); - fs::write(dir.join("a.svh"), "`define W 8\n").expect("write"); - fs::write(dir.join("b.svh"), "`define W 16\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n wire [`W-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top_text, "`W-")).expect("hover")); - assert!(body.contains("is defined 2 times"), "got {body}"); - assert!(body.contains("`define W 8"), "got {body}"); - assert!(body.contains("`define W 16"), "got {body}"); - - let _ = fs::remove_dir_all(&dir); - } - - /// A workspace whose files are `files`, with `top.sv` opened. - fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { - let dir = temp_dir(tag); - for (name, text) in files { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top = dir.join("top.sv"); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); - (dir, ws, uri) - } - - /// A `top.sv` using `` `W ``, with whatever include lines precede it. - fn top_using_w(includes: &str) -> String { - format!("{includes}module top;\n wire [`W-1:0] a;\nendmodule\n") - } - - #[test] - fn one_hop_of_include_picks_the_definition_the_file_actually_reaches() { - // Two files define `W`; only one of them is included. Before the - // include graph this hover listed both and refused to choose. - let (dir, ws, uri) = included( - "reach1", - &[ - ("a.svh", "`define W 8\n"), - ("b.svh", "`define W 16\n"), - ("top.sv", &top_using_w("`include \"a.svh\"\n")), - ], - ); - let body = text_of( - &hover(&ws, &uri, at(&top_using_w("`include \"a.svh\"\n"), "`W-")).expect("hover"), - ); - assert!(body.contains("`define W 8"), "the reachable one: got {body}"); - assert!(!body.contains("`define W 16"), "and not the other: got {body}"); - assert!(body.contains("a.svh:1"), "named with its origin: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn two_hops_of_include_reach_just_as_far() { - let text = top_using_w("`include \"mid.svh\"\n"); - let (dir, ws, uri) = included( - "reach2", - &[ - ("mid.svh", "`include \"deep.svh\"\n"), - ("deep.svh", "`define W 8\n"), - ("elsewhere.svh", "`define W 16\n"), - ("top.sv", &text), - ], - ); - let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); - assert!(body.contains("`define W 8") && body.contains("deep.svh:1"), "got {body}"); - assert!(!body.contains("`define W 16"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_include_cycle_terminates_and_both_files_stay_reachable() { - let text = top_using_w("`include \"a.svh\"\n"); - let (dir, ws, uri) = included( - "reachcycle", - &[ - ("a.svh", "`include \"b.svh\"\n"), - ("b.svh", "`include \"a.svh\"\n`define W 8\n"), - ("elsewhere.svh", "`define W 16\n"), - ("top.sv", &text), - ], - ); - let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); - assert!(body.contains("`define W 8") && body.contains("b.svh:2"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_definition_nothing_includes_is_still_shown_when_it_is_all_there_is() { - // The fallback that must not regress: an unreachable definition is - // better than none, and a project that does not use `` `include`` at - // all sees exactly what it saw before this feature. - let text = top_using_w(""); - let (dir, ws, uri) = - included("reachnone", &[("far.svh", "`define W 8\n"), ("top.sv", &text)]); - let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); - assert!(body.contains("`define W 8") && body.contains("far.svh:1"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn two_definitions_neither_of_them_reachable_are_still_both_listed() { - let text = top_using_w("`include \"empty.svh\"\n"); - let (dir, ws, uri) = included( - "reachambiguous", - &[ - ("empty.svh", "// nothing here\n"), - ("a.svh", "`define W 8\n"), - ("b.svh", "`define W 16\n"), - ("top.sv", &text), - ], - ); - let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); - assert!(body.contains("is defined 2 times"), "the honest answer: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn two_reachable_definitions_are_listed_rather_than_guessed_between() { - // The graph orders nothing here — both files are included — so the - // all-candidates answer stands. - let text = top_using_w("`include \"a.svh\"\n`include \"b.svh\"\n"); - let (dir, ws, uri) = included( - "reachboth", - &[("a.svh", "`define W 8\n"), ("b.svh", "`define W 16\n"), ("top.sv", &text)], - ); - let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); - assert!(body.contains("is defined 2 times"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn hovering_a_use_shows_its_declaration() { - let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "[WIDTH") + 1).expect("hover")); - // The heading says what the source says. Since 2026-09-02 a - // `localparam` is its own kind, so the label and the snippet below it - // in the same card no longer disagree. - assert!(body.contains("**localparam**"), "got {body}"); - // Fenced with the grammar's language id — see the macro hover test. - assert!( - body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), - "the decl snippet: got {body}" - ); - } - - // ------------------------------------------------------------------ - // non-ANSI split ports: two sections, each with its comment - // ------------------------------------------------------------------ - - const SPLIT: &str = "\ -module alu ( - // the operand - data_in, - result // the result -); - -input signed [31:0] data_in; // 32-bit operand A -output reg [63:0] result; -endmodule -"; - - #[test] - fn a_split_port_hovers_as_two_sections_with_their_comments() { - // The same card from both places the port is declared: the header - // name and the body declaration. - let (ws, uri) = document(SPLIT); - for needle in ["data_in,", "data_in;"] { - let body = text_of(&hover(&ws, &uri, at(SPLIT, needle)).expect("hover")); - assert!(body.contains("**port** `data_in`"), "the heading: {needle:?} -> {body}"); - // Section one: the header, with the comment-only line above it. - assert!( - body.contains("```systemverilog\n // the operand\n data_in,\n```"), - "the header section, comment attached: {needle:?} -> {body}" - ); - // Section two: the body declaration, with its same-line comment. - assert!( - body.contains( - "```systemverilog\ninput signed [31:0] data_in; // 32-bit operand A\n```" - ), - "the detail section, comment included: {needle:?} -> {body}" - ); - // Two sections, not one merged block: two fences for one card. - assert!( - body.matches("```systemverilog").count() >= 2, - "two fenced sections: {needle:?} -> {body}" - ); - } - } - - #[test] - fn a_comments_below_a_declaration_attach_only_when_no_port_follows_them() { - // Below-comments attach when only the closer follows them (nothing - // else could they document)… - let below = "module alu (data_in);\ninput [7:0] data_in;\n// the operand\nendmodule\n"; - let (ws, uri) = document(below); - let body = text_of(&hover(&ws, &uri, at(below, "data_in;")).expect("hover")); - assert!( - body.contains("input [7:0] data_in;\n// the operand"), - "a comment under the last declaration is attached: got {body}" - ); - - // …but a comment block sitting just above the *next* port's - // declaration is that port's leading comment, not this one's. - let stolen = "module alu (data_in, result);\ninput [7:0] data_in;\n// about result\noutput result;\nendmodule\n"; - let (ws, uri) = document(stolen); - let body = text_of(&hover(&ws, &uri, at(stolen, "data_in,")).expect("hover")); - assert!( - !body.contains("// about result"), - "the next port's leading comment is not stolen: got {body}" - ); - // …and it does reach the port it documents. - let body = text_of(&hover(&ws, &uri, at(stolen, "result;") + 1).expect("hover")); - assert!(body.contains("// about result"), "attached to its own port: got {body}"); - } - - #[test] - fn an_old_style_task_argument_hovers_as_two_sections_too() { - // QA, PDS-3: a task or function argument named in the header and - // finished in the body is the same split shape a module port is, and - // now gets the same two-section card. - let text = "\ -module m; - // the operand - task t(a); - input [7:0] a; // 8 bits wide - $display(a); - endtask -endmodule -"; - let (ws, uri) = document(text); - for needle in ["a);", "a; //"] { - let body = text_of(&hover(&ws, &uri, at(text, needle)).expect("hover")); - assert!( - body.contains("```systemverilog\n // the operand\n task t(a);\n```"), - "the header section: {needle:?} -> {body}" - ); - assert!( - body.contains("```systemverilog\n input [7:0] a; // 8 bits wide\n```"), - "the body declaration's section: {needle:?} -> {body}" - ); - } - } - - #[test] - fn a_wrapped_next_declaration_keeps_its_own_leading_comment() { - // QA, PDS-1: the guard used to ask whether the line after a - // below-comment carried an identifier the port grammar could not - // account for. A declaration that *wraps*, with its direction keyword - // alone on the first line, carries no such identifier there — so the - // guard read "no other port here" and handed `result`'s comment to - // `data_in`. Only a line positively recognised as a closer may let a - // comment through now. - let wrapped = "\ -module alu (data_in, result); -input [7:0] data_in; -// about result -input - [7:0] result; -endmodule -"; - let (ws, uri) = document(wrapped); - let body = text_of(&hover(&ws, &uri, at(wrapped, "data_in;")).expect("hover")); - assert!( - !body.contains("// about result"), - "a wrapped next declaration's comment is not stolen: got {body}" - ); - // …and it reaches the port it was written for, above its own lines. - let body = text_of(&hover(&ws, &uri, at(wrapped, "result;")).expect("hover")); - assert!( - body.contains("// about result\ninput\n [7:0] result;"), - "attached above the wrapped declaration it documents: got {body}" - ); - } - - #[test] - fn a_wrapped_declaration_keeps_the_comment_below_it() { - // The other half of PDS-1: a wrapped declaration that really is the - // last one still takes the comment under it, because what follows the - // comment is a closer. - let text = "\ -module alu (data_in); -input - [7:0] data_in; -// the operand -endmodule -"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); - assert!( - body.contains("input\n [7:0] data_in;\n// the operand"), - "the last, wrapped declaration takes the comment below it: got {body}" - ); - } - - #[test] - fn a_declaration_shows_the_comments_above_beside_and_below_it_at_once() { - // The owner's rule reads the three sources independently: same line, - // above, below. QA, PDS-2 — the implementation used to run a priority - // chain, so an above-comment or a trailing one silently suppressed - // the block below even when nothing else could claim it. - let text = "\ -module alu (data_in); -// above -input [7:0] data_in; // beside -// below -endmodule -"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); - assert!( - body.contains("// above\ninput [7:0] data_in; // beside\n// below"), - "all three comments, in source order: got {body}" - ); - } - - #[test] - fn a_header_port_shows_the_comments_above_and_below_it_at_once() { - // PDS-2's own repros, both in one header: an above-comment (repro 1) - // and a same-line trailing comment (repro 2) each used to suppress - // the block below, which only `);` follows. - let text = "\ -module alu ( - // above - data_in, // beside - // below - result -); -input [7:0] data_in; -input result; -endmodule -"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "data_in,")).expect("hover")); - // `result` follows the block, so it is `result`'s comment, not this - // port's — the guard stays exactly as strict as it was. - assert!(!body.contains("// below"), "another port's comment is not stolen: got {body}"); - assert!( - body.contains(" // above\n data_in, // beside"), - "above and beside both attach: got {body}" - ); - - // With nothing but the closer after it, the same block does attach. - let last = "\ -module alu ( - // above - data_in // beside - // below -); -input [7:0] data_in; -endmodule -"; - let (ws, uri) = document(last); - let body = text_of(&hover(&ws, &uri, at(last, "data_in ")).expect("hover")); - assert!( - body.contains(" // above\n data_in // beside\n // below"), - "all three attach when only the closer follows: got {body}" - ); - } - - #[test] - fn the_line_above_a_header_port_does_not_leak_its_trailing_comment() { - // `result, // the result` above `data_in`'s own line: the line above - // carries another port, so its trailing comment stays result's. - let text = "\ -module alu ( - result, // the result - data_in -); -input [7:0] data_in; -endmodule -"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "data_in\n")).expect("hover")); - assert!(!body.contains("the result"), "not the port above's comment: got {body}"); - } - - #[test] - fn a_cross_file_split_port_shows_both_sections() { - let sub = "module sub (\n addr,\n ready\n);\ninput logic [15:0] addr;\noutput ready;\nendmodule\n"; - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("splitx", &[("sub.sv", sub), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!( - body.contains("```systemverilog\n addr,\n```"), - "the header section, from the index's spans: got {body}" - ); - assert!( - body.contains("```systemverilog\ninput logic [15:0] addr;\n```"), - "the detail section, from the index's detail span: got {body}" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn hovering_a_declaration_shows_its_own_info() { - let text = "module top;\n wire a;\nendmodule\n"; - let (ws, uri) = document(text); - let body = text_of(&hover(&ws, &uri, at(text, "top")).expect("hover")); - assert!(body.contains("**module** `top`"), "got {body}"); - } - - #[test] - fn hovering_a_cross_file_module_names_its_file() { - let dir = temp_dir("xhover"); - fs::write(dir.join("sub.sv"), "module sub (input clk);\nendmodule\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top_text, "sub u")).expect("hover")); - assert!(body.contains("**module**"), "got {body}"); - assert!(body.contains("sub.sv:1"), "got {body}"); - - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // the declaration behind a cross-file answer - // ------------------------------------------------------------------ - - const PORTS: &str = - "module sub (\n input logic [7:0] addr,\n output logic ready\n);\nendmodule\n"; - - #[test] - fn a_cross_file_port_connection_shows_the_ports_own_declaration_line() { - // The ask this round answers: direction, type and width, not just a - // file and a line. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("portdecl", &[("sub.sv", PORTS), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!( - body.contains("**port** — declared in `sub.sv:2`"), - "the heading stays: got {body}" - ); - assert!( - body.contains("```systemverilog\n input logic [7:0] addr,\n```"), - "the declaration itself: got {body}" - ); - assert!(!body.contains("output logic ready"), "only its own line: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_cross_file_module_instance_shows_its_header_line() { - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("moduledecl", &[("sub.sv", PORTS), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); - assert!(body.contains("**module** — declared in `sub.sv:1`"), "got {body}"); - assert!(body.contains("```systemverilog\nmodule sub (\n```"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() { - // The round's central claim: `file:line` for an indexed declaration is - // `Def::lines`, recorded when the file was scanned, so the heading - // costs no read at all. Proved by removing the file from under the - // index — a heading that still names the line cannot have read it. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]); - fs::remove_file(dir.join("sub.sv")).expect("remove"); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}"); - // The snippet is the half that really wanted the text, and it is - // dropped rather than guessed at — exactly as it always was for a - // file that cannot be read. - assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_second_hover_into_one_closed_file_reads_nothing() { - // The other half: the snippet's read is shared through - // `Workspace::file_view`, so the file is read once and the next hover - // into it — the same card, or another name in the same file — is - // served from what that read left behind. Observed the only honest - // way: rewrite the file behind the server's back and require the - // second card to be the first one. Stale text can only ever *omit* a - // snippet (the `spells_exactly` guard), never show a wrong line. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]); - let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(first.contains("input logic [7:0] addr"), "premise: got {first}"); - - fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n") - .expect("write"); - let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert_eq!(second, first, "the second hover did not read the file again"); - let _ = fs::remove_dir_all(&dir); - } - - /// QA (2026-08-28): the staleness window the README's Assumptions section - /// claims — "a line is a fact about the same snapshot the span is... where - /// the file has changed on disk with nothing telling the server, both are - /// stale together" — reproduced rather than taken on faith, and in the - /// one shape that could actually disagree: the index was built from the - /// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`, - /// no watcher event, no `update_one`/`rebuild_index` call, so the index is - /// never told — **before the view cache ever reads it**, so the first - /// hover's disk read sees the *new* bytes under the *old* span and offset. - /// The heading must still show the line the index recorded at the last - /// scan (stale, not a fresh-read line the index never computed), and the - /// snippet, reading the genuinely current text, must find the old span no - /// longer spells `addr` there and drop itself via `spells_exactly` rather - /// than show whatever now sits at that byte range. - #[test] - fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() { - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]); - - // Edited behind the server's back, before any hover has read this - // file at all: four lines inserted above the module, so `addr`'s true - // line is now 6 — and the byte offset the index still holds for it - // (from the *original* `sub.sv`) now lands inside a comment, not - // `addr`. The view cache is empty for this path, so the hover below - // is a genuinely fresh disk read of the edited bytes. - fs::write( - dir.join("sub.sv"), - "// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\ - \x20 output logic ready\n);\nendmodule\n", - ) - .expect("write"); - - let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!( - after.contains("**port** — declared in `sub.sv:2`"), - "the heading must show the line the index recorded, not the file's true current \ - line (6), until something reindexes it: got {after}" - ); - assert!( - !after.contains("```systemverilog"), - "the snippet must be dropped, not show the comment the stale span now lands on: \ - got {after}" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_package_member_shows_its_declaration_line() { - let pkg = - "package p;\n localparam WIDTH = 8;\n typedef logic [3:0] nibble_t;\nendpackage\n"; - let top = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\n nibble_t n;\nendmodule\n"; - let (dir, ws, uri) = included("pkgdecl", &[("p.sv", pkg), ("top.sv", top)]); - - let body = text_of(&hover(&ws, &uri, at(top, "WIDTH-1")).expect("hover")); - assert!(body.contains("**localparam** — declared in `p.sv:2`"), "got {body}"); - assert!(body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), "got {body}"); - - let body = text_of(&hover(&ws, &uri, at(top, "nibble_t n")).expect("hover")); - assert!( - body.contains("```systemverilog\n typedef logic [3:0] nibble_t;\n```"), - "a typedef reads the same way: got {body}" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span() { - // The index's span is against the last *saved* text. Reading it out of - // the open buffer would print whatever the shifted offsets now cover. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let (dir, mut ws, uri) = included("livemove", &[("sub.sv", saved), ("top.sv", top)]); - let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); - let edited = "// two lines\n// pushed it down\nmodule sub (\n input logic [15:0] addr\n);\nendmodule\n"; - ws.set_document(sub_uri, edited.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!( - body.contains("```systemverilog\n input logic [15:0] addr\n```"), - "the live line, width and all: got {body}" - ); - assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - /// TODO §64.1. The same live-span read for a declaration only a - /// **hierarchical** path can reach — a module's internal net, named from - /// another file as `u_leaf.sig`. - /// - /// `declaration_snippet` reaches it through `live_symbol` → - /// `nav::indexed_def_for_symbol`, which asked `WorkspaceIndex::member` - /// (the *connection* surface) until §64.1 and so mapped no live symbol - /// back to this `Def` at all: the card came out with its heading and no - /// fence, on a file that was open and perfectly readable. It now shows the - /// live line, which is the same guarantee the port above gets — and the - /// guard is untouched, so a buffer whose live text no longer declares the - /// name still prints nothing (asserted below). - #[test] - fn a_hierarchical_only_declaration_is_read_at_its_live_span_too() { - let top = - "module top;\n leaf u_leaf ();\n wire w;\n assign w = u_leaf.sig;\nendmodule\n"; - let saved = "module leaf;\n logic [7:0] sig;\nendmodule\n"; - let (dir, mut ws, uri) = included("livehier", &[("leaf.sv", saved), ("top.sv", top)]); - let leaf_uri = path_to_uri(&dir.join("leaf.sv")).expect("uri"); - let edited = - "// two lines\n// pushed it down\nmodule leaf;\n logic [15:0] sig;\nendmodule\n"; - ws.set_document(leaf_uri.clone(), edited.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); - assert!( - body.contains("```systemverilog\n logic [15:0] sig;\n```"), - "the live line, width and all: got {body}" - ); - assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); - - // The guard half, on the same shape: the net renamed away in the - // buffer leaves the heading and no fence. - ws.set_document(leaf_uri, "module leaf;\n logic [15:0] renamed;\nendmodule\n".to_string()); - let guarded = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); - assert!(guarded.contains("— declared in"), "today's card, intact: got {guarded}"); - assert!(!guarded.contains("```"), "and no snippet at all: got {guarded}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() { - // The file changed on disk under a live index — a rescan the server has - // not run yet. The recorded span now covers something that is not the - // name, so there is nothing honest to print. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let (dir, ws, uri) = included("stalespan", &[("sub.sv", saved), ("top.sv", top)]); - fs::write(dir.join("sub.sv"), format!("// {}\n{saved}", "x".repeat(40))).expect("rewrite"); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(body.contains("**port** — declared in"), "today's card, intact: got {body}"); - assert!(!body.contains("```"), "and no snippet at all: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet() { - // The other half of the guard: the target file is open and its live - // text has renamed the port away, so no live symbol is that indexed - // declaration and nothing may be printed for it. - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let (dir, mut ws, uri) = included("livemiss", &[("sub.sv", saved), ("top.sv", top)]); - let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); - ws.set_document( - sub_uri, - "module sub (\n input logic [7:0] renamed\n);\nendmodule\n".to_string(), - ); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(body.contains("**port** — declared in"), "got {body}"); - assert!(!body.contains("```"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_very_long_declaration_line_is_cut_with_a_note() { - // Netlist lines have no bound; a hover card does. - let filler = "z".repeat(SNIPPET_CHARS + 100); - let sub = format!("module sub (\n input logic [7:0] addr /* {filler} */\n);\nendmodule\n"); - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("longline", &[("sub.sv", &sub), ("top.sv", top)]); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(body.contains("input logic [7:0] addr"), "the useful half survives: got {body}"); - assert!(body.contains(" …\n```"), "cut with an ellipsis"); - assert!(body.contains(&format!("*shown to {SNIPPET_CHARS} characters*")), "and says so"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_declaration_spanning_many_lines_is_cut_at_the_line_limit() { - // A module's `decl_span` is its whole body, which the live path widens - // to — fine for a port, a card-swallowing wall for a big module. - let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); - for n in 0..20 { - sub.push_str(&format!(" wire w{n};\n")); - } - sub.push_str("endmodule\n"); - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, mut ws, uri) = included("longdecl", &[("sub.sv", &sub), ("top.sv", top)]); - let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri, sub.clone()); - - let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); - assert!(body.contains("```systemverilog\nmodule sub ("), "got {body}"); - assert!(body.contains(&format!("*shown to {SNIPPET_LINES} lines*")), "got {body}"); - assert!(!body.contains("w19"), "the body is not printed: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn two_files_declaring_one_name_each_get_their_own_snippet() { - let top = "module top;\n dup u (.*);\nendmodule\n"; - let (dir, ws, uri) = included( - "dupdecl", - &[ - ("a.sv", "module dup (input logic a_clk);\nendmodule\n"), - ("b.sv", "module dup (input logic b_clk);\nendmodule\n"), - ("top.sv", top), - ], - ); - let body = text_of(&hover(&ws, &uri, at(top, "dup u")).expect("hover")); - assert!(body.contains("a.sv:1") && body.contains("b.sv:1"), "both candidates: got {body}"); - assert!(body.contains("input logic a_clk"), "got {body}"); - assert!(body.contains("input logic b_clk"), "each with its own line: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn hovering_whitespace_returns_nothing() { - let text = "module m;\n\n wire a;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(hover(&ws, &uri, at(text, "\n\n") + 1).is_none()); - } - - #[test] - fn a_macro_name_stops_at_its_argument_list() { - let text = "`define M(a) a\nmodule m;\n wire x = `M(1);\nendmodule\n"; - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - let token = doc.tokens.iter().find(|t| t.is_macro()).expect("a macro usage token"); - assert_eq!(macro_name(token), Some("M")); - } -} +mod tests; /// QA (M10 include-nav): a defect pinned rather than fixed — see the QA log /// in `docs/features/include-nav/README.md` for the writeup and the fix /// options weighed there. #[cfg(test)] -mod qa_findings { - use super::*; - use crate::settings::ClientSettings; - use crate::uri::path_to_uri; - use std::fs; - - /// The angled form is correctly wired into the narrowing overlay: not a - /// finding, recorded as a permanent regression test since the six tests - /// the dev shipped in this file only exercise the quoted form. - #[test] - fn an_angled_include_narrows_hover_same_as_a_quoted_one() { - let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_sys_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(dir.join("inc")).expect("mkdir"); - fs::write(dir.join("inc/uvm_macros.svh"), "`define W 8\n").expect("write"); - fs::write(dir.join("elsewhere.svh"), "`define W 16\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "`include \nmodule top;\n wire [`W-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/uvm_macros.svh\nelsewhere.svh\n") - .expect("write"); - - let mut ws = Workspace::default(); - ws.set_client_settings(ClientSettings { - filelist: Some(dir.join("files.f").display().to_string()), - ..Default::default() - }); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); - let body = match &h.contents { - HoverContents::Markup(m) => m.value.clone(), - _ => panic!("markup"), - }; - assert!(body.contains("`define W 8") && body.contains("uvm_macros.svh:1"), "got {body}"); - assert!(!body.contains("`define W 16"), "got {body}"); - - let _ = fs::remove_dir_all(&dir); - } - - /// QA finding (M10, HIGH), fixed 2026-08-25. On a case-insensitive - /// filesystem (the default on macOS — this machine — and on Windows) - /// `Path::is_file` succeeds for a case-mismatched candidate, and - /// `normalize` only folds `.`/`..`, so `IncludeGraph::resolve` used to - /// return the path *as written* in the `` `include ``. `WorkspaceIndex` - /// meanwhile records the file under the case that was read off disk, so - /// the two spellings were different `PathBuf`s and - /// `narrowed_to_the_include_graph`'s `reachable.contains(p)` check - /// silently missed a file that **is** genuinely reachable. - /// - /// Below, `top.sv` includes both `defs.svh` (case-mismatched: the file is - /// `Defs.svh`) and `other.svh` (spelled correctly), and both are equally - /// reachable in truth. Two reachable definitions must fall back to the - /// honest "defined 2 times" answer — the same thing - /// `two_reachable_definitions_are_listed_rather_than_guessed_between` - /// above pins for the case-matched spelling. Before the fix this narrowed - /// to the correctly-cased file alone and showed it with full confidence, - /// which is "may only narrow, never widen" failing in the one direction - /// that matters. `IncludeGraph::as_the_index_spells_it` now re-spells a - /// resolved path to the index's own when exactly one in-scope file - /// matches it case-insensitively. - /// - /// Case-gated: only macOS/Windows default to a case-insensitive - /// filesystem, so only there does the premise (`is_file` succeeding for - /// the wrong case) hold. - #[cfg(any(target_os = "macos", target_os = "windows"))] - #[test] - fn a_case_mismatched_include_still_counts_as_reachable() { - let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_case_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("mkdir"); - fs::write(dir.join("Defs.svh"), "`define W 8\n").expect("write"); - fs::write(dir.join("other.svh"), "`define W 16\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "`include \"defs.svh\"\n`include \"other.svh\"\nmodule top;\n \ - wire [`W-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); - let body = match &h.contents { - HoverContents::Markup(m) => m.value.clone(), - _ => panic!("markup"), - }; - // Both files are reachable, so neither may be dropped and neither may - // be presented as the answer. - assert!(body.contains("is defined 2 times"), "got {body}"); - assert!(body.contains("`define W 8") && body.contains("Defs.svh:1"), "got {body}"); - assert!(body.contains("`define W 16") && body.contains("other.svh:1"), "got {body}"); - - let _ = fs::remove_dir_all(&dir); - } -} +mod qa_findings; /// QA (hover-declarations, 2026-08-27): adversarial probes against /// `declaration_snippet`. See the QA log in /// `docs/features/hover-declarations/README.md` for the writeup of each. #[cfg(test)] -mod qa_hover_declarations { - use super::*; - use crate::uri::path_to_uri; - use std::fs; - use std::path::PathBuf; - // Its one user is the case-insensitive-filesystem test below. - #[cfg(any(target_os = "macos", target_os = "windows"))] - use std::str::FromStr; - - fn temp_dir(tag: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("lucisv_qa_hoverdecl_{tag}_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("temp dir"); - dir - } - - /// Angle 1: the disk-path guard slices `def.name_span` — a *fixed-length* - /// byte range, the old name's length, taken when the index was built — - /// and compares it for equality with the hovered name. It never checks - /// what comes immediately *after* that range. So an edit that extends the - /// declared identifier by appending characters (no reindex yet) leaves - /// the first `name.len()` bytes at the old offset still spelling the old - /// name — the guard passes — while the *actual* identifier at that - /// position is now a different, longer one that the file no longer - /// declares under the hovered name at all. - /// - /// This is exactly the "same name at the stale span by coincidence" - /// attack the QA charter asks for, and it succeeds: the card claims to - /// show `addr`'s declaration and instead shows `addr2`'s, with no - /// indication anything is wrong. FINDING (see QA log, MEDIUM): the guard - /// needs a word-boundary check, not just a fixed-length substring match. - #[test] - fn a_disk_edit_that_only_appends_to_the_name_defeats_the_guard() { - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("guardappend", &[("sub.sv", saved), ("top.sv", top)]); - // Same bytes up to and including "addr", then more identifier - // characters glued directly on — the stale span still lines up with - // "addr" as a prefix of the new, longer name. - let corrupted = "module sub (\n input logic [7:0] addr2\n);\nendmodule\n"; - let prefix_len = saved.find("addr").unwrap() + 4; - assert_eq!( - &corrupted[..prefix_len], - &saved[..prefix_len], - "the attack requires the stale span to still land on the same bytes" - ); - fs::write(dir.join("sub.sv"), corrupted).expect("rewrite"); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - let shows_wrong_declaration = body.contains("addr2"); - if shows_wrong_declaration { - panic!( - "GUARD DEFEATED: the card for `.addr(...)` shows `addr2`'s line, \ - not `addr`'s (which no longer exists) — got {body:?}" - ); - } - } - - fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { - let dir = temp_dir(tag); - for (name, text) in files { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top = dir.join("top.sv"); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); - (dir, ws, uri) - } - - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - fn text_of(hover: &Hover) -> String { - match &hover.contents { - HoverContents::Markup(m) => m.value.clone(), - other => panic!("expected markup, got {other:?}"), - } - } - - /// Angle 3: two live declarations of the same port name in an open - /// buffer (a transient state while editing — e.g. mid-refactor before the - /// stale one is deleted). The index still has one persisted `Def` for the - /// name, so `indexed_def_for_symbol` maps *either* live symbol back to - /// it, and `live_symbol`'s `.find()` picks whichever comes first in - /// `Semantics::symbols()` order. - /// - /// Not a wrong-line *lie* — the guard still requires the chosen symbol's - /// own text to spell the name, which it always does by construction — but - /// it is a silent, arbitrary choice between two candidates with no signal - /// to the user that the buffer is ambiguous. This is inherited from - /// `nav.rs`'s pre-existing matcher (unchanged by this round: "one - /// matcher, so hover and go-to-definition can never disagree"), so it is - /// filed as an accepted pre-existing limitation, not a new defect. Pinned - /// here so a future change to the matcher's tie-break is not silent. - #[test] - fn duplicate_live_declarations_of_one_name_pick_the_first_one_silently() { - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let (dir, mut ws, uri) = included("dupdup", &[("sub.sv", saved), ("top.sv", top)]); - let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); - // Two ports named `addr`, different widths, in the same scope/kind. - let edited = - "module sub (\n input logic [7:0] addr,\n input logic [15:0] addr\n);\nendmodule\n"; - ws.set_document(sub_uri, edited.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - // Exactly one of the two widths appears — never both, never neither — - // confirming the pick is total but not both fenced blocks are shown. - let has_first = body.contains("[7:0] addr"); - let has_second = body.contains("[15:0] addr"); - assert!(has_first ^ has_second, "expected exactly one candidate shown: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - /// Angle 2 (CRLF): a multi-line snippet from a CRLF file used to keep the - /// `\r` on every line except the last, where `cut_to_size`'s `trim_end` - /// stripped it — an embedded control character in the middle of a fenced - /// block. QA filed it (hover-declarations finding 2, port-detail-spans - /// PDS-4); `attached_lines` now strips the carriage return as it composes - /// each line, so the fence holds `\n`-separated lines whatever the file's - /// line endings are. Display text only: nothing writes to the buffer. - #[test] - fn a_crlf_multiline_snippet_carries_no_carriage_returns() { - // `wide`'s `decl_span` is its whole body (a module, like `PORTS` in - // the dev's own tests), so its live-path snippet spans several CRLF - // lines and is exactly where an interior, un-trimmed `\r` would show. - // Both modules must exist at the *initial* index build — rewriting a - // module name into a file after `open_whole_workspace` without - // reindexing leaves the index not knowing that name, which is a - // workspace-setup mistake, not something this test is probing. - let wide = - "module wide (\r\n input logic a\r\n);\r\n wire w0;\r\n wire w1;\r\nendmodule\r\n"; - let top = "module top;\r\n wide u ();\r\nendmodule\r\n"; - let (dir, mut ws, uri) = included("crlfdecl", &[("wide.sv", wide), ("top.sv", top)]); - let wide_uri = path_to_uri(&dir.join("wide.sv")).expect("uri"); - // Open the target so the live path (which widens `decl_span`, the - // multi-line span) is exercised rather than the disk path. - ws.set_document(wide_uri, wide.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover")); - assert!(body.contains("module wide ("), "got {body:?}"); - assert!(!body.contains('\r'), "no carriage return survives into the card: got {body:?}"); - assert!( - body.contains("module wide (\n input logic a\n);\n wire w0;"), - "the lines read as written, joined with plain newlines: got {body:?}" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Angle 2: multi-byte UTF-8 content earlier in the same file (and on the - /// same line, before the declaration) must not panic `span_text` or - /// `whole_lines`. Both are `.get()`-based, so this is a belt-and-braces - /// regression pin rather than a discovered defect. - #[test] - fn multibyte_utf8_before_the_declaration_does_not_panic() { - // The identifier itself must stay ASCII (SV identifiers are), but the - // comment above it — which the widened whole-line span never reaches, - // yet whose byte length shifts every offset after it — is not. - let sub = - "// 世界 comment — üñïçødé\nmodule sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, ws, uri) = included("utf8decl", &[("sub.sv", sub), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - assert!(body.contains("input logic [7:0] addr"), "got {body}"); - assert!(!body.contains("世界"), "only the declaration's own line: got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - /// Angle 4: exactly `SNIPPET_LINES` lines is not cut (no note, no - /// ellipsis); one more line is. - #[test] - fn exactly_the_line_cap_is_not_cut_one_more_is() { - let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); - // decl_span (module header .. matching paren, widened to whole lines) - // needs to land at exactly SNIPPET_LINES lines for the boundary case; - // instead, directly probe `cut_to_size`, which is what actually owns - // the boundary and is unit-testable without fighting the parser's - // span shape. - let _ = &mut sub; - let five = "a\nb\nc\nd\ne"; - let (text, note) = cut_to_size(five); - assert_eq!(text, "a\nb\nc\nd\ne", "5 lines, unmodified: got {text:?}"); - assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); - - let six = "a\nb\nc\nd\ne\nf"; - let (text6, note6) = cut_to_size(six); - assert_eq!(text6, "a\nb\nc\nd\ne …", "the first 5 lines, `f` dropped: got {text6:?}"); - assert_eq!(note6, Some("*shown to 5 lines*".to_string())); - } - - /// Angle 4: exactly `SNIPPET_CHARS` characters is not cut; one more is, - /// and the cut always lands on a character boundary even when the - /// boundary character is multi-byte. - #[test] - fn exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe() { - let exact = "a".repeat(SNIPPET_CHARS); - let (text, note) = cut_to_size(&exact); - assert_eq!(text.chars().count(), SNIPPET_CHARS); - assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); - - let over = "a".repeat(SNIPPET_CHARS + 1); - let (text2, note2) = cut_to_size(&over); - assert_eq!(text2, format!("{} …", "a".repeat(SNIPPET_CHARS))); - assert!(note2.is_some()); - - // The 400th character itself is multi-byte (3-byte '世'); char-based - // cutting must not split it and must not panic. - let mut mixed = "a".repeat(SNIPPET_CHARS - 1); - mixed.push('世'); - mixed.push_str("bbbb"); - let (text3, note3) = cut_to_size(&mixed); - // 400 kept chars (399 `a`s + the whole `世`, never half of it) plus the - // 2-char " …" suffix — the boundary character survives intact. - assert_eq!(text3.chars().count(), SNIPPET_CHARS + 2, "got {text3:?}"); - assert!(text3.ends_with("世 …"), "the multi-byte char is not split: got {text3:?}"); - assert!(note3.is_some()); - } - - /// Angle 2: the declared name sits at the very start of the file (offset - /// 0), with no character before it — `whole_lines`/`span_text` must not - /// underflow or panic. - #[test] - fn a_declaration_at_the_very_start_of_the_file_is_shown() { - let sub = "sub_pkg_marker foo;\nmodule sub (input logic clk);\nendmodule\n"; - // `foo` at offset 0 is not itself a declaration hover's target here; - // instead exercise the disk path with `def.name_span.start == 0` by - // hovering a module whose file begins with the keyword `module`. - let sub2 = "module sub (input logic clk);\nendmodule\n"; - let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; - let (dir, ws, uri) = included("startdecl", &[("sub.sv", sub2), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); - assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - let _ = sub; - } - - /// Angle 2: the declaration is on the last line of the file, which has no - /// trailing newline. `whole_lines`'s `line_range(last).end` must resolve - /// to the true end of text, not run past it or leave a dangling range. - #[test] - fn a_declaration_on_the_last_line_with_no_trailing_newline_is_shown() { - let sub = "module sub (input logic clk);\nendmodule"; // no trailing \n - let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; - let (dir, ws, uri) = included("notrailingnl", &[("sub.sv", sub), ("top.sv", top)]); - let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); - assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - /// Angle 3: the target file is open under a *different* `Uri` whose path - /// differs only in case from the index's recorded path (macOS/Windows - /// default to a case-insensitive filesystem, so this is the same file on - /// disk). `document_for_path` compares `PathBuf`s with `==`, which is - /// case-sensitive even on a case-insensitive filesystem, so the open - /// buffer is *not* found as "the target file open" and the code falls - /// back to the disk-read path. That fallback is exactly the safe - /// direction — it cannot show unsaved live edits, but it also cannot mix - /// up two differently-cased identities — so this is a documented - /// limitation, not a defect: an unsaved edit in a case-mismatched buffer - /// is invisible to hover until saved. - #[cfg(any(target_os = "macos", target_os = "windows"))] - #[test] - fn a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk() { - let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let (dir, mut ws, uri) = included("casefallback", &[("sub.sv", saved), ("top.sv", top)]); - // Open the same file via an upper-cased path. - let upper = dir.join("SUB.sv"); - let upper_uri = Uri::from_str(&format!("file://{}", upper.display())).expect("uri"); - let edited = "module sub (\n input logic [15:0] addr\n);\nendmodule\n"; - ws.set_document(upper_uri, edited.to_string()); - - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - // Disk (saved) text wins, not the case-mismatched buffer's edit — - // confirms the fallback direction is the safe one. - assert!(body.contains("[7:0] addr"), "got {body}"); - assert!(!body.contains("[15:0]"), "got {body}"); - let _ = fs::remove_dir_all(&dir); - } - - /// Angle 7 (perf smell): the **first** hover resolving into a large - /// *closed* file reads the whole file from disk and builds a fresh - /// `LineIndex` over it. It once did that twice — heading and snippet - /// independently — then once, through a per-hover memo, and since - /// `hover-line-index` (2026-08-28) it does it once *per file per - /// generation of that file*: the heading no longer wants any text at all - /// (`Def::lines`), and the snippet's read is held in - /// `Workspace::file_view` for the next hover. So this number is the first - /// touch, which is the one that still costs; the repeat is measured in - /// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a - /// correctness assertion, just the number; run with `cargo test --release - /// -p lucisv_server large_closed -- --ignored --nocapture` to see it. - #[test] - #[ignore = "perf measurement, not a correctness assertion — see QA log"] - fn hovering_into_a_large_closed_file_reads_it_once() { - let dir = temp_dir("bigfile"); - let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); - for n in 0..600_000 { - sub.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n")); - } - sub.push_str("endmodule\n"); - fs::write(dir.join("sub.sv"), &sub).expect("write"); - let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; - let top_path = dir.join("top.sv"); - fs::write(&top_path, top).expect("write"); - - let mut ws = Workspace::default(); - // The default `maxFileSize` is 1 MiB (`DEFAULT_MAX_FILE_SIZE`); a - // netlist-shaped file this size needs the cap raised or it is never - // indexed at all, which would make this measure nothing. - ws.set_client_settings(crate::settings::ClientSettings { - max_file_size: 100_000_000, - ..Default::default() - }); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top.to_string()); - - let start = std::time::Instant::now(); - let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); - let elapsed = start.elapsed(); - assert!(body.contains("[7:0] addr"), "got {body}"); - let start = std::time::Instant::now(); - let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover"); - let again = start.elapsed(); - eprintln!( - "hover into a {:.1} MB closed file took {:?} the first time (one read + one \ - LineIndex, for the snippet alone) and {:?} the second (nothing read)", - sub.len() as f64 / 1_000_000.0, - elapsed, - again - ); - let _ = fs::remove_dir_all(&dir); - } -} +mod qa_hover_declarations; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hover/qa_findings.rs b/crates/lucisv_server/src/hover/qa_findings.rs new file mode 100644 index 0000000..2e39b47 --- /dev/null +++ b/crates/lucisv_server/src/hover/qa_findings.rs @@ -0,0 +1,101 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::settings::ClientSettings; +use crate::uri::path_to_uri; +use std::fs; + +/// The angled form is correctly wired into the narrowing overlay: not a +/// finding, recorded as a permanent regression test since the six tests +/// the dev shipped in this file only exercise the quoted form. +#[test] +fn an_angled_include_narrows_hover_same_as_a_quoted_one() { + let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_sys_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("inc")).expect("mkdir"); + fs::write(dir.join("inc/uvm_macros.svh"), "`define W 8\n").expect("write"); + fs::write(dir.join("elsewhere.svh"), "`define W 16\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \nmodule top;\n wire [`W-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/uvm_macros.svh\nelsewhere.svh\n") + .expect("write"); + + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + filelist: Some(dir.join("files.f").display().to_string()), + ..Default::default() + }); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); + let body = match &h.contents { + HoverContents::Markup(m) => m.value.clone(), + _ => panic!("markup"), + }; + assert!(body.contains("`define W 8") && body.contains("uvm_macros.svh:1"), "got {body}"); + assert!(!body.contains("`define W 16"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); +} + +/// QA finding (M10, HIGH), fixed 2026-08-25. On a case-insensitive +/// filesystem (the default on macOS — this machine — and on Windows) +/// `Path::is_file` succeeds for a case-mismatched candidate, and +/// `normalize` only folds `.`/`..`, so `IncludeGraph::resolve` used to +/// return the path *as written* in the `` `include ``. `WorkspaceIndex` +/// meanwhile records the file under the case that was read off disk, so +/// the two spellings were different `PathBuf`s and +/// `narrowed_to_the_include_graph`'s `reachable.contains(p)` check +/// silently missed a file that **is** genuinely reachable. +/// +/// Below, `top.sv` includes both `defs.svh` (case-mismatched: the file is +/// `Defs.svh`) and `other.svh` (spelled correctly), and both are equally +/// reachable in truth. Two reachable definitions must fall back to the +/// honest "defined 2 times" answer — the same thing +/// `two_reachable_definitions_are_listed_rather_than_guessed_between` +/// above pins for the case-matched spelling. Before the fix this narrowed +/// to the correctly-cased file alone and showed it with full confidence, +/// which is "may only narrow, never widen" failing in the one direction +/// that matters. `IncludeGraph::as_the_index_spells_it` now re-spells a +/// resolved path to the index's own when exactly one in-scope file +/// matches it case-insensitively. +/// +/// Case-gated: only macOS/Windows default to a case-insensitive +/// filesystem, so only there does the premise (`is_file` succeeding for +/// the wrong case) hold. +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +fn a_case_mismatched_include_still_counts_as_reachable() { + let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_case_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("mkdir"); + fs::write(dir.join("Defs.svh"), "`define W 8\n").expect("write"); + fs::write(dir.join("other.svh"), "`define W 16\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \"defs.svh\"\n`include \"other.svh\"\nmodule top;\n \ + wire [`W-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); + let body = match &h.contents { + HoverContents::Markup(m) => m.value.clone(), + _ => panic!("markup"), + }; + // Both files are reachable, so neither may be dropped and neither may + // be presented as the answer. + assert!(body.contains("is defined 2 times"), "got {body}"); + assert!(body.contains("`define W 8") && body.contains("Defs.svh:1"), "got {body}"); + assert!(body.contains("`define W 16") && body.contains("other.svh:1"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hover/qa_hover_declarations.rs b/crates/lucisv_server/src/hover/qa_hover_declarations.rs new file mode 100644 index 0000000..6b47df4 --- /dev/null +++ b/crates/lucisv_server/src/hover/qa_hover_declarations.rs @@ -0,0 +1,340 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use std::fs; +use std::path::PathBuf; +// Its one user is the case-insensitive-filesystem test below. +#[cfg(any(target_os = "macos", target_os = "windows"))] +use std::str::FromStr; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("lucisv_qa_hoverdecl_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir +} + +/// Angle 1: the disk-path guard slices `def.name_span` — a *fixed-length* +/// byte range, the old name's length, taken when the index was built — +/// and compares it for equality with the hovered name. It never checks +/// what comes immediately *after* that range. So an edit that extends the +/// declared identifier by appending characters (no reindex yet) leaves +/// the first `name.len()` bytes at the old offset still spelling the old +/// name — the guard passes — while the *actual* identifier at that +/// position is now a different, longer one that the file no longer +/// declares under the hovered name at all. +/// +/// This is exactly the "same name at the stale span by coincidence" +/// attack the QA charter asks for, and it succeeds: the card claims to +/// show `addr`'s declaration and instead shows `addr2`'s, with no +/// indication anything is wrong. FINDING (see QA log, MEDIUM): the guard +/// needs a word-boundary check, not just a fixed-length substring match. +#[test] +fn a_disk_edit_that_only_appends_to_the_name_defeats_the_guard() { + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("guardappend", &[("sub.sv", saved), ("top.sv", top)]); + // Same bytes up to and including "addr", then more identifier + // characters glued directly on — the stale span still lines up with + // "addr" as a prefix of the new, longer name. + let corrupted = "module sub (\n input logic [7:0] addr2\n);\nendmodule\n"; + let prefix_len = saved.find("addr").unwrap() + 4; + assert_eq!( + &corrupted[..prefix_len], + &saved[..prefix_len], + "the attack requires the stale span to still land on the same bytes" + ); + fs::write(dir.join("sub.sv"), corrupted).expect("rewrite"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + let shows_wrong_declaration = body.contains("addr2"); + if shows_wrong_declaration { + panic!( + "GUARD DEFEATED: the card for `.addr(...)` shows `addr2`'s line, \ + not `addr`'s (which no longer exists) — got {body:?}" + ); + } +} + +fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top = dir.join("top.sv"); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); + (dir, ws, uri) +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +fn text_of(hover: &Hover) -> String { + match &hover.contents { + HoverContents::Markup(m) => m.value.clone(), + other => panic!("expected markup, got {other:?}"), + } +} + +/// Angle 3: two live declarations of the same port name in an open +/// buffer (a transient state while editing — e.g. mid-refactor before the +/// stale one is deleted). The index still has one persisted `Def` for the +/// name, so `indexed_def_for_symbol` maps *either* live symbol back to +/// it, and `live_symbol`'s `.find()` picks whichever comes first in +/// `Semantics::symbols()` order. +/// +/// Not a wrong-line *lie* — the guard still requires the chosen symbol's +/// own text to spell the name, which it always does by construction — but +/// it is a silent, arbitrary choice between two candidates with no signal +/// to the user that the buffer is ambiguous. This is inherited from +/// `nav.rs`'s pre-existing matcher (unchanged by this round: "one +/// matcher, so hover and go-to-definition can never disagree"), so it is +/// filed as an accepted pre-existing limitation, not a new defect. Pinned +/// here so a future change to the matcher's tie-break is not silent. +#[test] +fn duplicate_live_declarations_of_one_name_pick_the_first_one_silently() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("dupdup", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + // Two ports named `addr`, different widths, in the same scope/kind. + let edited = + "module sub (\n input logic [7:0] addr,\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(sub_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + // Exactly one of the two widths appears — never both, never neither — + // confirming the pick is total but not both fenced blocks are shown. + let has_first = body.contains("[7:0] addr"); + let has_second = body.contains("[15:0] addr"); + assert!(has_first ^ has_second, "expected exactly one candidate shown: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +/// Angle 2 (CRLF): a multi-line snippet from a CRLF file used to keep the +/// `\r` on every line except the last, where `cut_to_size`'s `trim_end` +/// stripped it — an embedded control character in the middle of a fenced +/// block. QA filed it (hover-declarations finding 2, port-detail-spans +/// PDS-4); `attached_lines` now strips the carriage return as it composes +/// each line, so the fence holds `\n`-separated lines whatever the file's +/// line endings are. Display text only: nothing writes to the buffer. +#[test] +fn a_crlf_multiline_snippet_carries_no_carriage_returns() { + // `wide`'s `decl_span` is its whole body (a module, like `PORTS` in + // the dev's own tests), so its live-path snippet spans several CRLF + // lines and is exactly where an interior, un-trimmed `\r` would show. + // Both modules must exist at the *initial* index build — rewriting a + // module name into a file after `open_whole_workspace` without + // reindexing leaves the index not knowing that name, which is a + // workspace-setup mistake, not something this test is probing. + let wide = + "module wide (\r\n input logic a\r\n);\r\n wire w0;\r\n wire w1;\r\nendmodule\r\n"; + let top = "module top;\r\n wide u ();\r\nendmodule\r\n"; + let (dir, mut ws, uri) = included("crlfdecl", &[("wide.sv", wide), ("top.sv", top)]); + let wide_uri = path_to_uri(&dir.join("wide.sv")).expect("uri"); + // Open the target so the live path (which widens `decl_span`, the + // multi-line span) is exercised rather than the disk path. + ws.set_document(wide_uri, wide.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "wide u")).expect("hover")); + assert!(body.contains("module wide ("), "got {body:?}"); + assert!(!body.contains('\r'), "no carriage return survives into the card: got {body:?}"); + assert!( + body.contains("module wide (\n input logic a\n);\n wire w0;"), + "the lines read as written, joined with plain newlines: got {body:?}" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Angle 2: multi-byte UTF-8 content earlier in the same file (and on the +/// same line, before the declaration) must not panic `span_text` or +/// `whole_lines`. Both are `.get()`-based, so this is a belt-and-braces +/// regression pin rather than a discovered defect. +#[test] +fn multibyte_utf8_before_the_declaration_does_not_panic() { + // The identifier itself must stay ASCII (SV identifiers are), but the + // comment above it — which the widened whole-line span never reaches, + // yet whose byte length shifts every offset after it — is not. + let sub = "// 世界 comment — üñïçødé\nmodule sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("utf8decl", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("input logic [7:0] addr"), "got {body}"); + assert!(!body.contains("世界"), "only the declaration's own line: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +/// Angle 4: exactly `SNIPPET_LINES` lines is not cut (no note, no +/// ellipsis); one more line is. +#[test] +fn exactly_the_line_cap_is_not_cut_one_more_is() { + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + // decl_span (module header .. matching paren, widened to whole lines) + // needs to land at exactly SNIPPET_LINES lines for the boundary case; + // instead, directly probe `cut_to_size`, which is what actually owns + // the boundary and is unit-testable without fighting the parser's + // span shape. + let _ = &mut sub; + let five = "a\nb\nc\nd\ne"; + let (text, note) = cut_to_size(five); + assert_eq!(text, "a\nb\nc\nd\ne", "5 lines, unmodified: got {text:?}"); + assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); + + let six = "a\nb\nc\nd\ne\nf"; + let (text6, note6) = cut_to_size(six); + assert_eq!(text6, "a\nb\nc\nd\ne …", "the first 5 lines, `f` dropped: got {text6:?}"); + assert_eq!(note6, Some("*shown to 5 lines*".to_string())); +} + +/// Angle 4: exactly `SNIPPET_CHARS` characters is not cut; one more is, +/// and the cut always lands on a character boundary even when the +/// boundary character is multi-byte. +#[test] +fn exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe() { + let exact = "a".repeat(SNIPPET_CHARS); + let (text, note) = cut_to_size(&exact); + assert_eq!(text.chars().count(), SNIPPET_CHARS); + assert!(note.is_none(), "no note at exactly the cap: got {note:?}"); + + let over = "a".repeat(SNIPPET_CHARS + 1); + let (text2, note2) = cut_to_size(&over); + assert_eq!(text2, format!("{} …", "a".repeat(SNIPPET_CHARS))); + assert!(note2.is_some()); + + // The 400th character itself is multi-byte (3-byte '世'); char-based + // cutting must not split it and must not panic. + let mut mixed = "a".repeat(SNIPPET_CHARS - 1); + mixed.push('世'); + mixed.push_str("bbbb"); + let (text3, note3) = cut_to_size(&mixed); + // 400 kept chars (399 `a`s + the whole `世`, never half of it) plus the + // 2-char " …" suffix — the boundary character survives intact. + assert_eq!(text3.chars().count(), SNIPPET_CHARS + 2, "got {text3:?}"); + assert!(text3.ends_with("世 …"), "the multi-byte char is not split: got {text3:?}"); + assert!(note3.is_some()); +} + +/// Angle 2: the declared name sits at the very start of the file (offset +/// 0), with no character before it — `whole_lines`/`span_text` must not +/// underflow or panic. +#[test] +fn a_declaration_at_the_very_start_of_the_file_is_shown() { + let sub = "sub_pkg_marker foo;\nmodule sub (input logic clk);\nendmodule\n"; + // `foo` at offset 0 is not itself a declaration hover's target here; + // instead exercise the disk path with `def.name_span.start == 0` by + // hovering a module whose file begins with the keyword `module`. + let sub2 = "module sub (input logic clk);\nendmodule\n"; + let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; + let (dir, ws, uri) = included("startdecl", &[("sub.sv", sub2), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + let _ = sub; +} + +/// Angle 2: the declaration is on the last line of the file, which has no +/// trailing newline. `whole_lines`'s `line_range(last).end` must resolve +/// to the true end of text, not run past it or leave a dangling range. +#[test] +fn a_declaration_on_the_last_line_with_no_trailing_newline_is_shown() { + let sub = "module sub (input logic clk);\nendmodule"; // no trailing \n + let top = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; + let (dir, ws, uri) = included("notrailingnl", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +/// Angle 3: the target file is open under a *different* `Uri` whose path +/// differs only in case from the index's recorded path (macOS/Windows +/// default to a case-insensitive filesystem, so this is the same file on +/// disk). `document_for_path` compares `PathBuf`s with `==`, which is +/// case-sensitive even on a case-insensitive filesystem, so the open +/// buffer is *not* found as "the target file open" and the code falls +/// back to the disk-read path. That fallback is exactly the safe +/// direction — it cannot show unsaved live edits, but it also cannot mix +/// up two differently-cased identities — so this is a documented +/// limitation, not a defect: an unsaved edit in a case-mismatched buffer +/// is invisible to hover until saved. +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +fn a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk() { + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, mut ws, uri) = included("casefallback", &[("sub.sv", saved), ("top.sv", top)]); + // Open the same file via an upper-cased path. + let upper = dir.join("SUB.sv"); + let upper_uri = Uri::from_str(&format!("file://{}", upper.display())).expect("uri"); + let edited = "module sub (\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(upper_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + // Disk (saved) text wins, not the case-mismatched buffer's edit — + // confirms the fallback direction is the safe one. + assert!(body.contains("[7:0] addr"), "got {body}"); + assert!(!body.contains("[15:0]"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +/// Angle 7 (perf smell): the **first** hover resolving into a large +/// *closed* file reads the whole file from disk and builds a fresh +/// `LineIndex` over it. It once did that twice — heading and snippet +/// independently — then once, through a per-hover memo, and since +/// `hover-line-index` (2026-08-28) it does it once *per file per +/// generation of that file*: the heading no longer wants any text at all +/// (`Def::lines`), and the snippet's read is held in +/// `Workspace::file_view` for the next hover. So this number is the first +/// touch, which is the one that still costs; the repeat is measured in +/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a +/// correctness assertion, just the number; run with `cargo test --release +/// -p lucisv_server large_closed -- --ignored --nocapture` to see it. +#[test] +#[ignore = "perf measurement, not a correctness assertion — see QA log"] +fn hovering_into_a_large_closed_file_reads_it_once() { + let dir = temp_dir("bigfile"); + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + for n in 0..600_000 { + sub.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n")); + } + sub.push_str("endmodule\n"); + fs::write(dir.join("sub.sv"), &sub).expect("write"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let top_path = dir.join("top.sv"); + fs::write(&top_path, top).expect("write"); + + let mut ws = Workspace::default(); + // The default `maxFileSize` is 1 MiB (`DEFAULT_MAX_FILE_SIZE`); a + // netlist-shaped file this size needs the cap raised or it is never + // indexed at all, which would make this measure nothing. + ws.set_client_settings(crate::settings::ClientSettings { + max_file_size: 100_000_000, + ..Default::default() + }); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + + let start = std::time::Instant::now(); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + let elapsed = start.elapsed(); + assert!(body.contains("[7:0] addr"), "got {body}"); + let start = std::time::Instant::now(); + let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover"); + let again = start.elapsed(); + eprintln!( + "hover into a {:.1} MB closed file took {:?} the first time (one read + one \ + LineIndex, for the snippet alone) and {:?} the second (nothing read)", + sub.len() as f64 / 1_000_000.0, + elapsed, + again + ); + let _ = fs::remove_dir_all(&dir); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/hover/tests.rs b/crates/lucisv_server/src/hover/tests.rs new file mode 100644 index 0000000..732f572 --- /dev/null +++ b/crates/lucisv_server/src/hover/tests.rs @@ -0,0 +1,916 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use std::fs; +use std::path::PathBuf; +use std::str::FromStr; + +fn document(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +fn text_of(hover: &Hover) -> String { + match &hover.contents { + HoverContents::Markup(m) => m.value.clone(), + other => panic!("expected markup, got {other:?}"), + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("lucisv_server_hover_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir +} + +#[test] +fn hovering_a_macro_usage_shows_its_body() { + let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let hover = hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover"); + let body = text_of(&hover); + // The fence tag is load-bearing: it is the language id the extension + // registers its TextMate grammar for, and the only reason a hover card + // renders highlighted. Pinned here so a rename cannot pass silently. + assert!(body.contains("```systemverilog\n`define WIDTH 8\n```"), "got {body}"); +} + +#[test] +fn hovering_a_function_like_macro_shows_its_signature() { + let text = + "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(1, 2);\nendmodule\n"; + let (ws, uri) = document(text); + let hover = hover(&ws, &uri, at(text, "`MAX(1")).expect("hover"); + let body = text_of(&hover); + assert!(body.contains("`define MAX(a, b)"), "got {body}"); + assert!(body.contains("? (a) : (b)"), "got {body}"); +} + +#[test] +fn hovering_a_call_shows_what_it_expands_to_in_one_step() { + let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p, q+1);\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover")); + // The definition stays, and the expansion is added under it — same + // fence tag, since that is what colours a hover card (0.4.1). + assert!(body.contains("```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```")); + assert!( + body.contains("**expands to**\n\n```systemverilog\n((p) > (q+1) ? (p) : (q+1))\n```"), + "got {body}" + ); + assert!(!body.contains("one step:"), "nothing left unexpanded here: got {body}"); +} + +#[test] +fn a_plain_object_like_macro_gets_no_second_section() { + // Its expansion *is* its body, which the card already shows. + let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover")); + assert!(!body.contains("expands to"), "got {body}"); +} + +#[test] +fn an_object_like_macro_that_calls_another_shows_where_one_step_stopped() { + let text = "`define BASE 4\n`define W `BASE + 1\nmodule m;\n wire [`W-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "[`W-") + 1).expect("hover")); + assert!(body.contains("**expands to**\n\n```systemverilog\n`BASE + 1\n```"), "got {body}"); + assert!(body.contains("*one step: a nested macro use is left as written*"), "got {body}"); + assert!(!body.contains("`define BASE 4"), "one step, not two: got {body}"); +} + +#[test] +fn a_call_whose_argument_count_is_wrong_keeps_todays_card_and_guesses_nothing() { + let text = + "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p);\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover")); + assert!(body.contains("`define MAX(a, b)"), "the card is unchanged: got {body}"); + assert!(!body.contains("expands to"), "got {body}"); +} + +#[test] +fn an_argument_may_carry_commas_and_strings_of_its_own() { + let text = "`define SHOW(a, b) $display(a, b)\nmodule m;\n initial `SHOW(\"x, y\", f(1, 2));\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "`SHOW(\"")).expect("hover")); + assert!( + body.contains("```systemverilog\n$display(\"x, y\", f(1, 2))\n```"), + "the commas inside the string and the call did not split it: got {body}" + ); +} + +#[test] +fn a_long_body_is_truncated_with_a_note() { + let filler = "z".repeat(crate::expand::CAP + 100); + let text = format!("`define BIG(a) a + {filler}\nmodule m;\n wire x = `BIG(1);\nendmodule\n"); + let (ws, uri) = document(&text); + let body = text_of(&hover(&ws, &uri, at(&text, "`BIG(1")).expect("hover")); + assert!(body.contains(" …\n```"), "cut with an ellipsis: got {}", &body[..200.min(body.len())]); + assert!( + body.contains(&format!("*truncated at {} characters*", crate::expand::CAP)), + "and says so" + ); +} + +#[test] +fn the_expansion_follows_the_definition_the_card_narrowed_to() { + // M10's include narrowing picks `a.svh`; the expansion must be that + // definition's, not the other file's. + let text = "`include \"a.svh\"\nmodule top;\n wire x = `M(7);\nendmodule\n"; + let (dir, ws, uri) = included( + "expandreach", + &[("a.svh", "`define M(x) x + 1\n"), ("b.svh", "`define M(x) x + 2\n"), ("top.sv", text)], + ); + let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover")); + assert!(body.contains("a.svh:1"), "got {body}"); + assert!(body.contains("**expands to**\n\n```systemverilog\n7 + 1\n```"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn several_candidate_definitions_expand_nothing() { + let text = "module top;\n wire x = `M(7);\nendmodule\n"; + let (dir, ws, uri) = included( + "expandambiguous", + &[("a.svh", "`define M(x) x + 1\n"), ("b.svh", "`define M(x) x + 2\n"), ("top.sv", text)], + ); + let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover")); + assert!(body.contains("is defined 2 times"), "got {body}"); + assert!(!body.contains("expands to"), "no winner to expand: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_undefined_macro_says_so_rather_than_returning_nothing() { + let text = "module m;\n wire x = `NOPE;\nendmodule\n"; + let (ws, uri) = document(text); + let hover = hover(&ws, &uri, at(text, "`NOPE")).expect("hover"); + assert!(text_of(&hover).contains("no definition found")); +} + +#[test] +fn a_workspace_define_is_found_when_this_file_does_not_define_it() { + let dir = temp_dir("define"); + fs::write(dir.join("defs.svh"), "`define WIDTH 8\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n wire [`WIDTH-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let hover = hover(&ws, &uri, at(top_text, "`WIDTH")).expect("hover"); + let body = text_of(&hover); + assert!(body.contains("`define WIDTH 8"), "got {body}"); + assert!(body.contains("defs.svh:1"), "the file and line: got {body}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn several_workspace_definitions_are_all_listed() { + let dir = temp_dir("dupdefine"); + fs::write(dir.join("a.svh"), "`define W 8\n").expect("write"); + fs::write(dir.join("b.svh"), "`define W 16\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n wire [`W-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top_text, "`W-")).expect("hover")); + assert!(body.contains("is defined 2 times"), "got {body}"); + assert!(body.contains("`define W 8"), "got {body}"); + assert!(body.contains("`define W 16"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); +} + +/// A workspace whose files are `files`, with `top.sv` opened. +fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top = dir.join("top.sv"); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); + (dir, ws, uri) +} + +/// A `top.sv` using `` `W ``, with whatever include lines precede it. +fn top_using_w(includes: &str) -> String { + format!("{includes}module top;\n wire [`W-1:0] a;\nendmodule\n") +} + +#[test] +fn one_hop_of_include_picks_the_definition_the_file_actually_reaches() { + // Two files define `W`; only one of them is included. Before the + // include graph this hover listed both and refused to choose. + let (dir, ws, uri) = included( + "reach1", + &[ + ("a.svh", "`define W 8\n"), + ("b.svh", "`define W 16\n"), + ("top.sv", &top_using_w("`include \"a.svh\"\n")), + ], + ); + let body = + text_of(&hover(&ws, &uri, at(&top_using_w("`include \"a.svh\"\n"), "`W-")).expect("hover")); + assert!(body.contains("`define W 8"), "the reachable one: got {body}"); + assert!(!body.contains("`define W 16"), "and not the other: got {body}"); + assert!(body.contains("a.svh:1"), "named with its origin: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn two_hops_of_include_reach_just_as_far() { + let text = top_using_w("`include \"mid.svh\"\n"); + let (dir, ws, uri) = included( + "reach2", + &[ + ("mid.svh", "`include \"deep.svh\"\n"), + ("deep.svh", "`define W 8\n"), + ("elsewhere.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("deep.svh:1"), "got {body}"); + assert!(!body.contains("`define W 16"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_include_cycle_terminates_and_both_files_stay_reachable() { + let text = top_using_w("`include \"a.svh\"\n"); + let (dir, ws, uri) = included( + "reachcycle", + &[ + ("a.svh", "`include \"b.svh\"\n"), + ("b.svh", "`include \"a.svh\"\n`define W 8\n"), + ("elsewhere.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("b.svh:2"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_definition_nothing_includes_is_still_shown_when_it_is_all_there_is() { + // The fallback that must not regress: an unreachable definition is + // better than none, and a project that does not use `` `include`` at + // all sees exactly what it saw before this feature. + let text = top_using_w(""); + let (dir, ws, uri) = included("reachnone", &[("far.svh", "`define W 8\n"), ("top.sv", &text)]); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("far.svh:1"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn two_definitions_neither_of_them_reachable_are_still_both_listed() { + let text = top_using_w("`include \"empty.svh\"\n"); + let (dir, ws, uri) = included( + "reachambiguous", + &[ + ("empty.svh", "// nothing here\n"), + ("a.svh", "`define W 8\n"), + ("b.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("is defined 2 times"), "the honest answer: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn two_reachable_definitions_are_listed_rather_than_guessed_between() { + // The graph orders nothing here — both files are included — so the + // all-candidates answer stands. + let text = top_using_w("`include \"a.svh\"\n`include \"b.svh\"\n"); + let (dir, ws, uri) = included( + "reachboth", + &[("a.svh", "`define W 8\n"), ("b.svh", "`define W 16\n"), ("top.sv", &text)], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("is defined 2 times"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn hovering_a_use_shows_its_declaration() { + let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "[WIDTH") + 1).expect("hover")); + // The heading says what the source says. Since 2026-09-02 a + // `localparam` is its own kind, so the label and the snippet below it + // in the same card no longer disagree. + assert!(body.contains("**localparam**"), "got {body}"); + // Fenced with the grammar's language id — see the macro hover test. + assert!( + body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), + "the decl snippet: got {body}" + ); +} + +// ------------------------------------------------------------------ +// non-ANSI split ports: two sections, each with its comment +// ------------------------------------------------------------------ + +const SPLIT: &str = "\ +module alu ( + // the operand + data_in, + result // the result +); + +input signed [31:0] data_in; // 32-bit operand A +output reg [63:0] result; +endmodule +"; + +#[test] +fn a_split_port_hovers_as_two_sections_with_their_comments() { + // The same card from both places the port is declared: the header + // name and the body declaration. + let (ws, uri) = document(SPLIT); + for needle in ["data_in,", "data_in;"] { + let body = text_of(&hover(&ws, &uri, at(SPLIT, needle)).expect("hover")); + assert!(body.contains("**port** `data_in`"), "the heading: {needle:?} -> {body}"); + // Section one: the header, with the comment-only line above it. + assert!( + body.contains("```systemverilog\n // the operand\n data_in,\n```"), + "the header section, comment attached: {needle:?} -> {body}" + ); + // Section two: the body declaration, with its same-line comment. + assert!( + body.contains( + "```systemverilog\ninput signed [31:0] data_in; // 32-bit operand A\n```" + ), + "the detail section, comment included: {needle:?} -> {body}" + ); + // Two sections, not one merged block: two fences for one card. + assert!( + body.matches("```systemverilog").count() >= 2, + "two fenced sections: {needle:?} -> {body}" + ); + } +} + +#[test] +fn a_comments_below_a_declaration_attach_only_when_no_port_follows_them() { + // Below-comments attach when only the closer follows them (nothing + // else could they document)… + let below = "module alu (data_in);\ninput [7:0] data_in;\n// the operand\nendmodule\n"; + let (ws, uri) = document(below); + let body = text_of(&hover(&ws, &uri, at(below, "data_in;")).expect("hover")); + assert!( + body.contains("input [7:0] data_in;\n// the operand"), + "a comment under the last declaration is attached: got {body}" + ); + + // …but a comment block sitting just above the *next* port's + // declaration is that port's leading comment, not this one's. + let stolen = "module alu (data_in, result);\ninput [7:0] data_in;\n// about result\noutput result;\nendmodule\n"; + let (ws, uri) = document(stolen); + let body = text_of(&hover(&ws, &uri, at(stolen, "data_in,")).expect("hover")); + assert!( + !body.contains("// about result"), + "the next port's leading comment is not stolen: got {body}" + ); + // …and it does reach the port it documents. + let body = text_of(&hover(&ws, &uri, at(stolen, "result;") + 1).expect("hover")); + assert!(body.contains("// about result"), "attached to its own port: got {body}"); +} + +#[test] +fn an_old_style_task_argument_hovers_as_two_sections_too() { + // QA, PDS-3: a task or function argument named in the header and + // finished in the body is the same split shape a module port is, and + // now gets the same two-section card. + let text = "\ +module m; + // the operand + task t(a); + input [7:0] a; // 8 bits wide + $display(a); + endtask +endmodule +"; + let (ws, uri) = document(text); + for needle in ["a);", "a; //"] { + let body = text_of(&hover(&ws, &uri, at(text, needle)).expect("hover")); + assert!( + body.contains("```systemverilog\n // the operand\n task t(a);\n```"), + "the header section: {needle:?} -> {body}" + ); + assert!( + body.contains("```systemverilog\n input [7:0] a; // 8 bits wide\n```"), + "the body declaration's section: {needle:?} -> {body}" + ); + } +} + +#[test] +fn a_wrapped_next_declaration_keeps_its_own_leading_comment() { + // QA, PDS-1: the guard used to ask whether the line after a + // below-comment carried an identifier the port grammar could not + // account for. A declaration that *wraps*, with its direction keyword + // alone on the first line, carries no such identifier there — so the + // guard read "no other port here" and handed `result`'s comment to + // `data_in`. Only a line positively recognised as a closer may let a + // comment through now. + let wrapped = "\ +module alu (data_in, result); +input [7:0] data_in; +// about result +input + [7:0] result; +endmodule +"; + let (ws, uri) = document(wrapped); + let body = text_of(&hover(&ws, &uri, at(wrapped, "data_in;")).expect("hover")); + assert!( + !body.contains("// about result"), + "a wrapped next declaration's comment is not stolen: got {body}" + ); + // …and it reaches the port it was written for, above its own lines. + let body = text_of(&hover(&ws, &uri, at(wrapped, "result;")).expect("hover")); + assert!( + body.contains("// about result\ninput\n [7:0] result;"), + "attached above the wrapped declaration it documents: got {body}" + ); +} + +#[test] +fn a_wrapped_declaration_keeps_the_comment_below_it() { + // The other half of PDS-1: a wrapped declaration that really is the + // last one still takes the comment under it, because what follows the + // comment is a closer. + let text = "\ +module alu (data_in); +input + [7:0] data_in; +// the operand +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); + assert!( + body.contains("input\n [7:0] data_in;\n// the operand"), + "the last, wrapped declaration takes the comment below it: got {body}" + ); +} + +#[test] +fn a_declaration_shows_the_comments_above_beside_and_below_it_at_once() { + // The owner's rule reads the three sources independently: same line, + // above, below. QA, PDS-2 — the implementation used to run a priority + // chain, so an above-comment or a trailing one silently suppressed + // the block below even when nothing else could claim it. + let text = "\ +module alu (data_in); +// above +input [7:0] data_in; // beside +// below +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in;")).expect("hover")); + assert!( + body.contains("// above\ninput [7:0] data_in; // beside\n// below"), + "all three comments, in source order: got {body}" + ); +} + +#[test] +fn a_header_port_shows_the_comments_above_and_below_it_at_once() { + // PDS-2's own repros, both in one header: an above-comment (repro 1) + // and a same-line trailing comment (repro 2) each used to suppress + // the block below, which only `);` follows. + let text = "\ +module alu ( + // above + data_in, // beside + // below + result +); +input [7:0] data_in; +input result; +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in,")).expect("hover")); + // `result` follows the block, so it is `result`'s comment, not this + // port's — the guard stays exactly as strict as it was. + assert!(!body.contains("// below"), "another port's comment is not stolen: got {body}"); + assert!( + body.contains(" // above\n data_in, // beside"), + "above and beside both attach: got {body}" + ); + + // With nothing but the closer after it, the same block does attach. + let last = "\ +module alu ( + // above + data_in // beside + // below +); +input [7:0] data_in; +endmodule +"; + let (ws, uri) = document(last); + let body = text_of(&hover(&ws, &uri, at(last, "data_in ")).expect("hover")); + assert!( + body.contains(" // above\n data_in // beside\n // below"), + "all three attach when only the closer follows: got {body}" + ); +} + +#[test] +fn the_line_above_a_header_port_does_not_leak_its_trailing_comment() { + // `result, // the result` above `data_in`'s own line: the line above + // carries another port, so its trailing comment stays result's. + let text = "\ +module alu ( + result, // the result + data_in +); +input [7:0] data_in; +endmodule +"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "data_in\n")).expect("hover")); + assert!(!body.contains("the result"), "not the port above's comment: got {body}"); +} + +#[test] +fn a_cross_file_split_port_shows_both_sections() { + let sub = + "module sub (\n addr,\n ready\n);\ninput logic [15:0] addr;\noutput ready;\nendmodule\n"; + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("splitx", &[("sub.sv", sub), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + body.contains("```systemverilog\n addr,\n```"), + "the header section, from the index's spans: got {body}" + ); + assert!( + body.contains("```systemverilog\ninput logic [15:0] addr;\n```"), + "the detail section, from the index's detail span: got {body}" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn hovering_a_declaration_shows_its_own_info() { + let text = "module top;\n wire a;\nendmodule\n"; + let (ws, uri) = document(text); + let body = text_of(&hover(&ws, &uri, at(text, "top")).expect("hover")); + assert!(body.contains("**module** `top`"), "got {body}"); +} + +#[test] +fn hovering_a_cross_file_module_names_its_file() { + let dir = temp_dir("xhover"); + fs::write(dir.join("sub.sv"), "module sub (input clk);\nendmodule\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n sub u (.clk(1'b0));\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top_text, "sub u")).expect("hover")); + assert!(body.contains("**module**"), "got {body}"); + assert!(body.contains("sub.sv:1"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// the declaration behind a cross-file answer +// ------------------------------------------------------------------ + +const PORTS: &str = + "module sub (\n input logic [7:0] addr,\n output logic ready\n);\nendmodule\n"; + +#[test] +fn a_cross_file_port_connection_shows_the_ports_own_declaration_line() { + // The ask this round answers: direction, type and width, not just a + // file and a line. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("portdecl", &[("sub.sv", PORTS), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in `sub.sv:2`"), "the heading stays: got {body}"); + assert!( + body.contains("```systemverilog\n input logic [7:0] addr,\n```"), + "the declaration itself: got {body}" + ); + assert!(!body.contains("output logic ready"), "only its own line: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_cross_file_module_instance_shows_its_header_line() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("moduledecl", &[("sub.sv", PORTS), ("top.sv", top)]); + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("**module** — declared in `sub.sv:1`"), "got {body}"); + assert!(body.contains("```systemverilog\nmodule sub (\n```"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() { + // The round's central claim: `file:line` for an indexed declaration is + // `Def::lines`, recorded when the file was scanned, so the heading + // costs no read at all. Proved by removing the file from under the + // index — a heading that still names the line cannot have read it. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]); + fs::remove_file(dir.join("sub.sv")).expect("remove"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}"); + // The snippet is the half that really wanted the text, and it is + // dropped rather than guessed at — exactly as it always was for a + // file that cannot be read. + assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_second_hover_into_one_closed_file_reads_nothing() { + // The other half: the snippet's read is shared through + // `Workspace::file_view`, so the file is read once and the next hover + // into it — the same card, or another name in the same file — is + // served from what that read left behind. Observed the only honest + // way: rewrite the file behind the server's back and require the + // second card to be the first one. Stale text can only ever *omit* a + // snippet (the `spells_exactly` guard), never show a wrong line. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]); + let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(first.contains("input logic [7:0] addr"), "premise: got {first}"); + + fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n") + .expect("write"); + let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert_eq!(second, first, "the second hover did not read the file again"); + let _ = fs::remove_dir_all(&dir); +} + +/// QA (2026-08-28): the staleness window the README's Assumptions section +/// claims — "a line is a fact about the same snapshot the span is... where +/// the file has changed on disk with nothing telling the server, both are +/// stale together" — reproduced rather than taken on faith, and in the +/// one shape that could actually disagree: the index was built from the +/// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`, +/// no watcher event, no `update_one`/`rebuild_index` call, so the index is +/// never told — **before the view cache ever reads it**, so the first +/// hover's disk read sees the *new* bytes under the *old* span and offset. +/// The heading must still show the line the index recorded at the last +/// scan (stale, not a fresh-read line the index never computed), and the +/// snippet, reading the genuinely current text, must find the old span no +/// longer spells `addr` there and drop itself via `spells_exactly` rather +/// than show whatever now sits at that byte range. +#[test] +fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() { + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]); + + // Edited behind the server's back, before any hover has read this + // file at all: four lines inserted above the module, so `addr`'s true + // line is now 6 — and the byte offset the index still holds for it + // (from the *original* `sub.sv`) now lands inside a comment, not + // `addr`. The view cache is empty for this path, so the hover below + // is a genuinely fresh disk read of the edited bytes. + fs::write( + dir.join("sub.sv"), + "// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\ + \x20 output logic ready\n);\nendmodule\n", + ) + .expect("write"); + + let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + after.contains("**port** — declared in `sub.sv:2`"), + "the heading must show the line the index recorded, not the file's true current \ + line (6), until something reindexes it: got {after}" + ); + assert!( + !after.contains("```systemverilog"), + "the snippet must be dropped, not show the comment the stale span now lands on: \ + got {after}" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_package_member_shows_its_declaration_line() { + let pkg = "package p;\n localparam WIDTH = 8;\n typedef logic [3:0] nibble_t;\nendpackage\n"; + let top = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\n nibble_t n;\nendmodule\n"; + let (dir, ws, uri) = included("pkgdecl", &[("p.sv", pkg), ("top.sv", top)]); + + let body = text_of(&hover(&ws, &uri, at(top, "WIDTH-1")).expect("hover")); + assert!(body.contains("**localparam** — declared in `p.sv:2`"), "got {body}"); + assert!(body.contains("```systemverilog\n localparam WIDTH = 8;\n```"), "got {body}"); + + let body = text_of(&hover(&ws, &uri, at(top, "nibble_t n")).expect("hover")); + assert!( + body.contains("```systemverilog\n typedef logic [3:0] nibble_t;\n```"), + "a typedef reads the same way: got {body}" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span() { + // The index's span is against the last *saved* text. Reading it out of + // the open buffer would print whatever the shifted offsets now cover. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("livemove", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + let edited = + "// two lines\n// pushed it down\nmodule sub (\n input logic [15:0] addr\n);\nendmodule\n"; + ws.set_document(sub_uri, edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!( + body.contains("```systemverilog\n input logic [15:0] addr\n```"), + "the live line, width and all: got {body}" + ); + assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +/// TODO §64.1. The same live-span read for a declaration only a +/// **hierarchical** path can reach — a module's internal net, named from +/// another file as `u_leaf.sig`. +/// +/// `declaration_snippet` reaches it through `live_symbol` → +/// `nav::indexed_def_for_symbol`, which asked `WorkspaceIndex::member` +/// (the *connection* surface) until §64.1 and so mapped no live symbol +/// back to this `Def` at all: the card came out with its heading and no +/// fence, on a file that was open and perfectly readable. It now shows the +/// live line, which is the same guarantee the port above gets — and the +/// guard is untouched, so a buffer whose live text no longer declares the +/// name still prints nothing (asserted below). +#[test] +fn a_hierarchical_only_declaration_is_read_at_its_live_span_too() { + let top = "module top;\n leaf u_leaf ();\n wire w;\n assign w = u_leaf.sig;\nendmodule\n"; + let saved = "module leaf;\n logic [7:0] sig;\nendmodule\n"; + let (dir, mut ws, uri) = included("livehier", &[("leaf.sv", saved), ("top.sv", top)]); + let leaf_uri = path_to_uri(&dir.join("leaf.sv")).expect("uri"); + let edited = "// two lines\n// pushed it down\nmodule leaf;\n logic [15:0] sig;\nendmodule\n"; + ws.set_document(leaf_uri.clone(), edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); + assert!( + body.contains("```systemverilog\n logic [15:0] sig;\n```"), + "the live line, width and all: got {body}" + ); + assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); + + // The guard half, on the same shape: the net renamed away in the + // buffer leaves the heading and no fence. + ws.set_document(leaf_uri, "module leaf;\n logic [15:0] renamed;\nendmodule\n".to_string()); + let guarded = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); + assert!(guarded.contains("— declared in"), "today's card, intact: got {guarded}"); + assert!(!guarded.contains("```"), "and no snippet at all: got {guarded}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() { + // The file changed on disk under a live index — a rescan the server has + // not run yet. The recorded span now covers something that is not the + // name, so there is nothing honest to print. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, ws, uri) = included("stalespan", &[("sub.sv", saved), ("top.sv", top)]); + fs::write(dir.join("sub.sv"), format!("// {}\n{saved}", "x".repeat(40))).expect("rewrite"); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in"), "today's card, intact: got {body}"); + assert!(!body.contains("```"), "and no snippet at all: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet() { + // The other half of the guard: the target file is open and its live + // text has renamed the port away, so no live symbol is that indexed + // declaration and nothing may be printed for it. + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let saved = "module sub (\n input logic [7:0] addr\n);\nendmodule\n"; + let (dir, mut ws, uri) = included("livemiss", &[("sub.sv", saved), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + ws.set_document( + sub_uri, + "module sub (\n input logic [7:0] renamed\n);\nendmodule\n".to_string(), + ); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("**port** — declared in"), "got {body}"); + assert!(!body.contains("```"), "got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_very_long_declaration_line_is_cut_with_a_note() { + // Netlist lines have no bound; a hover card does. + let filler = "z".repeat(SNIPPET_CHARS + 100); + let sub = format!("module sub (\n input logic [7:0] addr /* {filler} */\n);\nendmodule\n"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, ws, uri) = included("longline", &[("sub.sv", &sub), ("top.sv", top)]); + + let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover")); + assert!(body.contains("input logic [7:0] addr"), "the useful half survives: got {body}"); + assert!(body.contains(" …\n```"), "cut with an ellipsis"); + assert!(body.contains(&format!("*shown to {SNIPPET_CHARS} characters*")), "and says so"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_declaration_spanning_many_lines_is_cut_at_the_line_limit() { + // A module's `decl_span` is its whole body, which the live path widens + // to — fine for a port, a card-swallowing wall for a big module. + let mut sub = String::from("module sub (\n input logic [7:0] addr\n);\n"); + for n in 0..20 { + sub.push_str(&format!(" wire w{n};\n")); + } + sub.push_str("endmodule\n"); + let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n"; + let (dir, mut ws, uri) = included("longdecl", &[("sub.sv", &sub), ("top.sv", top)]); + let sub_uri = path_to_uri(&dir.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri, sub.clone()); + + let body = text_of(&hover(&ws, &uri, at(top, "sub u")).expect("hover")); + assert!(body.contains("```systemverilog\nmodule sub ("), "got {body}"); + assert!(body.contains(&format!("*shown to {SNIPPET_LINES} lines*")), "got {body}"); + assert!(!body.contains("w19"), "the body is not printed: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn two_files_declaring_one_name_each_get_their_own_snippet() { + let top = "module top;\n dup u (.*);\nendmodule\n"; + let (dir, ws, uri) = included( + "dupdecl", + &[ + ("a.sv", "module dup (input logic a_clk);\nendmodule\n"), + ("b.sv", "module dup (input logic b_clk);\nendmodule\n"), + ("top.sv", top), + ], + ); + let body = text_of(&hover(&ws, &uri, at(top, "dup u")).expect("hover")); + assert!(body.contains("a.sv:1") && body.contains("b.sv:1"), "both candidates: got {body}"); + assert!(body.contains("input logic a_clk"), "got {body}"); + assert!(body.contains("input logic b_clk"), "each with its own line: got {body}"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn hovering_whitespace_returns_nothing() { + let text = "module m;\n\n wire a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(hover(&ws, &uri, at(text, "\n\n") + 1).is_none()); +} + +#[test] +fn a_macro_name_stops_at_its_argument_list() { + let text = "`define M(a) a\nmodule m;\n wire x = `M(1);\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let token = doc.tokens.iter().find(|t| t.is_macro()).expect("a macro usage token"); + assert_eq!(macro_name(token), Some("M")); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index ee1d005..8af18a2 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -969,7 +969,7 @@ mod tests { } #[test] - #[ignore] + #[ignore = "perf probe over corpus/, timing printed not asserted; see the `perf` doc"] fn building_the_graph_over_the_whole_corpus_is_milliseconds() { // The cost this feature adds to every index rebuild. Measured // 2026-08-25: 860 files (119 of which include something), ~6ms diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs index 89364b3..0ca63e9 100644 --- a/crates/lucisv_server/src/index_cache.rs +++ b/crates/lucisv_server/src/index_cache.rs @@ -769,1171 +769,6 @@ fn os_cache_dir() -> Option { mod reuse_tests; #[cfg(test)] -mod tests { - use super::*; - - /// A throwaway directory, removed on drop — the same shape - /// `lucisv_core::cache`'s tests use. - struct TempDir { - path: PathBuf, - } - - impl TempDir { - fn new(tag: &str) -> TempDir { - use std::sync::atomic::{AtomicUsize, Ordering}; - static COUNTER: AtomicUsize = AtomicUsize::new(0); - let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir() - .join(format!("lucisv-index-cache-{}-{tag}-{n}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).expect("create temp dir"); - TempDir { path } - } - - /// A source file on disk, so `render`'s existence check keeps its - /// entry. - fn file(&self, name: &str, text: &str) -> PathBuf { - let path = self.path.join(name); - std::fs::write(&path, text).expect("write file"); - path - } - - fn store_text(&self) -> String { - std::fs::read_to_string(self.path.join(FILE)).expect("read store") - } - } - - impl Drop for TempDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.path); - } - } - - const M: &str = "module m;\n sub u ();\nendmodule\n"; - - fn facts(path: &Path, text: &str) -> FileFacts { - FileFacts::of(path.to_path_buf(), text) - } - - #[test] - fn a_record_written_in_one_session_is_read_in_the_next() { - let dir = TempDir::new("roundtrip"); - let file = dir.file("m.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - assert!(cache.facts_for(&file, M).is_none(), "an empty store answers nothing"); - cache.record(&facts(&file, M), M); - cache.compact(); - - let reopened = IndexCache::open(Some(dir.path.clone())); - assert_eq!(reopened.facts_for(&file, M), Some(facts(&file, M))); - // The content is the whole key: the same path with other bytes is a - // miss, and so is another path. - assert!(reopened.facts_for(&file, "module m; endmodule\n").is_none()); - assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none()); - } - - /// **The R3b tie, both ways.** `facts_now` is the same content key - /// `facts_for` is — a record answers for the bytes it was read off and for - /// no others — and it leaves the scan's own work counters alone. - /// - /// The stale case is the one that matters: a record written from one text - /// must never be handed to a refactoring reading a different text, because - /// the refactoring would index it as that file's facts and edit against an - /// index describing bytes nobody has. - #[test] - fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() { - let dir = TempDir::new("factsnow"); - let file = dir.file("m.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&file, M), M); - cache.compact(); - - let reopened = IndexCache::open(Some(dir.path.clone())); - let before = reopened.work(); - assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes"); - // Every way the bytes can differ, and the wrong path too. - const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n"; - assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served"); - assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's"); - assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short"); - assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's"); - let after = reopened.work(); - assert_eq!( - (after.hits, after.misses, after.decode_ns, after.lookup_ns), - (before.hits, before.misses, before.decode_ns, before.lookup_ns), - "a refactoring's reads are not a scan's work" - ); - // The counted reader, asked the same questions, answers the same way. - assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M)); - assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED)); - } - - #[test] - fn a_record_survives_a_session_that_never_compacted() { - // The crash case: records are written through as they are made, so a - // session that is killed before it can rewrite the store still leaves - // every file it had already parsed in it. - let dir = TempDir::new("crash"); - let first = dir.file("a.sv", M); - let second = dir.file("b.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&first, M), M); - cache.record(&facts(&second, M), M); - drop(cache); // killed here — no compaction - - let reopened = IndexCache::open(Some(dir.path.clone())); - assert!(reopened.facts_for(&first, M).is_some()); - assert!(reopened.facts_for(&second, M).is_some()); - } - - #[test] - fn a_torn_final_record_costs_one_file_and_nothing_else() { - let dir = TempDir::new("torn"); - let good = dir.file("a.sv", M); - let bad = dir.file("b.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&good, M), M); - cache.record(&facts(&bad, M), M); - drop(cache); - - // Cut the store mid-way through its last line, the way a process - // killed inside a write would. - let text = dir.store_text(); - let cut = text.len() - (text.lines().last().expect("a last line").len() / 2); - std::fs::write(dir.path.join(FILE), &text[..cut]).expect("truncate"); - - let reopened = IndexCache::open(Some(dir.path.clone())); - assert!(reopened.facts_for(&good, M).is_some(), "the whole records survive"); - assert!(reopened.facts_for(&bad, M).is_none(), "the torn one is simply gone"); - } - - #[test] - fn a_store_from_another_version_is_dropped_whole_and_replaced() { - let dir = TempDir::new("version"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - let foreign = format!( - "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-one\n{}\n", - line(content_hash(M.as_bytes()), &encoded) - ); - std::fs::write(dir.path.join(FILE), foreign).expect("write"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - assert!(cache.facts_for(&file, M).is_none(), "another version's records are not read"); - // …and the first write of this session replaces the file rather than - // appending under a header nobody can read. - cache.record(&facts(&file, M), M); - let text = dir.store_text(); - assert!(text.starts_with(&header()), "{text}"); - assert!(!text.contains("0.0.0-not-this-one"), "{text}"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); - } - - #[test] - fn a_store_from_any_previous_facts_format_is_dropped_not_misread() { - // Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT` - // and `VERSION` — so the header's format field is the only thing that - // can catch them. Written as a loop rather than against one number so - // it cannot go stale the next time a record grows a field: it was - // pinned at 2 for the `detail_span` bump (QA finding, - // `docs/features/port-detail-spans/README.md`) and would have gone on - // testing 2 forever. - let dir = TempDir::new("factsformats"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - for format in 1..FACTS_FORMAT { - let old_format_store = format!( - "lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n", - line(content_hash(M.as_bytes()), &encoded) - ); - std::fs::write(dir.path.join(FILE), old_format_store).expect("write"); - let cache = IndexCache::open(Some(dir.path.clone())); - assert!( - cache.facts_for(&file, M).is_none(), - "a format-{format} record must not be read as a format-{FACTS_FORMAT} one" - ); - } - - // And the belt to that brace: a record really written in an older - // *layout* — this one is a format-4 record, which is today's minus - // every field `vscode-hierarchy-sidebar` added and minus the declared - // type name `class-member-access` round 2 added (format 5 → 6 changed - // the census, not the layout; 6 → 7 changed both) — does not decode as - // one of today's *even if* something served it past the header. - // Field-shifting is what the length prefixes and the end-of-record - // check exist to make impossible. - let previous = as_a_format_4_record(&encoded); - assert_ne!(previous, encoded, "premise: the fixture has fields to strip"); - assert!( - FileFacts::decode(&previous).is_none(), - "a format-4 record decoded as a format-{FACTS_FORMAT} one: {previous}" - ); - - // Finally, the store is replaced under this build's header rather than - // appended to, and reopening reads the fresh record back. - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&file, M), M); - let text = dir.store_text(); - assert!( - text.starts_with(&header()), - "the store was replaced under this build's header: {text}" - ); - assert!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some(), - "reopening reads the freshly written record back" - ); - } - - /// Today's encoded record, minus everything `FACTS_FORMAT` 5 and 7 added - /// — i.e. exactly what format 4 wrote for the same file. Four additions - /// and all four come out: a declaration's `decl_span`, a file-scope - /// declaration's client positions, an instantiation's per-instance - /// occurrences (format 5), and a declaration's declared type name - /// (format 7). - /// - /// `M` declares exactly one unit, no members, and one instantiation of one - /// instance, so every group's field index can be computed rather than - /// parsed. Highest index first, so removing one strip does not move the - /// others. - fn as_a_format_4_record(encoded: &str) -> String { - let mut fields: Vec<&str> = encoded.split('\t').collect(); - let Some(instantiations) = fields.iter().position(|f| *f == "I") else { - return encoded.to_string(); - }; - // I, count, module, owner (name + two ranges), site range — ten - // fields, then the occurrence count and its one thirteen-field - // occurrence. - fields.drain(instantiations + 10..instantiations + 10 + 1 + 13); - let Some(units) = fields.iter().position(|f| *f == "U") else { - return encoded.to_string(); - }; - // U, count, then name, kind, name_span×2, decl_span×2, detail×2, - // lines×2, type_name, and the unit's two client ranges — four numbers - // each. - let decl_at = units + 2; - fields.drain(decl_at + 11..decl_at + 19); - fields.drain(decl_at + 10..decl_at + 11); - fields.drain(decl_at + 4..decl_at + 6); - fields.join("\t") - } - - #[test] - fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() { - // The one shape `create_new` introduces: a zero-byte store, left by a - // session killed between claiming the file and writing its header (or - // seen for an instant by a second session racing the first). Neither - // "another build's store" nor "ours" — the right move is to write the - // header that is missing and carry on, which is what makes a crashed - // claim cost nothing and a lost race cost nothing. - let dir = TempDir::new("emptyclaim"); - let file = dir.file("m.sv", M); - std::fs::write(dir.path.join(FILE), "").expect("write"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&file, M), M); - let text = dir.store_text(); - assert!(text.starts_with(&header()), "{text}"); - assert_eq!(text.lines().count(), 2, "the header, then the record: {text}"); - assert_eq!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), - Some(facts(&file, M)) - ); - } - - #[test] - fn a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not() { - let dir = TempDir::new("corrupt"); - let good = dir.file("a.sv", M); - let encoded = facts(&good, M).encode().expect("encodes"); - let other = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); - // A whole record whose facts have been altered under an unchanged - // checksum, and one written without a checksum field at all — the two - // shapes a record damaged after it was written takes. - let unchecksummed = format!("{:016x}\t{other}", content_hash(M.as_bytes())); - let mismatched = format!("{:016x}\t{other}\t0000000000000000", content_hash(M.as_bytes())); - for corrupt in [ - "garbage", - "", - "\0\0\0", - "not-hex\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", - // A hash of the wrong width — 16 hex digits, exactly. - "0001\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", - "0000000000000001\t/w/x.sv\tD0\tU0\tM0\tI0", - "0000000000000001", - unchecksummed.as_str(), - mismatched.as_str(), - ] { - let text = format!( - "{}\n{}\n{corrupt}\n", - header(), - line(content_hash(M.as_bytes()), &encoded) - ); - std::fs::write(dir.path.join(FILE), text).expect("write"); - let cache = IndexCache::open(Some(dir.path.clone())); - assert!( - cache.facts_for(&good, M).is_some(), - "one bad record must not cost the good ones: {corrupt:?}" - ); - assert!( - cache.facts_for(Path::new("/w/x.sv"), M).is_none(), - "and the bad record itself is never served: {corrupt:?}" - ); - } - } - - /// A store two files were recorded into and then compacted — this build's - /// header and one line per path in path order, which is what every - /// session after a whole rescan finds on disk. - fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) { - let one = dir.file("a.sv", M); - let two = dir.file("b.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&one, M), M); - cache.record(&facts(&two, M), M); - cache.compact(); - assert_eq!(cache.work().compactions, 1, "premise: the store was written"); - (one, two) - } - - /// The store's bytes and its modification time — "not rewritten" as - /// something a test can see rather than infer. - fn store_stamp(dir: &TempDir) -> (Vec, std::time::SystemTime) { - let path = dir.path.join(FILE); - let bytes = std::fs::read(&path).expect("read store"); - let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime"); - (bytes, stamp) - } - - /// Rewrite the store's record lines, keeping this build's header. - fn rewrite_records(dir: &TempDir, records: &[String]) { - let mut text = header(); - for record in records { - text.push('\n'); - text.push_str(record); - } - text.push('\n'); - std::fs::write(dir.path.join(FILE), text).expect("write store"); - } - - /// The store's record lines, header excluded. - fn records_of(dir: &TempDir) -> Vec { - dir.store_text().lines().skip(1).map(str::to_string).collect() - } - - #[test] - fn a_canonical_store_nothing_appended_to_is_not_rewritten() { - // §P4b (a): a warm session hits the store for every file, appends - // nothing, and would rewrite 44 MiB to produce the same 44 MiB — - // 182 ms of a 1.33 s start. What is on disk is already what `render` - // writes, so the rewrite is skipped and the file is not touched at - // all: not its bytes, not even its modification time. - let dir = TempDir::new("alreadycompact"); - let (one, _) = compacted_store(&dir); - let before = store_stamp(&dir); - - let mut warm = IndexCache::open(Some(dir.path.clone())); - assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads"); - warm.compact(); - - assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical"); - assert_eq!(store_stamp(&dir), before, "so the store was not touched"); - // And what is on disk is still a store: the next session reads it. - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); - } - - #[test] - fn a_record_the_store_already_holds_is_not_appended_again() { - // An open buffer is indexed from its own analysis on *every* scan and - // its record is written through with it, so a warm session would - // append a byte-identical duplicate for each open buffer — which - // costs the store its canonical shape and so owes the next scan a - // whole 44 MiB rewrite. The same record is a no-op; a changed one is - // not (`docs/features/perf5-p4/README.md`, §P4b (a)). - let dir = TempDir::new("repeatrecord"); - let (one, _) = compacted_store(&dir); - let before = store_stamp(&dir); - - let mut warm = IndexCache::open(Some(dir.path.clone())); - warm.record(&facts(&one, M), M); - assert_eq!(warm.work().records, 0, "nothing was appended"); - assert_eq!(warm.work().repeats, 1, "and the store was already holding it"); - assert_eq!(store_stamp(&dir), before, "so the store on disk did not move"); - warm.compact(); - assert_eq!(warm.work().compactions, 0, "which leaves it canonical"); - assert_eq!(store_stamp(&dir), before); - - // One byte of difference and the record is written exactly as before. - let edited = "module m;\n sub u ();\n wire w;\nendmodule\n"; - warm.record(&facts(&one, edited), edited); - assert_eq!(warm.work().records, 1, "different bytes are a new record"); - assert_eq!(warm.work().repeats, 1); - warm.compact(); - assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again"); - assert_eq!( - IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited), - Some(facts(&one, edited)), - "the newer record is what the next session reads" - ); - } - - #[test] - fn a_store_with_two_lines_for_one_path_is_compacted() { - // The growth bound the skip must not cost: a session that saved a - // file appended a second line for its path, and only a rewrite folds - // the two back into one. - let dir = TempDir::new("dupline"); - let (one, _) = compacted_store(&dir); - let mut records = records_of(&dir); - let repeat = records[0].clone(); - records.push(repeat); - rewrite_records(&dir, &records); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical"); - assert_eq!(records_of(&dir).len(), 2, "one line per path again"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); - } - - #[test] - fn a_store_with_a_line_this_build_cannot_read_is_compacted() { - // A record dropped at load — a torn append, bit rot, a checksum that - // no longer matches — means the file on disk holds a line `render` - // would not write, so the store is not canonical and the rewrite is - // what removes it. - let dir = TempDir::new("droppedline"); - let (one, _) = compacted_store(&dir); - let mut records = records_of(&dir); - records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0)); - rewrite_records(&dir, &records); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical"); - assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); - } - - #[test] - fn a_store_whose_records_are_out_of_path_order_is_compacted() { - // `render` writes paths sorted, so a store that arrives unsorted was - // not written by a compaction of this shape and rewriting it is not a - // no-op — even though every line in it is a good record. - let dir = TempDir::new("unsorted"); - let (one, _) = compacted_store(&dir); - let mut records = records_of(&dir); - records.reverse(); - rewrite_records(&dir, &records); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical"); - let sorted: Vec = records_of(&dir); - assert_eq!(sorted.len(), 2); - assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); - } - - #[test] - fn a_session_that_recorded_one_file_compacts() { - // The moment an append happens the store on disk is no longer the - // store `render` would write — the appended line is out of order at - // best and a second line for its path at worst — so the rewrite is - // owed exactly as it always was. - let dir = TempDir::new("appended"); - let (one, _) = compacted_store(&dir); - let third = dir.file("c.sv", M); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - assert!(cache.facts_for(&one, M).is_some(), "the other two still hit"); - cache.record(&facts(&third, M), M); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite"); - assert_eq!(records_of(&dir).len(), 3); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some()); - } - - #[test] - fn a_store_holding_a_file_that_is_gone_is_compacted() { - // `render` drops an entry whose file no longer exists, so a store - // holding one is not what a rewrite would produce — and the rewrite - // is what prunes it, exactly as before. - let dir = TempDir::new("goneentry"); - let (one, two) = compacted_store(&dir); - std::fs::remove_file(&two).expect("remove"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned"); - assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); - } - - #[test] - fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() { - // The header is the one line the skip may never leave standing: its - // records were dropped at load, so a session that keeps it leaves a - // store nobody can read on disk for ever. - let dir = TempDir::new("foreignheader"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - let foreign = format!( - "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n", - line(content_hash(M.as_bytes()), &encoded) - ); - std::fs::write(dir.path.join(FILE), foreign).expect("write"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.compact(); - - assert_eq!(cache.work().compactions, 1, "another version's header is not canonical"); - let text = dir.store_text(); - assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}"); - } - - #[test] - fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() { - // The line is well-formed as far as the store is concerned — hash, - // then a path, then a checksum that matches the facts as written — - // but the facts themselves are truncated. Nothing may come of it - // except a parse. - let dir = TempDir::new("halfrecord"); - let file = dir.file("m.sv", M); - let half = format!("{}\tD0\tU1", file.display()); - let text = format!("{}\n{}\n", header(), line(content_hash(M.as_bytes()), &half)); - std::fs::write(dir.path.join(FILE), text).expect("write"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none()); - } - - #[test] - fn a_store_from_the_previous_store_format_is_dropped_whole_and_replaced() { - // The checksum field bumped `CACHE_FORMAT` 1 → 2, and the rule at the - // constant is that a store stamped with a number this build does not - // write is not read at all — no error, no half-trust, just a cache - // that starts empty and refills. Written the way format 1 wrote it: - // no checksum field on the record either. - let dir = TempDir::new("oldformat"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - let old = format!( - "lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}\n{:016x}\t{encoded}\n", - content_hash(M.as_bytes()) - ); - std::fs::write(dir.path.join(FILE), old).expect("write"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - assert!(cache.facts_for(&file, M).is_none(), "format 1's records are not read"); - cache.record(&facts(&file, M), M); - let text = dir.store_text(); - assert!(text.starts_with(&header()), "{text}"); - assert_eq!(text.lines().count(), 2, "replaced, not appended to: {text}"); - assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); - } - - #[test] - fn compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone() { - let dir = TempDir::new("compact"); - let kept = dir.file("kept.sv", M); - let gone = dir.file("gone.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - // The same path recorded three times, as a session's worth of saves - // would. - for text in ["module a; endmodule\n", "module b; endmodule\n", M] { - cache.record(&facts(&kept, text), text); - } - cache.record(&facts(&gone, M), M); - assert_eq!(dir.store_text().lines().count(), 5, "the log holds every write"); - - std::fs::remove_file(&gone).expect("remove"); - cache.compact(); - - let text = dir.store_text(); - assert_eq!(text.lines().count(), 2, "header plus one live entry: {text}"); - assert!(text.contains("kept.sv"), "{text}"); - assert!(!text.contains("gone.sv"), "an entry for a file that is gone: {text}"); - // The surviving entry is the *last* one written for that path. - assert_eq!( - IndexCache::open(Some(dir.path.clone())).facts_for(&kept, M), - Some(facts(&kept, M)) - ); - } - - /// QA (2026-08-27), attack surface 1, fixed 2026-08-27: a record whose - /// facts do not match the checksum they were written with is dropped, not - /// served. Before the checksum, `facts_for` verified a record against the - /// *file's* content hash and nothing else, so any line whose hash matched - /// real bytes served whatever facts sat beside it — which is what every - /// accidental way a record can change after it was written looks like: a - /// flipped bit, a torn append two servers interleaved, an editor that - /// rewrote the file. All of those are now misses. - /// - /// The second half of this test is the part that is *not* fixed, on - /// purpose: a forger recomputes the checksum, because it is an FNV-1a and - /// not a keyed MAC. That is the accepted threat model — anything that can - /// write this store can write the source files it describes, and a key - /// stored beside the data it authenticates is theatre. Pinned so nobody - /// mistakes the checksum for a security boundary. - #[test] - fn a_record_whose_facts_do_not_match_their_checksum_is_dropped() { - let dir = TempDir::new("poison"); - let file = dir.file("m.sv", M); - let genuine = facts(&file, M); - // Same path, same hash (of `M`'s real bytes) — but facts that belong - // to text that was never in `M` at all, spliced into a genuine - // record's line under the *genuine* checksum. - let evil_text = "module evil_backdoor;\nendmodule\n"; - let evil = facts(&file, evil_text); - let honest_line = line(content_hash(M.as_bytes()), &genuine.encode().expect("encodes")); - let checksum = honest_line.rsplit('\t').next().expect("a checksum field"); - let tampered = format!( - "{:016x}\t{}\t{checksum}", - content_hash(M.as_bytes()), - evil.encode().expect("encodes") - ); - std::fs::write(dir.path.join(FILE), format!("{}\n{tampered}\n", header())).expect("write"); - assert!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), - "facts that are not the facts the checksum was taken over are not served" - ); - - // …and the honest record beside it is read exactly as before: the - // checksum drops damaged records, it does not make the store fussier - // about whole ones. - std::fs::write(dir.path.join(FILE), format!("{}\n{honest_line}\n", header())) - .expect("write"); - assert_eq!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), - Some(genuine.clone()) - ); - - // The accepted residue: a forger recomputes the checksum, and this - // store has no secret to stop them. Anyone who can write here can - // write `m.sv` itself. - let forged = line(content_hash(M.as_bytes()), &evil.encode().expect("encodes")); - std::fs::write(dir.path.join(FILE), format!("{}\n{forged}\n", header())).expect("write"); - let served = IndexCache::open(Some(dir.path.clone())) - .facts_for(&file, M) - .expect("a deliberately reforged record is still a hit — the threat model says so"); - assert_eq!(served, evil, "the checksum is an accident detector, not a MAC"); - assert_ne!(served, genuine); - } - - /// QA (2026-08-27), crash shapes, fixed 2026-08-27: kill -9 at every byte - /// offset of a real store. Three properties must hold at *every* cut: no - /// panic, nothing served is ever wrong, and — the part that used to fail — - /// a cut costs only the record it landed in. A store holding a multi-byte - /// character (a macro body with non-ASCII text) is what pins the third: - /// `open` used to load with `read_to_string`, which rejects the *whole* - /// buffer when its tail is not valid UTF-8, so a cut inside a multi-byte - /// sequence threw away every intact record before it as well. `open` now - /// reads bytes and validates a line at a time, so the assertion below is - /// exact: past both good lines, both good records survive every single - /// cut. - #[test] - fn truncating_the_store_at_every_byte_offset_costs_only_the_torn_record() { - let dir = TempDir::new("bytetear"); - let a = dir.file("a.sv", M); - let b = dir.file("b.sv", M); - let unicode_text = "`define GREETING \"h\u{e9}llo w\u{f6}rld\"\nmodule m; endmodule\n"; - let c = dir.file("c.sv", unicode_text); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&a, M), M); - cache.record(&facts(&b, M), M); - cache.record(&facts(&c, unicode_text), unicode_text); - cache.compact(); - - let bytes = std::fs::read(dir.path.join(FILE)).expect("read store bytes"); - // Where a.sv's and b.sv's *own* lines end, so a cut past both of them - // is a cut where both records are fully present in the truncated - // bytes — collateral loss past this point is not "the tail was - // torn", it is the whole file being thrown away for a reason that - // has nothing to do with either record. - let text = String::from_utf8(bytes.clone()).expect("the untruncated store is valid UTF-8"); - let b_line_end = { - let mut offset = 0; - let mut end = None; - for line in text.lines() { - offset += line.len() + 1; - if line.contains("b.sv") { - end = Some(offset); - break; - } - } - end.expect("b.sv's line") - }; - let mut lost_everything = 0; - let mut collateral_loss = 0; - let mut mid_character_cuts = 0; - for cut in 1..bytes.len() { - std::fs::write(dir.path.join(FILE), &bytes[..cut]).expect("truncate"); - // Must never panic — the whole point of the exercise. - let reopened = IndexCache::open(Some(dir.path.clone())); - let mut hits = 0; - for (path, text, genuine) in [ - (&a, M, facts(&a, M)), - (&b, M, facts(&b, M)), - (&c, unicode_text, facts(&c, unicode_text)), - ] { - if let Some(served) = reopened.facts_for(path, text) { - hits += 1; - assert_eq!( - served, genuine, - "cut at byte {cut}: served facts must never be wrong" - ); - } - } - if hits == 0 { - lost_everything += 1; - } - if std::str::from_utf8(&bytes[..cut]).is_err() { - mid_character_cuts += 1; - } - if cut >= b_line_end { - // a.sv's and b.sv's lines are both whole inside - // `bytes[..cut]`; the only thing torn is c.sv's. Nothing - // about that tear — including a cut landing deep inside one - // of its multi-byte characters — may cost a record that is - // entirely present. - if hits < 2 { - collateral_loss += 1; - } - assert!( - hits >= 2, - "cut at byte {cut}: both whole records must survive a torn last line, \ - {hits} did" - ); - } - } - eprintln!( - "{lost_everything} of {} truncation points lost every record (all of them before the \ - first whole record); {collateral_loss} lost an already-whole record; \ - {mid_character_cuts} cuts landed inside a multi-byte character", - bytes.len() - 1 - ); - assert!( - mid_character_cuts > 0, - "premise: some cut must land mid-character, or this test proves nothing" - ); - assert_eq!(collateral_loss, 0, "no cut may cost more than the record it landed in"); - } - - /// QA (2026-08-27), "two servers, one store", fixed 2026-08-27: four - /// sessions racing to append their very *first* record now keep all - /// hundred of them. The old `append` truncated whenever its own - /// `header_ok` was false — which is every session's state the moment its - /// workspace is first scanned — so a second cold starter erased the - /// first's already-appended lines, and QA measured 25 of 100 records - /// standing. `claim` replaces that with `File::create_new`: exactly one - /// session creates the store, the rest find its header and append under - /// it, and truncation is left for a header this build cannot read. - /// - /// The count is deterministic, not merely likely. The three shapes a - /// loser can find are the three `settled_header` returns, and none of - /// them drops a byte: `Ours` appends; `Empty` (the winner caught between - /// its `create_new` and its header) appends the identical header line - /// first, which at worst leaves a duplicate header the reader treats as - /// one more malformed record; `Foreign` cannot happen here, because - /// nothing but this build ever writes this directory. Every record and - /// every header goes out in one `write_all` on an `O_APPEND` handle, so - /// no line can land inside another. - #[test] - fn concurrent_first_writers_all_survive_and_none_is_ever_wrong() { - let dir = TempDir::new("concurrent"); - let mut writers = Vec::new(); - for w in 0..4 { - let path = dir.path.clone(); - writers.push(std::thread::spawn(move || { - let mut cache = IndexCache::open(Some(path)); - let mut written = Vec::new(); - for n in 0..25 { - // Long bodies, to widen whatever window a real interleave - // would need. - let body = format!("writer{w}-record{n}-{}", "x".repeat(2000)); - let text = format!("`define BODY \"{body}\"\nmodule m{w}_{n}; endmodule\n"); - let file = PathBuf::from(format!("/w/writer{w}_{n}.sv")); - let f = facts(&file, &text); - cache.record(&f, &text); - written.push((file, text, f)); - } - written - })); - } - let mut all_written = Vec::new(); - for w in writers { - all_written.extend(w.join().expect("writer thread")); - } - - // No compaction: read exactly what four racing append logs left - // behind. - let reopened = IndexCache::open(Some(dir.path.clone())); - let mut survived = 0; - for (path, text, genuine) in &all_written { - if let Some(served) = reopened.facts_for(path, text) { - survived += 1; - assert_eq!( - served, *genuine, - "a served record must never be a mix of two writers' bytes" - ); - } - } - eprintln!( - "{survived} of {} records from 4 racing first-writers survived with no compaction", - all_written.len() - ); - assert_eq!(survived, all_written.len(), "a racing cold start may not cost a record"); - } - - /// QA (2026-08-27): the header comparison is exact-string equality, so - /// pin both directions explicitly — a header this exact build wrote is - /// accepted, and one with anything appended after the version field - /// (a hypothetical future extra column) is rejected wholesale, the same - /// as a wrong version number. There is no forward-compatible "unknown - /// trailing field is ignored" path. - #[test] - fn a_header_with_an_extra_trailing_field_is_rejected_like_any_other_mismatch() { - let dir = TempDir::new("headerextra"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - let text = - format!("{}\textra-field\n{}\n", header(), line(content_hash(M.as_bytes()), &encoded)); - std::fs::write(dir.path.join(FILE), text).expect("write"); - assert!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), - "an extra header field must not be tolerated" - ); - } - - /// QA (2026-08-27): a store file holding two lines for the same path — - /// not two `record()` calls in one session (already covered by - /// `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone`), - /// but two lines actually sitting in the file, the shape a hand-edited - /// or externally concatenated store would take. `open`'s loop inserts - /// into the map in file order, so the *last* line for a path is what - /// answers — pinned directly against the raw file rather than through - /// `record`. - #[test] - fn two_raw_lines_for_the_same_path_in_the_store_file_last_one_wins() { - let dir = TempDir::new("duplicate"); - let file = dir.file("m.sv", "module first; endmodule\n"); - let first = facts(&file, "module first; endmodule\n").encode().expect("encodes"); - let second_text = "module second; endmodule\n"; - let second = facts(&file, second_text).encode().expect("encodes"); - let text = format!( - "{}\n{}\n{}\n", - header(), - line(content_hash(b"module first; endmodule\n"), &first), - line(content_hash(second_text.as_bytes()), &second) - ); - std::fs::write(dir.path.join(FILE), text).expect("write"); - - let cache = IndexCache::open(Some(dir.path.clone())); - assert!( - cache.facts_for(&file, "module first; endmodule\n").is_none(), - "the first line lost" - ); - assert_eq!(cache.facts_for(&file, second_text), Some(facts(&file, second_text))); - } - - /// QA (2026-08-27), crash shapes: a compaction killed between the - /// temp-file write and the rename leaves `index-cache..tmp` - /// sitting next to the real store. It is harmless to correctness — - /// `open` only ever reads the exact name `index-cache`, so a stray - /// `.tmp` file is invisible to it — but nothing anywhere sweeps one up: - /// not `open`, not a later `compact` (which names its own tmp file - /// after *this* process's pid, a name the dead process's leftover will - /// only collide with by pid reuse). A machine whose editor is killed - /// mid-compaction repeatedly accumulates one orphaned file per crash, - /// each up to the size of the whole store. Filed as a minor, - /// unbounded-but-slow disk leak — not a correctness issue. - #[test] - fn an_orphaned_compaction_tmp_file_is_never_swept_up() { - let dir = TempDir::new("orphantmp"); - let file = dir.file("m.sv", M); - // Simulate a previous process's compaction, killed after the write - // but before the rename — a stray tmp file under some pid that is - // not this process's. - let orphan = dir.path.join("index-cache.999999.tmp"); - std::fs::write(&orphan, "leftover from a killed compaction\n").expect("write"); - - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&file, M), M); - cache.compact(); - - assert!(orphan.exists(), "nothing sweeps up a tmp file from another pid"); - // And it did not interfere with the real store either. - assert_eq!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), - Some(facts(&file, M)) - ); - } - - /// QA (2026-08-27), crash shapes: a write failure must never panic and - /// must never corrupt a store that already exists. Simulated with a - /// directory whose owner-write bit is cleared, which — like a full disk - /// — fails any attempt to *create* a file in it. This does not stop an - /// append to an already-open, already-existing file (a directory's - /// write permission gates creating and unlinking entries, not writing - /// through a handle opened before the permission changed, or reopening - /// a file that already exists), so `record` keeps succeeding; `compact` - /// does fail — its temp file is a new directory entry — and does so the - /// documented way: silently, via the `.is_ok()` check, leaving whatever - /// is already on disk in place rather than a half-written store. - #[test] - #[cfg(unix)] - fn a_write_failure_is_silent_and_never_panics_or_leaves_a_half_written_store() { - use std::os::unix::fs::PermissionsExt; - - let dir = TempDir::new("readonly"); - let file = dir.file("m.sv", M); - let mut cache = IndexCache::open(Some(dir.path.clone())); - cache.record(&facts(&file, M), M); - cache.compact(); - - let mut perms = std::fs::metadata(&dir.path).expect("meta").permissions(); - perms.set_mode(0o500); // r-x: no new directory entries, no rename - std::fs::set_permissions(&dir.path, perms).expect("chmod"); - - let second = dir.path.join("second.sv"); - cache.record(&facts(&second, M), M); // must not panic - cache.compact(); // must not panic — its rename cannot land, and must not half-write - - let mut restore = std::fs::metadata(&dir.path).expect("meta").permissions(); - restore.set_mode(0o700); - std::fs::set_permissions(&dir.path, restore).expect("chmod back"); - - // Whatever is left on disk must still be a whole, valid store: the - // header intact and the original entry still readable. `compact`'s - // failed rename must not have left a torn file in `index-cache`'s - // place — only ever in its own tmp name, which `open` never reads. - let reopened = IndexCache::open(Some(dir.path.clone())); - assert_eq!( - reopened.facts_for(&file, M), - Some(facts(&file, M)), - "the original entry must still be readable after the failed compaction" - ); - } - - /// QA fix-round re-verification (2026-08-27): the checksum field itself, - /// corrupted three ways — odd length, wrong-but-right-length (non-hex), - /// and simply absent. None of these may panic, and all three must drop - /// the line rather than serve it. (`a_corrupt_record_is_dropped_and_the_ - /// rest_of_the_store_is_not` already exercises two of these shapes - /// incidentally; this test names them explicitly, one at a time, and - /// checks the good record beside each survives.) - #[test] - fn a_corrupted_checksum_field_drops_the_line_and_never_panics() { - let dir = TempDir::new("checksumshapes"); - let good = dir.file("a.sv", M); - let good_line = line(content_hash(M.as_bytes()), &facts(&good, M).encode().expect("x")); - let victim = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); - let hash = format!("{:016x}", content_hash(M.as_bytes())); - - // Odd length: the genuine checksum with its last hex digit dropped — - // 15 characters, and (`format!("{:015x}", ...)` would not have - // guaranteed this: it is a *minimum* width, not a truncation, so a - // naturally-16-digit value survives it unchanged and the record - // would have decoded as genuinely valid). - let real_checksum = format!("{:016x}", content_hash(victim.as_bytes())); - let odd = format!("{hash}\t{victim}\t{}", &real_checksum[..15]); - // Right length, not hex. - let non_hex = format!("{hash}\t{victim}\tzzzzzzzzzzzzzzzz"); - // Missing entirely: the line ends at the facts with no third field — - // constructed so the facts themselves hold no tab, so `rsplit_once` - // has nothing to split off as a checksum at all. - let missing = format!("{hash}\tjust-one-field-no-tabs-here"); - - for corrupt in [odd.as_str(), non_hex.as_str(), missing.as_str()] { - let text = format!("{}\n{good_line}\n{corrupt}\n", header()); - std::fs::write(dir.path.join(FILE), text).expect("write"); - // Must not panic (the loop itself is the assertion) and must not - // serve the malformed record under any path. - let cache = IndexCache::open(Some(dir.path.clone())); - assert!( - cache.facts_for(&good, M).is_some(), - "a corrupted checksum field must not cost an unrelated good record: {corrupt:?}" - ); - assert!( - cache.facts_for(Path::new("/w/x.sv"), M).is_none(), - "a corrupted checksum field must never itself be served: {corrupt:?}" - ); - } - } - - /// QA fix-round re-verification (2026-08-27): the checksum is over the - /// exact bytes `decode` receives, not over the decoded *value* the bytes - /// happen to produce. Constructed by finding a shape where two distinct - /// byte strings decode to the identical [`FileFacts`] — `u32::parse` - /// accepts a leading zero (`"00"` parses to `0`) even though `encode` - /// never writes one — and confirming that a record whose facts were - /// silently re-spelled that way, but whose checksum is still the - /// *original* bytes' checksum, is dropped rather than "close enough". - /// This is the structural property that makes the checksum sound against - /// any equivalent-but-different-bytes re-escaping, not only against - /// arbitrary tampering: nothing about "decode would agree anyway" - /// excuses a byte mismatch, because the checksum never looks at the - /// decoded value at all. - #[test] - fn a_benign_reencoding_with_the_original_checksum_is_still_dropped() { - let dir = TempDir::new("benignreencode"); - let file = dir.file("m.sv", M); - let encoded = facts(&file, M).encode().expect("encodes"); - // `M` has no `` `define``s, so its D-count field is a lone "0". - let reencoded = encoded.replacen("\tD\t0\t", "\tD\t00\t", 1); - assert_ne!(encoded, reencoded, "premise: the reencoding actually changed a byte"); - assert_eq!( - FileFacts::decode(&reencoded), - FileFacts::decode(&encoded), - "premise: the two byte strings decode to the same facts" - ); - let original_checksum = format!("{:016x}", content_hash(encoded.as_bytes())); - let stale = - format!("{:016x}\t{reencoded}\t{original_checksum}", content_hash(M.as_bytes())); - std::fs::write(dir.path.join(FILE), format!("{}\n{stale}\n", header())).expect("write"); - assert!( - IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), - "the checksum must reject bytes it was not computed over, even when decode would \ - have agreed with the original" - ); - } - - /// QA fix-round re-verification (2026-08-27): the crash shape the - /// `Empty` arm exists for, raced for real rather than constructed as a - /// single sequential write. A store already sitting at zero bytes (a - /// writer that crashed between its `create_new` and its header, exactly - /// as `an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace` - /// sets up) is then found by *two* fresh sessions at once, both of which - /// must decide `Empty` and both write the identical header line — the - /// duplicate-header residue the work log describes, not a corrupted - /// store. Every one of both writers' records must still be readable - /// afterward. - #[test] - fn two_writers_racing_the_empty_arm_leave_a_valid_store() { - let dir = TempDir::new("emptyrace"); - // Simulate the crashed writer: the file exists, and is empty. - std::fs::write(dir.path.join(FILE), "").expect("write"); - - let mut writers = Vec::new(); - for w in 0..2 { - let path = dir.path.clone(); - writers.push(std::thread::spawn(move || { - let mut cache = IndexCache::open(Some(path)); - let file = PathBuf::from(format!("/w/racer{w}.sv")); - let text = format!("module racer{w}; endmodule\n"); - let f = facts(&file, &text); - cache.record(&f, &text); - (file, text, f) - })); - } - let written: Vec<_> = writers.into_iter().map(|w| w.join().expect("thread")).collect(); - - let text = dir.store_text(); - let header_lines = text.lines().filter(|l| *l == header()).count(); - assert!(header_lines >= 1, "the header must be present at least once: {text}"); - // Every non-header line must still be a well-formed, checksummed - // record or the reader's own rejection of it — never a panic, and - // never a line that swallows part of another. - let reopened = IndexCache::open(Some(dir.path.clone())); - for (path, content, genuine) in &written { - assert_eq!( - reopened.facts_for(path, content), - Some(genuine.clone()), - "both racers' records must survive a shared Empty-arm race: {text}" - ); - } - } - - #[test] - fn a_disabled_cache_reads_nothing_and_writes_nothing() { - let dir = TempDir::new("disabled"); - let file = dir.file("m.sv", M); - let mut warm = IndexCache::open(Some(dir.path.clone())); - warm.record(&facts(&file, M), M); - warm.compact(); - let before = dir.store_text(); - - let mut off = IndexCache::disabled(); - assert!(off.facts_for(&file, M).is_none(), "persist: false must not read"); - off.record(&facts(&file, M), M); - off.compact(); - assert_eq!(dir.store_text(), before, "persist: false must not write"); - assert_eq!(off.dir(), None); - } - - #[test] - fn nothing_is_created_until_something_is_recorded() { - let dir = TempDir::new("lazy"); - let nested = dir.path.join("deep/inner"); - let cache = IndexCache::open(Some(nested.clone())); - assert!(!nested.exists(), "opening an empty store creates no directory"); - assert_eq!(cache.dir(), Some(nested.as_path())); - - let file = dir.file("m.sv", M); - let mut cache = IndexCache::open(Some(nested.clone())); - cache.record(&facts(&file, M), M); - assert!(nested.join(FILE).exists(), "the directory is made on demand"); - cache.compact(); - assert_eq!(std::fs::read_to_string(nested.join(".gitignore")).expect("ignore"), "*\n"); - let leftovers: Vec = std::fs::read_dir(&nested) - .expect("read dir") - .filter_map(|entry| entry.ok()) - .map(|entry| entry.file_name().to_string_lossy().into_owned()) - .filter(|name| name.ends_with(".tmp")) - .collect(); - assert!(leftovers.is_empty(), "{leftovers:?}"); - } - - #[test] - fn the_cache_directory_is_the_highest_rung_that_answers() { - let settings = |persist: bool, path: Option<&str>| ClientSettings { - index_persist: persist, - index_cache_path: path.map(str::to_string), - ..ClientSettings::default() - }; - let roots = [PathBuf::from("/w/root"), PathBuf::from("/w/aaa")]; - let storage = Path::new("/storage/ws"); - let filelist = Path::new("/w/project.f"); - - // Rung 1 beats everything, and a relative path hangs off the first - // root — the rule `lucisv.filelist` already uses. - assert_eq!( - cache_dir(&settings(true, Some("/abs/cache")), Some(storage), &roots, Some(filelist)), - Some(PathBuf::from("/abs/cache")) - ); - assert_eq!( - cache_dir(&settings(true, Some(".lucisv_index")), Some(storage), &roots, None), - Some(PathBuf::from("/w/root/.lucisv_index")) - ); - // Rung 2: what the editor said. - assert_eq!( - cache_dir(&settings(true, None), Some(storage), &roots, None), - Some(storage.to_path_buf()) - ); - // Rung 3: the OS directory, keyed by the roots in sorted order — so - // the same two folders opened the other way round is one store. - let os = cache_dir(&settings(true, None), None, &roots, None).expect("an OS cache dir"); - let swapped = - cache_dir(&settings(true, None), None, &[roots[1].clone(), roots[0].clone()], None); - assert_eq!(Some(os.clone()), swapped, "the root order is not part of the identity"); - assert!(os.starts_with(os_cache_dir().expect("an OS cache dir")), "{}", os.display()); - assert!(os.ends_with(workspace_key(&roots, None).expect("a key")), "{}", os.display()); - // A different workspace is a different store. - assert_ne!(Some(os), cache_dir(&settings(true, None), None, &roots[..1], None)); - // A rootless session is keyed by its filelist, and has no store - // without one. - assert!(cache_dir(&settings(true, None), None, &[], Some(filelist)).is_some()); - assert_eq!(cache_dir(&settings(true, None), None, &[], None), None); - // Rung 4: off is off, whatever every other rung says. - assert_eq!( - cache_dir(&settings(false, Some("/abs/cache")), Some(storage), &roots, None), - None - ); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/index_cache/tests.rs b/crates/lucisv_server/src/index_cache/tests.rs new file mode 100644 index 0000000..e465e08 --- /dev/null +++ b/crates/lucisv_server/src/index_cache/tests.rs @@ -0,0 +1,1142 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; + +/// A throwaway directory, removed on drop — the same shape +/// `lucisv_core::cache`'s tests use. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(tag: &str) -> TempDir { + use std::sync::atomic::{AtomicUsize, Ordering}; + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir() + .join(format!("lucisv-index-cache-{}-{tag}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempDir { path } + } + + /// A source file on disk, so `render`'s existence check keeps its + /// entry. + fn file(&self, name: &str, text: &str) -> PathBuf { + let path = self.path.join(name); + std::fs::write(&path, text).expect("write file"); + path + } + + fn store_text(&self) -> String { + std::fs::read_to_string(self.path.join(FILE)).expect("read store") + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +const M: &str = "module m;\n sub u ();\nendmodule\n"; + +fn facts(path: &Path, text: &str) -> FileFacts { + FileFacts::of(path.to_path_buf(), text) +} + +#[test] +fn a_record_written_in_one_session_is_read_in_the_next() { + let dir = TempDir::new("roundtrip"); + let file = dir.file("m.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&file, M).is_none(), "an empty store answers nothing"); + cache.record(&facts(&file, M), M); + cache.compact(); + + let reopened = IndexCache::open(Some(dir.path.clone())); + assert_eq!(reopened.facts_for(&file, M), Some(facts(&file, M))); + // The content is the whole key: the same path with other bytes is a + // miss, and so is another path. + assert!(reopened.facts_for(&file, "module m; endmodule\n").is_none()); + assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none()); +} + +/// **The R3b tie, both ways.** `facts_now` is the same content key +/// `facts_for` is — a record answers for the bytes it was read off and for +/// no others — and it leaves the scan's own work counters alone. +/// +/// The stale case is the one that matters: a record written from one text +/// must never be handed to a refactoring reading a different text, because +/// the refactoring would index it as that file's facts and edit against an +/// index describing bytes nobody has. +#[test] +fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() { + let dir = TempDir::new("factsnow"); + let file = dir.file("m.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&file, M), M); + cache.compact(); + + let reopened = IndexCache::open(Some(dir.path.clone())); + let before = reopened.work(); + assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes"); + // Every way the bytes can differ, and the wrong path too. + const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n"; + assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served"); + assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's"); + assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short"); + assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's"); + let after = reopened.work(); + assert_eq!( + (after.hits, after.misses, after.decode_ns, after.lookup_ns), + (before.hits, before.misses, before.decode_ns, before.lookup_ns), + "a refactoring's reads are not a scan's work" + ); + // The counted reader, asked the same questions, answers the same way. + assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M)); + assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED)); +} + +#[test] +fn a_record_survives_a_session_that_never_compacted() { + // The crash case: records are written through as they are made, so a + // session that is killed before it can rewrite the store still leaves + // every file it had already parsed in it. + let dir = TempDir::new("crash"); + let first = dir.file("a.sv", M); + let second = dir.file("b.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&first, M), M); + cache.record(&facts(&second, M), M); + drop(cache); // killed here — no compaction + + let reopened = IndexCache::open(Some(dir.path.clone())); + assert!(reopened.facts_for(&first, M).is_some()); + assert!(reopened.facts_for(&second, M).is_some()); +} + +#[test] +fn a_torn_final_record_costs_one_file_and_nothing_else() { + let dir = TempDir::new("torn"); + let good = dir.file("a.sv", M); + let bad = dir.file("b.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&good, M), M); + cache.record(&facts(&bad, M), M); + drop(cache); + + // Cut the store mid-way through its last line, the way a process + // killed inside a write would. + let text = dir.store_text(); + let cut = text.len() - (text.lines().last().expect("a last line").len() / 2); + std::fs::write(dir.path.join(FILE), &text[..cut]).expect("truncate"); + + let reopened = IndexCache::open(Some(dir.path.clone())); + assert!(reopened.facts_for(&good, M).is_some(), "the whole records survive"); + assert!(reopened.facts_for(&bad, M).is_none(), "the torn one is simply gone"); +} + +#[test] +fn a_store_from_another_version_is_dropped_whole_and_replaced() { + let dir = TempDir::new("version"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + let foreign = format!( + "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-one\n{}\n", + line(content_hash(M.as_bytes()), &encoded) + ); + std::fs::write(dir.path.join(FILE), foreign).expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&file, M).is_none(), "another version's records are not read"); + // …and the first write of this session replaces the file rather than + // appending under a header nobody can read. + cache.record(&facts(&file, M), M); + let text = dir.store_text(); + assert!(text.starts_with(&header()), "{text}"); + assert!(!text.contains("0.0.0-not-this-one"), "{text}"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); +} + +#[test] +fn a_store_from_any_previous_facts_format_is_dropped_not_misread() { + // Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT` + // and `VERSION` — so the header's format field is the only thing that + // can catch them. Written as a loop rather than against one number so + // it cannot go stale the next time a record grows a field: it was + // pinned at 2 for the `detail_span` bump (QA finding, + // `docs/features/port-detail-spans/README.md`) and would have gone on + // testing 2 forever. + let dir = TempDir::new("factsformats"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + for format in 1..FACTS_FORMAT { + let old_format_store = format!( + "lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n", + line(content_hash(M.as_bytes()), &encoded) + ); + std::fs::write(dir.path.join(FILE), old_format_store).expect("write"); + let cache = IndexCache::open(Some(dir.path.clone())); + assert!( + cache.facts_for(&file, M).is_none(), + "a format-{format} record must not be read as a format-{FACTS_FORMAT} one" + ); + } + + // And the belt to that brace: a record really written in an older + // *layout* — this one is a format-4 record, which is today's minus + // every field `vscode-hierarchy-sidebar` added and minus the declared + // type name `class-member-access` round 2 added (format 5 → 6 changed + // the census, not the layout; 6 → 7 changed both) — does not decode as + // one of today's *even if* something served it past the header. + // Field-shifting is what the length prefixes and the end-of-record + // check exist to make impossible. + let previous = as_a_format_4_record(&encoded); + assert_ne!(previous, encoded, "premise: the fixture has fields to strip"); + assert!( + FileFacts::decode(&previous).is_none(), + "a format-4 record decoded as a format-{FACTS_FORMAT} one: {previous}" + ); + + // Finally, the store is replaced under this build's header rather than + // appended to, and reopening reads the fresh record back. + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&file, M), M); + let text = dir.store_text(); + assert!( + text.starts_with(&header()), + "the store was replaced under this build's header: {text}" + ); + assert!( + IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some(), + "reopening reads the freshly written record back" + ); +} + +/// Today's encoded record, minus everything `FACTS_FORMAT` 5 and 7 added +/// — i.e. exactly what format 4 wrote for the same file. Four additions +/// and all four come out: a declaration's `decl_span`, a file-scope +/// declaration's client positions, an instantiation's per-instance +/// occurrences (format 5), and a declaration's declared type name +/// (format 7). +/// +/// `M` declares exactly one unit, no members, and one instantiation of one +/// instance, so every group's field index can be computed rather than +/// parsed. Highest index first, so removing one strip does not move the +/// others. +fn as_a_format_4_record(encoded: &str) -> String { + let mut fields: Vec<&str> = encoded.split('\t').collect(); + let Some(instantiations) = fields.iter().position(|f| *f == "I") else { + return encoded.to_string(); + }; + // I, count, module, owner (name + two ranges), site range — ten + // fields, then the occurrence count and its one thirteen-field + // occurrence. + fields.drain(instantiations + 10..instantiations + 10 + 1 + 13); + let Some(units) = fields.iter().position(|f| *f == "U") else { + return encoded.to_string(); + }; + // U, count, then name, kind, name_span×2, decl_span×2, detail×2, + // lines×2, type_name, and the unit's two client ranges — four numbers + // each. + let decl_at = units + 2; + fields.drain(decl_at + 11..decl_at + 19); + fields.drain(decl_at + 10..decl_at + 11); + fields.drain(decl_at + 4..decl_at + 6); + fields.join("\t") +} + +#[test] +fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() { + // The one shape `create_new` introduces: a zero-byte store, left by a + // session killed between claiming the file and writing its header (or + // seen for an instant by a second session racing the first). Neither + // "another build's store" nor "ours" — the right move is to write the + // header that is missing and carry on, which is what makes a crashed + // claim cost nothing and a lost race cost nothing. + let dir = TempDir::new("emptyclaim"); + let file = dir.file("m.sv", M); + std::fs::write(dir.path.join(FILE), "").expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&file, M), M); + let text = dir.store_text(); + assert!(text.starts_with(&header()), "{text}"); + assert_eq!(text.lines().count(), 2, "the header, then the record: {text}"); + assert_eq!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(facts(&file, M))); +} + +#[test] +fn a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not() { + let dir = TempDir::new("corrupt"); + let good = dir.file("a.sv", M); + let encoded = facts(&good, M).encode().expect("encodes"); + let other = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); + // A whole record whose facts have been altered under an unchanged + // checksum, and one written without a checksum field at all — the two + // shapes a record damaged after it was written takes. + let unchecksummed = format!("{:016x}\t{other}", content_hash(M.as_bytes())); + let mismatched = format!("{:016x}\t{other}\t0000000000000000", content_hash(M.as_bytes())); + for corrupt in [ + "garbage", + "", + "\0\0\0", + "not-hex\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", + // A hash of the wrong width — 16 hex digits, exactly. + "0001\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", + "0000000000000001\t/w/x.sv\tD0\tU0\tM0\tI0", + "0000000000000001", + unchecksummed.as_str(), + mismatched.as_str(), + ] { + let text = + format!("{}\n{}\n{corrupt}\n", header(), line(content_hash(M.as_bytes()), &encoded)); + std::fs::write(dir.path.join(FILE), text).expect("write"); + let cache = IndexCache::open(Some(dir.path.clone())); + assert!( + cache.facts_for(&good, M).is_some(), + "one bad record must not cost the good ones: {corrupt:?}" + ); + assert!( + cache.facts_for(Path::new("/w/x.sv"), M).is_none(), + "and the bad record itself is never served: {corrupt:?}" + ); + } +} + +/// A store two files were recorded into and then compacted — this build's +/// header and one line per path in path order, which is what every +/// session after a whole rescan finds on disk. +fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) { + let one = dir.file("a.sv", M); + let two = dir.file("b.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&one, M), M); + cache.record(&facts(&two, M), M); + cache.compact(); + assert_eq!(cache.work().compactions, 1, "premise: the store was written"); + (one, two) +} + +/// The store's bytes and its modification time — "not rewritten" as +/// something a test can see rather than infer. +fn store_stamp(dir: &TempDir) -> (Vec, std::time::SystemTime) { + let path = dir.path.join(FILE); + let bytes = std::fs::read(&path).expect("read store"); + let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime"); + (bytes, stamp) +} + +/// Rewrite the store's record lines, keeping this build's header. +fn rewrite_records(dir: &TempDir, records: &[String]) { + let mut text = header(); + for record in records { + text.push('\n'); + text.push_str(record); + } + text.push('\n'); + std::fs::write(dir.path.join(FILE), text).expect("write store"); +} + +/// The store's record lines, header excluded. +fn records_of(dir: &TempDir) -> Vec { + dir.store_text().lines().skip(1).map(str::to_string).collect() +} + +#[test] +fn a_canonical_store_nothing_appended_to_is_not_rewritten() { + // §P4b (a): a warm session hits the store for every file, appends + // nothing, and would rewrite 44 MiB to produce the same 44 MiB — + // 182 ms of a 1.33 s start. What is on disk is already what `render` + // writes, so the rewrite is skipped and the file is not touched at + // all: not its bytes, not even its modification time. + let dir = TempDir::new("alreadycompact"); + let (one, _) = compacted_store(&dir); + let before = store_stamp(&dir); + + let mut warm = IndexCache::open(Some(dir.path.clone())); + assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads"); + warm.compact(); + + assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical"); + assert_eq!(store_stamp(&dir), before, "so the store was not touched"); + // And what is on disk is still a store: the next session reads it. + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); +} + +#[test] +fn a_record_the_store_already_holds_is_not_appended_again() { + // An open buffer is indexed from its own analysis on *every* scan and + // its record is written through with it, so a warm session would + // append a byte-identical duplicate for each open buffer — which + // costs the store its canonical shape and so owes the next scan a + // whole 44 MiB rewrite. The same record is a no-op; a changed one is + // not (`docs/features/perf5-p4/README.md`, §P4b (a)). + let dir = TempDir::new("repeatrecord"); + let (one, _) = compacted_store(&dir); + let before = store_stamp(&dir); + + let mut warm = IndexCache::open(Some(dir.path.clone())); + warm.record(&facts(&one, M), M); + assert_eq!(warm.work().records, 0, "nothing was appended"); + assert_eq!(warm.work().repeats, 1, "and the store was already holding it"); + assert_eq!(store_stamp(&dir), before, "so the store on disk did not move"); + warm.compact(); + assert_eq!(warm.work().compactions, 0, "which leaves it canonical"); + assert_eq!(store_stamp(&dir), before); + + // One byte of difference and the record is written exactly as before. + let edited = "module m;\n sub u ();\n wire w;\nendmodule\n"; + warm.record(&facts(&one, edited), edited); + assert_eq!(warm.work().records, 1, "different bytes are a new record"); + assert_eq!(warm.work().repeats, 1); + warm.compact(); + assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again"); + assert_eq!( + IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited), + Some(facts(&one, edited)), + "the newer record is what the next session reads" + ); +} + +#[test] +fn a_store_with_two_lines_for_one_path_is_compacted() { + // The growth bound the skip must not cost: a session that saved a + // file appended a second line for its path, and only a rewrite folds + // the two back into one. + let dir = TempDir::new("dupline"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + let repeat = records[0].clone(); + records.push(repeat); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical"); + assert_eq!(records_of(&dir).len(), 2, "one line per path again"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); +} + +#[test] +fn a_store_with_a_line_this_build_cannot_read_is_compacted() { + // A record dropped at load — a torn append, bit rot, a checksum that + // no longer matches — means the file on disk holds a line `render` + // would not write, so the store is not canonical and the rewrite is + // what removes it. + let dir = TempDir::new("droppedline"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0)); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical"); + assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); +} + +#[test] +fn a_store_whose_records_are_out_of_path_order_is_compacted() { + // `render` writes paths sorted, so a store that arrives unsorted was + // not written by a compaction of this shape and rewriting it is not a + // no-op — even though every line in it is a good record. + let dir = TempDir::new("unsorted"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + records.reverse(); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical"); + let sorted: Vec = records_of(&dir); + assert_eq!(sorted.len(), 2); + assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); +} + +#[test] +fn a_session_that_recorded_one_file_compacts() { + // The moment an append happens the store on disk is no longer the + // store `render` would write — the appended line is out of order at + // best and a second line for its path at worst — so the rewrite is + // owed exactly as it always was. + let dir = TempDir::new("appended"); + let (one, _) = compacted_store(&dir); + let third = dir.file("c.sv", M); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&one, M).is_some(), "the other two still hit"); + cache.record(&facts(&third, M), M); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite"); + assert_eq!(records_of(&dir).len(), 3); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some()); +} + +#[test] +fn a_store_holding_a_file_that_is_gone_is_compacted() { + // `render` drops an entry whose file no longer exists, so a store + // holding one is not what a rewrite would produce — and the rewrite + // is what prunes it, exactly as before. + let dir = TempDir::new("goneentry"); + let (one, two) = compacted_store(&dir); + std::fs::remove_file(&two).expect("remove"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned"); + assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); +} + +#[test] +fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() { + // The header is the one line the skip may never leave standing: its + // records were dropped at load, so a session that keeps it leaves a + // store nobody can read on disk for ever. + let dir = TempDir::new("foreignheader"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + let foreign = format!( + "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n", + line(content_hash(M.as_bytes()), &encoded) + ); + std::fs::write(dir.path.join(FILE), foreign).expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "another version's header is not canonical"); + let text = dir.store_text(); + assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}"); +} + +#[test] +fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() { + // The line is well-formed as far as the store is concerned — hash, + // then a path, then a checksum that matches the facts as written — + // but the facts themselves are truncated. Nothing may come of it + // except a parse. + let dir = TempDir::new("halfrecord"); + let file = dir.file("m.sv", M); + let half = format!("{}\tD0\tU1", file.display()); + let text = format!("{}\n{}\n", header(), line(content_hash(M.as_bytes()), &half)); + std::fs::write(dir.path.join(FILE), text).expect("write"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none()); +} + +#[test] +fn a_store_from_the_previous_store_format_is_dropped_whole_and_replaced() { + // The checksum field bumped `CACHE_FORMAT` 1 → 2, and the rule at the + // constant is that a store stamped with a number this build does not + // write is not read at all — no error, no half-trust, just a cache + // that starts empty and refills. Written the way format 1 wrote it: + // no checksum field on the record either. + let dir = TempDir::new("oldformat"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + let old = format!( + "lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}\n{:016x}\t{encoded}\n", + content_hash(M.as_bytes()) + ); + std::fs::write(dir.path.join(FILE), old).expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&file, M).is_none(), "format 1's records are not read"); + cache.record(&facts(&file, M), M); + let text = dir.store_text(); + assert!(text.starts_with(&header()), "{text}"); + assert_eq!(text.lines().count(), 2, "replaced, not appended to: {text}"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); +} + +#[test] +fn compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone() { + let dir = TempDir::new("compact"); + let kept = dir.file("kept.sv", M); + let gone = dir.file("gone.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + // The same path recorded three times, as a session's worth of saves + // would. + for text in ["module a; endmodule\n", "module b; endmodule\n", M] { + cache.record(&facts(&kept, text), text); + } + cache.record(&facts(&gone, M), M); + assert_eq!(dir.store_text().lines().count(), 5, "the log holds every write"); + + std::fs::remove_file(&gone).expect("remove"); + cache.compact(); + + let text = dir.store_text(); + assert_eq!(text.lines().count(), 2, "header plus one live entry: {text}"); + assert!(text.contains("kept.sv"), "{text}"); + assert!(!text.contains("gone.sv"), "an entry for a file that is gone: {text}"); + // The surviving entry is the *last* one written for that path. + assert_eq!(IndexCache::open(Some(dir.path.clone())).facts_for(&kept, M), Some(facts(&kept, M))); +} + +/// QA (2026-08-27), attack surface 1, fixed 2026-08-27: a record whose +/// facts do not match the checksum they were written with is dropped, not +/// served. Before the checksum, `facts_for` verified a record against the +/// *file's* content hash and nothing else, so any line whose hash matched +/// real bytes served whatever facts sat beside it — which is what every +/// accidental way a record can change after it was written looks like: a +/// flipped bit, a torn append two servers interleaved, an editor that +/// rewrote the file. All of those are now misses. +/// +/// The second half of this test is the part that is *not* fixed, on +/// purpose: a forger recomputes the checksum, because it is an FNV-1a and +/// not a keyed MAC. That is the accepted threat model — anything that can +/// write this store can write the source files it describes, and a key +/// stored beside the data it authenticates is theatre. Pinned so nobody +/// mistakes the checksum for a security boundary. +#[test] +fn a_record_whose_facts_do_not_match_their_checksum_is_dropped() { + let dir = TempDir::new("poison"); + let file = dir.file("m.sv", M); + let genuine = facts(&file, M); + // Same path, same hash (of `M`'s real bytes) — but facts that belong + // to text that was never in `M` at all, spliced into a genuine + // record's line under the *genuine* checksum. + let evil_text = "module evil_backdoor;\nendmodule\n"; + let evil = facts(&file, evil_text); + let honest_line = line(content_hash(M.as_bytes()), &genuine.encode().expect("encodes")); + let checksum = honest_line.rsplit('\t').next().expect("a checksum field"); + let tampered = format!( + "{:016x}\t{}\t{checksum}", + content_hash(M.as_bytes()), + evil.encode().expect("encodes") + ); + std::fs::write(dir.path.join(FILE), format!("{}\n{tampered}\n", header())).expect("write"); + assert!( + IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), + "facts that are not the facts the checksum was taken over are not served" + ); + + // …and the honest record beside it is read exactly as before: the + // checksum drops damaged records, it does not make the store fussier + // about whole ones. + std::fs::write(dir.path.join(FILE), format!("{}\n{honest_line}\n", header())).expect("write"); + assert_eq!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(genuine.clone())); + + // The accepted residue: a forger recomputes the checksum, and this + // store has no secret to stop them. Anyone who can write here can + // write `m.sv` itself. + let forged = line(content_hash(M.as_bytes()), &evil.encode().expect("encodes")); + std::fs::write(dir.path.join(FILE), format!("{}\n{forged}\n", header())).expect("write"); + let served = IndexCache::open(Some(dir.path.clone())) + .facts_for(&file, M) + .expect("a deliberately reforged record is still a hit — the threat model says so"); + assert_eq!(served, evil, "the checksum is an accident detector, not a MAC"); + assert_ne!(served, genuine); +} + +/// QA (2026-08-27), crash shapes, fixed 2026-08-27: kill -9 at every byte +/// offset of a real store. Three properties must hold at *every* cut: no +/// panic, nothing served is ever wrong, and — the part that used to fail — +/// a cut costs only the record it landed in. A store holding a multi-byte +/// character (a macro body with non-ASCII text) is what pins the third: +/// `open` used to load with `read_to_string`, which rejects the *whole* +/// buffer when its tail is not valid UTF-8, so a cut inside a multi-byte +/// sequence threw away every intact record before it as well. `open` now +/// reads bytes and validates a line at a time, so the assertion below is +/// exact: past both good lines, both good records survive every single +/// cut. +#[test] +fn truncating_the_store_at_every_byte_offset_costs_only_the_torn_record() { + let dir = TempDir::new("bytetear"); + let a = dir.file("a.sv", M); + let b = dir.file("b.sv", M); + let unicode_text = "`define GREETING \"h\u{e9}llo w\u{f6}rld\"\nmodule m; endmodule\n"; + let c = dir.file("c.sv", unicode_text); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&a, M), M); + cache.record(&facts(&b, M), M); + cache.record(&facts(&c, unicode_text), unicode_text); + cache.compact(); + + let bytes = std::fs::read(dir.path.join(FILE)).expect("read store bytes"); + // Where a.sv's and b.sv's *own* lines end, so a cut past both of them + // is a cut where both records are fully present in the truncated + // bytes — collateral loss past this point is not "the tail was + // torn", it is the whole file being thrown away for a reason that + // has nothing to do with either record. + let text = String::from_utf8(bytes.clone()).expect("the untruncated store is valid UTF-8"); + let b_line_end = { + let mut offset = 0; + let mut end = None; + for line in text.lines() { + offset += line.len() + 1; + if line.contains("b.sv") { + end = Some(offset); + break; + } + } + end.expect("b.sv's line") + }; + let mut lost_everything = 0; + let mut collateral_loss = 0; + let mut mid_character_cuts = 0; + for cut in 1..bytes.len() { + std::fs::write(dir.path.join(FILE), &bytes[..cut]).expect("truncate"); + // Must never panic — the whole point of the exercise. + let reopened = IndexCache::open(Some(dir.path.clone())); + let mut hits = 0; + for (path, text, genuine) in [ + (&a, M, facts(&a, M)), + (&b, M, facts(&b, M)), + (&c, unicode_text, facts(&c, unicode_text)), + ] { + if let Some(served) = reopened.facts_for(path, text) { + hits += 1; + assert_eq!(served, genuine, "cut at byte {cut}: served facts must never be wrong"); + } + } + if hits == 0 { + lost_everything += 1; + } + if std::str::from_utf8(&bytes[..cut]).is_err() { + mid_character_cuts += 1; + } + if cut >= b_line_end { + // a.sv's and b.sv's lines are both whole inside + // `bytes[..cut]`; the only thing torn is c.sv's. Nothing + // about that tear — including a cut landing deep inside one + // of its multi-byte characters — may cost a record that is + // entirely present. + if hits < 2 { + collateral_loss += 1; + } + assert!( + hits >= 2, + "cut at byte {cut}: both whole records must survive a torn last line, \ + {hits} did" + ); + } + } + eprintln!( + "{lost_everything} of {} truncation points lost every record (all of them before the \ + first whole record); {collateral_loss} lost an already-whole record; \ + {mid_character_cuts} cuts landed inside a multi-byte character", + bytes.len() - 1 + ); + assert!( + mid_character_cuts > 0, + "premise: some cut must land mid-character, or this test proves nothing" + ); + assert_eq!(collateral_loss, 0, "no cut may cost more than the record it landed in"); +} + +/// QA (2026-08-27), "two servers, one store", fixed 2026-08-27: four +/// sessions racing to append their very *first* record now keep all +/// hundred of them. The old `append` truncated whenever its own +/// `header_ok` was false — which is every session's state the moment its +/// workspace is first scanned — so a second cold starter erased the +/// first's already-appended lines, and QA measured 25 of 100 records +/// standing. `claim` replaces that with `File::create_new`: exactly one +/// session creates the store, the rest find its header and append under +/// it, and truncation is left for a header this build cannot read. +/// +/// The count is deterministic, not merely likely. The three shapes a +/// loser can find are the three `settled_header` returns, and none of +/// them drops a byte: `Ours` appends; `Empty` (the winner caught between +/// its `create_new` and its header) appends the identical header line +/// first, which at worst leaves a duplicate header the reader treats as +/// one more malformed record; `Foreign` cannot happen here, because +/// nothing but this build ever writes this directory. Every record and +/// every header goes out in one `write_all` on an `O_APPEND` handle, so +/// no line can land inside another. +#[test] +fn concurrent_first_writers_all_survive_and_none_is_ever_wrong() { + let dir = TempDir::new("concurrent"); + let mut writers = Vec::new(); + for w in 0..4 { + let path = dir.path.clone(); + writers.push(std::thread::spawn(move || { + let mut cache = IndexCache::open(Some(path)); + let mut written = Vec::new(); + for n in 0..25 { + // Long bodies, to widen whatever window a real interleave + // would need. + let body = format!("writer{w}-record{n}-{}", "x".repeat(2000)); + let text = format!("`define BODY \"{body}\"\nmodule m{w}_{n}; endmodule\n"); + let file = PathBuf::from(format!("/w/writer{w}_{n}.sv")); + let f = facts(&file, &text); + cache.record(&f, &text); + written.push((file, text, f)); + } + written + })); + } + let mut all_written = Vec::new(); + for w in writers { + all_written.extend(w.join().expect("writer thread")); + } + + // No compaction: read exactly what four racing append logs left + // behind. + let reopened = IndexCache::open(Some(dir.path.clone())); + let mut survived = 0; + for (path, text, genuine) in &all_written { + if let Some(served) = reopened.facts_for(path, text) { + survived += 1; + assert_eq!( + served, *genuine, + "a served record must never be a mix of two writers' bytes" + ); + } + } + eprintln!( + "{survived} of {} records from 4 racing first-writers survived with no compaction", + all_written.len() + ); + assert_eq!(survived, all_written.len(), "a racing cold start may not cost a record"); +} + +/// QA (2026-08-27): the header comparison is exact-string equality, so +/// pin both directions explicitly — a header this exact build wrote is +/// accepted, and one with anything appended after the version field +/// (a hypothetical future extra column) is rejected wholesale, the same +/// as a wrong version number. There is no forward-compatible "unknown +/// trailing field is ignored" path. +#[test] +fn a_header_with_an_extra_trailing_field_is_rejected_like_any_other_mismatch() { + let dir = TempDir::new("headerextra"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + let text = + format!("{}\textra-field\n{}\n", header(), line(content_hash(M.as_bytes()), &encoded)); + std::fs::write(dir.path.join(FILE), text).expect("write"); + assert!( + IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), + "an extra header field must not be tolerated" + ); +} + +/// QA (2026-08-27): a store file holding two lines for the same path — +/// not two `record()` calls in one session (already covered by +/// `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone`), +/// but two lines actually sitting in the file, the shape a hand-edited +/// or externally concatenated store would take. `open`'s loop inserts +/// into the map in file order, so the *last* line for a path is what +/// answers — pinned directly against the raw file rather than through +/// `record`. +#[test] +fn two_raw_lines_for_the_same_path_in_the_store_file_last_one_wins() { + let dir = TempDir::new("duplicate"); + let file = dir.file("m.sv", "module first; endmodule\n"); + let first = facts(&file, "module first; endmodule\n").encode().expect("encodes"); + let second_text = "module second; endmodule\n"; + let second = facts(&file, second_text).encode().expect("encodes"); + let text = format!( + "{}\n{}\n{}\n", + header(), + line(content_hash(b"module first; endmodule\n"), &first), + line(content_hash(second_text.as_bytes()), &second) + ); + std::fs::write(dir.path.join(FILE), text).expect("write"); + + let cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&file, "module first; endmodule\n").is_none(), "the first line lost"); + assert_eq!(cache.facts_for(&file, second_text), Some(facts(&file, second_text))); +} + +/// QA (2026-08-27), crash shapes: a compaction killed between the +/// temp-file write and the rename leaves `index-cache..tmp` +/// sitting next to the real store. It is harmless to correctness — +/// `open` only ever reads the exact name `index-cache`, so a stray +/// `.tmp` file is invisible to it — but nothing anywhere sweeps one up: +/// not `open`, not a later `compact` (which names its own tmp file +/// after *this* process's pid, a name the dead process's leftover will +/// only collide with by pid reuse). A machine whose editor is killed +/// mid-compaction repeatedly accumulates one orphaned file per crash, +/// each up to the size of the whole store. Filed as a minor, +/// unbounded-but-slow disk leak — not a correctness issue. +#[test] +fn an_orphaned_compaction_tmp_file_is_never_swept_up() { + let dir = TempDir::new("orphantmp"); + let file = dir.file("m.sv", M); + // Simulate a previous process's compaction, killed after the write + // but before the rename — a stray tmp file under some pid that is + // not this process's. + let orphan = dir.path.join("index-cache.999999.tmp"); + std::fs::write(&orphan, "leftover from a killed compaction\n").expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&file, M), M); + cache.compact(); + + assert!(orphan.exists(), "nothing sweeps up a tmp file from another pid"); + // And it did not interfere with the real store either. + assert_eq!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(facts(&file, M))); +} + +/// QA (2026-08-27), crash shapes: a write failure must never panic and +/// must never corrupt a store that already exists. Simulated with a +/// directory whose owner-write bit is cleared, which — like a full disk +/// — fails any attempt to *create* a file in it. This does not stop an +/// append to an already-open, already-existing file (a directory's +/// write permission gates creating and unlinking entries, not writing +/// through a handle opened before the permission changed, or reopening +/// a file that already exists), so `record` keeps succeeding; `compact` +/// does fail — its temp file is a new directory entry — and does so the +/// documented way: silently, via the `.is_ok()` check, leaving whatever +/// is already on disk in place rather than a half-written store. +#[test] +#[cfg(unix)] +fn a_write_failure_is_silent_and_never_panics_or_leaves_a_half_written_store() { + use std::os::unix::fs::PermissionsExt; + + let dir = TempDir::new("readonly"); + let file = dir.file("m.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&file, M), M); + cache.compact(); + + let mut perms = std::fs::metadata(&dir.path).expect("meta").permissions(); + perms.set_mode(0o500); // r-x: no new directory entries, no rename + std::fs::set_permissions(&dir.path, perms).expect("chmod"); + + let second = dir.path.join("second.sv"); + cache.record(&facts(&second, M), M); // must not panic + cache.compact(); // must not panic — its rename cannot land, and must not half-write + + let mut restore = std::fs::metadata(&dir.path).expect("meta").permissions(); + restore.set_mode(0o700); + std::fs::set_permissions(&dir.path, restore).expect("chmod back"); + + // Whatever is left on disk must still be a whole, valid store: the + // header intact and the original entry still readable. `compact`'s + // failed rename must not have left a torn file in `index-cache`'s + // place — only ever in its own tmp name, which `open` never reads. + let reopened = IndexCache::open(Some(dir.path.clone())); + assert_eq!( + reopened.facts_for(&file, M), + Some(facts(&file, M)), + "the original entry must still be readable after the failed compaction" + ); +} + +/// QA fix-round re-verification (2026-08-27): the checksum field itself, +/// corrupted three ways — odd length, wrong-but-right-length (non-hex), +/// and simply absent. None of these may panic, and all three must drop +/// the line rather than serve it. (`a_corrupt_record_is_dropped_and_the_ +/// rest_of_the_store_is_not` already exercises two of these shapes +/// incidentally; this test names them explicitly, one at a time, and +/// checks the good record beside each survives.) +#[test] +fn a_corrupted_checksum_field_drops_the_line_and_never_panics() { + let dir = TempDir::new("checksumshapes"); + let good = dir.file("a.sv", M); + let good_line = line(content_hash(M.as_bytes()), &facts(&good, M).encode().expect("x")); + let victim = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); + let hash = format!("{:016x}", content_hash(M.as_bytes())); + + // Odd length: the genuine checksum with its last hex digit dropped — + // 15 characters, and (`format!("{:015x}", ...)` would not have + // guaranteed this: it is a *minimum* width, not a truncation, so a + // naturally-16-digit value survives it unchanged and the record + // would have decoded as genuinely valid). + let real_checksum = format!("{:016x}", content_hash(victim.as_bytes())); + let odd = format!("{hash}\t{victim}\t{}", &real_checksum[..15]); + // Right length, not hex. + let non_hex = format!("{hash}\t{victim}\tzzzzzzzzzzzzzzzz"); + // Missing entirely: the line ends at the facts with no third field — + // constructed so the facts themselves hold no tab, so `rsplit_once` + // has nothing to split off as a checksum at all. + let missing = format!("{hash}\tjust-one-field-no-tabs-here"); + + for corrupt in [odd.as_str(), non_hex.as_str(), missing.as_str()] { + let text = format!("{}\n{good_line}\n{corrupt}\n", header()); + std::fs::write(dir.path.join(FILE), text).expect("write"); + // Must not panic (the loop itself is the assertion) and must not + // serve the malformed record under any path. + let cache = IndexCache::open(Some(dir.path.clone())); + assert!( + cache.facts_for(&good, M).is_some(), + "a corrupted checksum field must not cost an unrelated good record: {corrupt:?}" + ); + assert!( + cache.facts_for(Path::new("/w/x.sv"), M).is_none(), + "a corrupted checksum field must never itself be served: {corrupt:?}" + ); + } +} + +/// QA fix-round re-verification (2026-08-27): the checksum is over the +/// exact bytes `decode` receives, not over the decoded *value* the bytes +/// happen to produce. Constructed by finding a shape where two distinct +/// byte strings decode to the identical [`FileFacts`] — `u32::parse` +/// accepts a leading zero (`"00"` parses to `0`) even though `encode` +/// never writes one — and confirming that a record whose facts were +/// silently re-spelled that way, but whose checksum is still the +/// *original* bytes' checksum, is dropped rather than "close enough". +/// This is the structural property that makes the checksum sound against +/// any equivalent-but-different-bytes re-escaping, not only against +/// arbitrary tampering: nothing about "decode would agree anyway" +/// excuses a byte mismatch, because the checksum never looks at the +/// decoded value at all. +#[test] +fn a_benign_reencoding_with_the_original_checksum_is_still_dropped() { + let dir = TempDir::new("benignreencode"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + // `M` has no `` `define``s, so its D-count field is a lone "0". + let reencoded = encoded.replacen("\tD\t0\t", "\tD\t00\t", 1); + assert_ne!(encoded, reencoded, "premise: the reencoding actually changed a byte"); + assert_eq!( + FileFacts::decode(&reencoded), + FileFacts::decode(&encoded), + "premise: the two byte strings decode to the same facts" + ); + let original_checksum = format!("{:016x}", content_hash(encoded.as_bytes())); + let stale = format!("{:016x}\t{reencoded}\t{original_checksum}", content_hash(M.as_bytes())); + std::fs::write(dir.path.join(FILE), format!("{}\n{stale}\n", header())).expect("write"); + assert!( + IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), + "the checksum must reject bytes it was not computed over, even when decode would \ + have agreed with the original" + ); +} + +/// QA fix-round re-verification (2026-08-27): the crash shape the +/// `Empty` arm exists for, raced for real rather than constructed as a +/// single sequential write. A store already sitting at zero bytes (a +/// writer that crashed between its `create_new` and its header, exactly +/// as `an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace` +/// sets up) is then found by *two* fresh sessions at once, both of which +/// must decide `Empty` and both write the identical header line — the +/// duplicate-header residue the work log describes, not a corrupted +/// store. Every one of both writers' records must still be readable +/// afterward. +#[test] +fn two_writers_racing_the_empty_arm_leave_a_valid_store() { + let dir = TempDir::new("emptyrace"); + // Simulate the crashed writer: the file exists, and is empty. + std::fs::write(dir.path.join(FILE), "").expect("write"); + + let mut writers = Vec::new(); + for w in 0..2 { + let path = dir.path.clone(); + writers.push(std::thread::spawn(move || { + let mut cache = IndexCache::open(Some(path)); + let file = PathBuf::from(format!("/w/racer{w}.sv")); + let text = format!("module racer{w}; endmodule\n"); + let f = facts(&file, &text); + cache.record(&f, &text); + (file, text, f) + })); + } + let written: Vec<_> = writers.into_iter().map(|w| w.join().expect("thread")).collect(); + + let text = dir.store_text(); + let header_lines = text.lines().filter(|l| *l == header()).count(); + assert!(header_lines >= 1, "the header must be present at least once: {text}"); + // Every non-header line must still be a well-formed, checksummed + // record or the reader's own rejection of it — never a panic, and + // never a line that swallows part of another. + let reopened = IndexCache::open(Some(dir.path.clone())); + for (path, content, genuine) in &written { + assert_eq!( + reopened.facts_for(path, content), + Some(genuine.clone()), + "both racers' records must survive a shared Empty-arm race: {text}" + ); + } +} + +#[test] +fn a_disabled_cache_reads_nothing_and_writes_nothing() { + let dir = TempDir::new("disabled"); + let file = dir.file("m.sv", M); + let mut warm = IndexCache::open(Some(dir.path.clone())); + warm.record(&facts(&file, M), M); + warm.compact(); + let before = dir.store_text(); + + let mut off = IndexCache::disabled(); + assert!(off.facts_for(&file, M).is_none(), "persist: false must not read"); + off.record(&facts(&file, M), M); + off.compact(); + assert_eq!(dir.store_text(), before, "persist: false must not write"); + assert_eq!(off.dir(), None); +} + +#[test] +fn nothing_is_created_until_something_is_recorded() { + let dir = TempDir::new("lazy"); + let nested = dir.path.join("deep/inner"); + let cache = IndexCache::open(Some(nested.clone())); + assert!(!nested.exists(), "opening an empty store creates no directory"); + assert_eq!(cache.dir(), Some(nested.as_path())); + + let file = dir.file("m.sv", M); + let mut cache = IndexCache::open(Some(nested.clone())); + cache.record(&facts(&file, M), M); + assert!(nested.join(FILE).exists(), "the directory is made on demand"); + cache.compact(); + assert_eq!(std::fs::read_to_string(nested.join(".gitignore")).expect("ignore"), "*\n"); + let leftovers: Vec = std::fs::read_dir(&nested) + .expect("read dir") + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".tmp")) + .collect(); + assert!(leftovers.is_empty(), "{leftovers:?}"); +} + +#[test] +fn the_cache_directory_is_the_highest_rung_that_answers() { + let settings = |persist: bool, path: Option<&str>| ClientSettings { + index_persist: persist, + index_cache_path: path.map(str::to_string), + ..ClientSettings::default() + }; + let roots = [PathBuf::from("/w/root"), PathBuf::from("/w/aaa")]; + let storage = Path::new("/storage/ws"); + let filelist = Path::new("/w/project.f"); + + // Rung 1 beats everything, and a relative path hangs off the first + // root — the rule `lucisv.filelist` already uses. + assert_eq!( + cache_dir(&settings(true, Some("/abs/cache")), Some(storage), &roots, Some(filelist)), + Some(PathBuf::from("/abs/cache")) + ); + assert_eq!( + cache_dir(&settings(true, Some(".lucisv_index")), Some(storage), &roots, None), + Some(PathBuf::from("/w/root/.lucisv_index")) + ); + // Rung 2: what the editor said. + assert_eq!( + cache_dir(&settings(true, None), Some(storage), &roots, None), + Some(storage.to_path_buf()) + ); + // Rung 3: the OS directory, keyed by the roots in sorted order — so + // the same two folders opened the other way round is one store. + let os = cache_dir(&settings(true, None), None, &roots, None).expect("an OS cache dir"); + let swapped = + cache_dir(&settings(true, None), None, &[roots[1].clone(), roots[0].clone()], None); + assert_eq!(Some(os.clone()), swapped, "the root order is not part of the identity"); + assert!(os.starts_with(os_cache_dir().expect("an OS cache dir")), "{}", os.display()); + assert!(os.ends_with(workspace_key(&roots, None).expect("a key")), "{}", os.display()); + // A different workspace is a different store. + assert_ne!(Some(os), cache_dir(&settings(true, None), None, &roots[..1], None)); + // A rootless session is keyed by its filelist, and has no store + // without one. + assert!(cache_dir(&settings(true, None), None, &[], Some(filelist)).is_some()); + assert_eq!(cache_dir(&settings(true, None), None, &[], None), None); + // Rung 4: off is off, whatever every other rung says. + assert_eq!(cache_dir(&settings(false, Some("/abs/cache")), Some(storage), &roots, None), None); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/inlay.rs b/crates/lucisv_server/src/inlay.rs index 952db14..ea263b0 100644 --- a/crates/lucisv_server/src/inlay.rs +++ b/crates/lucisv_server/src/inlay.rs @@ -227,705 +227,6 @@ impl<'w> Plans<'w> { } #[cfg(test)] -mod tests { - use super::*; - use crate::uri::path_to_uri; - use lsp_types::Position; - use std::fs; - use std::path::PathBuf; - - const SUB: &str = "\ -module sub #( - parameter int WIDTH = 8, - parameter int DEPTH = 16 -) ( - input logic clk, - input logic rst_n, - input logic [WIDTH-1:0] data -); -endmodule -"; - - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_inlay_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - /// The whole buffer, as a range. - fn everything() -> Range { - Range { - start: Position { line: 0, character: 0 }, - end: Position { line: u32::MAX, character: 0 }, - } - } - - /// Every hint in `top`, as `(line, character, label)`. - fn hints_of(name: &str, top: &str) -> Vec<(u32, u32, String)> { - hints_in(name, top, everything(), &[("sub.sv", SUB)]) - } - - /// Every hint in `top` within `range`, against a workspace of `files`. - fn hints_in( - name: &str, - top: &str, - range: Range, - files: &[(&str, &str)], - ) -> Vec<(u32, u32, String)> { - let tree = Tree::new(name); - for (rel, text) in files { - tree.write(rel, text); - } - let path = tree.write("top.sv", top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), top.to_string()); - inlay_hints(&ws, &uri, range) - .into_iter() - .map(|hint| { - let InlayHintLabel::String(label) = hint.label else { panic!("a string label") }; - (hint.position.line, hint.position.character, label) - }) - .collect() - } - - /// Just the labels, in order. - fn labels(hints: &[(u32, u32, String)]) -> Vec<&str> { - hints.iter().map(|(_, _, label)| label.as_str()).collect() - } - - #[test] - fn an_ordered_connection_list_names_every_port_in_order() { - let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; - let hints = hints_of("ordered", top); - assert_eq!( - hints, - vec![ - (1, 10, "clk:".to_string()), - (1, 15, "rst_n:".to_string()), - (1, 22, "data:".to_string()), - ], - "one hint per connection, at the start of its expression" - ); - } - - #[test] - fn every_hint_is_a_parameter_kind_with_padding_after_it() { - // The two fields a client actually renders with; a hint glued to the - // expression it labels reads as part of the code. - let tree = Tree::new("shape"); - tree.write("sub.sv", SUB); - let top = "module top;\n sub u1 (clk);\nendmodule\n"; - let path = tree.write("top.sv", top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), top.to_string()); - let hints = inlay_hints(&ws, &uri, everything()); - assert_eq!(hints.len(), 1); - assert_eq!(hints[0].kind, Some(InlayHintKind::PARAMETER)); - assert_eq!(hints[0].padding_right, Some(true)); - assert_eq!(hints[0].padding_left, None); - assert_eq!(hints[0].text_edits, None, "a hint here inserts nothing"); - } - - #[test] - fn a_named_connection_list_gets_nothing() { - let top = "module top;\n sub u1 (.clk(clk), .rst_n(rst_n));\nendmodule\n"; - assert!(hints_of("named", top).is_empty(), "the names are already written"); - } - - #[test] - fn a_wildcard_connection_gets_nothing() { - let top = "module top;\n sub u1 (.*);\nendmodule\n"; - assert!(hints_of("wildcard", top).is_empty()); - } - - #[test] - fn an_omitted_position_gets_nothing_and_still_counts() { - // `u (a, , c)` connects the *third* port to `c`; the hole has no - // expression to label, and skipping it must not shift `data` onto - // `rst_n`. - let top = "module top;\n sub u1 (clk, , data);\nendmodule\n"; - let hints = hints_of("omitted", top); - assert_eq!(labels(&hints), ["clk:", "data:"]); - assert_eq!(hints[1].0, 1, "still on line 1"); - } - - #[test] - fn an_empty_connection_list_gets_nothing() { - let top = "module top;\n sub u1 ();\nendmodule\n"; - assert!(hints_of("empty", top).is_empty()); - } - - #[test] - fn a_connection_list_mixing_the_two_spellings_is_survived() { - // Illegal SystemVerilog, and typeable. Whichever way the parser - // recovers, what must not happen is a hint on a `.name(...)` entry or - // a panic — so the assertion is on the labels that *can* appear. - for top in [ - "module top;\n sub u1 (clk, .rst_n(r));\nendmodule\n", - "module top;\n sub u1 (.clk(c), rst_n);\nendmodule\n", - ] { - // Today both come back empty — the first shape stops the item - // parsing at all, the second is a `Connections::Named` — but the - // assertion is deliberately the weaker invariant, so a change in - // the parser's recovery is not a test failure. - let hints = hints_of("mixedconns", top); - assert!( - hints.iter().all(|(_, _, label)| label == "clk:"), - "no hint may land on a named entry: {hints:?}" - ); - } - } - - #[test] - fn more_connections_than_ports_leaves_the_extras_unlabelled() { - // Never guess: `sub` has three ports, so the fourth and fifth name - // nothing at all. - let top = "module top;\n sub u1 (clk, rst_n, data, extra, more);\nendmodule\n"; - assert_eq!(labels(&hints_of("overrun", top)), ["clk:", "rst_n:", "data:"]); - } - - #[test] - fn fewer_connections_than_ports_is_fine() { - let top = "module top;\n sub u1 (clk);\nendmodule\n"; - assert_eq!(labels(&hints_of("underrun", top)), ["clk:"]); - } - - #[test] - fn ordered_parameter_overrides_are_named_too() { - let top = "module top;\n sub #(8, 16) u1 (clk);\nendmodule\n"; - let hints = hints_of("params", top); - assert_eq!( - hints, - vec![ - (1, 8, "WIDTH:".to_string()), - (1, 11, "DEPTH:".to_string()), - (1, 19, "clk:".to_string()), - ], - "the overrides, then the connection" - ); - } - - #[test] - fn named_parameter_overrides_get_nothing() { - let top = "module top;\n sub #(.WIDTH(8), .DEPTH(16)) u1 (clk);\nendmodule\n"; - assert_eq!(labels(&hints_of("namedparams", top)), ["clk:"], "the ports only"); - } - - #[test] - fn a_parameter_list_mixing_the_two_spellings_gets_nothing() { - // Illegal SystemVerilog, and typeable. The positional half is exactly - // the part whose meaning stops being obvious, so nothing is claimed. - let top = "module top;\n sub #(8, .DEPTH(16)) u1 (clk);\nendmodule\n"; - assert_eq!(labels(&hints_of("mixedparams", top)), ["clk:"]); - } - - #[test] - fn an_empty_parameter_list_gets_nothing() { - let top = "module top;\n sub #() u1 (clk);\nendmodule\n"; - assert_eq!(labels(&hints_of("emptyparams", top)), ["clk:"]); - } - - #[test] - fn more_overrides_than_parameters_leaves_the_extras_unlabelled() { - let top = "module top;\n sub #(8, 16, 32) u1 ();\nendmodule\n"; - assert_eq!(labels(&hints_of("paramoverrun", top)), ["WIDTH:", "DEPTH:"]); - } - - #[test] - fn commas_inside_a_connected_expression_do_not_shift_a_position() { - // The failure a comma-counting implementation makes: `f(a, b)` reads - // as two connections and every later hint is one port too far along. - let top = "module top;\n sub u1 (f(a, b), {x, y}, data[c:d]);\nendmodule\n"; - assert_eq!(labels(&hints_of("nested", top)), ["clk:", "rst_n:", "data:"]); - } - - #[test] - fn an_unknown_module_gets_nothing() { - let top = "module top;\n nope u1 (a, b, c);\nendmodule\n"; - assert!(hints_of("unknown", top).is_empty()); - } - - #[test] - fn a_module_two_files_declare_gets_nothing() { - // `module_definition` refuses to guess which one; a hint from the - // wrong declaration would be a lie the reader cannot see through. - let top = "module top;\n dup u1 (a, b);\nendmodule\n"; - let dup = "module dup (input logic x, input logic y);\nendmodule\n"; - let hints = hints_in("ambiguous", top, everything(), &[("a.sv", dup), ("b.sv", dup)]); - assert!(hints.is_empty(), "{hints:?}"); - } - - #[test] - fn a_gate_primitive_gets_nothing() { - // A gate's arguments are ordered and have no port names at all. - let top = "module top;\n and u1 (q, a, b);\n not u2 (nq, q);\nendmodule\n"; - assert!(hints_of("gate", top).is_empty()); - } - - #[test] - fn an_instance_array_hints_like_a_single_instance() { - let top = "module top;\n sub u1 [3:0] (clk, rst_n, data);\nendmodule\n"; - assert_eq!(labels(&hints_of("array", top)), ["clk:", "rst_n:", "data:"]); - } - - #[test] - fn every_instance_of_one_declaration_is_hinted() { - // `sub u1 (...), u2 (...);` is one item with two instances. - let top = "module top;\n sub u1 (clk), u2 (rst_n);\nendmodule\n"; - assert_eq!( - labels(&hints_of("twoinstances", top)), - ["clk:", "clk:"], - "both start at port 0" - ); - } - - #[test] - fn an_instantiation_inside_a_generate_block_is_reached() { - let top = "\ -module top; - generate - for (genvar i = 0; i < 4; i++) begin : g - sub u1 (clk, rst_n, data); - end - endgenerate -endmodule -"; - assert_eq!(labels(&hints_of("generate", top)), ["clk:", "rst_n:", "data:"]); - } - - #[test] - fn only_the_requested_range_is_hinted() { - let top = "\ -module top; - sub u1 (clk); - sub u2 (rst_n); - sub u3 (data); -endmodule -"; - let line = |line: u32| Range { - start: Position { line, character: 0 }, - end: Position { line, character: 40 }, - }; - assert_eq!(labels(&hints_in("range", top, line(2), &[("sub.sv", SUB)])), ["clk:"]); - // The middle line only, by its own line number. - let hints = hints_in("range2", top, line(2), &[("sub.sv", SUB)]); - assert_eq!(hints[0].0, 2, "the hint is on the line asked for"); - // Two lines at once. - let two = Range { - start: Position { line: 1, character: 0 }, - end: Position { line: 2, character: 40 }, - }; - assert_eq!(labels(&hints_in("range3", top, two, &[("sub.sv", SUB)])), ["clk:", "clk:"]); - // A range covering nothing hintable. - let none = Range { - start: Position { line: 0, character: 0 }, - end: Position { line: 0, character: 5 }, - }; - assert!(hints_in("range4", top, none, &[("sub.sv", SUB)]).is_empty()); - } - - #[test] - fn a_position_is_utf16_units_on_a_line_carrying_multibyte_text() { - // The hint's column is what the client draws at, so an `é` on the same - // line must not push it two columns right (2 UTF-8 bytes, 1 unit). - let top = "module top;\n sub u1 (/* é 🎉 */ clk); // é\n sub u2 (rst_n);\nendmodule\n"; - let hints = hints_of("utf16", top); - // `/* é 🎉 */ ` is 10 characters and 11 UTF-16 units, because `🎉` is a - // surrogate pair; counting bytes would put the hint six columns right. - assert_eq!(hints[0], (1, 21, "clk:".to_string())); - assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉"); - } - - /// A buffer mid-edit still hints where the *positions* are known, and - /// stops where they are not. - /// - /// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n` - /// used to fail to parse at all, so there was nothing to hint from. Now - /// the instantiation survives with both positional connections, and both - /// are at the index they were written at, so both are hinted. The second - /// half is the rule that replaces "does not parse": a list the parser - /// *recovered* inside holds text nobody can index, so `port_sites` and - /// `param_sites` decline the whole list rather than mislabel what follows - /// the hole. - #[test] - fn a_truncated_list_hints_and_a_recovered_one_does_not() { - let top = "module top;\n sub u1 (clk, rst_n\n"; - assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]); - let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n"; - assert!(hints_of("recovered", holed).is_empty()); - } - - #[test] - fn an_unopened_document_answers_with_no_hints() { - let ws = Workspace::default(); - let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri"); - assert!(inlay_hints(&ws, &uri, everything()).is_empty()); - } - - #[test] - fn a_positional_parameter_override_writes_no_name_of_its_own() { - // The premise `param_sites` rests on, stated as a test: the parser - // spells a positional override as a `Connection` with an empty name. - let text = "module top;\n sub #(8, .DEPTH(16)) u1 ();\nendmodule\n"; - let (tree, _) = vlog_parser::parse_source_tolerant(text); - let insts = instantiations::sites(&tree.items); - let params = insts[0].inst.params.as_ref().expect("a `#( ... )`"); - let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect(); - assert_eq!(params[0].name, "", "`8` names nothing"); - assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does"); - } - - // ---- QA regressions (2026-08-24) ---- - // - // See the QA log in `docs/features/inlay-hints/README.md` for how each of - // these was found and what it rules out. - - #[test] - fn an_ifdef_carrying_declaration_gets_no_hints_rather_than_a_wrong_one() { - // `instantiation_plan` lists every `` `ifdef`` arm's ports in one flat, - // declaration-ordered list (by design — see its own doc comment): here - // that is `[a, b, clk]`, three entries no single configuration ever - // has at once (real shape is `(a, clk)` or `(b, clk)`, never all - // three). Before this fix, `sub u1 (x, y)` was hinted `a: x, b: y` — - // wrong under *both* configurations, since the true second port is - // always `clk`. A hint the reader cannot verify is exactly the case - // the module's own doc comment says must stay silent. - let sub = "\ -module sub ( -`ifdef CFG_A - input logic a, -`else - input logic b, -`endif - input logic clk -); -endmodule -"; - let top = "module top;\n sub u1 (x, y);\nendmodule\n"; - assert!( - hints_in("ifdefports", top, everything(), &[("sub.sv", sub)]).is_empty(), - "a port list whose shape depends on the configuration must not be hinted" - ); - } - - #[test] - fn an_ifdef_carrying_parameter_list_gets_no_hints_either() { - let sub = "\ -module sub #( -`ifdef CFG_A - parameter int A = 1, -`else - parameter int B = 2, -`endif - parameter int WIDTH = 8 -) ( - input logic clk -); -endmodule -"; - let top = "module top;\n sub #(4, 8) u1 (clk);\nendmodule\n"; - assert_eq!( - labels(&hints_in("ifdefparams", top, everything(), &[("sub.sv", sub)])), - Vec::<&str>::new(), - "the port hint would be safe on its own, but the whole instantiation stays \ - silent because the module carries a directive-bearing list at all" - ); - } - - #[test] - fn a_self_instantiating_module_does_not_crash() { - // `top` here has no port list at all, so there is nothing to hint — - // the point of the test is that walking into the recursive - // instantiation and fetching `top`'s own plan does not loop or panic. - let top = "module top;\n top u1 (clk);\nendmodule\n"; - assert!(hints_of("recursive", top).is_empty()); - } - - #[test] - fn a_comment_nested_inside_a_connected_expression_does_not_shift_utf16_columns() { - // The nested-call test above pins that a comma inside `f(a, b)` is - // not a connection separator; this pins the same for a multi-byte - // comment nested the same way, so the *column* after it is not off - // too. `🎉` is a surrogate pair (2 UTF-16 units) and `é` is one. - let top = "module top;\n sub u1 (f(/* 🎉é */ a, b), rst_n, data);\nendmodule\n"; - let hints = hints_of("emojinested", top); - assert_eq!(labels(&hints), ["clk:", "rst_n:", "data:"]); - assert_eq!(hints[1].1, 29, "rst_n follows the nested comment, not the raw byte count"); - } - - #[test] - fn a_port_whose_width_depends_on_a_parameter_still_hints_by_name_only() { - // The label is just the port's name; a `[WIDTH-1:0]` type that - // depends on an overridden parameter must not be evaluated or crash. - let sub = "\ -module psub #( - parameter int WIDTH = 8 -) ( - input logic [WIDTH-1:0] data -); -endmodule -"; - let top = "module top;\n psub #(16) u1 (data_q);\nendmodule\n"; - assert_eq!( - labels(&hints_in("paramwidth", top, everything(), &[("psub.sv", sub)])), - ["WIDTH:", "data:"] - ); - } - - #[test] - fn a_non_ansi_header_definition_hints_correctly() { - let sub = "\ -module nasub (clk, rst_n, data); - input clk; - input rst_n; - input [7:0] data; -endmodule -"; - let top = "module top;\n nasub u1 (c, r, d);\nendmodule\n"; - assert_eq!( - labels(&hints_in("nonansi", top, everything(), &[("nasub.sv", sub)])), - ["clk:", "rst_n:", "data:"] - ); - } - - #[test] - fn a_range_starting_mid_instantiation_hints_only_the_visible_connections() { - // The range filter is per-site, not per-instantiation: a viewport - // that starts after `clk,` hints `rst_n` and `data` but not `clk`, - // which is off the top of it. - let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; - // " sub u1 (clk, rst_n, data);" -- the comma after clk is column 13. - let mid_range = Range { - start: Position { line: 1, character: 13 }, - end: Position { line: 1, character: 40 }, - }; - assert_eq!( - labels(&hints_in("midrange", top, mid_range, &[("sub.sv", SUB)])), - ["rst_n:", "data:"] - ); - } - - #[test] - fn an_open_unsaved_buffer_of_the_defining_file_wins_over_disk() { - // Handshake claim: "a defining file edited between two requests is - // never read from a stale copy." An unsaved `didChange` to the - // defining module, still open in the workspace, must be what a hint - // request in another file reads — not the last-saved disk copy. - let tree = Tree::new("staleness"); - let sub_path = tree.write("sub.sv", SUB); - let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; - let top_path = tree.write("top.sv", top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let sub_uri = path_to_uri(&sub_path).expect("uri"); - let top_uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(top_uri.clone(), top.to_string()); - // Renamed in the open buffer only; disk still says `clk`. - ws.set_document(sub_uri, SUB.replace("clk", "clk_renamed")); - let hints = inlay_hints(&ws, &top_uri, everything()); - let labels: Vec = hints - .into_iter() - .map(|h| { - let InlayHintLabel::String(s) = h.label else { panic!("string") }; - s - }) - .collect(); - assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]); - } - - // ------------------------------------------------------------------ - // the default scope (TODO §37.2 / `performance_take2.md` §4b, §8) - // ------------------------------------------------------------------ - - /// An opentitan-shaped tree: an IP block with its RTL and its testbench, - /// and a shared library folder outside that block. Opening - /// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to - /// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is - /// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against - /// `hw/dv/sv/common_ifs/pins_if.sv`. - fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) { - const TB: &str = - "module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n"; - let tree = Tree::new(name); - fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs"); - fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs"); - fs::create_dir_all(tree.path.join("dv/common")).expect("dirs"); - tree.write("ip/aes/rtl/sub.sv", SUB); - tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n"); - let tb = tree.write("ip/aes/dv/tb/tb.sv", TB); - - let mut ws = Workspace::default(); - // The shipped default: no `index.scope`, `scopeDepth` 2. - ws.set_client_settings(crate::settings::ClientSettings::default()); - ws.adopt_roots(vec![tree.path.clone()]); - let uri = path_to_uri(&tb).expect("uri"); - ws.set_document(uri.clone(), TB.to_string()); - ws.rebuild_index(); - (tree, ws, uri, TB) - } - - #[test] - fn the_default_scope_hints_a_module_the_didopen_widen_reached() { - // `performance_take2.md` §4b measured 0 hints at the default scope - // where the workspace scope gives 4, and §8 filed it as a correctness - // gap. It is not one: the hints that scope answers are exactly the - // instantiations whose module the widen reached. - let (tree, ws, uri, _) = default_scoped("default_scope"); - assert!( - ws.index().files().iter().any(|f| f.ends_with("sub.sv")), - "the widen reached the block's own RTL: {:?}", - ws.index().files() - ); - assert!( - !ws.index().files().iter().any(|f| f.ends_with("far.sv")), - "and not the library folder beside it" - ); - - let hints = inlay_hints(&ws, &uri, everything()); - let labels: Vec = hints - .into_iter() - .map(|h| { - let InlayHintLabel::String(s) = h.label else { panic!("string") }; - s - }) - .collect(); - assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted"); - drop(tree); - } - - #[test] - fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() { - // The other half of the same finding: the `far` instantiation gets no - // hints — and go-to-definition and hover give nothing for it either. - // The zero is the scope's, not this module's; inlay uses the same - // `module_definition` lookup its neighbours do. - let (tree, ws, uri, tb) = default_scoped("out_of_scope"); - let hints = inlay_hints(&ws, &uri, everything()); - assert!( - hints.iter().all(|hint| hint.position.line != 2), - "nothing on the `far` line: {hints:#?}" - ); - - let far = tb.find("far u_far").expect("the instantiation") as u32; - assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer"); - assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover"); - - // And the moment the scope reaches it, all three answer. - let mut wide = Workspace::default(); - wide.open_whole_workspace(vec![tree.path.clone()]); - wide.set_document(uri.clone(), tb.to_string()); - let hints = inlay_hints(&wide, &uri, everything()); - assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}"); - assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1); - } - - /// Order-of-magnitude perf checks, not run as part of the ordinary suite: - /// timing assertions in a shared CI runner are flaky by nature. Run with - /// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`. - mod qa_perf { - use super::*; - - #[test] - #[ignore] - fn forty_distinct_ordered_modules_one_screen() { - // Cheap rebuild of the dev's deleted harness: forty distinct - // ~90-line module definitions, each instantiated once, ordered, - // on one 40-line "screen" (range-scoped request). Measured - // 2026-08-24: 840 hints in ~2.8ms release / this machine — same - // order of magnitude as the README's 12.2ms for the same shape. - let tree = Tree::new("qaperf40"); - let mut top = String::from("module top;\n"); - for i in 0..40 { - let mut def = format!("module m{i} (\n"); - for p in 0..20 { - def.push_str(&format!(" input logic p{p},\n")); - } - def.push_str(" input logic last\n);\n"); - for _ in 0..85 { - def.push_str(" // filler line to reach ~90 lines\n"); - } - def.push_str("endmodule\n"); - tree.write(&format!("m{i}.sv"), &def); - let conns: Vec = (0..20).map(|p| format!("p{p}")).collect(); - top.push_str(&format!(" m{i} u{i} ({}, last);\n", conns.join(", "))); - } - top.push_str("endmodule\n"); - let path = tree.write("top.sv", &top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), top.clone()); - let screen = Range { - start: Position { line: 0, character: 0 }, - end: Position { line: 41, character: 0 }, - }; - // Warm run (index build etc.) then timed run. - let _ = inlay_hints(&ws, &uri, screen); - let start = std::time::Instant::now(); - let hints = inlay_hints(&ws, &uri, screen); - let elapsed = start.elapsed(); - eprintln!( - "QA perf: 40 distinct ordered modules, one screen: {} hints in {:?}", - hints.len(), - elapsed - ); - assert_eq!(hints.len(), 40 * 21); - } - - #[test] - #[ignore] - fn same_module_instantiated_100_times_is_o_distinct_not_o_instances() { - // Measured 2026-08-24: 300 hints in ~163µs release / this - // machine — the plan cache collapses 100 instances of one module - // into a single parse, as the README's Cost section claims. - let tree = Tree::new("qaperf100same"); - tree.write("sub.sv", SUB); - let mut top = String::from("module top;\n"); - for i in 0..100 { - top.push_str(&format!(" sub u{i} (clk, rst_n, data);\n")); - } - top.push_str("endmodule\n"); - let path = tree.write("top.sv", &top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), top.clone()); - let _ = inlay_hints(&ws, &uri, everything()); - let start = std::time::Instant::now(); - let hints = inlay_hints(&ws, &uri, everything()); - let elapsed = start.elapsed(); - eprintln!( - "QA perf: same module x100 ordered, whole file: {} hints in {:?}", - hints.len(), - elapsed - ); - assert_eq!(hints.len(), 300); - } - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/inlay/tests.rs b/crates/lucisv_server/src/inlay/tests.rs new file mode 100644 index 0000000..1c8be51 --- /dev/null +++ b/crates/lucisv_server/src/inlay/tests.rs @@ -0,0 +1,697 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use lsp_types::Position; +use std::fs; +use std::path::PathBuf; + +const SUB: &str = "\ +module sub #( + parameter int WIDTH = 8, + parameter int DEPTH = 16 +) ( + input logic clk, + input logic rst_n, + input logic [WIDTH-1:0] data +); +endmodule +"; + +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = + std::env::temp_dir().join(format!("lucisv_server_inlay_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +/// The whole buffer, as a range. +fn everything() -> Range { + Range { + start: Position { line: 0, character: 0 }, + end: Position { line: u32::MAX, character: 0 }, + } +} + +/// Every hint in `top`, as `(line, character, label)`. +fn hints_of(name: &str, top: &str) -> Vec<(u32, u32, String)> { + hints_in(name, top, everything(), &[("sub.sv", SUB)]) +} + +/// Every hint in `top` within `range`, against a workspace of `files`. +fn hints_in( + name: &str, + top: &str, + range: Range, + files: &[(&str, &str)], +) -> Vec<(u32, u32, String)> { + let tree = Tree::new(name); + for (rel, text) in files { + tree.write(rel, text); + } + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + inlay_hints(&ws, &uri, range) + .into_iter() + .map(|hint| { + let InlayHintLabel::String(label) = hint.label else { panic!("a string label") }; + (hint.position.line, hint.position.character, label) + }) + .collect() +} + +/// Just the labels, in order. +fn labels(hints: &[(u32, u32, String)]) -> Vec<&str> { + hints.iter().map(|(_, _, label)| label.as_str()).collect() +} + +#[test] +fn an_ordered_connection_list_names_every_port_in_order() { + let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; + let hints = hints_of("ordered", top); + assert_eq!( + hints, + vec![ + (1, 10, "clk:".to_string()), + (1, 15, "rst_n:".to_string()), + (1, 22, "data:".to_string()), + ], + "one hint per connection, at the start of its expression" + ); +} + +#[test] +fn every_hint_is_a_parameter_kind_with_padding_after_it() { + // The two fields a client actually renders with; a hint glued to the + // expression it labels reads as part of the code. + let tree = Tree::new("shape"); + tree.write("sub.sv", SUB); + let top = "module top;\n sub u1 (clk);\nendmodule\n"; + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let hints = inlay_hints(&ws, &uri, everything()); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].kind, Some(InlayHintKind::PARAMETER)); + assert_eq!(hints[0].padding_right, Some(true)); + assert_eq!(hints[0].padding_left, None); + assert_eq!(hints[0].text_edits, None, "a hint here inserts nothing"); +} + +#[test] +fn a_named_connection_list_gets_nothing() { + let top = "module top;\n sub u1 (.clk(clk), .rst_n(rst_n));\nendmodule\n"; + assert!(hints_of("named", top).is_empty(), "the names are already written"); +} + +#[test] +fn a_wildcard_connection_gets_nothing() { + let top = "module top;\n sub u1 (.*);\nendmodule\n"; + assert!(hints_of("wildcard", top).is_empty()); +} + +#[test] +fn an_omitted_position_gets_nothing_and_still_counts() { + // `u (a, , c)` connects the *third* port to `c`; the hole has no + // expression to label, and skipping it must not shift `data` onto + // `rst_n`. + let top = "module top;\n sub u1 (clk, , data);\nendmodule\n"; + let hints = hints_of("omitted", top); + assert_eq!(labels(&hints), ["clk:", "data:"]); + assert_eq!(hints[1].0, 1, "still on line 1"); +} + +#[test] +fn an_empty_connection_list_gets_nothing() { + let top = "module top;\n sub u1 ();\nendmodule\n"; + assert!(hints_of("empty", top).is_empty()); +} + +#[test] +fn a_connection_list_mixing_the_two_spellings_is_survived() { + // Illegal SystemVerilog, and typeable. Whichever way the parser + // recovers, what must not happen is a hint on a `.name(...)` entry or + // a panic — so the assertion is on the labels that *can* appear. + for top in [ + "module top;\n sub u1 (clk, .rst_n(r));\nendmodule\n", + "module top;\n sub u1 (.clk(c), rst_n);\nendmodule\n", + ] { + // Today both come back empty — the first shape stops the item + // parsing at all, the second is a `Connections::Named` — but the + // assertion is deliberately the weaker invariant, so a change in + // the parser's recovery is not a test failure. + let hints = hints_of("mixedconns", top); + assert!( + hints.iter().all(|(_, _, label)| label == "clk:"), + "no hint may land on a named entry: {hints:?}" + ); + } +} + +#[test] +fn more_connections_than_ports_leaves_the_extras_unlabelled() { + // Never guess: `sub` has three ports, so the fourth and fifth name + // nothing at all. + let top = "module top;\n sub u1 (clk, rst_n, data, extra, more);\nendmodule\n"; + assert_eq!(labels(&hints_of("overrun", top)), ["clk:", "rst_n:", "data:"]); +} + +#[test] +fn fewer_connections_than_ports_is_fine() { + let top = "module top;\n sub u1 (clk);\nendmodule\n"; + assert_eq!(labels(&hints_of("underrun", top)), ["clk:"]); +} + +#[test] +fn ordered_parameter_overrides_are_named_too() { + let top = "module top;\n sub #(8, 16) u1 (clk);\nendmodule\n"; + let hints = hints_of("params", top); + assert_eq!( + hints, + vec![ + (1, 8, "WIDTH:".to_string()), + (1, 11, "DEPTH:".to_string()), + (1, 19, "clk:".to_string()), + ], + "the overrides, then the connection" + ); +} + +#[test] +fn named_parameter_overrides_get_nothing() { + let top = "module top;\n sub #(.WIDTH(8), .DEPTH(16)) u1 (clk);\nendmodule\n"; + assert_eq!(labels(&hints_of("namedparams", top)), ["clk:"], "the ports only"); +} + +#[test] +fn a_parameter_list_mixing_the_two_spellings_gets_nothing() { + // Illegal SystemVerilog, and typeable. The positional half is exactly + // the part whose meaning stops being obvious, so nothing is claimed. + let top = "module top;\n sub #(8, .DEPTH(16)) u1 (clk);\nendmodule\n"; + assert_eq!(labels(&hints_of("mixedparams", top)), ["clk:"]); +} + +#[test] +fn an_empty_parameter_list_gets_nothing() { + let top = "module top;\n sub #() u1 (clk);\nendmodule\n"; + assert_eq!(labels(&hints_of("emptyparams", top)), ["clk:"]); +} + +#[test] +fn more_overrides_than_parameters_leaves_the_extras_unlabelled() { + let top = "module top;\n sub #(8, 16, 32) u1 ();\nendmodule\n"; + assert_eq!(labels(&hints_of("paramoverrun", top)), ["WIDTH:", "DEPTH:"]); +} + +#[test] +fn commas_inside_a_connected_expression_do_not_shift_a_position() { + // The failure a comma-counting implementation makes: `f(a, b)` reads + // as two connections and every later hint is one port too far along. + let top = "module top;\n sub u1 (f(a, b), {x, y}, data[c:d]);\nendmodule\n"; + assert_eq!(labels(&hints_of("nested", top)), ["clk:", "rst_n:", "data:"]); +} + +#[test] +fn an_unknown_module_gets_nothing() { + let top = "module top;\n nope u1 (a, b, c);\nendmodule\n"; + assert!(hints_of("unknown", top).is_empty()); +} + +#[test] +fn a_module_two_files_declare_gets_nothing() { + // `module_definition` refuses to guess which one; a hint from the + // wrong declaration would be a lie the reader cannot see through. + let top = "module top;\n dup u1 (a, b);\nendmodule\n"; + let dup = "module dup (input logic x, input logic y);\nendmodule\n"; + let hints = hints_in("ambiguous", top, everything(), &[("a.sv", dup), ("b.sv", dup)]); + assert!(hints.is_empty(), "{hints:?}"); +} + +#[test] +fn a_gate_primitive_gets_nothing() { + // A gate's arguments are ordered and have no port names at all. + let top = "module top;\n and u1 (q, a, b);\n not u2 (nq, q);\nendmodule\n"; + assert!(hints_of("gate", top).is_empty()); +} + +#[test] +fn an_instance_array_hints_like_a_single_instance() { + let top = "module top;\n sub u1 [3:0] (clk, rst_n, data);\nendmodule\n"; + assert_eq!(labels(&hints_of("array", top)), ["clk:", "rst_n:", "data:"]); +} + +#[test] +fn every_instance_of_one_declaration_is_hinted() { + // `sub u1 (...), u2 (...);` is one item with two instances. + let top = "module top;\n sub u1 (clk), u2 (rst_n);\nendmodule\n"; + assert_eq!(labels(&hints_of("twoinstances", top)), ["clk:", "clk:"], "both start at port 0"); +} + +#[test] +fn an_instantiation_inside_a_generate_block_is_reached() { + let top = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (clk, rst_n, data); + end + endgenerate +endmodule +"; + assert_eq!(labels(&hints_of("generate", top)), ["clk:", "rst_n:", "data:"]); +} + +#[test] +fn only_the_requested_range_is_hinted() { + let top = "\ +module top; + sub u1 (clk); + sub u2 (rst_n); + sub u3 (data); +endmodule +"; + let line = |line: u32| Range { + start: Position { line, character: 0 }, + end: Position { line, character: 40 }, + }; + assert_eq!(labels(&hints_in("range", top, line(2), &[("sub.sv", SUB)])), ["clk:"]); + // The middle line only, by its own line number. + let hints = hints_in("range2", top, line(2), &[("sub.sv", SUB)]); + assert_eq!(hints[0].0, 2, "the hint is on the line asked for"); + // Two lines at once. + let two = Range { + start: Position { line: 1, character: 0 }, + end: Position { line: 2, character: 40 }, + }; + assert_eq!(labels(&hints_in("range3", top, two, &[("sub.sv", SUB)])), ["clk:", "clk:"]); + // A range covering nothing hintable. + let none = Range { + start: Position { line: 0, character: 0 }, + end: Position { line: 0, character: 5 }, + }; + assert!(hints_in("range4", top, none, &[("sub.sv", SUB)]).is_empty()); +} + +#[test] +fn a_position_is_utf16_units_on_a_line_carrying_multibyte_text() { + // The hint's column is what the client draws at, so an `é` on the same + // line must not push it two columns right (2 UTF-8 bytes, 1 unit). + let top = "module top;\n sub u1 (/* é 🎉 */ clk); // é\n sub u2 (rst_n);\nendmodule\n"; + let hints = hints_of("utf16", top); + // `/* é 🎉 */ ` is 10 characters and 11 UTF-16 units, because `🎉` is a + // surrogate pair; counting bytes would put the hint six columns right. + assert_eq!(hints[0], (1, 21, "clk:".to_string())); + assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉"); +} + +/// A buffer mid-edit still hints where the *positions* are known, and +/// stops where they are not. +/// +/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n` +/// used to fail to parse at all, so there was nothing to hint from. Now +/// the instantiation survives with both positional connections, and both +/// are at the index they were written at, so both are hinted. The second +/// half is the rule that replaces "does not parse": a list the parser +/// *recovered* inside holds text nobody can index, so `port_sites` and +/// `param_sites` decline the whole list rather than mislabel what follows +/// the hole. +#[test] +fn a_truncated_list_hints_and_a_recovered_one_does_not() { + let top = "module top;\n sub u1 (clk, rst_n\n"; + assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]); + let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n"; + assert!(hints_of("recovered", holed).is_empty()); +} + +#[test] +fn an_unopened_document_answers_with_no_hints() { + let ws = Workspace::default(); + let uri = path_to_uri(std::path::Path::new("/nowhere/top.sv")).expect("uri"); + assert!(inlay_hints(&ws, &uri, everything()).is_empty()); +} + +#[test] +fn a_positional_parameter_override_writes_no_name_of_its_own() { + // The premise `param_sites` rests on, stated as a test: the parser + // spells a positional override as a `Connection` with an empty name. + let text = "module top;\n sub #(8, .DEPTH(16)) u1 ();\nendmodule\n"; + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let insts = instantiations::sites(&tree.items); + let params = insts[0].inst.params.as_ref().expect("a `#( ... )`"); + let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect(); + assert_eq!(params[0].name, "", "`8` names nothing"); + assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does"); +} + +// ---- QA regressions (2026-08-24) ---- +// +// See the QA log in `docs/features/inlay-hints/README.md` for how each of +// these was found and what it rules out. + +#[test] +fn an_ifdef_carrying_declaration_gets_no_hints_rather_than_a_wrong_one() { + // `instantiation_plan` lists every `` `ifdef`` arm's ports in one flat, + // declaration-ordered list (by design — see its own doc comment): here + // that is `[a, b, clk]`, three entries no single configuration ever + // has at once (real shape is `(a, clk)` or `(b, clk)`, never all + // three). Before this fix, `sub u1 (x, y)` was hinted `a: x, b: y` — + // wrong under *both* configurations, since the true second port is + // always `clk`. A hint the reader cannot verify is exactly the case + // the module's own doc comment says must stay silent. + let sub = "\ +module sub ( +`ifdef CFG_A + input logic a, +`else + input logic b, +`endif + input logic clk +); +endmodule +"; + let top = "module top;\n sub u1 (x, y);\nendmodule\n"; + assert!( + hints_in("ifdefports", top, everything(), &[("sub.sv", sub)]).is_empty(), + "a port list whose shape depends on the configuration must not be hinted" + ); +} + +#[test] +fn an_ifdef_carrying_parameter_list_gets_no_hints_either() { + let sub = "\ +module sub #( +`ifdef CFG_A + parameter int A = 1, +`else + parameter int B = 2, +`endif + parameter int WIDTH = 8 +) ( + input logic clk +); +endmodule +"; + let top = "module top;\n sub #(4, 8) u1 (clk);\nendmodule\n"; + assert_eq!( + labels(&hints_in("ifdefparams", top, everything(), &[("sub.sv", sub)])), + Vec::<&str>::new(), + "the port hint would be safe on its own, but the whole instantiation stays \ + silent because the module carries a directive-bearing list at all" + ); +} + +#[test] +fn a_self_instantiating_module_does_not_crash() { + // `top` here has no port list at all, so there is nothing to hint — + // the point of the test is that walking into the recursive + // instantiation and fetching `top`'s own plan does not loop or panic. + let top = "module top;\n top u1 (clk);\nendmodule\n"; + assert!(hints_of("recursive", top).is_empty()); +} + +#[test] +fn a_comment_nested_inside_a_connected_expression_does_not_shift_utf16_columns() { + // The nested-call test above pins that a comma inside `f(a, b)` is + // not a connection separator; this pins the same for a multi-byte + // comment nested the same way, so the *column* after it is not off + // too. `🎉` is a surrogate pair (2 UTF-16 units) and `é` is one. + let top = "module top;\n sub u1 (f(/* 🎉é */ a, b), rst_n, data);\nendmodule\n"; + let hints = hints_of("emojinested", top); + assert_eq!(labels(&hints), ["clk:", "rst_n:", "data:"]); + assert_eq!(hints[1].1, 29, "rst_n follows the nested comment, not the raw byte count"); +} + +#[test] +fn a_port_whose_width_depends_on_a_parameter_still_hints_by_name_only() { + // The label is just the port's name; a `[WIDTH-1:0]` type that + // depends on an overridden parameter must not be evaluated or crash. + let sub = "\ +module psub #( + parameter int WIDTH = 8 +) ( + input logic [WIDTH-1:0] data +); +endmodule +"; + let top = "module top;\n psub #(16) u1 (data_q);\nendmodule\n"; + assert_eq!( + labels(&hints_in("paramwidth", top, everything(), &[("psub.sv", sub)])), + ["WIDTH:", "data:"] + ); +} + +#[test] +fn a_non_ansi_header_definition_hints_correctly() { + let sub = "\ +module nasub (clk, rst_n, data); + input clk; + input rst_n; + input [7:0] data; +endmodule +"; + let top = "module top;\n nasub u1 (c, r, d);\nendmodule\n"; + assert_eq!( + labels(&hints_in("nonansi", top, everything(), &[("nasub.sv", sub)])), + ["clk:", "rst_n:", "data:"] + ); +} + +#[test] +fn a_range_starting_mid_instantiation_hints_only_the_visible_connections() { + // The range filter is per-site, not per-instantiation: a viewport + // that starts after `clk,` hints `rst_n` and `data` but not `clk`, + // which is off the top of it. + let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; + // " sub u1 (clk, rst_n, data);" -- the comma after clk is column 13. + let mid_range = Range { + start: Position { line: 1, character: 13 }, + end: Position { line: 1, character: 40 }, + }; + assert_eq!( + labels(&hints_in("midrange", top, mid_range, &[("sub.sv", SUB)])), + ["rst_n:", "data:"] + ); +} + +#[test] +fn an_open_unsaved_buffer_of_the_defining_file_wins_over_disk() { + // Handshake claim: "a defining file edited between two requests is + // never read from a stale copy." An unsaved `didChange` to the + // defining module, still open in the workspace, must be what a hint + // request in another file reads — not the last-saved disk copy. + let tree = Tree::new("staleness"); + let sub_path = tree.write("sub.sv", SUB); + let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n"; + let top_path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let sub_uri = path_to_uri(&sub_path).expect("uri"); + let top_uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(top_uri.clone(), top.to_string()); + // Renamed in the open buffer only; disk still says `clk`. + ws.set_document(sub_uri, SUB.replace("clk", "clk_renamed")); + let hints = inlay_hints(&ws, &top_uri, everything()); + let labels: Vec = hints + .into_iter() + .map(|h| { + let InlayHintLabel::String(s) = h.label else { panic!("string") }; + s + }) + .collect(); + assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]); +} + +// ------------------------------------------------------------------ +// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8) +// ------------------------------------------------------------------ + +/// An opentitan-shaped tree: an IP block with its RTL and its testbench, +/// and a shared library folder outside that block. Opening +/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to +/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is +/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against +/// `hw/dv/sv/common_ifs/pins_if.sv`. +fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) { + const TB: &str = "module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n"; + let tree = Tree::new(name); + fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs"); + fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs"); + fs::create_dir_all(tree.path.join("dv/common")).expect("dirs"); + tree.write("ip/aes/rtl/sub.sv", SUB); + tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n"); + let tb = tree.write("ip/aes/dv/tb/tb.sv", TB); + + let mut ws = Workspace::default(); + // The shipped default: no `index.scope`, `scopeDepth` 2. + ws.set_client_settings(crate::settings::ClientSettings::default()); + ws.adopt_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&tb).expect("uri"); + ws.set_document(uri.clone(), TB.to_string()); + ws.rebuild_index(); + (tree, ws, uri, TB) +} + +#[test] +fn the_default_scope_hints_a_module_the_didopen_widen_reached() { + // `performance_take2.md` §4b measured 0 hints at the default scope + // where the workspace scope gives 4, and §8 filed it as a correctness + // gap. It is not one: the hints that scope answers are exactly the + // instantiations whose module the widen reached. + let (tree, ws, uri, _) = default_scoped("default_scope"); + assert!( + ws.index().files().iter().any(|f| f.ends_with("sub.sv")), + "the widen reached the block's own RTL: {:?}", + ws.index().files() + ); + assert!( + !ws.index().files().iter().any(|f| f.ends_with("far.sv")), + "and not the library folder beside it" + ); + + let hints = inlay_hints(&ws, &uri, everything()); + let labels: Vec = hints + .into_iter() + .map(|h| { + let InlayHintLabel::String(s) = h.label else { panic!("string") }; + s + }) + .collect(); + assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted"); + drop(tree); +} + +#[test] +fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() { + // The other half of the same finding: the `far` instantiation gets no + // hints — and go-to-definition and hover give nothing for it either. + // The zero is the scope's, not this module's; inlay uses the same + // `module_definition` lookup its neighbours do. + let (tree, ws, uri, tb) = default_scoped("out_of_scope"); + let hints = inlay_hints(&ws, &uri, everything()); + assert!( + hints.iter().all(|hint| hint.position.line != 2), + "nothing on the `far` line: {hints:#?}" + ); + + let far = tb.find("far u_far").expect("the instantiation") as u32; + assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer"); + assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover"); + + // And the moment the scope reaches it, all three answer. + let mut wide = Workspace::default(); + wide.open_whole_workspace(vec![tree.path.clone()]); + wide.set_document(uri.clone(), tb.to_string()); + let hints = inlay_hints(&wide, &uri, everything()); + assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}"); + assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1); +} + +/// Order-of-magnitude perf checks, not run as part of the ordinary suite: +/// timing assertions in a shared CI runner are flaky by nature. Run with +/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`. +mod qa_perf { + use super::*; + + #[test] + #[ignore = "perf probe on a generated tree, timing printed not asserted; see the `qa_perf` doc"] + fn forty_distinct_ordered_modules_one_screen() { + // Cheap rebuild of the dev's deleted harness: forty distinct + // ~90-line module definitions, each instantiated once, ordered, + // on one 40-line "screen" (range-scoped request). Measured + // 2026-08-24: 840 hints in ~2.8ms release / this machine — same + // order of magnitude as the README's 12.2ms for the same shape. + let tree = Tree::new("qaperf40"); + let mut top = String::from("module top;\n"); + for i in 0..40 { + let mut def = format!("module m{i} (\n"); + for p in 0..20 { + def.push_str(&format!(" input logic p{p},\n")); + } + def.push_str(" input logic last\n);\n"); + for _ in 0..85 { + def.push_str(" // filler line to reach ~90 lines\n"); + } + def.push_str("endmodule\n"); + tree.write(&format!("m{i}.sv"), &def); + let conns: Vec = (0..20).map(|p| format!("p{p}")).collect(); + top.push_str(&format!(" m{i} u{i} ({}, last);\n", conns.join(", "))); + } + top.push_str("endmodule\n"); + let path = tree.write("top.sv", &top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.clone()); + let screen = Range { + start: Position { line: 0, character: 0 }, + end: Position { line: 41, character: 0 }, + }; + // Warm run (index build etc.) then timed run. + let _ = inlay_hints(&ws, &uri, screen); + let start = std::time::Instant::now(); + let hints = inlay_hints(&ws, &uri, screen); + let elapsed = start.elapsed(); + eprintln!( + "QA perf: 40 distinct ordered modules, one screen: {} hints in {:?}", + hints.len(), + elapsed + ); + assert_eq!(hints.len(), 40 * 21); + } + + #[test] + #[ignore = "perf probe on a generated tree, timing printed not asserted; see the `qa_perf` doc"] + fn same_module_instantiated_100_times_is_o_distinct_not_o_instances() { + // Measured 2026-08-24: 300 hints in ~163µs release / this + // machine — the plan cache collapses 100 instances of one module + // into a single parse, as the README's Cost section claims. + let tree = Tree::new("qaperf100same"); + tree.write("sub.sv", SUB); + let mut top = String::from("module top;\n"); + for i in 0..100 { + top.push_str(&format!(" sub u{i} (clk, rst_n, data);\n")); + } + top.push_str("endmodule\n"); + let path = tree.write("top.sv", &top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.clone()); + let _ = inlay_hints(&ws, &uri, everything()); + let start = std::time::Instant::now(); + let hints = inlay_hints(&ws, &uri, everything()); + let elapsed = start.elapsed(); + eprintln!( + "QA perf: same module x100 ordered, whole file: {} hints in {:?}", + hints.len(), + elapsed + ); + assert_eq!(hints.len(), 300); + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/inline.rs b/crates/lucisv_server/src/inline.rs index b20fd83..691e95e 100644 --- a/crates/lucisv_server/src/inline.rs +++ b/crates/lucisv_server/src/inline.rs @@ -603,1713 +603,6 @@ fn render(body: &[Line]) -> String { } #[cfg(test)] -mod tests { - use super::*; - use crate::settings::ClientSettings; - use crate::uri::path_to_uri; - use std::path::PathBuf; - use std::str::FromStr; - use vlog_parser::PARSE_STACK_SIZE; - - /// A one-file workspace with `path` open and the cursor at `needle`'s end. - /// No files on disk: nothing here reads the index. - fn asking_in(path: &str, text: &str, needle: &str) -> (Workspace, Uri, Position) { - let uri = path_to_uri(&PathBuf::from(path)).expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - let offset = (text.find(needle).expect("needle present") + needle.len()) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - (ws, uri, position) - } - - /// [`triggered`] used to sweep the token vector backwards from its end for - /// the last non-`Eof` token ending at or before the cursor. It now bounds - /// that sweep with a binary search; the token it lands on must be the same - /// one at every byte. - #[test] - fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() { - let text = crate::state::mixed_buffer(20); - let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.clone()); - let doc = ws.document(&uri).expect("open"); - for offset in 0..=text.len() as u32 { - let swept = doc - .tokens - .iter() - .rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset); - let reached = doc.tokens.partition_point(|token| token.span.end <= offset); - let searched = - doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof); - assert_eq!(swept, searched, "at offset {offset}"); - } - } - - /// The same, in a SystemVerilog buffer. - fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) { - asking_in("/rtl/top.sv", text, needle) - } - - /// Every snippet offered at `needle`'s end, in order. - fn all_offered(text: &str, needle: &str) -> Vec { - offered_in("/rtl/top.sv", text, needle) - } - - /// Every snippet offered at `needle`'s end in a buffer called `path`. - fn offered_in(path: &str, text: &str, needle: &str) -> Vec { - let (ws, uri, position) = asking_in(path, text, needle); - match inline_completions(&ws, &uri, position) { - None => Vec::new(), - Some(items) => items.items.iter().map(|i| i.insert_text.value.clone()).collect(), - } - } - - /// The one snippet offered at `needle`'s end, if any. - fn offered(text: &str, needle: &str) -> Option { - let mut items = all_offered(text, needle); - assert!(items.len() <= 1, "one ghost or none, got {items:?}"); - items.pop() - } - - /// `snippet` as VS Code really writes it into the buffer. - /// - /// `SnippetSession.adjustWhitespace` prepends the insertion line's own - /// leading whitespace — `base` — to every line after the first, then - /// `TextModel.normalizeIndentation` re-spells the whole leading run in the - /// editor's tabs-or-spaces, which is what turns each `\t` the server sent - /// into one `step`. - fn accepted(snippet: &str, base: &str, step: &str) -> String { - let mut out: Vec = Vec::new(); - for (index, line) in snippet.split('\n').enumerate() { - if index == 0 { - out.push(line.to_string()); - continue; - } - let steps = line.chars().take_while(|c| *c == '\t').count(); - out.push(format!("{base}{}{}", step.repeat(steps), &line[steps..])); - } - out.join("\n") - } - - /// `snippet` with every hole filled in the way the editor would preselect - /// it — the plain text a Tab really produces. The registry's grammar is - /// `${n:default}` and `$n` and nothing else, which - /// `every_hole_is_a_tabstop` pins. - fn filled(snippet: &str) -> String { - let mut out = String::new(); - let mut rest = snippet; - let mut mirrors: Vec<(&str, &str)> = Vec::new(); - while let Some(at) = rest.find('$') { - out.push_str(&rest[..at]); - rest = &rest[at + 1..]; - if let Some(braced) = rest.strip_prefix('{') { - let close = braced.find('}').expect("a hole is closed"); - let hole = &braced[..close]; - if let Some((number, default)) = hole.split_once(':') { - mirrors.push((number, default)); - out.push_str(default); - } - rest = &braced[close + 1..]; - continue; - } - let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); - let number = &rest[..digits]; - // A bare `$n` repeats what `${n:…}` was given, the way the editor - // mirrors a placeholder; `$0` was never declared and is nothing. - if let Some((_, default)) = mirrors.iter().find(|(n, _)| *n == number) { - out.push_str(default); - } - rest = &rest[digits..]; - } - out.push_str(rest); - out - } - - // ------------------------------------------------------------------ - // the emission contract: relative, not absolute - // ------------------------------------------------------------------ - - #[test] - fn a_snippet_is_indented_relative_to_the_trigger_line() { - // The 0.6.0 bug: the body used to carry the trigger line's own - // indentation, and VS Code prepends it *again* on insert, so the `end` - // landed a level deeper than the `begin` it closes. One `\t` per step - // and nothing else is what the editor can place correctly. - let text = "module top;\n always_comb begin\nendmodule\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); - } - - #[test] - fn the_editor_puts_the_end_level_with_its_opener() { - // What the user actually sees after Tab, with the two things VS Code - // does to the text modelled: the base prepended, one `\t` widened to - // the editor's indent. - let text = "module top;\n always_comb begin\nendmodule\n"; - let snippet = offered(text, "always_comb begin").expect("a ghost"); - assert_eq!(accepted(&snippet, " ", " "), "\n $0\n end"); - // ...at any depth, and in tabs as readily as in spaces. - assert_eq!(accepted(&snippet, "\t\t", "\t"), "\n\t\t\t$0\n\t\tend"); - } - - #[test] - fn the_line_indentation_never_reaches_the_snippet() { - // The same three lines however deep the trigger sits and however the - // buffer spells its indentation: the server has stopped having an - // opinion about either. - for line in ["always_comb begin", " always_comb begin", "\t\talways_comb begin"] { - let text = format!("module top;\n{line}\nendmodule\n"); - assert_eq!(offered(&text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); - } - } - - #[test] - fn the_indent_setting_no_longer_reaches_a_snippet() { - // `lucisv.indent` still decides what the *formatter* writes and what the - // completion popup inserts; an accepted inline snippet is laid out by - // the editor's own tab settings, because the editor re-spells the - // leading whitespace on insert whatever the server sent. - let text = "module top;\n always_comb begin\nendmodule\n"; - let (mut ws, uri, position) = asking(text, "always_comb begin"); - ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() }); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!(items.items[0].insert_text.value, "\n\t$0\nend"); - } - - // ------------------------------------------------------------------ - // the triggers - // ------------------------------------------------------------------ - - #[test] - fn an_open_if_paren_offers_the_rest_of_the_block() { - let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n"; - assert_eq!( - offered(text, " if (").as_deref(), - Some("${1:cond}) begin\n\t$0\nend"), - "the condition first and the body last" - ); - } - - #[test] - fn an_else_if_offers_the_same_block() { - let text = "\ -module top; - always_comb begin - if (a) begin - end else if ( - end -endmodule -"; - assert_eq!(offered(text, "else if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); - } - - #[test] - fn a_fresh_begin_offers_its_end() { - let text = "module top;\n always_comb begin\nendmodule\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); - } - - #[test] - fn a_while_offers_the_same_block_as_an_if() { - let text = "module top;\n initial begin\n while (\n end\nendmodule\n"; - assert_eq!(offered(text, "while (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); - } - - #[test] - fn a_for_loop_follows_the_buffers_dialect() { - // The same two bodies `templates.rs` offers in the popup, minus the - // `for (` the user has already typed. - let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; - assert_eq!( - offered_in("/rtl/top.sv", text, "for ("), - vec!["int ${1:i} = 0; $1 < ${2:N}; $1++) begin\n\t$0\nend"], - "SystemVerilog declares the loop variable in the header" - ); - assert_eq!( - offered_in("/rtl/top.v", text, "for ("), - vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"], - "Verilog has no `++` and no local loop variable" - ); - } - - #[test] - fn every_case_flavour_offers_the_same_arms_and_an_endcase() { - for keyword in ["case", "casez", "casex"] { - let text = - format!("module top;\n always_comb begin\n {keyword} (\n end\nendmodule\n"); - assert_eq!( - offered(&text, &format!("{keyword} (")).as_deref(), - Some("${1:sel})\n\t${2:value}: $0;\n\tdefault: ;\nendcase"), - "{keyword}" - ); - } - } - - #[test] - fn casex_is_offered_here_although_the_popup_does_not_list_it() { - // `templates.rs` leaves `casex` out on purpose: it is the flavour most - // style guides warn against, and an unused entry is noise in a list. - // Ghost text is not a list — it only ever appears once the user has - // typed `casex (` and committed to it — so the noise argument does not - // apply and refusing to finish the construct would just be unhelpful. - let text = "module top;\n always_comb begin\n casex (\n end\nendmodule\n"; - assert!(offered(text, "casex (").is_some()); - } - - #[test] - fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() { - let text = "module top;\n always @(\nendmodule\n"; - assert_eq!( - all_offered(text, "always @("), - vec![ - "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(), - "posedge ${1:clk}) begin\n\t$0\nend".to_string(), - "*) begin\n\t$0\nend".to_string(), - ], - "clocked first: `always @(` is overwhelmingly a flop, and most flops reset" - ); - } - - #[test] - fn always_ff_is_systemverilog_only() { - let text = "module top;\n always_ff @(\nendmodule\n"; - assert_eq!( - offered_in("/rtl/top.sv", text, "always_ff @("), - vec![ - "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend", - "posedge ${1:clk}) begin\n\t$0\nend" - ] - ); - assert!( - offered_in("/rtl/top.v", text, "always_ff @(").is_empty(), - "a `.v` compiler rejects `always_ff`" - ); - } - - #[test] - fn fork_generate_and_module_offer_their_own_closers() { - let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; - assert_eq!(offered(text, " fork").as_deref(), Some("\n\t$0\njoin")); - - let text = "module top;\n generate\nendmodule\n"; - assert_eq!(offered(text, " generate").as_deref(), Some("\n\t$0\nendgenerate")); - - // A module needs a name before its `;`, so the body writes one — the - // leading space is deliberate, the user's cursor sits right after the - // `e` of `module`. - assert_eq!(offered("module", "module").as_deref(), Some(" ${1:name};\n\t$0\nendmodule")); - } - - // ------------------------------------------------------------------ - // the negatives - // ------------------------------------------------------------------ - - #[test] - fn a_comment_or_a_string_never_triggers() { - // Neither is a token: a comment is lexer trivia, and the literal is one - // `String` token whose text is not a keyword. - for (text, needle, what) in [ - ("module top;\n // if (\nendmodule\n", "// if (", "a line comment"), - ("module top;\n /* if ( */\nendmodule\n", "/* if (", "a block comment"), - ( - "module top;\n initial $display(\"if (\");\nendmodule\n", - "\"if (", - "inside a string", - ), - ("module top;\n initial $display(\"begin\");\nendmodule\n", "\"begin", "ditto"), - ("module top;\n // begin\nendmodule\n", "// begin", "a commented begin"), - ("module top;\n // case (\nendmodule\n", "// case (", "a commented case"), - ] { - assert_eq!(offered(text, needle), None, "{what}: {text}"); - } - } - - #[test] - fn an_identifier_that_merely_ends_in_the_keyword_never_triggers() { - let text = "module top;\n always_comb begin\n my_if (\n end\nendmodule\n"; - assert_eq!(offered(text, "my_if ("), None, "`my_if` is an identifier"); - let text = "module top;\n logic my_begin;\n assign my_begin\nendmodule\n"; - assert_eq!(offered(text, "assign my_begin"), None); - } - - #[test] - fn a_line_with_anything_after_the_cursor_never_triggers() { - let text = - "module top;\n always_comb begin\n if (a) begin\n end\n end\nendmodule\n"; - assert_eq!(offered(text, " if ("), None, "the condition is already written"); - let text = "module top;\n always_comb begin ; end\nendmodule\n"; - assert_eq!(offered(text, "always_comb begin"), None); - } - - #[test] - fn whitespace_between_the_keyword_and_the_cursor_never_triggers() { - // The cursor must be exactly at the token's end — "you just typed - // this", and nothing looser. - let text = "module top;\n always_comb begin \nendmodule\n"; - assert_eq!(offered(text, "always_comb begin "), None); - let text = "module top;\n always_comb begin\n if ( \n end\nendmodule\n"; - assert_eq!(offered(text, "if ( "), None); - } - - #[test] - fn a_begin_that_already_has_its_end_offers_nothing() { - // The `end` below belongs to the `begin` just typed — `pairs::analyze` - // matches them — so a second one would break the file. - let text = "\ -module top; - always_comb begin - begin - end - end -endmodule -"; - assert_eq!(offered(text, " begin"), None, "the inner begin is matched"); - // ...and the one that really is unclosed still offers. - let text = "module top;\n always_comb begin\n end\n initial begin\nendmodule\n"; - assert!(offered(text, "initial begin").is_some(), "this one lost its end"); - } - - #[test] - fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() { - // The new `begin` steals the `always_comb` block's `end` in the stack - // matcher; the gate asks the auto-`end` question instead - // (`completion-ux` fix round, 2026-11-17). - let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n"; - assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend")); - } - - #[test] - fn a_scope_keyword_that_already_has_its_closer_offers_nothing() { - // The same rule as `begin`, for the three keywords that joined it. - let text = "module top;\n initial begin\n fork\n join\n end\nendmodule\n"; - assert_eq!(offered(text, " fork"), None); - let text = "module top;\n generate\n endgenerate\nendmodule\n"; - assert_eq!(offered(text, " generate"), None); - let text = "module\nendmodule\n"; - assert_eq!(offered(text, "module"), None); - // `disable fork;` names a fork rather than opening one — `pairs.rs` - // knows, and the gate inherits that. - let text = "module top;\n initial begin\n disable fork\n end\nendmodule\n"; - assert_eq!(offered(text, "disable fork"), None); - } - - #[test] - fn a_case_that_already_has_its_endcase_offers_nothing() { - // Both halves of the `case (` gate matter. Here the `endcase` below is - // this `case`'s own, so a second one would leave the file unbalanced — - // even though the `(` really is unclosed. - let text = "\ -module top; - always_comb begin - case ( - endcase - end -endmodule -"; - assert_eq!(offered(text, " case ("), None, "the endcase is already there"); - // ...and when the `endcase` below belongs to a nested, complete `case`, - // the one just typed still owes its own. - let text = "\ -module top; - always_comb begin - case ( - case (b) - default: ; - endcase - end -endmodule -"; - assert!(offered(text, " case (").is_some(), "this case is genuinely unclosed"); - } - - #[test] - fn an_if_paren_that_is_already_closed_offers_nothing() { - // A `)` further down the buffer is the one this `(` will pair with; - // writing a second would leave the file unbalanced the other way. - let text = "module top;\n always_comb begin\n if (\n a) begin\n end\n end\nendmodule\n"; - assert_eq!(offered(text, " if ("), None); - } - - #[test] - fn a_later_call_does_not_cancel_the_paren_just_typed() { - // A running `(` minus `)` count would see the `)` of `f(1)` below and - // decide this `(` was already closed. It is a stack, so the call's own - // paren pairs with its own closer and the `if (` stays open. - let text = "\ -module top; - always_comb begin - if ( - x = f(1); - end -endmodule -"; - assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); - } - - #[test] - fn a_paren_the_line_below_closes_still_counts_as_closed() { - // The mirror of the test above: when the `)` really is this `(`'s own, - // no ghost — even though a plain "is anything unbalanced" check on the - // rest of the file would say yes because of the `f(` beside it. - let text = "\ -module top; - always_comb begin - if ( - f(1) > 0) begin - end - end -endmodule -"; - assert_eq!(offered(text, " if ("), None); - } - - #[test] - fn an_always_without_its_event_control_offers_nothing() { - // The opener is a *sequence*: both `@` and `(` must be there, in that - // order, or the user has not committed to an event-controlled block. - // A bare `always` grows no block — only the keyword ghost's `_ff`, - // which is a different feature with its own setting. - let text = "module top;\n always\nendmodule\n"; - assert_eq!(offered(text, " always").as_deref(), Some("_ff")); - let text = "module top;\n always @\nendmodule\n"; - assert_eq!(offered(text, "always @"), None); - let text = "module top;\n always (\nendmodule\n"; - assert_eq!(offered(text, "always ("), None, "`(` alone is not `@(`"); - } - - #[test] - fn a_buffer_that_does_not_lex_is_declined() { - let text = "module top;\n /* unterminated\n always_comb begin\n"; - let (ws, uri, position) = asking(text, "always_comb begin"); - assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens"); - assert!(inline_completions(&ws, &uri, position).is_none()); - } - - #[test] - fn a_trigger_at_the_true_end_of_file_still_offers_a_ghost() { - // QA find, 2026-08-25: `tokenize` appends a zero-width `Eof` token - // whose span starts and ends at `text.len()`. When the file's very - // last byte is the trigger's own last character — no trailing - // newline, nothing typed after it yet — that `Eof` token shares the - // trigger token's `span.end`, and `rposition` (searching from the - // back) finds the `Eof` first. `triggered` then compares a - // `TokenKind::Eof` against `TokenKind::Keyword` and silently declines - // — exactly the moment a user typing at the end of a growing file - // most wants the ghost text to appear. - let text = "module top;\n always_comb begin"; - let (ws, uri, position) = asking(text, "always_comb begin"); - assert!( - inline_completions(&ws, &uri, position).is_some(), - "the file ends right after `begin`, with no Eof-adjacency confusion" - ); - - let text = "module top;\n always_comb begin\n if ("; - let (ws, uri, position) = asking(text, " if ("); - assert!( - inline_completions(&ws, &uri, position).is_some(), - "same for `if (` at true end of file" - ); - } - - #[test] - fn a_deeply_nested_file_neither_crashes_nor_misses_the_trigger() { - // History: the one recursion-depth bug this codebase had was in the - // *parser*'s AST (TODO.md §1, fixed by `MAX_NESTING_DEPTH`). This - // module never walks that tree — `triggered`/`unfinished` read - // `doc.tokens` and `pairs::analyze`, both flat loops over the token - // stream, so neither can overflow the stack the way the parser once - // did. QA find, 2026-08-25: `pairs::analyze` was quadratic in the - // depth of rainbow nesting back then, which mattered because this - // module calls it on every keystroke inside an unclosed `begin`. It - // is linear now — `Stack`'s running counts in `pairs.rs`, whose own - // tests pin the scaling — and this depth stands guard on the caller's - // side of that contract. - let depth = 3_000; - let mut text = String::from("module top;\n"); - for _ in 0..depth { - text.push_str(" begin\n"); - } - // A trailing newline, so this test isolates depth from the separate - // true-end-of-file `Eof`-adjacency case pinned above. - text.push_str("initial begin\n"); - // Opening the document *parses* it, and since §36.1 a bare `begin` at - // item scope is a generate block the tolerant parser descends into — - // so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4 - // MiB of stack in a debug build. That is exactly what - // `PARSE_STACK_SIZE` is for; every production thread that may reach a - // parse is given it (`main.rs`), libtest's own thread is not, so the - // body runs on one of its own. Nothing here is about the inline path, - // which still never recurses. - std::thread::Builder::new() - .stack_size(PARSE_STACK_SIZE) - .spawn(move || { - let (ws, uri, position) = asking(&text, "initial begin"); - assert!( - !ws.document(&uri).expect("open").tokens.is_empty(), - "the lexer never recurses" - ); - let items = inline_completions(&ws, &uri, position); - assert!( - items.is_some(), - "the innermost, truly unclosed `begin` still offers its `end`" - ); - }) - .expect("spawn") - .join() - .expect("the inline path crashed"); - } - - #[test] - fn an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic() { - let mut ws = Workspace::default(); - let uri = path_to_uri(&PathBuf::from("/rtl/empty.sv")).expect("uri"); - ws.set_document(uri.clone(), String::new()); - assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); - } - - #[test] - fn a_position_past_the_end_of_its_line_clamps_rather_than_panics() { - // Clients do send these — a keystroke can outrun the position the - // client had in hand. `convert.rs`'s `offset` clamps it to the line's - // real content end, which here happens to land exactly on the - // trigger, so the ghost still appears rather than nothing panicking - // but nothing offered either. - let text = "module top;\n always_comb begin\nendmodule\n"; - let (ws, uri, _) = asking(text, "always_comb begin"); - let items = inline_completions(&ws, &uri, Position { line: 1, character: 9_999 }); - assert!(items.is_some(), "clamped to right after `begin`, same as the exact position"); - // (0, 0) on a non-empty file: nowhere near a trigger, not a panic. - assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); - } - - #[test] - fn no_space_between_the_keyword_and_the_paren_still_triggers() { - // Token spans carry no inter-token whitespace of their own, so `if(` - // and `if (` must be indistinguishable to `triggered`. - let text = "module top;\n always_comb begin\n if(\n end\nendmodule\n"; - assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); - // ...and the same for a two-symbol opener written tight. - let text = "module top;\n always@(\nendmodule\n"; - assert_eq!(all_offered(text, "always@(").len(), 3); - } - - #[test] - fn crlf_line_endings_still_trigger() { - // `rest_of_line_is_blank` splits on `\n` alone, so a CRLF file's `\r` - // rides along in the slice — `char::is_whitespace('\r')` is `true`, - // so it still reads as "nothing after the cursor". - let text = "module top;\r\n always_comb begin\r\nendmodule\r\n"; - assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); - - let text = "module top;\r\n always_comb begin\r\n if (\r\n end\r\nendmodule\r\n"; - assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); - } - - #[test] - fn an_unknown_document_is_declined() { - let ws = Workspace::default(); - let uri = path_to_uri(&PathBuf::from("/rtl/gone.sv")).expect("uri"); - assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); - } - - #[test] - fn the_setting_turns_the_whole_feature_off() { - let text = "module top;\n always_comb begin\nendmodule\n"; - let (mut ws, uri, position) = asking(text, "always_comb begin"); - assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default"); - ws.set_client_settings(ClientSettings { - inline_templates: Some(false), - ..Default::default() - }); - assert!(inline_completions(&ws, &uri, position).is_none()); - ws.set_client_settings(ClientSettings { - inline_templates: Some(true), - ..Default::default() - }); - assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again"); - } - - // ------------------------------------------------------------------ - // the registry's own hygiene - // ------------------------------------------------------------------ - - /// Every body in the table, with the trigger it belongs to. - fn every() -> Vec<(&'static Trigger, &'static [Line])> { - TRIGGERS.iter().flat_map(|t| t.bodies.iter().map(move |body| (t, *body))).collect() - } - - /// What the user has typed by the time `trigger` fires. - fn typed(trigger: &Trigger) -> String { - let mut out = trigger.keyword.to_string(); - for symbol in trigger.opener { - out.push_str(symbol); - } - out - } - - /// `text` planted where its construct may legally be written. - /// - /// The default is statement position, so a trigger added without a thought - /// for this list either parses there — which is the common case — or fails - /// loudly. - fn planted(trigger: &Trigger, text: &str) -> String { - match trigger.keyword { - "module" => format!("{text}\n"), - "generate" | "always" | "always_ff" => { - format!("module lucisv_probe;\n {text}\nendmodule\n") - } - _ => { - format!("module lucisv_probe;\n always @(*) begin\n {text}\n end\nendmodule\n") - } - } - } - - #[test] - fn every_hole_is_a_tabstop() { - // The editor-snippets lesson: VS Code substitutes an unknown `$NAME` - // with nothing and says nothing, so a system task written into a body - // would vanish silently. None is written today; this is what stops one - // being added unescaped. - for (trigger, body) in every() { - for (_, line) in body { - let mut rest = *line; - while let Some(at) = rest.find('$') { - rest = &rest[at + 1..]; - assert!( - rest.starts_with('{') || rest.starts_with(|c: char| c.is_ascii_digit()), - "`{}`: `${}` is not a tabstop", - trigger.keyword, - rest.chars().next().unwrap_or(' ') - ); - } - } - } - } - - #[test] - fn every_accepted_ghost_parses() { - // What Tab really writes — the snippet as the *editor* lays it out, - // with every hole filled in — planted where the trigger fires and - // handed to the parser. A body that did not parse would be a formatter - // that refuses the file the moment the user accepts a suggestion. - for (trigger, body) in every() { - let text = filled(&accepted(&render(body), " ", " ")); - let probe = planted(trigger, &format!("{}{text}", typed(trigger))); - let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe); - assert!( - diagnostics.is_empty(), - "`{}` does not parse:\n{probe}\n{diagnostics:#?}", - trigger.keyword - ); - } - } - - #[test] - fn every_trigger_word_is_a_keyword_the_lexer_knows() { - // The detection compares against `TokenKind::Keyword`, so a trigger - // naming a word the lexer calls an identifier could never fire. - for trigger in TRIGGERS { - assert!( - vlog_parser::KEYWORDS.contains(&trigger.keyword), - "`{}` is not a keyword", - trigger.keyword - ); - } - } - - #[test] - fn every_accepted_ghost_is_scope_balanced() { - // What the user typed plus what Tab writes closes exactly what it - // opens: no dangling `begin`, no orphan `endcase`. The same matcher - // the gates ask, run over the result rather than over the buffer. - for (trigger, body) in every() { - let text = format!("{}{}", typed(trigger), filled(&render(body))); - let tokens = vlog_parser::tokenize(&text).expect("a body lexes"); - let analysis = pairs::analyze(&tokens); - assert!( - analysis.unmatched_open.is_empty() && analysis.unmatched_close.is_empty(), - "`{}` does not balance:\n{text}", - trigger.keyword - ); - } - } - - #[test] - fn every_gate_is_the_one_the_body_needs() { - // The rule behind the three `Unclosed` variants, derived from the - // bodies rather than restated: a body that writes a closer for a scope - // it did not open — `end` after a bare `begin`, `endcase` after - // `case (` — is finishing the *user's* keyword, so the gate must ask - // whether that keyword is still open. A body whose own `begin` its - // `end` closes needs no such question. And a trigger whose opener ends - // in `(` writes the `)`, so it must ask about the paren. - for trigger in TRIGGERS { - let closes_the_users_keyword = trigger.bodies.iter().any(|body| { - let tokens = vlog_parser::tokenize(&filled(&render(body))).expect("a body lexes"); - !pairs::analyze(&tokens).unmatched_close.is_empty() - }); - let writes_a_closing_paren = trigger.opener.last() == Some(&"("); - let (scope, paren) = match trigger.gate { - Unclosed::Paren => (false, true), - Unclosed::Scope => (true, false), - Unclosed::ParenAndScope => (true, true), - }; - assert_eq!( - closes_the_users_keyword, scope, - "`{}`: the scope half of the gate does not match the body", - trigger.keyword - ); - assert_eq!( - writes_a_closing_paren, paren, - "`{}`: the paren half of the gate does not match the opener", - trigger.keyword - ); - } - } - - #[test] - fn every_trigger_offers_at_least_one_body() { - for trigger in TRIGGERS { - assert!(!trigger.bodies.is_empty(), "`{}` offers nothing", trigger.keyword); - } - } - - // ------------------------------------------------------------------ - // round 2 QA: `accepted()` cross-checked against VS Code's own algorithm - // ------------------------------------------------------------------ - // - // `accepted()` above is a shortcut: it prepends `base` verbatim and only - // re-spells the `\t`s the body added. The real - // `SnippetSession.adjustWhitespace` re-derives the *whole* leading run — - // base included — from column counts (`TextModel.normalizeIndentation`), - // and normalizes the snippet's first line too. The shortcut is exact only - // when the trigger line's own indentation is already spelled the way the - // editor is configured — the ordinary case, and the only one these two - // tests assume — but "ordinary" was itself an assumption worth checking - // rather than trusting, so it is checked here against a second, - // independent model built straight off the quoted source rather than off - // `accepted`'s shortcut. - - /// `TextModel.normalizeIndentationFromWhitespace`. `ws` is assumed to be - /// entirely leading whitespace: every `\t` counts as `indent_size` - /// columns, every other character as one, and the whole run is re-spelled - /// as tabs-then-spaces (`insert_spaces: false`) or all spaces (`true`). - fn normalize_indentation_from_whitespace( - ws: &str, - indent_size: usize, - insert_spaces: bool, - ) -> String { - let columns: usize = ws.chars().map(|c| if c == '\t' { indent_size } else { 1 }).sum(); - let mut out = String::new(); - let mut spaces = columns; - if !insert_spaces { - out.extend(std::iter::repeat_n('\t', columns / indent_size)); - spaces = columns % indent_size; - } - out.extend(std::iter::repeat_n(' ', spaces)); - out - } - - /// `TextModel.normalizeIndentation`: only the leading run of spaces and - /// tabs is touched; everything from the first other character on is left - /// alone. - fn normalize_indentation(line: &str, indent_size: usize, insert_spaces: bool) -> String { - let split = line.find(|c: char| c != ' ' && c != '\t').unwrap_or(line.len()); - let (ws, rest) = line.split_at(split); - format!("{}{rest}", normalize_indentation_from_whitespace(ws, indent_size, insert_spaces)) - } - - /// `snippet` as `SnippetSession.adjustWhitespace` really writes it, - /// modelled directly off the quoted source: the first line is normalized - /// *alone* — `lines[0] = model.normalizeIndentation(lines[0])`, no - /// prepend, because `snippet.offset(marker) === 0` — and every later line - /// gets the trigger line's own leading whitespace prepended before - /// normalizing: `model.normalizeIndentation(lineLeadingWhitespace + - /// lines[i])`. - fn accepted_faithful( - snippet: &str, - trigger_line_indent: &str, - indent_size: usize, - insert_spaces: bool, - ) -> String { - snippet - .split('\n') - .enumerate() - .map(|(i, line)| match i { - 0 => normalize_indentation(line, indent_size, insert_spaces), - _ => normalize_indentation( - &format!("{trigger_line_indent}{line}"), - indent_size, - insert_spaces, - ), - }) - .collect::>() - .join("\n") - } - - #[test] - fn the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer() { - // A buffer whose own indentation already matches the editor's current - // `tabSize`/`insertSpaces` — spaces at 2, spaces at 4, tabs — at - // several depths, for every trigger's every body. - for (indent_size, insert_spaces, unit) in - [(2usize, true, " ".repeat(2)), (4, true, " ".repeat(4)), (4, false, "\t".to_string())] - { - let step = if insert_spaces { unit.clone() } else { "\t".to_string() }; - for depth in [0usize, 1, 2, 5] { - let base = unit.repeat(depth); - for (trigger, body) in every() { - let snippet = render(body); - let shortcut = accepted(&snippet, &base, &step); - let faithful = accepted_faithful(&snippet, &base, indent_size, insert_spaces); - assert_eq!( - shortcut, faithful, - "`{}` at depth {depth}, indent_size {indent_size}, insert_spaces {insert_spaces}: \ - the shortcut `accepted()` every other test uses disagrees with VS Code's own \ - normalizeIndentation", - trigger.keyword - ); - } - } - } - } - - #[test] - fn every_bodys_first_line_is_stable_under_normalization() { - // `accepted()`'s line-0 shortcut (`out.push(line.to_string())`, no - // normalization at all) is only correct because every body's first - // line today has either no leading whitespace or exactly one leading - // space, and a single space normalizes to itself at every indent_size - // VS Code allows. A future body whose first line picked up two or - // more leading spaces (or a leading tab) would make the shortcut - // silently wrong, and nothing else in this file would notice, because - // `every_accepted_ghost_parses` and its siblings only ever call - // `accepted`, never `accepted_faithful`. - for (trigger, body) in every() { - let (_, first_line) = body[0]; - for (indent_size, insert_spaces) in [(2usize, true), (4, true), (4, false), (8, false)] - { - assert_eq!( - normalize_indentation(first_line, indent_size, insert_spaces), - first_line, - "`{}`'s first line {first_line:?} is not stable at indent_size {indent_size}, \ - insert_spaces {insert_spaces} — `accepted()`'s line-0 shortcut would now be wrong", - trigger.keyword - ); - } - } - } - - #[test] - fn every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in() { - // The user's exact report: "the end lands deeper than its opener." - // Checked against the table's own `(level, text)` metadata rather - // than by re-deriving it, at several depths, in both indent styles, - // and for every trigger — not just the one construct the round-1 - // suite happened to cover. - let configs: &[(&str, &str)] = &[(" ", " "), (" ", " "), ("\t", "\t")]; - for (unit, step) in configs { - for depth in [0usize, 1, 2, 5] { - let base = unit.repeat(depth); - for (trigger, body) in every() { - let got = accepted(&render(body), &base, step); - let got_lines: Vec<&str> = got.split('\n').collect(); - assert_eq!(got_lines.len(), body.len(), "`{}`: line count", trigger.keyword); - for (i, (level, text)) in body.iter().enumerate() { - let expected = if i == 0 { - text.to_string() - } else { - format!("{base}{}{text}", step.repeat(*level as usize)) - }; - assert_eq!( - got_lines[i], expected, - "`{}`: line {i} at depth {depth}, base {unit:?}", - trigger.keyword - ); - } - // The closer is always the body's last line, and it must - // sit at level 0 — exactly the trigger line's own - // indentation, never a step deeper. - let (closer_level, _) = *body.last().expect("a body has a closer"); - assert_eq!(closer_level, 0, "`{}`: closer is not level 0", trigger.keyword); - } - } - } - } - - // ------------------------------------------------------------------ - // round 2 QA: attacking the new triggers - // ------------------------------------------------------------------ - - #[test] - fn casez_triggers_in_a_verilog_file_too() { - // `case`/`casez`/`casex` are `dialect: None` — a Verilog buffer gets - // the same ghost a SystemVerilog one does. - let text = "module top;\n always @(*) begin\n casez (\n end\nendmodule\n"; - assert!(!offered_in("/rtl/top.v", text, "casez (").is_empty()); - } - - #[test] - fn a_for_loop_in_a_pathless_buffer_gets_the_verilog_body() { - // `templates::dialect` resolves a pathless buffer to Verilog — the - // same default the completion tier documents — so an `untitled:` - // buffer (no path at all, unlike a `.v` or a `.sv` one) gets the loop - // with no local variable declaration and no `++`. - // - // `offered_in` goes through `path_to_uri`, which always mints a - // `file://` URI, so it cannot produce a genuinely pathless document — - // this builds the `untitled:` URI directly, the way `state.rs`'s own - // `an_untitled_buffer_has_no_path` does. - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - let offset = (text.find("for (").expect("needle present") + "for (".len()) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!( - items.items.iter().map(|i| i.insert_text.value.clone()).collect::>(), - vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"] - ); - } - - #[test] - fn always_at_space_paren_still_offers_both_items() { - // The lexer does not tokenize whitespace, so `@` and `(` end up - // adjacent in `doc.tokens` whether or not the user left a space - // between them; the opener sequence match is on tokens, not text — - // the tight `always@(` is already pinned by - // `no_space_between_the_keyword_and_the_paren_still_triggers`, this - // pins the opposite spacing. - let text = "module top;\n always @ (\nendmodule\n"; - assert_eq!(all_offered(text, "always @ (").len(), 3); - } - - #[test] - fn module_mid_file_above_an_existing_closed_module_still_offers() { - // `pairs::analyze` reports the *new* `module`'s own span in - // `unmatched_open` — an earlier, already-closed module does not - // cancel it out, the same rule - // `a_case_that_already_has_its_endcase_offers_nothing` proves for - // `case`. - let text = "module first;\nendmodule\n\nmodule"; - assert!(offered(text, "\nmodule").is_some()); - } - - #[test] - fn generate_offers_even_when_an_earlier_generate_is_balanced() { - let text = "module top;\n generate\n endgenerate\n generate\nendmodule\n"; - assert!( - offered(text, "endgenerate\n generate").is_some(), - "the second generate is genuinely open" - ); - } - - #[test] - fn fork_offers_in_both_dialects() { - let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; - assert!(!offered_in("/rtl/top.sv", text, " fork").is_empty()); - assert!(!offered_in("/rtl/top.v", text, " fork").is_empty()); - } - - #[test] - fn a_casex_whose_paren_is_closed_two_lines_down_offers_nothing() { - // Same rule `a_paren_the_line_below_closes_still_counts_as_closed` - // pins for `if (`, attacked on the trigger whose gate also asks about - // a scope: the paren half alone is enough to decline. - let text = "\ -module top; - always_comb begin - casex ( - sel) - 1: ; - endcase - end -endmodule -"; - assert_eq!(offered(text, "casex ("), None, "the `)` two lines down still closes the paren"); - } - - #[test] - fn nested_unclosed_parens_each_see_their_own_gate() { - // `if (` on one line and `always @(` on the next: two different - // unclosed parens. `paren_is_closed` is a stack keyed by the exact - // span passed in, so neither paren can be mistaken for the other's - // counterpart — both must still offer. - let text = "module top;\n if (\n always @(\nendmodule\n"; - assert!(offered(text, " if (").is_some()); - assert_eq!(all_offered(text, " always @(").len(), 3); - } - - // ------------------------------------------------------------------ - // the wire - // ------------------------------------------------------------------ - - #[test] - fn the_wire_shape_is_what_the_client_reads() { - // The whole reason these types are hand-rolled. `lsp-types` 0.97 spells - // `insertText` as a bare `String`, and `vscode-languageclient`'s - // `asInlineCompletionItem` inserts a bare string as **plain text** — - // every `${1:cond}` would appear literally in the buffer. Only the - // `{"kind": "snippet"}` object becomes a `SnippetString`. If a future - // `lsp-types` bump tempts anyone to use its item type, this fails. - let text = "module top;\n always_comb begin\nendmodule\n"; - let (ws, uri, position) = asking(text, "always_comb begin"); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!( - serde_json::to_value(&items).expect("serializes"), - serde_json::json!({ - "items": [{ - "insertText": { "kind": "snippet", "value": "\n\t$0\nend" }, - "range": { - "start": { "line": 1, "character": 19 }, - "end": { "line": 1, "character": 19 } - } - }] - }) - ); - } - - #[test] - fn a_multi_item_response_repeats_the_range_and_nothing_else() { - let text = "module top;\n always @(\nendmodule\n"; - let (ws, uri, position) = asking(text, "always @("); - let items = inline_completions(&ws, &uri, position).expect("two ghosts"); - assert_eq!( - serde_json::to_value(&items).expect("serializes"), - serde_json::json!({ - "items": [ - { - "insertText": { - "kind": "snippet", - "value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend" - }, - "range": { - "start": { "line": 1, "character": 11 }, - "end": { "line": 1, "character": 11 } - } - }, - { - "insertText": { - "kind": "snippet", - "value": "posedge ${1:clk}) begin\n\t$0\nend" - }, - "range": { - "start": { "line": 1, "character": 11 }, - "end": { "line": 1, "character": 11 } - } - }, - { - "insertText": { "kind": "snippet", "value": "*) begin\n\t$0\nend" }, - "range": { - "start": { "line": 1, "character": 11 }, - "end": { "line": 1, "character": 11 } - } - } - ] - }) - ); - } - - #[test] - fn the_range_is_empty_and_at_the_cursor() { - // The protocol requires a range to begin and end on one line, and this - // item inserts rather than replaces — so the only honest range is the - // caret itself. - let text = "module top;\n always_comb begin\nendmodule\n"; - let (ws, uri, position) = asking(text, "always_comb begin"); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!(items.items[0].range.start, position); - assert_eq!(items.items[0].range.end, position); - } - - #[test] - fn a_multibyte_line_puts_the_range_where_the_cursor_really_is() { - // The `é` is 2 bytes and 1 UTF-16 unit; a byte-based position would - // put the ghost one column late. - let text = "module top;\n // é\n always_comb begin\nendmodule\n"; - let (ws, uri, position) = asking(text, "always_comb begin"); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 }); - } - - // ------------------------------------------------------------------ - // the instantiation ghost (2026-08-30) - // ------------------------------------------------------------------ - - /// A scratch workspace root, removed on drop. The instantiation ghost is - /// the one path here that reads the index, so its tests need real files. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_inline_{}_{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).expect("temp dir"); - } - std::fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.path); - } - } - - /// The module every ghost below instantiates: parameters *and* ports, one - /// of which (`clk`) the buffer declares and so binds itself. - const SUB: &str = "\ -module sub #( - parameter int WIDTH = 8 -) ( - input logic clk, - input logic [WIDTH-1:0] data, - output logic ready -); -endmodule -"; - - /// The ghost `SUB`'s header produces, with the name the user typed *and - /// the space that armed it* already cut off the front. Written out once, - /// because half the tests below are about whether it appears at all rather - /// than about what it says. - const SUB_GHOST: &str = "#(\n\t.WIDTH(${1:8})\n) ${2:u_sub} (\n\t.clk(clk),\n\t\ - .data(${3:data}),\n\t.ready(${4:ready})\n);"; - - /// A workspace holding `files` plus an open `top.sv`, with the cursor at - /// `needle`'s end. - fn workspace( - name: &str, - files: &[(&str, &str)], - top: &str, - needle: &str, - ) -> (Tree, Workspace, Uri, Position) { - workspace_at(name, files, "top.sv", top, needle) - } - - /// The same, with the open buffer written at `top_rel` — which is what the - /// nearest-definition rule reads, so a test about *which* copy is chosen - /// has to be able to say where the asking buffer lives. - fn workspace_at( - name: &str, - files: &[(&str, &str)], - top_rel: &str, - top: &str, - needle: &str, - ) -> (Tree, Workspace, Uri, Position) { - let tree = Tree::new(name); - for (rel, text) in files { - tree.write(rel, text); - } - let path = tree.write(top_rel, top); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), top.to_string()); - let offset = (top.find(needle).expect("needle present") + needle.len()) as u32; - let position = ws.document(&uri).expect("open").positions().position(offset); - (tree, ws, uri, position) - } - - /// The one ghost offered at `needle`'s end in a workspace declaring `SUB`. - /// - /// `needle` names the text the cursor sits after, and every caller here - /// spells the arming space into it: since 2026-08-30 the ghost answers - /// `sub ` and never `sub`, because `sub` alone may still be growing into - /// `sub_dft`. - fn ghosted(name: &str, top: &str, needle: &str) -> Option { - ghosted_among(name, &[("sub.sv", SUB)], top, needle) - } - - /// The same, over a workspace spelled out by the caller. - fn ghosted_among( - name: &str, - files: &[(&str, &str)], - top: &str, - needle: &str, - ) -> Option { - ghosted_at(name, files, "top.sv", top, needle) - } - - /// The same again, with the asking buffer's own path spelled out. - fn ghosted_at( - name: &str, - files: &[(&str, &str)], - top_rel: &str, - top: &str, - needle: &str, - ) -> Option { - let (_tree, ws, uri, position) = workspace_at(name, files, top_rel, top, needle); - let items = inline_completions(&ws, &uri, position)?; - assert_eq!(items.items.len(), 1, "an instantiation is one offer, not a menu"); - Some(items.items[0].insert_text.value.clone()) - } - - #[test] - fn an_exactly_spelled_module_name_and_a_space_ghost_the_whole_instantiation() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - assert_eq!(ghosted("exact", top, " sub ").as_deref(), Some(SUB_GHOST)); - } - - /// The owner's ruling of 2026-08-30, both halves in one place: the space is - /// what arms the ghost, and without it there is nothing — *even though* - /// `sub` is a module the workspace really declares and the cursor really is - /// at a legal site. `aes` is not a commitment while `aes_dft` may still be - /// coming; `aes ` is. - #[test] - fn the_name_alone_offers_nothing_and_the_name_and_a_space_offer_everything() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - assert_eq!(ghosted("armed_no", top, " sub"), None, "the name alone is not a commitment"); - assert_eq!(ghosted("armed_yes", top, " sub ").as_deref(), Some(SUB_GHOST)); - } - - /// One space, and the one just typed. Two of them is a cursor parked in - /// whitespace rather than a name just finished, and a tab is not the - /// character this rule is about at all. - #[test] - fn only_a_single_space_arms_the_ghost() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - assert_eq!(ghosted("twospaces", top, " sub "), None, "two spaces is not `just typed`"); - let top = "module top;\n logic clk;\n sub\t\nendmodule\n"; - assert_eq!(ghosted("tab", top, " sub\t"), None, "a tab does not arm it"); - // …and the first of the two spaces still does, which is the same rule - // read from the other side: the byte before the cursor is a space and - // the byte before that is not. - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - assert_eq!(ghosted("firstspace", top, " sub ").as_deref(), Some(SUB_GHOST)); - } - - /// A name that is not a module, followed by a space, is the overwhelmingly - /// common keystroke on this path — it must cost the binary search and stop. - #[test] - fn a_space_after_a_name_that_is_not_a_module_ghosts_nothing() { - let top = "module top;\n logic clk;\n widget \nendmodule\n"; - assert_eq!(ghosted("notamodule", top, " widget "), None); - } - - /// The layout `vlog_refactor` renders really does put exactly one space - /// between a module's name and whatever follows it, in both shapes: a - /// parameterised header (`sub #(`) and a bare one (`bare u_bare`). The cut - /// in `instantiation_ghost` asserts this rather than assuming it — see - /// [`NoGhost::UnexpectedLayout`] — and this is what would fail first if the - /// spelling ever changed. - #[test] - fn the_rendered_skeleton_really_does_put_one_space_after_the_name() { - for (name, module, files) in [ - ("layout_params", "sub", &[("sub.sv", SUB)][..]), - ("layout_bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..]), - ] { - let top = format!("module top;\n logic clk;\n {module} \nendmodule\n"); - let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost"); - assert!( - !ghost.starts_with(char::is_whitespace), - "{module}: the arming space is the ghost's, not the user's: {ghost:?}" - ); - } - } - - /// The accepted text is what the popup's skeleton used to insert, byte for - /// byte — which is the argument that level 2 gives up nothing level 1 gave - /// away. The layout the server sends is relative; the editor supplies the - /// site's own indentation and the width of a step. - #[test] - fn the_accepted_ghost_is_the_skeleton_the_popup_used_to_insert() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - let ghost = ghosted("accepted", top, " sub ").expect("a ghost"); - assert_eq!( - format!("sub {}", accepted(&ghost, " ", " ")), - "\ -sub #( - .WIDTH(${1:8}) - ) ${2:u_sub} ( - .clk(clk), - .data(${3:data}), - .ready(${4:ready}) - );" - ); - // …and it follows the editor's tabs, not `lucisv.indent`, at any depth. - assert!(accepted(&ghost, "\t\t", "\t").contains("\n\t\t\t.clk(clk),"), "{ghost}"); - } - - /// What the user ends up with must parse. The typed name, the accepted - /// body, every hole filled in the way the editor preselects it, planted at - /// the item position the gate insisted on. - #[test] - fn the_accepted_ghost_parses_where_it_was_offered() { - for (name, module, files, holes) in [ - ("ports", "sub", &[("sub.sv", SUB)][..], 4), - ("bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..], 1), - ( - "portless", - "empty", - &[("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n")][..], - 2, - ), - ] { - let top = format!("module top;\n logic clk;\n {module} \nendmodule\n"); - let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost"); - assert_eq!( - ghost.matches("${").count(), - holes, - "{module}: every fill-in is a tabstop: {ghost}" - ); - // The name, the space that armed the ghost, and the ghost itself — - // which is exactly what the buffer holds after Tab. - let written = filled(&format!("{module} {}", accepted(&ghost, " ", " "))); - let probe = format!("module lucisv_probe;\n logic clk;\n {written}\nendmodule\n"); - assert!( - vlog_parser::parse_source_tolerant(&probe).1.is_empty(), - "the accepted text must parse:\n{probe}" - ); - } - } - - /// The premise the "the accepted text must parse" probe above rests on: - /// the probe can still fail. Header recovery (TODO §32) widened what a - /// tolerant parse reads — a half-typed connection list is now a recovered - /// instantiation rather than a dead item — so the probe is only worth - /// asking while text that does not parse still says so. - #[test] - fn the_accepted_text_probe_still_reports_text_that_does_not_parse() { - let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n"; - assert!( - !vlog_parser::parse_source_tolerant(probe).1.is_empty(), - "recovery must not make a broken instantiation look clean" - ); - } - - #[test] - fn a_module_with_no_ports_ghosts_a_sane_instantiation() { - let top = "module top;\n bare \nendmodule\n"; - assert_eq!( - ghosted_among("bareports", &[("bare.sv", "module bare;\nendmodule\n")], top, " bare ") - .as_deref(), - Some("${1:u_bare} ();") - ); - } - - #[test] - fn a_half_typed_name_ghosts_nothing() { - // The popup is what answers here — with the *name*, which is the whole - // division of labour between the two levels. - let top = "module top;\n logic clk;\n su \nendmodule\n"; - assert_eq!(ghosted("partial", top, " su "), None); - // …and one character past the name is not the name either. - let top = "module top;\n logic clk;\n subs \nendmodule\n"; - assert_eq!(ghosted("past", top, " subs "), None); - } - - #[test] - fn a_case_mismatched_name_ghosts_nothing() { - // The popup's substring match folds case; this one must not. `SUB` is - // not a module any Verilog tool would find. - for typed in ["SUB", "Sub", "sUb"] { - let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n"); - assert_eq!(ghosted("case", &top, &format!(" {typed} ")), None, "{typed}"); - } - } - - #[test] - fn a_name_the_workspace_does_not_declare_as_a_module_ghosts_nothing() { - let files = - &[("sub.sv", SUB), ("p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n")]; - for typed in ["pkg", "W", "clk", "nothing_at_all"] { - let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n"); - assert_eq!( - ghosted_among("nonmodule", files, &top, &format!(" {typed} ")), - None, - "{typed} is not a module" - ); - } - } - - #[test] - fn anything_after_the_cursor_on_the_line_ghosts_nothing() { - // The rest-of-line rule the templates already live by: a name with a - // `;` after it is code the user has finished writing. - let top = "module top;\n logic clk;\n sub u_sub ();\nendmodule\n"; - assert_eq!(ghosted("after", top, " sub "), None); - } - - #[test] - fn a_name_that_is_not_at_item_position_ghosts_nothing() { - // Every one of these spells `sub` exactly and none of them is a place - // an instantiation may be written. The gate is `completion.rs`'s own, - // so this is the ghost inheriting the popup's answer rather than - // inventing a second one. - for (name, top, needle) in [ - ("connection", "module top;\n other u (.aes(sub \nendmodule\n", ".aes(sub "), - ("assign", "module top;\n wire x;\n assign x = sub \nendmodule\n", "= sub "), - ("declaration", "module top;\n logic sub \nendmodule\n", "logic sub "), - ( - "procedural", - "module top;\n initial begin\n sub \n end\nendmodule\n", - " sub ", - ), - ( - "function", - "module top;\n function int f();\n sub \n endfunction\nendmodule\n", - " sub ", - ), - ("file scope", "sub \nmodule top;\nendmodule\n", "sub "), - ("port list", "module top (sub \n);\nendmodule\n", "top (sub "), - ] { - assert_eq!(ghosted("position", top, needle), None, "{name}: {top}"); - } - } - - #[test] - fn a_generate_block_is_still_item_position_for_the_ghost() { - let top = "module top;\n logic clk;\n generate\n sub \n endgenerate\nendmodule\n"; - assert_eq!(ghosted("gen", top, " sub ").as_deref(), Some(SUB_GHOST)); - } - - #[test] - fn a_module_name_in_a_comment_or_a_string_ghosts_nothing() { - // A token property, not a check of this module's own: a comment is - // lexer trivia and never a token, and a string literal is one `String` - // token whose kind is not `Ident`. - let top = "module top;\n // sub \nendmodule\n"; - assert_eq!(ghosted("comment", top, "// sub "), None); - let top = "module top;\n initial $display(\"sub \nendmodule\n"; - assert_eq!(ghosted("string", top, "\"sub "), None); - } - - #[test] - fn a_buffer_that_does_not_lex_ghosts_nothing() { - let top = "module top;\n /* unterminated\n sub \n"; - let (_tree, ws, uri, position) = workspace("nolex", &[("sub.sv", SUB)], top, " sub "); - assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens"); - assert!(inline_completions(&ws, &uri, position).is_none()); - } - - #[test] - fn an_exact_name_at_the_true_end_of_the_file_still_ghosts() { - // The `Eof` sentinel shares the last real token's end, so the same - // skip the templates needed (QA find, 2026-08-25) is what lets a name - // typed as the buffer's very last bytes answer. - // True EOF is now the buffer ending with the *space*: the name plus - // the keystroke that arms it, with nothing after either. - let top = "module top;\n logic clk;\n sub "; - assert_eq!(ghosted("eof", top, " sub ").as_deref(), Some(SUB_GHOST)); - } - - /// opentitan's `ast_dft` and `io_osc` in miniature: one module, one copy - /// under each of two tops, with headers that differ so the ghost says which - /// copy it read. - const TWO_TOPS: &[(&str, &str)] = &[ - ("top_earlgrey/ast_dft.sv", "module ast_dft (input logic clk_earlgrey);\nendmodule\n"), - ("top_darjeeling/ast_dft.sv", "module ast_dft (input logic clk_darjeeling);\nendmodule\n"), - ]; - - /// What each copy of `ast_dft` ghosts. Neither port is declared in the - /// asking buffer, so neither auto-connects and the port name is visible in - /// the hole — which is how these tests tell the two copies apart. - const EARLGREY_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_earlgrey(${2:clk_earlgrey})\n);"; - const DARJEELING_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_darjeeling(${2:clk_darjeeling})\n);"; - - #[test] - fn a_module_declared_twice_ghosts_the_copy_nearest_the_buffer() { - // Round 1 gave a twice-declared module no ghost at all: - // `module_definition` refuses to guess which file to read, and the - // ghost inherited the refusal. In opentitan that silenced `ast_dft` - // and `io_osc`, each declared once under `hw/top_earlgrey/ip/ast/rtl` - // and once under `hw/top_darjeeling/ip/ast/rtl` — two whole IP blocks. - // Owner ruling, 2026-08-30: every indexed module expands, so the - // server chooses the copy whose path shares the longest run of leading - // path components with the buffer asking. - let top = "module top;\n ast_dft \nendmodule\n"; - assert_eq!( - ghosted_at("earlgrey", TWO_TOPS, "top_earlgrey/top.sv", top, " ast_dft ").as_deref(), - Some(EARLGREY_GHOST), - "a buffer under top_earlgrey gets top_earlgrey's copy" - ); - assert_eq!( - ghosted_at("darjeeling", TWO_TOPS, "top_darjeeling/top.sv", top, " ast_dft ") - .as_deref(), - Some(DARJEELING_GHOST), - "…and one under top_darjeeling gets the other" - ); - } - - #[test] - fn a_buffer_near_neither_copy_gets_the_lexicographically_smaller_path() { - // No shared prefix to rank by, so the tie-break decides — and it is a - // property of the paths rather than of the order the index was built - // in, which is what makes it reproducible. `top_darjeeling` sorts - // before `top_earlgrey`. - let top = "module top;\n ast_dft \nendmodule\n"; - assert_eq!( - ghosted_at("neither", TWO_TOPS, "elsewhere/top.sv", top, " ast_dft ").as_deref(), - Some(DARJEELING_GHOST) - ); - } - - #[test] - fn the_two_copies_may_have_different_headers_and_the_nearest_one_wins() { - // The accepted semantics, written down: the copies are not required to - // agree, and the user gets the one their own file is nearest to. Here - // one copy has a parameter the other has not, so the two ghosts do not - // even have the same shape. - let files = &[ - ( - "top_a/dup.sv", - "module dup #(\n parameter int W = 4\n) (input logic a);\nendmodule\n", - ), - ("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"), - ]; - let top = "module top;\n dup \nendmodule\n"; - assert_eq!( - ghosted_at("hdr_a", files, "top_a/top.sv", top, " dup ").as_deref(), - Some("#(\n\t.W(${1:4})\n) ${2:u_dup} (\n\t.a(${3:a})\n);") - ); - assert_eq!( - ghosted_at("hdr_b", files, "top_b/top.sv", top, " dup ").as_deref(), - Some("${1:u_dup} (\n\t.b(${2:b})\n);") - ); - } - - #[test] - fn a_plan_with_an_escaped_identifier_gets_no_ghost() { - // An escaped identifier may legally contain `$`, `}` and `\` — the - // snippet grammar's own punctuation — and the names are written by the - // layout, outside every hole, where no escaping can reach them. The - // popup answered this with a plain-text item; an inline completion has - // no plain-text spelling, so it answers with nothing. - let files = - &[("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n")]; - let top = "module top;\n logic clk;\n odd \nendmodule\n"; - assert_eq!(ghosted_among("escaped", files, top, " odd "), None); - } - - #[test] - fn a_module_may_ghost_itself() { - // Cursor inside `top`, typing `top`. The plan is real — `top` is a - // module the workspace declares and the instantiation is legal - // Verilog — so it is offered. Whether instantiating yourself is a good - // idea is the user's business; an elaborator will tell them soon - // enough, and refusing would be this server having an opinion about - // recursion that it cannot back up (a `generate` guarded by a - // parameter is a legitimate recursive structure). - let top = "module top (input logic clk);\n top \nendmodule\n"; - assert_eq!( - ghosted("self", top, " top ").as_deref(), - Some("${1:u_top} (\n\t.clk(clk)\n);") - ); - } - - #[test] - fn the_setting_turns_the_instantiation_ghost_off_and_leaves_the_templates_on() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - let (_tree, mut ws, uri, position) = - workspace("setting", &[("sub.sv", SUB)], top, " sub "); - assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default"); - ws.set_client_settings(ClientSettings { - inline_instantiation: Some(false), - ..Default::default() - }); - assert!(inline_completions(&ws, &uri, position).is_none()); - ws.set_client_settings(ClientSettings { - inline_instantiation: Some(true), - ..Default::default() - }); - assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again"); - - // The two settings are independent in both directions: the templates - // answer with the instantiation off, and the reverse. - let (_tree, mut ws, uri, position) = - workspace("both", &[("sub.sv", SUB)], "module top;\n always_comb begin\n", "begin"); - ws.set_client_settings(ClientSettings { - inline_instantiation: Some(false), - ..Default::default() - }); - assert!( - inline_completions(&ws, &uri, position).is_some(), - "a template is not an offer \ - the instantiation setting governs" - ); - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - let (_tree, mut ws, uri, position) = - workspace("tmploff", &[("sub.sv", SUB)], top, " sub "); - ws.set_client_settings(ClientSettings { - inline_templates: Some(false), - ..Default::default() - }); - assert!(inline_completions(&ws, &uri, position).is_some(), "…and the other way round"); - } - - #[test] - fn the_only_residue_over_a_workspace_is_the_escaped_identifier() { - // Round 2, part C: after the space-armed trigger and the - // nearest-definition chooser, the reasons an indexed module does *not* - // ghost have to be enumerable — so a sweep over every module a - // workspace declares can bucket its misses by reason instead of - // shrugging at them. This is that sweep in miniature, over a workspace - // carrying one of every shape the planner meets: parameters and ports, - // neither, parameters only, a non-ANSI port list, a name two files - // declare, and the one shape that genuinely cannot be ghosted. - let files = &[ - ("sub.sv", SUB), - ("bare.sv", "module bare;\nendmodule\n"), - ("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n"), - ( - "nonansi.sv", - "module nonansi (a, b);\n input wire a;\n output wire b;\nendmodule\n", - ), - ("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n"), - ("top_a/dup.sv", "module dup (input logic a);\nendmodule\n"), - ("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"), - ]; - let top = "module top;\n logic clk;\n probe \nendmodule\n"; - let (_tree, ws, uri, _) = workspace("residue", files, top, " probe "); - let doc = ws.document(&uri).expect("open"); - let at = top.find(" probe").expect("the probe line") as u32 + 2; - - let modules: Vec = - ws.candidates().modules("").iter().map(|name| name.to_string()).collect(); - assert!(modules.len() >= 7, "premise: the sweep really covers the workspace: {modules:?}"); - let refused: Vec<(&str, NoGhost)> = modules - .iter() - .filter_map(|module| { - instantiation_ghost(&ws, doc, module, at).err().map(|why| (module.as_str(), why)) - }) - .collect(); - assert_eq!( - refused, - vec![("odd", NoGhost::EscapedIdentifier)], - "the residue is the escaped identifier and nothing else" - ); - } - - #[test] - fn the_instantiation_wire_shape_is_one_snippet_item_at_the_cursor() { - let top = "module top;\n logic clk;\n sub \nendmodule\n"; - let (_tree, ws, uri, position) = workspace("wire", &[("sub.sv", SUB)], top, " sub "); - let items = inline_completions(&ws, &uri, position).expect("a ghost"); - assert_eq!( - serde_json::to_value(&items).expect("serializes"), - serde_json::json!({ - "items": [{ - "insertText": { "kind": "snippet", "value": SUB_GHOST }, - "range": { - "start": { "line": 2, "character": 6 }, - "end": { "line": 2, "character": 6 } - } - }] - }) - ); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/inline/tests.rs b/crates/lucisv_server/src/inline/tests.rs new file mode 100644 index 0000000..5da6f73 --- /dev/null +++ b/crates/lucisv_server/src/inline/tests.rs @@ -0,0 +1,1672 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::settings::ClientSettings; +use crate::uri::path_to_uri; +use std::path::PathBuf; +use std::str::FromStr; +use vlog_parser::PARSE_STACK_SIZE; + +/// A one-file workspace with `path` open and the cursor at `needle`'s end. +/// No files on disk: nothing here reads the index. +fn asking_in(path: &str, text: &str, needle: &str) -> (Workspace, Uri, Position) { + let uri = path_to_uri(&PathBuf::from(path)).expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find(needle).expect("needle present") + needle.len()) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + (ws, uri, position) +} + +/// [`triggered`] used to sweep the token vector backwards from its end for +/// the last non-`Eof` token ending at or before the cursor. It now bounds +/// that sweep with a binary search; the token it lands on must be the same +/// one at every byte. +#[test] +fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() { + let text = crate::state::mixed_buffer(20); + let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.clone()); + let doc = ws.document(&uri).expect("open"); + for offset in 0..=text.len() as u32 { + let swept = doc + .tokens + .iter() + .rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset); + let reached = doc.tokens.partition_point(|token| token.span.end <= offset); + let searched = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof); + assert_eq!(swept, searched, "at offset {offset}"); + } +} + +/// The same, in a SystemVerilog buffer. +fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) { + asking_in("/rtl/top.sv", text, needle) +} + +/// Every snippet offered at `needle`'s end, in order. +fn all_offered(text: &str, needle: &str) -> Vec { + offered_in("/rtl/top.sv", text, needle) +} + +/// Every snippet offered at `needle`'s end in a buffer called `path`. +fn offered_in(path: &str, text: &str, needle: &str) -> Vec { + let (ws, uri, position) = asking_in(path, text, needle); + match inline_completions(&ws, &uri, position) { + None => Vec::new(), + Some(items) => items.items.iter().map(|i| i.insert_text.value.clone()).collect(), + } +} + +/// The one snippet offered at `needle`'s end, if any. +fn offered(text: &str, needle: &str) -> Option { + let mut items = all_offered(text, needle); + assert!(items.len() <= 1, "one ghost or none, got {items:?}"); + items.pop() +} + +/// `snippet` as VS Code really writes it into the buffer. +/// +/// `SnippetSession.adjustWhitespace` prepends the insertion line's own +/// leading whitespace — `base` — to every line after the first, then +/// `TextModel.normalizeIndentation` re-spells the whole leading run in the +/// editor's tabs-or-spaces, which is what turns each `\t` the server sent +/// into one `step`. +fn accepted(snippet: &str, base: &str, step: &str) -> String { + let mut out: Vec = Vec::new(); + for (index, line) in snippet.split('\n').enumerate() { + if index == 0 { + out.push(line.to_string()); + continue; + } + let steps = line.chars().take_while(|c| *c == '\t').count(); + out.push(format!("{base}{}{}", step.repeat(steps), &line[steps..])); + } + out.join("\n") +} + +/// `snippet` with every hole filled in the way the editor would preselect +/// it — the plain text a Tab really produces. The registry's grammar is +/// `${n:default}` and `$n` and nothing else, which +/// `every_hole_is_a_tabstop` pins. +fn filled(snippet: &str) -> String { + let mut out = String::new(); + let mut rest = snippet; + let mut mirrors: Vec<(&str, &str)> = Vec::new(); + while let Some(at) = rest.find('$') { + out.push_str(&rest[..at]); + rest = &rest[at + 1..]; + if let Some(braced) = rest.strip_prefix('{') { + let close = braced.find('}').expect("a hole is closed"); + let hole = &braced[..close]; + if let Some((number, default)) = hole.split_once(':') { + mirrors.push((number, default)); + out.push_str(default); + } + rest = &braced[close + 1..]; + continue; + } + let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + let number = &rest[..digits]; + // A bare `$n` repeats what `${n:…}` was given, the way the editor + // mirrors a placeholder; `$0` was never declared and is nothing. + if let Some((_, default)) = mirrors.iter().find(|(n, _)| *n == number) { + out.push_str(default); + } + rest = &rest[digits..]; + } + out.push_str(rest); + out +} + +// ------------------------------------------------------------------ +// the emission contract: relative, not absolute +// ------------------------------------------------------------------ + +#[test] +fn a_snippet_is_indented_relative_to_the_trigger_line() { + // The 0.6.0 bug: the body used to carry the trigger line's own + // indentation, and VS Code prepends it *again* on insert, so the `end` + // landed a level deeper than the `begin` it closes. One `\t` per step + // and nothing else is what the editor can place correctly. + let text = "module top;\n always_comb begin\nendmodule\n"; + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); +} + +#[test] +fn the_editor_puts_the_end_level_with_its_opener() { + // What the user actually sees after Tab, with the two things VS Code + // does to the text modelled: the base prepended, one `\t` widened to + // the editor's indent. + let text = "module top;\n always_comb begin\nendmodule\n"; + let snippet = offered(text, "always_comb begin").expect("a ghost"); + assert_eq!(accepted(&snippet, " ", " "), "\n $0\n end"); + // ...at any depth, and in tabs as readily as in spaces. + assert_eq!(accepted(&snippet, "\t\t", "\t"), "\n\t\t\t$0\n\t\tend"); +} + +#[test] +fn the_line_indentation_never_reaches_the_snippet() { + // The same three lines however deep the trigger sits and however the + // buffer spells its indentation: the server has stopped having an + // opinion about either. + for line in ["always_comb begin", " always_comb begin", "\t\talways_comb begin"] { + let text = format!("module top;\n{line}\nendmodule\n"); + assert_eq!(offered(&text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); + } +} + +#[test] +fn the_indent_setting_no_longer_reaches_a_snippet() { + // `lucisv.indent` still decides what the *formatter* writes and what the + // completion popup inserts; an accepted inline snippet is laid out by + // the editor's own tab settings, because the editor re-spells the + // leading whitespace on insert whatever the server sent. + let text = "module top;\n always_comb begin\nendmodule\n"; + let (mut ws, uri, position) = asking(text, "always_comb begin"); + ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() }); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!(items.items[0].insert_text.value, "\n\t$0\nend"); +} + +// ------------------------------------------------------------------ +// the triggers +// ------------------------------------------------------------------ + +#[test] +fn an_open_if_paren_offers_the_rest_of_the_block() { + let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n"; + assert_eq!( + offered(text, " if (").as_deref(), + Some("${1:cond}) begin\n\t$0\nend"), + "the condition first and the body last" + ); +} + +#[test] +fn an_else_if_offers_the_same_block() { + let text = "\ +module top; + always_comb begin + if (a) begin + end else if ( + end +endmodule +"; + assert_eq!(offered(text, "else if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); +} + +#[test] +fn a_fresh_begin_offers_its_end() { + let text = "module top;\n always_comb begin\nendmodule\n"; + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); +} + +#[test] +fn a_while_offers_the_same_block_as_an_if() { + let text = "module top;\n initial begin\n while (\n end\nendmodule\n"; + assert_eq!(offered(text, "while (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); +} + +#[test] +fn a_for_loop_follows_the_buffers_dialect() { + // The same two bodies `templates.rs` offers in the popup, minus the + // `for (` the user has already typed. + let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; + assert_eq!( + offered_in("/rtl/top.sv", text, "for ("), + vec!["int ${1:i} = 0; $1 < ${2:N}; $1++) begin\n\t$0\nend"], + "SystemVerilog declares the loop variable in the header" + ); + assert_eq!( + offered_in("/rtl/top.v", text, "for ("), + vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"], + "Verilog has no `++` and no local loop variable" + ); +} + +#[test] +fn every_case_flavour_offers_the_same_arms_and_an_endcase() { + for keyword in ["case", "casez", "casex"] { + let text = format!("module top;\n always_comb begin\n {keyword} (\n end\nendmodule\n"); + assert_eq!( + offered(&text, &format!("{keyword} (")).as_deref(), + Some("${1:sel})\n\t${2:value}: $0;\n\tdefault: ;\nendcase"), + "{keyword}" + ); + } +} + +#[test] +fn casex_is_offered_here_although_the_popup_does_not_list_it() { + // `templates.rs` leaves `casex` out on purpose: it is the flavour most + // style guides warn against, and an unused entry is noise in a list. + // Ghost text is not a list — it only ever appears once the user has + // typed `casex (` and committed to it — so the noise argument does not + // apply and refusing to finish the construct would just be unhelpful. + let text = "module top;\n always_comb begin\n casex (\n end\nendmodule\n"; + assert!(offered(text, "casex (").is_some()); +} + +#[test] +fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() { + let text = "module top;\n always @(\nendmodule\n"; + assert_eq!( + all_offered(text, "always @("), + vec![ + "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(), + "posedge ${1:clk}) begin\n\t$0\nend".to_string(), + "*) begin\n\t$0\nend".to_string(), + ], + "clocked first: `always @(` is overwhelmingly a flop, and most flops reset" + ); +} + +#[test] +fn always_ff_is_systemverilog_only() { + let text = "module top;\n always_ff @(\nendmodule\n"; + assert_eq!( + offered_in("/rtl/top.sv", text, "always_ff @("), + vec![ + "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend", + "posedge ${1:clk}) begin\n\t$0\nend" + ] + ); + assert!( + offered_in("/rtl/top.v", text, "always_ff @(").is_empty(), + "a `.v` compiler rejects `always_ff`" + ); +} + +#[test] +fn fork_generate_and_module_offer_their_own_closers() { + let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; + assert_eq!(offered(text, " fork").as_deref(), Some("\n\t$0\njoin")); + + let text = "module top;\n generate\nendmodule\n"; + assert_eq!(offered(text, " generate").as_deref(), Some("\n\t$0\nendgenerate")); + + // A module needs a name before its `;`, so the body writes one — the + // leading space is deliberate, the user's cursor sits right after the + // `e` of `module`. + assert_eq!(offered("module", "module").as_deref(), Some(" ${1:name};\n\t$0\nendmodule")); +} + +// ------------------------------------------------------------------ +// the negatives +// ------------------------------------------------------------------ + +#[test] +fn a_comment_or_a_string_never_triggers() { + // Neither is a token: a comment is lexer trivia, and the literal is one + // `String` token whose text is not a keyword. + for (text, needle, what) in [ + ("module top;\n // if (\nendmodule\n", "// if (", "a line comment"), + ("module top;\n /* if ( */\nendmodule\n", "/* if (", "a block comment"), + ("module top;\n initial $display(\"if (\");\nendmodule\n", "\"if (", "inside a string"), + ("module top;\n initial $display(\"begin\");\nendmodule\n", "\"begin", "ditto"), + ("module top;\n // begin\nendmodule\n", "// begin", "a commented begin"), + ("module top;\n // case (\nendmodule\n", "// case (", "a commented case"), + ] { + assert_eq!(offered(text, needle), None, "{what}: {text}"); + } +} + +#[test] +fn an_identifier_that_merely_ends_in_the_keyword_never_triggers() { + let text = "module top;\n always_comb begin\n my_if (\n end\nendmodule\n"; + assert_eq!(offered(text, "my_if ("), None, "`my_if` is an identifier"); + let text = "module top;\n logic my_begin;\n assign my_begin\nendmodule\n"; + assert_eq!(offered(text, "assign my_begin"), None); +} + +#[test] +fn a_line_with_anything_after_the_cursor_never_triggers() { + let text = "module top;\n always_comb begin\n if (a) begin\n end\n end\nendmodule\n"; + assert_eq!(offered(text, " if ("), None, "the condition is already written"); + let text = "module top;\n always_comb begin ; end\nendmodule\n"; + assert_eq!(offered(text, "always_comb begin"), None); +} + +#[test] +fn whitespace_between_the_keyword_and_the_cursor_never_triggers() { + // The cursor must be exactly at the token's end — "you just typed + // this", and nothing looser. + let text = "module top;\n always_comb begin \nendmodule\n"; + assert_eq!(offered(text, "always_comb begin "), None); + let text = "module top;\n always_comb begin\n if ( \n end\nendmodule\n"; + assert_eq!(offered(text, "if ( "), None); +} + +#[test] +fn a_begin_that_already_has_its_end_offers_nothing() { + // The `end` below belongs to the `begin` just typed — `pairs::analyze` + // matches them — so a second one would break the file. + let text = "\ +module top; + always_comb begin + begin + end + end +endmodule +"; + assert_eq!(offered(text, " begin"), None, "the inner begin is matched"); + // ...and the one that really is unclosed still offers. + let text = "module top;\n always_comb begin\n end\n initial begin\nendmodule\n"; + assert!(offered(text, "initial begin").is_some(), "this one lost its end"); +} + +#[test] +fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() { + // The new `begin` steals the `always_comb` block's `end` in the stack + // matcher; the gate asks the auto-`end` question instead + // (`completion-ux` fix round, 2026-11-17). + let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n"; + assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend")); +} + +#[test] +fn a_scope_keyword_that_already_has_its_closer_offers_nothing() { + // The same rule as `begin`, for the three keywords that joined it. + let text = "module top;\n initial begin\n fork\n join\n end\nendmodule\n"; + assert_eq!(offered(text, " fork"), None); + let text = "module top;\n generate\n endgenerate\nendmodule\n"; + assert_eq!(offered(text, " generate"), None); + let text = "module\nendmodule\n"; + assert_eq!(offered(text, "module"), None); + // `disable fork;` names a fork rather than opening one — `pairs.rs` + // knows, and the gate inherits that. + let text = "module top;\n initial begin\n disable fork\n end\nendmodule\n"; + assert_eq!(offered(text, "disable fork"), None); +} + +#[test] +fn a_case_that_already_has_its_endcase_offers_nothing() { + // Both halves of the `case (` gate matter. Here the `endcase` below is + // this `case`'s own, so a second one would leave the file unbalanced — + // even though the `(` really is unclosed. + let text = "\ +module top; + always_comb begin + case ( + endcase + end +endmodule +"; + assert_eq!(offered(text, " case ("), None, "the endcase is already there"); + // ...and when the `endcase` below belongs to a nested, complete `case`, + // the one just typed still owes its own. + let text = "\ +module top; + always_comb begin + case ( + case (b) + default: ; + endcase + end +endmodule +"; + assert!(offered(text, " case (").is_some(), "this case is genuinely unclosed"); +} + +#[test] +fn an_if_paren_that_is_already_closed_offers_nothing() { + // A `)` further down the buffer is the one this `(` will pair with; + // writing a second would leave the file unbalanced the other way. + let text = + "module top;\n always_comb begin\n if (\n a) begin\n end\n end\nendmodule\n"; + assert_eq!(offered(text, " if ("), None); +} + +#[test] +fn a_later_call_does_not_cancel_the_paren_just_typed() { + // A running `(` minus `)` count would see the `)` of `f(1)` below and + // decide this `(` was already closed. It is a stack, so the call's own + // paren pairs with its own closer and the `if (` stays open. + let text = "\ +module top; + always_comb begin + if ( + x = f(1); + end +endmodule +"; + assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); +} + +#[test] +fn a_paren_the_line_below_closes_still_counts_as_closed() { + // The mirror of the test above: when the `)` really is this `(`'s own, + // no ghost — even though a plain "is anything unbalanced" check on the + // rest of the file would say yes because of the `f(` beside it. + let text = "\ +module top; + always_comb begin + if ( + f(1) > 0) begin + end + end +endmodule +"; + assert_eq!(offered(text, " if ("), None); +} + +#[test] +fn an_always_without_its_event_control_offers_nothing() { + // The opener is a *sequence*: both `@` and `(` must be there, in that + // order, or the user has not committed to an event-controlled block. + // A bare `always` grows no block — only the keyword ghost's `_ff`, + // which is a different feature with its own setting. + let text = "module top;\n always\nendmodule\n"; + assert_eq!(offered(text, " always").as_deref(), Some("_ff")); + let text = "module top;\n always @\nendmodule\n"; + assert_eq!(offered(text, "always @"), None); + let text = "module top;\n always (\nendmodule\n"; + assert_eq!(offered(text, "always ("), None, "`(` alone is not `@(`"); +} + +#[test] +fn a_buffer_that_does_not_lex_is_declined() { + let text = "module top;\n /* unterminated\n always_comb begin\n"; + let (ws, uri, position) = asking(text, "always_comb begin"); + assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens"); + assert!(inline_completions(&ws, &uri, position).is_none()); +} + +#[test] +fn a_trigger_at_the_true_end_of_file_still_offers_a_ghost() { + // QA find, 2026-08-25: `tokenize` appends a zero-width `Eof` token + // whose span starts and ends at `text.len()`. When the file's very + // last byte is the trigger's own last character — no trailing + // newline, nothing typed after it yet — that `Eof` token shares the + // trigger token's `span.end`, and `rposition` (searching from the + // back) finds the `Eof` first. `triggered` then compares a + // `TokenKind::Eof` against `TokenKind::Keyword` and silently declines + // — exactly the moment a user typing at the end of a growing file + // most wants the ghost text to appear. + let text = "module top;\n always_comb begin"; + let (ws, uri, position) = asking(text, "always_comb begin"); + assert!( + inline_completions(&ws, &uri, position).is_some(), + "the file ends right after `begin`, with no Eof-adjacency confusion" + ); + + let text = "module top;\n always_comb begin\n if ("; + let (ws, uri, position) = asking(text, " if ("); + assert!( + inline_completions(&ws, &uri, position).is_some(), + "same for `if (` at true end of file" + ); +} + +#[test] +fn a_deeply_nested_file_neither_crashes_nor_misses_the_trigger() { + // History: the one recursion-depth bug this codebase had was in the + // *parser*'s AST (TODO.md §1, fixed by `MAX_NESTING_DEPTH`). This + // module never walks that tree — `triggered`/`unfinished` read + // `doc.tokens` and `pairs::analyze`, both flat loops over the token + // stream, so neither can overflow the stack the way the parser once + // did. QA find, 2026-08-25: `pairs::analyze` was quadratic in the + // depth of rainbow nesting back then, which mattered because this + // module calls it on every keystroke inside an unclosed `begin`. It + // is linear now — `Stack`'s running counts in `pairs.rs`, whose own + // tests pin the scaling — and this depth stands guard on the caller's + // side of that contract. + let depth = 3_000; + let mut text = String::from("module top;\n"); + for _ in 0..depth { + text.push_str(" begin\n"); + } + // A trailing newline, so this test isolates depth from the separate + // true-end-of-file `Eof`-adjacency case pinned above. + text.push_str("initial begin\n"); + // Opening the document *parses* it, and since §36.1 a bare `begin` at + // item scope is a generate block the tolerant parser descends into — + // so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4 + // MiB of stack in a debug build. That is exactly what + // `PARSE_STACK_SIZE` is for; every production thread that may reach a + // parse is given it (`main.rs`), libtest's own thread is not, so the + // body runs on one of its own. Nothing here is about the inline path, + // which still never recurses. + std::thread::Builder::new() + .stack_size(PARSE_STACK_SIZE) + .spawn(move || { + let (ws, uri, position) = asking(&text, "initial begin"); + assert!( + !ws.document(&uri).expect("open").tokens.is_empty(), + "the lexer never recurses" + ); + let items = inline_completions(&ws, &uri, position); + assert!( + items.is_some(), + "the innermost, truly unclosed `begin` still offers its `end`" + ); + }) + .expect("spawn") + .join() + .expect("the inline path crashed"); +} + +#[test] +fn an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic() { + let mut ws = Workspace::default(); + let uri = path_to_uri(&PathBuf::from("/rtl/empty.sv")).expect("uri"); + ws.set_document(uri.clone(), String::new()); + assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); +} + +#[test] +fn a_position_past_the_end_of_its_line_clamps_rather_than_panics() { + // Clients do send these — a keystroke can outrun the position the + // client had in hand. `convert.rs`'s `offset` clamps it to the line's + // real content end, which here happens to land exactly on the + // trigger, so the ghost still appears rather than nothing panicking + // but nothing offered either. + let text = "module top;\n always_comb begin\nendmodule\n"; + let (ws, uri, _) = asking(text, "always_comb begin"); + let items = inline_completions(&ws, &uri, Position { line: 1, character: 9_999 }); + assert!(items.is_some(), "clamped to right after `begin`, same as the exact position"); + // (0, 0) on a non-empty file: nowhere near a trigger, not a panic. + assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); +} + +#[test] +fn no_space_between_the_keyword_and_the_paren_still_triggers() { + // Token spans carry no inter-token whitespace of their own, so `if(` + // and `if (` must be indistinguishable to `triggered`. + let text = "module top;\n always_comb begin\n if(\n end\nendmodule\n"; + assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); + // ...and the same for a two-symbol opener written tight. + let text = "module top;\n always@(\nendmodule\n"; + assert_eq!(all_offered(text, "always@(").len(), 3); +} + +#[test] +fn crlf_line_endings_still_trigger() { + // `rest_of_line_is_blank` splits on `\n` alone, so a CRLF file's `\r` + // rides along in the slice — `char::is_whitespace('\r')` is `true`, + // so it still reads as "nothing after the cursor". + let text = "module top;\r\n always_comb begin\r\nendmodule\r\n"; + assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend")); + + let text = "module top;\r\n always_comb begin\r\n if (\r\n end\r\nendmodule\r\n"; + assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend")); +} + +#[test] +fn an_unknown_document_is_declined() { + let ws = Workspace::default(); + let uri = path_to_uri(&PathBuf::from("/rtl/gone.sv")).expect("uri"); + assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none()); +} + +#[test] +fn the_setting_turns_the_whole_feature_off() { + let text = "module top;\n always_comb begin\nendmodule\n"; + let (mut ws, uri, position) = asking(text, "always_comb begin"); + assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default"); + ws.set_client_settings(ClientSettings { inline_templates: Some(false), ..Default::default() }); + assert!(inline_completions(&ws, &uri, position).is_none()); + ws.set_client_settings(ClientSettings { inline_templates: Some(true), ..Default::default() }); + assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again"); +} + +// ------------------------------------------------------------------ +// the registry's own hygiene +// ------------------------------------------------------------------ + +/// Every body in the table, with the trigger it belongs to. +fn every() -> Vec<(&'static Trigger, &'static [Line])> { + TRIGGERS.iter().flat_map(|t| t.bodies.iter().map(move |body| (t, *body))).collect() +} + +/// What the user has typed by the time `trigger` fires. +fn typed(trigger: &Trigger) -> String { + let mut out = trigger.keyword.to_string(); + for symbol in trigger.opener { + out.push_str(symbol); + } + out +} + +/// `text` planted where its construct may legally be written. +/// +/// The default is statement position, so a trigger added without a thought +/// for this list either parses there — which is the common case — or fails +/// loudly. +fn planted(trigger: &Trigger, text: &str) -> String { + match trigger.keyword { + "module" => format!("{text}\n"), + "generate" | "always" | "always_ff" => { + format!("module lucisv_probe;\n {text}\nendmodule\n") + } + _ => { + format!("module lucisv_probe;\n always @(*) begin\n {text}\n end\nendmodule\n") + } + } +} + +#[test] +fn every_hole_is_a_tabstop() { + // The editor-snippets lesson: VS Code substitutes an unknown `$NAME` + // with nothing and says nothing, so a system task written into a body + // would vanish silently. None is written today; this is what stops one + // being added unescaped. + for (trigger, body) in every() { + for (_, line) in body { + let mut rest = *line; + while let Some(at) = rest.find('$') { + rest = &rest[at + 1..]; + assert!( + rest.starts_with('{') || rest.starts_with(|c: char| c.is_ascii_digit()), + "`{}`: `${}` is not a tabstop", + trigger.keyword, + rest.chars().next().unwrap_or(' ') + ); + } + } + } +} + +#[test] +fn every_accepted_ghost_parses() { + // What Tab really writes — the snippet as the *editor* lays it out, + // with every hole filled in — planted where the trigger fires and + // handed to the parser. A body that did not parse would be a formatter + // that refuses the file the moment the user accepts a suggestion. + for (trigger, body) in every() { + let text = filled(&accepted(&render(body), " ", " ")); + let probe = planted(trigger, &format!("{}{text}", typed(trigger))); + let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe); + assert!( + diagnostics.is_empty(), + "`{}` does not parse:\n{probe}\n{diagnostics:#?}", + trigger.keyword + ); + } +} + +#[test] +fn every_trigger_word_is_a_keyword_the_lexer_knows() { + // The detection compares against `TokenKind::Keyword`, so a trigger + // naming a word the lexer calls an identifier could never fire. + for trigger in TRIGGERS { + assert!( + vlog_parser::KEYWORDS.contains(&trigger.keyword), + "`{}` is not a keyword", + trigger.keyword + ); + } +} + +#[test] +fn every_accepted_ghost_is_scope_balanced() { + // What the user typed plus what Tab writes closes exactly what it + // opens: no dangling `begin`, no orphan `endcase`. The same matcher + // the gates ask, run over the result rather than over the buffer. + for (trigger, body) in every() { + let text = format!("{}{}", typed(trigger), filled(&render(body))); + let tokens = vlog_parser::tokenize(&text).expect("a body lexes"); + let analysis = pairs::analyze(&tokens); + assert!( + analysis.unmatched_open.is_empty() && analysis.unmatched_close.is_empty(), + "`{}` does not balance:\n{text}", + trigger.keyword + ); + } +} + +#[test] +fn every_gate_is_the_one_the_body_needs() { + // The rule behind the three `Unclosed` variants, derived from the + // bodies rather than restated: a body that writes a closer for a scope + // it did not open — `end` after a bare `begin`, `endcase` after + // `case (` — is finishing the *user's* keyword, so the gate must ask + // whether that keyword is still open. A body whose own `begin` its + // `end` closes needs no such question. And a trigger whose opener ends + // in `(` writes the `)`, so it must ask about the paren. + for trigger in TRIGGERS { + let closes_the_users_keyword = trigger.bodies.iter().any(|body| { + let tokens = vlog_parser::tokenize(&filled(&render(body))).expect("a body lexes"); + !pairs::analyze(&tokens).unmatched_close.is_empty() + }); + let writes_a_closing_paren = trigger.opener.last() == Some(&"("); + let (scope, paren) = match trigger.gate { + Unclosed::Paren => (false, true), + Unclosed::Scope => (true, false), + Unclosed::ParenAndScope => (true, true), + }; + assert_eq!( + closes_the_users_keyword, scope, + "`{}`: the scope half of the gate does not match the body", + trigger.keyword + ); + assert_eq!( + writes_a_closing_paren, paren, + "`{}`: the paren half of the gate does not match the opener", + trigger.keyword + ); + } +} + +#[test] +fn every_trigger_offers_at_least_one_body() { + for trigger in TRIGGERS { + assert!(!trigger.bodies.is_empty(), "`{}` offers nothing", trigger.keyword); + } +} + +// ------------------------------------------------------------------ +// round 2 QA: `accepted()` cross-checked against VS Code's own algorithm +// ------------------------------------------------------------------ +// +// `accepted()` above is a shortcut: it prepends `base` verbatim and only +// re-spells the `\t`s the body added. The real +// `SnippetSession.adjustWhitespace` re-derives the *whole* leading run — +// base included — from column counts (`TextModel.normalizeIndentation`), +// and normalizes the snippet's first line too. The shortcut is exact only +// when the trigger line's own indentation is already spelled the way the +// editor is configured — the ordinary case, and the only one these two +// tests assume — but "ordinary" was itself an assumption worth checking +// rather than trusting, so it is checked here against a second, +// independent model built straight off the quoted source rather than off +// `accepted`'s shortcut. + +/// `TextModel.normalizeIndentationFromWhitespace`. `ws` is assumed to be +/// entirely leading whitespace: every `\t` counts as `indent_size` +/// columns, every other character as one, and the whole run is re-spelled +/// as tabs-then-spaces (`insert_spaces: false`) or all spaces (`true`). +fn normalize_indentation_from_whitespace( + ws: &str, + indent_size: usize, + insert_spaces: bool, +) -> String { + let columns: usize = ws.chars().map(|c| if c == '\t' { indent_size } else { 1 }).sum(); + let mut out = String::new(); + let mut spaces = columns; + if !insert_spaces { + out.extend(std::iter::repeat_n('\t', columns / indent_size)); + spaces = columns % indent_size; + } + out.extend(std::iter::repeat_n(' ', spaces)); + out +} + +/// `TextModel.normalizeIndentation`: only the leading run of spaces and +/// tabs is touched; everything from the first other character on is left +/// alone. +fn normalize_indentation(line: &str, indent_size: usize, insert_spaces: bool) -> String { + let split = line.find(|c: char| c != ' ' && c != '\t').unwrap_or(line.len()); + let (ws, rest) = line.split_at(split); + format!("{}{rest}", normalize_indentation_from_whitespace(ws, indent_size, insert_spaces)) +} + +/// `snippet` as `SnippetSession.adjustWhitespace` really writes it, +/// modelled directly off the quoted source: the first line is normalized +/// *alone* — `lines[0] = model.normalizeIndentation(lines[0])`, no +/// prepend, because `snippet.offset(marker) === 0` — and every later line +/// gets the trigger line's own leading whitespace prepended before +/// normalizing: `model.normalizeIndentation(lineLeadingWhitespace + +/// lines[i])`. +fn accepted_faithful( + snippet: &str, + trigger_line_indent: &str, + indent_size: usize, + insert_spaces: bool, +) -> String { + snippet + .split('\n') + .enumerate() + .map(|(i, line)| match i { + 0 => normalize_indentation(line, indent_size, insert_spaces), + _ => normalize_indentation( + &format!("{trigger_line_indent}{line}"), + indent_size, + insert_spaces, + ), + }) + .collect::>() + .join("\n") +} + +#[test] +fn the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer() { + // A buffer whose own indentation already matches the editor's current + // `tabSize`/`insertSpaces` — spaces at 2, spaces at 4, tabs — at + // several depths, for every trigger's every body. + for (indent_size, insert_spaces, unit) in + [(2usize, true, " ".repeat(2)), (4, true, " ".repeat(4)), (4, false, "\t".to_string())] + { + let step = if insert_spaces { unit.clone() } else { "\t".to_string() }; + for depth in [0usize, 1, 2, 5] { + let base = unit.repeat(depth); + for (trigger, body) in every() { + let snippet = render(body); + let shortcut = accepted(&snippet, &base, &step); + let faithful = accepted_faithful(&snippet, &base, indent_size, insert_spaces); + assert_eq!( + shortcut, faithful, + "`{}` at depth {depth}, indent_size {indent_size}, insert_spaces {insert_spaces}: \ + the shortcut `accepted()` every other test uses disagrees with VS Code's own \ + normalizeIndentation", + trigger.keyword + ); + } + } + } +} + +#[test] +fn every_bodys_first_line_is_stable_under_normalization() { + // `accepted()`'s line-0 shortcut (`out.push(line.to_string())`, no + // normalization at all) is only correct because every body's first + // line today has either no leading whitespace or exactly one leading + // space, and a single space normalizes to itself at every indent_size + // VS Code allows. A future body whose first line picked up two or + // more leading spaces (or a leading tab) would make the shortcut + // silently wrong, and nothing else in this file would notice, because + // `every_accepted_ghost_parses` and its siblings only ever call + // `accepted`, never `accepted_faithful`. + for (trigger, body) in every() { + let (_, first_line) = body[0]; + for (indent_size, insert_spaces) in [(2usize, true), (4, true), (4, false), (8, false)] { + assert_eq!( + normalize_indentation(first_line, indent_size, insert_spaces), + first_line, + "`{}`'s first line {first_line:?} is not stable at indent_size {indent_size}, \ + insert_spaces {insert_spaces} — `accepted()`'s line-0 shortcut would now be wrong", + trigger.keyword + ); + } + } +} + +#[test] +fn every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in() { + // The user's exact report: "the end lands deeper than its opener." + // Checked against the table's own `(level, text)` metadata rather + // than by re-deriving it, at several depths, in both indent styles, + // and for every trigger — not just the one construct the round-1 + // suite happened to cover. + let configs: &[(&str, &str)] = &[(" ", " "), (" ", " "), ("\t", "\t")]; + for (unit, step) in configs { + for depth in [0usize, 1, 2, 5] { + let base = unit.repeat(depth); + for (trigger, body) in every() { + let got = accepted(&render(body), &base, step); + let got_lines: Vec<&str> = got.split('\n').collect(); + assert_eq!(got_lines.len(), body.len(), "`{}`: line count", trigger.keyword); + for (i, (level, text)) in body.iter().enumerate() { + let expected = if i == 0 { + text.to_string() + } else { + format!("{base}{}{text}", step.repeat(*level as usize)) + }; + assert_eq!( + got_lines[i], expected, + "`{}`: line {i} at depth {depth}, base {unit:?}", + trigger.keyword + ); + } + // The closer is always the body's last line, and it must + // sit at level 0 — exactly the trigger line's own + // indentation, never a step deeper. + let (closer_level, _) = *body.last().expect("a body has a closer"); + assert_eq!(closer_level, 0, "`{}`: closer is not level 0", trigger.keyword); + } + } + } +} + +// ------------------------------------------------------------------ +// round 2 QA: attacking the new triggers +// ------------------------------------------------------------------ + +#[test] +fn casez_triggers_in_a_verilog_file_too() { + // `case`/`casez`/`casex` are `dialect: None` — a Verilog buffer gets + // the same ghost a SystemVerilog one does. + let text = "module top;\n always @(*) begin\n casez (\n end\nendmodule\n"; + assert!(!offered_in("/rtl/top.v", text, "casez (").is_empty()); +} + +#[test] +fn a_for_loop_in_a_pathless_buffer_gets_the_verilog_body() { + // `templates::dialect` resolves a pathless buffer to Verilog — the + // same default the completion tier documents — so an `untitled:` + // buffer (no path at all, unlike a `.v` or a `.sv` one) gets the loop + // with no local variable declaration and no `++`. + // + // `offered_in` goes through `path_to_uri`, which always mints a + // `file://` URI, so it cannot produce a genuinely pathless document — + // this builds the `untitled:` URI directly, the way `state.rs`'s own + // `an_untitled_buffer_has_no_path` does. + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let text = "module top;\n initial begin\n for (\n end\nendmodule\n"; + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("for (").expect("needle present") + "for (".len()) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!( + items.items.iter().map(|i| i.insert_text.value.clone()).collect::>(), + vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"] + ); +} + +#[test] +fn always_at_space_paren_still_offers_both_items() { + // The lexer does not tokenize whitespace, so `@` and `(` end up + // adjacent in `doc.tokens` whether or not the user left a space + // between them; the opener sequence match is on tokens, not text — + // the tight `always@(` is already pinned by + // `no_space_between_the_keyword_and_the_paren_still_triggers`, this + // pins the opposite spacing. + let text = "module top;\n always @ (\nendmodule\n"; + assert_eq!(all_offered(text, "always @ (").len(), 3); +} + +#[test] +fn module_mid_file_above_an_existing_closed_module_still_offers() { + // `pairs::analyze` reports the *new* `module`'s own span in + // `unmatched_open` — an earlier, already-closed module does not + // cancel it out, the same rule + // `a_case_that_already_has_its_endcase_offers_nothing` proves for + // `case`. + let text = "module first;\nendmodule\n\nmodule"; + assert!(offered(text, "\nmodule").is_some()); +} + +#[test] +fn generate_offers_even_when_an_earlier_generate_is_balanced() { + let text = "module top;\n generate\n endgenerate\n generate\nendmodule\n"; + assert!( + offered(text, "endgenerate\n generate").is_some(), + "the second generate is genuinely open" + ); +} + +#[test] +fn fork_offers_in_both_dialects() { + let text = "module top;\n initial begin\n fork\n end\nendmodule\n"; + assert!(!offered_in("/rtl/top.sv", text, " fork").is_empty()); + assert!(!offered_in("/rtl/top.v", text, " fork").is_empty()); +} + +#[test] +fn a_casex_whose_paren_is_closed_two_lines_down_offers_nothing() { + // Same rule `a_paren_the_line_below_closes_still_counts_as_closed` + // pins for `if (`, attacked on the trigger whose gate also asks about + // a scope: the paren half alone is enough to decline. + let text = "\ +module top; + always_comb begin + casex ( + sel) + 1: ; + endcase + end +endmodule +"; + assert_eq!(offered(text, "casex ("), None, "the `)` two lines down still closes the paren"); +} + +#[test] +fn nested_unclosed_parens_each_see_their_own_gate() { + // `if (` on one line and `always @(` on the next: two different + // unclosed parens. `paren_is_closed` is a stack keyed by the exact + // span passed in, so neither paren can be mistaken for the other's + // counterpart — both must still offer. + let text = "module top;\n if (\n always @(\nendmodule\n"; + assert!(offered(text, " if (").is_some()); + assert_eq!(all_offered(text, " always @(").len(), 3); +} + +// ------------------------------------------------------------------ +// the wire +// ------------------------------------------------------------------ + +#[test] +fn the_wire_shape_is_what_the_client_reads() { + // The whole reason these types are hand-rolled. `lsp-types` 0.97 spells + // `insertText` as a bare `String`, and `vscode-languageclient`'s + // `asInlineCompletionItem` inserts a bare string as **plain text** — + // every `${1:cond}` would appear literally in the buffer. Only the + // `{"kind": "snippet"}` object becomes a `SnippetString`. If a future + // `lsp-types` bump tempts anyone to use its item type, this fails. + let text = "module top;\n always_comb begin\nendmodule\n"; + let (ws, uri, position) = asking(text, "always_comb begin"); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!( + serde_json::to_value(&items).expect("serializes"), + serde_json::json!({ + "items": [{ + "insertText": { "kind": "snippet", "value": "\n\t$0\nend" }, + "range": { + "start": { "line": 1, "character": 19 }, + "end": { "line": 1, "character": 19 } + } + }] + }) + ); +} + +#[test] +fn a_multi_item_response_repeats_the_range_and_nothing_else() { + let text = "module top;\n always @(\nendmodule\n"; + let (ws, uri, position) = asking(text, "always @("); + let items = inline_completions(&ws, &uri, position).expect("two ghosts"); + assert_eq!( + serde_json::to_value(&items).expect("serializes"), + serde_json::json!({ + "items": [ + { + "insertText": { + "kind": "snippet", + "value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend" + }, + "range": { + "start": { "line": 1, "character": 11 }, + "end": { "line": 1, "character": 11 } + } + }, + { + "insertText": { + "kind": "snippet", + "value": "posedge ${1:clk}) begin\n\t$0\nend" + }, + "range": { + "start": { "line": 1, "character": 11 }, + "end": { "line": 1, "character": 11 } + } + }, + { + "insertText": { "kind": "snippet", "value": "*) begin\n\t$0\nend" }, + "range": { + "start": { "line": 1, "character": 11 }, + "end": { "line": 1, "character": 11 } + } + } + ] + }) + ); +} + +#[test] +fn the_range_is_empty_and_at_the_cursor() { + // The protocol requires a range to begin and end on one line, and this + // item inserts rather than replaces — so the only honest range is the + // caret itself. + let text = "module top;\n always_comb begin\nendmodule\n"; + let (ws, uri, position) = asking(text, "always_comb begin"); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!(items.items[0].range.start, position); + assert_eq!(items.items[0].range.end, position); +} + +#[test] +fn a_multibyte_line_puts_the_range_where_the_cursor_really_is() { + // The `é` is 2 bytes and 1 UTF-16 unit; a byte-based position would + // put the ghost one column late. + let text = "module top;\n // é\n always_comb begin\nendmodule\n"; + let (ws, uri, position) = asking(text, "always_comb begin"); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 }); +} + +// ------------------------------------------------------------------ +// the instantiation ghost (2026-08-30) +// ------------------------------------------------------------------ + +/// A scratch workspace root, removed on drop. The instantiation ghost is +/// the one path here that reads the index, so its tests need real files. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_inline_{}_{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("temp dir"); + } + std::fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// The module every ghost below instantiates: parameters *and* ports, one +/// of which (`clk`) the buffer declares and so binds itself. +const SUB: &str = "\ +module sub #( + parameter int WIDTH = 8 +) ( + input logic clk, + input logic [WIDTH-1:0] data, + output logic ready +); +endmodule +"; + +/// The ghost `SUB`'s header produces, with the name the user typed *and +/// the space that armed it* already cut off the front. Written out once, +/// because half the tests below are about whether it appears at all rather +/// than about what it says. +const SUB_GHOST: &str = "#(\n\t.WIDTH(${1:8})\n) ${2:u_sub} (\n\t.clk(clk),\n\t\ + .data(${3:data}),\n\t.ready(${4:ready})\n);"; + +/// A workspace holding `files` plus an open `top.sv`, with the cursor at +/// `needle`'s end. +fn workspace( + name: &str, + files: &[(&str, &str)], + top: &str, + needle: &str, +) -> (Tree, Workspace, Uri, Position) { + workspace_at(name, files, "top.sv", top, needle) +} + +/// The same, with the open buffer written at `top_rel` — which is what the +/// nearest-definition rule reads, so a test about *which* copy is chosen +/// has to be able to say where the asking buffer lives. +fn workspace_at( + name: &str, + files: &[(&str, &str)], + top_rel: &str, + top: &str, + needle: &str, +) -> (Tree, Workspace, Uri, Position) { + let tree = Tree::new(name); + for (rel, text) in files { + tree.write(rel, text); + } + let path = tree.write(top_rel, top); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find(needle).expect("needle present") + needle.len()) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + (tree, ws, uri, position) +} + +/// The one ghost offered at `needle`'s end in a workspace declaring `SUB`. +/// +/// `needle` names the text the cursor sits after, and every caller here +/// spells the arming space into it: since 2026-08-30 the ghost answers +/// `sub ` and never `sub`, because `sub` alone may still be growing into +/// `sub_dft`. +fn ghosted(name: &str, top: &str, needle: &str) -> Option { + ghosted_among(name, &[("sub.sv", SUB)], top, needle) +} + +/// The same, over a workspace spelled out by the caller. +fn ghosted_among(name: &str, files: &[(&str, &str)], top: &str, needle: &str) -> Option { + ghosted_at(name, files, "top.sv", top, needle) +} + +/// The same again, with the asking buffer's own path spelled out. +fn ghosted_at( + name: &str, + files: &[(&str, &str)], + top_rel: &str, + top: &str, + needle: &str, +) -> Option { + let (_tree, ws, uri, position) = workspace_at(name, files, top_rel, top, needle); + let items = inline_completions(&ws, &uri, position)?; + assert_eq!(items.items.len(), 1, "an instantiation is one offer, not a menu"); + Some(items.items[0].insert_text.value.clone()) +} + +#[test] +fn an_exactly_spelled_module_name_and_a_space_ghost_the_whole_instantiation() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + assert_eq!(ghosted("exact", top, " sub ").as_deref(), Some(SUB_GHOST)); +} + +/// The owner's ruling of 2026-08-30, both halves in one place: the space is +/// what arms the ghost, and without it there is nothing — *even though* +/// `sub` is a module the workspace really declares and the cursor really is +/// at a legal site. `aes` is not a commitment while `aes_dft` may still be +/// coming; `aes ` is. +#[test] +fn the_name_alone_offers_nothing_and_the_name_and_a_space_offer_everything() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + assert_eq!(ghosted("armed_no", top, " sub"), None, "the name alone is not a commitment"); + assert_eq!(ghosted("armed_yes", top, " sub ").as_deref(), Some(SUB_GHOST)); +} + +/// One space, and the one just typed. Two of them is a cursor parked in +/// whitespace rather than a name just finished, and a tab is not the +/// character this rule is about at all. +#[test] +fn only_a_single_space_arms_the_ghost() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + assert_eq!(ghosted("twospaces", top, " sub "), None, "two spaces is not `just typed`"); + let top = "module top;\n logic clk;\n sub\t\nendmodule\n"; + assert_eq!(ghosted("tab", top, " sub\t"), None, "a tab does not arm it"); + // …and the first of the two spaces still does, which is the same rule + // read from the other side: the byte before the cursor is a space and + // the byte before that is not. + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + assert_eq!(ghosted("firstspace", top, " sub ").as_deref(), Some(SUB_GHOST)); +} + +/// A name that is not a module, followed by a space, is the overwhelmingly +/// common keystroke on this path — it must cost the binary search and stop. +#[test] +fn a_space_after_a_name_that_is_not_a_module_ghosts_nothing() { + let top = "module top;\n logic clk;\n widget \nendmodule\n"; + assert_eq!(ghosted("notamodule", top, " widget "), None); +} + +/// The layout `vlog_refactor` renders really does put exactly one space +/// between a module's name and whatever follows it, in both shapes: a +/// parameterised header (`sub #(`) and a bare one (`bare u_bare`). The cut +/// in `instantiation_ghost` asserts this rather than assuming it — see +/// [`NoGhost::UnexpectedLayout`] — and this is what would fail first if the +/// spelling ever changed. +#[test] +fn the_rendered_skeleton_really_does_put_one_space_after_the_name() { + for (name, module, files) in [ + ("layout_params", "sub", &[("sub.sv", SUB)][..]), + ("layout_bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..]), + ] { + let top = format!("module top;\n logic clk;\n {module} \nendmodule\n"); + let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost"); + assert!( + !ghost.starts_with(char::is_whitespace), + "{module}: the arming space is the ghost's, not the user's: {ghost:?}" + ); + } +} + +/// The accepted text is what the popup's skeleton used to insert, byte for +/// byte — which is the argument that level 2 gives up nothing level 1 gave +/// away. The layout the server sends is relative; the editor supplies the +/// site's own indentation and the width of a step. +#[test] +fn the_accepted_ghost_is_the_skeleton_the_popup_used_to_insert() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + let ghost = ghosted("accepted", top, " sub ").expect("a ghost"); + assert_eq!( + format!("sub {}", accepted(&ghost, " ", " ")), + "\ +sub #( + .WIDTH(${1:8}) + ) ${2:u_sub} ( + .clk(clk), + .data(${3:data}), + .ready(${4:ready}) + );" + ); + // …and it follows the editor's tabs, not `lucisv.indent`, at any depth. + assert!(accepted(&ghost, "\t\t", "\t").contains("\n\t\t\t.clk(clk),"), "{ghost}"); +} + +/// What the user ends up with must parse. The typed name, the accepted +/// body, every hole filled in the way the editor preselects it, planted at +/// the item position the gate insisted on. +#[test] +fn the_accepted_ghost_parses_where_it_was_offered() { + for (name, module, files, holes) in [ + ("ports", "sub", &[("sub.sv", SUB)][..], 4), + ("bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..], 1), + ( + "portless", + "empty", + &[("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n")][..], + 2, + ), + ] { + let top = format!("module top;\n logic clk;\n {module} \nendmodule\n"); + let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost"); + assert_eq!( + ghost.matches("${").count(), + holes, + "{module}: every fill-in is a tabstop: {ghost}" + ); + // The name, the space that armed the ghost, and the ghost itself — + // which is exactly what the buffer holds after Tab. + let written = filled(&format!("{module} {}", accepted(&ghost, " ", " "))); + let probe = format!("module lucisv_probe;\n logic clk;\n {written}\nendmodule\n"); + assert!( + vlog_parser::parse_source_tolerant(&probe).1.is_empty(), + "the accepted text must parse:\n{probe}" + ); + } +} + +/// The premise the "the accepted text must parse" probe above rests on: +/// the probe can still fail. Header recovery (TODO §32) widened what a +/// tolerant parse reads — a half-typed connection list is now a recovered +/// instantiation rather than a dead item — so the probe is only worth +/// asking while text that does not parse still says so. +#[test] +fn the_accepted_text_probe_still_reports_text_that_does_not_parse() { + let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n"; + assert!( + !vlog_parser::parse_source_tolerant(probe).1.is_empty(), + "recovery must not make a broken instantiation look clean" + ); +} + +#[test] +fn a_module_with_no_ports_ghosts_a_sane_instantiation() { + let top = "module top;\n bare \nendmodule\n"; + assert_eq!( + ghosted_among("bareports", &[("bare.sv", "module bare;\nendmodule\n")], top, " bare ") + .as_deref(), + Some("${1:u_bare} ();") + ); +} + +#[test] +fn a_half_typed_name_ghosts_nothing() { + // The popup is what answers here — with the *name*, which is the whole + // division of labour between the two levels. + let top = "module top;\n logic clk;\n su \nendmodule\n"; + assert_eq!(ghosted("partial", top, " su "), None); + // …and one character past the name is not the name either. + let top = "module top;\n logic clk;\n subs \nendmodule\n"; + assert_eq!(ghosted("past", top, " subs "), None); +} + +#[test] +fn a_case_mismatched_name_ghosts_nothing() { + // The popup's substring match folds case; this one must not. `SUB` is + // not a module any Verilog tool would find. + for typed in ["SUB", "Sub", "sUb"] { + let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n"); + assert_eq!(ghosted("case", &top, &format!(" {typed} ")), None, "{typed}"); + } +} + +#[test] +fn a_name_the_workspace_does_not_declare_as_a_module_ghosts_nothing() { + let files = &[("sub.sv", SUB), ("p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n")]; + for typed in ["pkg", "W", "clk", "nothing_at_all"] { + let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n"); + assert_eq!( + ghosted_among("nonmodule", files, &top, &format!(" {typed} ")), + None, + "{typed} is not a module" + ); + } +} + +#[test] +fn anything_after_the_cursor_on_the_line_ghosts_nothing() { + // The rest-of-line rule the templates already live by: a name with a + // `;` after it is code the user has finished writing. + let top = "module top;\n logic clk;\n sub u_sub ();\nendmodule\n"; + assert_eq!(ghosted("after", top, " sub "), None); +} + +#[test] +fn a_name_that_is_not_at_item_position_ghosts_nothing() { + // Every one of these spells `sub` exactly and none of them is a place + // an instantiation may be written. The gate is `completion.rs`'s own, + // so this is the ghost inheriting the popup's answer rather than + // inventing a second one. + for (name, top, needle) in [ + ("connection", "module top;\n other u (.aes(sub \nendmodule\n", ".aes(sub "), + ("assign", "module top;\n wire x;\n assign x = sub \nendmodule\n", "= sub "), + ("declaration", "module top;\n logic sub \nendmodule\n", "logic sub "), + ("procedural", "module top;\n initial begin\n sub \n end\nendmodule\n", " sub "), + ( + "function", + "module top;\n function int f();\n sub \n endfunction\nendmodule\n", + " sub ", + ), + ("file scope", "sub \nmodule top;\nendmodule\n", "sub "), + ("port list", "module top (sub \n);\nendmodule\n", "top (sub "), + ] { + assert_eq!(ghosted("position", top, needle), None, "{name}: {top}"); + } +} + +#[test] +fn a_generate_block_is_still_item_position_for_the_ghost() { + let top = "module top;\n logic clk;\n generate\n sub \n endgenerate\nendmodule\n"; + assert_eq!(ghosted("gen", top, " sub ").as_deref(), Some(SUB_GHOST)); +} + +#[test] +fn a_module_name_in_a_comment_or_a_string_ghosts_nothing() { + // A token property, not a check of this module's own: a comment is + // lexer trivia and never a token, and a string literal is one `String` + // token whose kind is not `Ident`. + let top = "module top;\n // sub \nendmodule\n"; + assert_eq!(ghosted("comment", top, "// sub "), None); + let top = "module top;\n initial $display(\"sub \nendmodule\n"; + assert_eq!(ghosted("string", top, "\"sub "), None); +} + +#[test] +fn a_buffer_that_does_not_lex_ghosts_nothing() { + let top = "module top;\n /* unterminated\n sub \n"; + let (_tree, ws, uri, position) = workspace("nolex", &[("sub.sv", SUB)], top, " sub "); + assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens"); + assert!(inline_completions(&ws, &uri, position).is_none()); +} + +#[test] +fn an_exact_name_at_the_true_end_of_the_file_still_ghosts() { + // The `Eof` sentinel shares the last real token's end, so the same + // skip the templates needed (QA find, 2026-08-25) is what lets a name + // typed as the buffer's very last bytes answer. + // True EOF is now the buffer ending with the *space*: the name plus + // the keystroke that arms it, with nothing after either. + let top = "module top;\n logic clk;\n sub "; + assert_eq!(ghosted("eof", top, " sub ").as_deref(), Some(SUB_GHOST)); +} + +/// opentitan's `ast_dft` and `io_osc` in miniature: one module, one copy +/// under each of two tops, with headers that differ so the ghost says which +/// copy it read. +const TWO_TOPS: &[(&str, &str)] = &[ + ("top_earlgrey/ast_dft.sv", "module ast_dft (input logic clk_earlgrey);\nendmodule\n"), + ("top_darjeeling/ast_dft.sv", "module ast_dft (input logic clk_darjeeling);\nendmodule\n"), +]; + +/// What each copy of `ast_dft` ghosts. Neither port is declared in the +/// asking buffer, so neither auto-connects and the port name is visible in +/// the hole — which is how these tests tell the two copies apart. +const EARLGREY_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_earlgrey(${2:clk_earlgrey})\n);"; +const DARJEELING_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_darjeeling(${2:clk_darjeeling})\n);"; + +#[test] +fn a_module_declared_twice_ghosts_the_copy_nearest_the_buffer() { + // Round 1 gave a twice-declared module no ghost at all: + // `module_definition` refuses to guess which file to read, and the + // ghost inherited the refusal. In opentitan that silenced `ast_dft` + // and `io_osc`, each declared once under `hw/top_earlgrey/ip/ast/rtl` + // and once under `hw/top_darjeeling/ip/ast/rtl` — two whole IP blocks. + // Owner ruling, 2026-08-30: every indexed module expands, so the + // server chooses the copy whose path shares the longest run of leading + // path components with the buffer asking. + let top = "module top;\n ast_dft \nendmodule\n"; + assert_eq!( + ghosted_at("earlgrey", TWO_TOPS, "top_earlgrey/top.sv", top, " ast_dft ").as_deref(), + Some(EARLGREY_GHOST), + "a buffer under top_earlgrey gets top_earlgrey's copy" + ); + assert_eq!( + ghosted_at("darjeeling", TWO_TOPS, "top_darjeeling/top.sv", top, " ast_dft ").as_deref(), + Some(DARJEELING_GHOST), + "…and one under top_darjeeling gets the other" + ); +} + +#[test] +fn a_buffer_near_neither_copy_gets_the_lexicographically_smaller_path() { + // No shared prefix to rank by, so the tie-break decides — and it is a + // property of the paths rather than of the order the index was built + // in, which is what makes it reproducible. `top_darjeeling` sorts + // before `top_earlgrey`. + let top = "module top;\n ast_dft \nendmodule\n"; + assert_eq!( + ghosted_at("neither", TWO_TOPS, "elsewhere/top.sv", top, " ast_dft ").as_deref(), + Some(DARJEELING_GHOST) + ); +} + +#[test] +fn the_two_copies_may_have_different_headers_and_the_nearest_one_wins() { + // The accepted semantics, written down: the copies are not required to + // agree, and the user gets the one their own file is nearest to. Here + // one copy has a parameter the other has not, so the two ghosts do not + // even have the same shape. + let files = &[ + ("top_a/dup.sv", "module dup #(\n parameter int W = 4\n) (input logic a);\nendmodule\n"), + ("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"), + ]; + let top = "module top;\n dup \nendmodule\n"; + assert_eq!( + ghosted_at("hdr_a", files, "top_a/top.sv", top, " dup ").as_deref(), + Some("#(\n\t.W(${1:4})\n) ${2:u_dup} (\n\t.a(${3:a})\n);") + ); + assert_eq!( + ghosted_at("hdr_b", files, "top_b/top.sv", top, " dup ").as_deref(), + Some("${1:u_dup} (\n\t.b(${2:b})\n);") + ); +} + +#[test] +fn a_plan_with_an_escaped_identifier_gets_no_ghost() { + // An escaped identifier may legally contain `$`, `}` and `\` — the + // snippet grammar's own punctuation — and the names are written by the + // layout, outside every hole, where no escaping can reach them. The + // popup answered this with a plain-text item; an inline completion has + // no plain-text spelling, so it answers with nothing. + let files = + &[("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n")]; + let top = "module top;\n logic clk;\n odd \nendmodule\n"; + assert_eq!(ghosted_among("escaped", files, top, " odd "), None); +} + +#[test] +fn a_module_may_ghost_itself() { + // Cursor inside `top`, typing `top`. The plan is real — `top` is a + // module the workspace declares and the instantiation is legal + // Verilog — so it is offered. Whether instantiating yourself is a good + // idea is the user's business; an elaborator will tell them soon + // enough, and refusing would be this server having an opinion about + // recursion that it cannot back up (a `generate` guarded by a + // parameter is a legitimate recursive structure). + let top = "module top (input logic clk);\n top \nendmodule\n"; + assert_eq!(ghosted("self", top, " top ").as_deref(), Some("${1:u_top} (\n\t.clk(clk)\n);")); +} + +#[test] +fn the_setting_turns_the_instantiation_ghost_off_and_leaves_the_templates_on() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + let (_tree, mut ws, uri, position) = workspace("setting", &[("sub.sv", SUB)], top, " sub "); + assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default"); + ws.set_client_settings(ClientSettings { + inline_instantiation: Some(false), + ..Default::default() + }); + assert!(inline_completions(&ws, &uri, position).is_none()); + ws.set_client_settings(ClientSettings { + inline_instantiation: Some(true), + ..Default::default() + }); + assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again"); + + // The two settings are independent in both directions: the templates + // answer with the instantiation off, and the reverse. + let (_tree, mut ws, uri, position) = + workspace("both", &[("sub.sv", SUB)], "module top;\n always_comb begin\n", "begin"); + ws.set_client_settings(ClientSettings { + inline_instantiation: Some(false), + ..Default::default() + }); + assert!( + inline_completions(&ws, &uri, position).is_some(), + "a template is not an offer \ + the instantiation setting governs" + ); + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + let (_tree, mut ws, uri, position) = workspace("tmploff", &[("sub.sv", SUB)], top, " sub "); + ws.set_client_settings(ClientSettings { inline_templates: Some(false), ..Default::default() }); + assert!(inline_completions(&ws, &uri, position).is_some(), "…and the other way round"); +} + +#[test] +fn the_only_residue_over_a_workspace_is_the_escaped_identifier() { + // Round 2, part C: after the space-armed trigger and the + // nearest-definition chooser, the reasons an indexed module does *not* + // ghost have to be enumerable — so a sweep over every module a + // workspace declares can bucket its misses by reason instead of + // shrugging at them. This is that sweep in miniature, over a workspace + // carrying one of every shape the planner meets: parameters and ports, + // neither, parameters only, a non-ANSI port list, a name two files + // declare, and the one shape that genuinely cannot be ghosted. + let files = &[ + ("sub.sv", SUB), + ("bare.sv", "module bare;\nendmodule\n"), + ("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n"), + ("nonansi.sv", "module nonansi (a, b);\n input wire a;\n output wire b;\nendmodule\n"), + ("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n"), + ("top_a/dup.sv", "module dup (input logic a);\nendmodule\n"), + ("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"), + ]; + let top = "module top;\n logic clk;\n probe \nendmodule\n"; + let (_tree, ws, uri, _) = workspace("residue", files, top, " probe "); + let doc = ws.document(&uri).expect("open"); + let at = top.find(" probe").expect("the probe line") as u32 + 2; + + let modules: Vec = + ws.candidates().modules("").iter().map(|name| name.to_string()).collect(); + assert!(modules.len() >= 7, "premise: the sweep really covers the workspace: {modules:?}"); + let refused: Vec<(&str, NoGhost)> = modules + .iter() + .filter_map(|module| { + instantiation_ghost(&ws, doc, module, at).err().map(|why| (module.as_str(), why)) + }) + .collect(); + assert_eq!( + refused, + vec![("odd", NoGhost::EscapedIdentifier)], + "the residue is the escaped identifier and nothing else" + ); +} + +#[test] +fn the_instantiation_wire_shape_is_one_snippet_item_at_the_cursor() { + let top = "module top;\n logic clk;\n sub \nendmodule\n"; + let (_tree, ws, uri, position) = workspace("wire", &[("sub.sv", SUB)], top, " sub "); + let items = inline_completions(&ws, &uri, position).expect("a ghost"); + assert_eq!( + serde_json::to_value(&items).expect("serializes"), + serde_json::json!({ + "items": [{ + "insertText": { "kind": "snippet", "value": SUB_GHOST }, + "range": { + "start": { "line": 2, "character": 6 }, + "end": { "line": 2, "character": 6 } + } + }] + }) + ); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/large.rs b/crates/lucisv_server/src/large.rs index 068a626..42dc734 100644 --- a/crates/lucisv_server/src/large.rs +++ b/crates/lucisv_server/src/large.rs @@ -361,598 +361,9 @@ fn is_word(byte: u8) -> bool { byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' } +// `pub(crate)`: the server's large-file tests time a request with the +// linear-growth helpers defined here. #[cfg(test)] -mod tests { - use super::*; - use lsp_types::{Position, Range}; - use std::path::PathBuf; - use std::time::{Duration, Instant}; - - /// A fast-path document over `text`. - fn large(text: &str) -> Document { - Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string()) - } - - fn range(from: u32, to: u32) -> Range { - Range { - start: Position { line: from, character: 0 }, - end: Position { line: to, character: 0 }, - } - } - - /// The text of every token a window produced, in order. - fn words(doc: &Document, window: &Window) -> Vec { - window - .tokens - .iter() - .filter(|t| t.kind != vlog_parser::token::TokenKind::Eof) - .map(|t| doc.text[t.span.as_range()].to_string()) - .collect() - } - - // ------------------------------------------------------------------ - // the window - // ------------------------------------------------------------------ - - #[test] - fn a_window_lexes_its_own_lines_and_reports_document_offsets() { - let doc = large("module a;\nwire b;\nwire c;\nendmodule\n"); - let window = window(&doc, range(1, 2)); - assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]); - // The spans are the document's, not the slice's: the first token is - // `wire` on line 1, which starts at byte 10. - assert_eq!(window.tokens[0].span.start, 10); - } - - #[test] - fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() { - let doc = large("module a;\nwire b;\n"); - let mid = Range { - start: Position { line: 1, character: 4 }, - end: Position { line: 1, character: 6 }, - }; - assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]); - } - - #[test] - fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() { - let doc = large("module a;\nendmodule\n"); - assert!(words(&doc, &window(&doc, range(900, 999))).is_empty()); - } - - #[test] - fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() { - let doc = large("/* a\n b\n c */ wire d;\nwire e;\n"); - // Lines 1..3: the window opens on ` b`, which is inside the comment - // opened on line 0, so the tail up to `*/` is a comment span and the - // lexer only saw what followed it. - let window = window(&doc, range(1, 3)); - assert_eq!(window.comments.len(), 1); - let comment = &doc.text[window.comments[0].as_range()]; - assert!(comment.ends_with("*/"), "{comment:?}"); - assert!(comment.starts_with(" b"), "{comment:?}"); - assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]); - } - - #[test] - fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() { - let mut text = String::from("/* opener\n"); - for _ in 0..40 { - text.push_str(" still a comment\n"); - } - text.push_str("*/\nwire a;\n"); - let doc = large(&text); - let window = window(&doc, range(10, 20)); - assert!(window.tokens.is_empty()); - assert_eq!(window.comments.len(), 1); - } - - #[test] - fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() { - // A block comment opened further back than BACKSCAN: the decision - // cannot be made, and the documented answer is "code". - let mut text = String::from("/* opener\n"); - text.push_str(&" filler filler filler filler\n".repeat(4000)); - assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget"); - text.push_str("wire a;\n"); - let doc = large(&text); - let last = doc.line_index.line_count() - 2; - let window = window(&doc, range(last, last)); - assert!(window.comments.is_empty(), "no comment was detected"); - assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code"); - } - - #[test] - fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() { - let doc = large("wire a;\nwire b;\n/* an unterminated banner\n"); - let window = window(&doc, range(0, 2)); - assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]); - assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment"); - assert!(doc.text[window.comments[0].as_range()].starts_with("/*")); - } - - #[test] - fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() { - let doc = large("wire a;\n$display(\"unterminated\n"); - let window = window(&doc, range(0, 1)); - assert_eq!(words(&doc, &window), ["wire", "a", ";"]); - assert!(window.comments.is_empty(), "an unterminated string is not a comment"); - } - - #[test] - fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() { - let doc = large("$display(\"unterminated\nwire a;\n"); - let window = window(&doc, range(0, 0)); - assert!(window.tokens.is_empty()); - assert!(window.comments.is_empty()); - } - - #[test] - fn a_window_is_capped_however_much_the_client_asks_for() { - // Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking - // for the whole document must still lex at most MAX_WINDOW of it. - let text = "wire a;\n".repeat(200_000); - assert!(text.len() as u32 > MAX_WINDOW, "the premise"); - let doc = large(&text); - let window = window(&doc, range(0, doc.line_index.line_count())); - let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); - assert!(last <= MAX_WINDOW, "lexed past the cap: {last}"); - assert!(last > MAX_WINDOW - 64, "and up to it: {last}"); - } - - #[test] - fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() { - let mut text = String::from("wire "); - text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000)); - text.push_str(";\n"); - let doc = large(&text); - let window = window(&doc, range(0, 0)); - // It still answers, and it did not read the whole line. - let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); - assert!(last <= MAX_WINDOW, "{last}"); - } - - #[test] - fn an_empty_buffer_answers_an_empty_window() { - let doc = large(""); - let window = window(&doc, range(0, 10)); - assert!(window.tokens.is_empty() || words(&doc, &window).is_empty()); - assert!(window.comments.is_empty()); - } - - /// QA attack: a buffer of nothing but newlines. Every line is empty, so - /// every byte offset the code touches (line starts, line ends, the - /// backward scan's window) coincides with several others — the shape most - /// likely to trip an off-by-one into an out-of-range slice. - #[test] - fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() { - let doc = large(&"\n".repeat(5_000)); - for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] { - let window = window(&doc, range(from, to)); - // Only the EOF token, which every `tokenize` call ends with even - // over blank input — no real token, and no panic getting there. - assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}"); - } - } - - /// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary - /// byte of its line (`convert.rs`'s own rule), so a window boundary lands - /// right before a `\r` rather than a `\n` — this pins that the window - /// still lexes the same tokens CRLF or not, and that the trailing `\r` on - /// each line does not get coloured as part of the token before it. - #[test] - fn a_crlf_netlist_windows_the_same_as_its_lf_twin() { - let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n"; - let doc = large(lf); - let window = window(&doc, range(1, 2)); - assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]); - // No token swallowed the `\r`: every token's text is exactly itself. - for token in &window.tokens { - let text = &doc.text[token.span.as_range()]; - assert!(!text.contains('\r'), "a token ate the line ending: {text:?}"); - } - } - - // ------------------------------------------------------------------ - // the shrink helper on its own - // ------------------------------------------------------------------ - - #[test] - fn lex_reports_how_much_of_the_slice_it_used() { - let (tokens, used) = lex("wire a;\n"); - assert!(!tokens.is_empty()); - assert_eq!(used, 8); - let (tokens, used) = lex("wire a;\n/* open"); - assert!(!tokens.is_empty()); - assert_eq!(used, 8, "the comment line was dropped"); - } - - #[test] - fn line_start_counts_lines_from_one() { - assert_eq!(line_start("a\nb\nc", 1), Some(0)); - assert_eq!(line_start("a\nb\nc", 2), Some(2)); - assert_eq!(line_start("a\nb\nc", 3), Some(4)); - assert_eq!(line_start("a\nb\nc", 4), None); - } - - // ------------------------------------------------------------------ - // definition and references - // ------------------------------------------------------------------ - - const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \ - .b(sig_b));\n assign sig_a = sig_b;\nendmodule\n"; - - /// The offset of the `n`-th occurrence of `needle`. - fn at(text: &str, needle: &str, n: usize) -> u32 { - text.match_indices(needle).nth(n).expect("occurrence").0 as u32 - } - - #[test] - fn a_declaration_is_found_by_the_keyword_before_it() { - let doc = large(NETLIST); - let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration"); - assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line"); - assert_eq!(&NETLIST[found.as_range()], "sig_a"); - } - - #[test] - fn a_name_no_keyword_introduces_has_no_definition() { - let doc = large(NETLIST); - assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name"); - } - - #[test] - fn a_cursor_that_is_not_on_a_word_answers_nothing() { - let doc = large(NETLIST); - let space = NETLIST.find(" wire").expect("indent") as u32; - assert!(definition(&doc, space).is_none()); - assert!(references(&doc, space, true).is_empty()); - } - - #[test] - fn references_are_whole_word_and_in_order() { - let doc = large(NETLIST); - let found = references(&doc, at(NETLIST, "sig_a", 0), true); - assert_eq!(found.len(), 3, "declaration, connection, assignment"); - assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start)); - // `sig_a` is not found inside `sig_ab`. - let doc = large("wire sig_ab;\nwire sig_a;\n"); - assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1); - } - - #[test] - fn excluding_the_declaration_drops_exactly_the_declaration() { - let doc = large(NETLIST); - let with = references(&doc, at(NETLIST, "sig_a", 1), true); - let without = references(&doc, at(NETLIST, "sig_a", 1), false); - assert_eq!(without.len(), with.len() - 1); - assert!(!without.contains(&with[0])); - } - - #[test] - fn the_reference_list_is_capped() { - let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500)); - let doc = large(&text); - assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT); - } - - // ------------------------------------------------------------------ - // the 100 MB probes - // ------------------------------------------------------------------ - - /// A netlist-shaped buffer of about `bytes` bytes. - /// - /// Instantiation lines, which is what a synthesized netlist really is, with - /// a declaration and a comment every so often so the scans have something - /// to find and the windows have something to colour. - fn netlist(bytes: usize) -> String { - let mut text = String::with_capacity(bytes + 4096); - text.push_str("module netlist_top;\n wire needle;\n"); - let mut n = 0u64; - while text.len() < bytes { - text.push_str(&format!( - " sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n", - n + 1 - )); - if n.is_multiple_of(500) { - text.push_str(" /* a banner comment, so the windows are not all code */\n"); - text.push_str(" wire net_local;\n"); - } - n += 1; - } - // A second declaration at the far end: a scan for it is the worst - // case, since the answer is the last thing in the file. - text.push_str(" wire tail_needle;\nendmodule\n"); - text - } - - /// **The measurement the feature README quotes.** Ignored by default: it - /// builds a 100 MB buffer, which is not something `cargo test` should do - /// on every run. Run it as - /// `cargo test -p lucisv_server --release -- --ignored --nocapture - /// large::tests::the_hundred_megabyte_probes`. - /// - /// The bounds asserted are deliberately loose — an order of magnitude over - /// what the numbers actually are on the machine this was written on — so - /// the probe fails on a regression in *kind* (someone made the open path - /// scan the file twice, someone made the window lex the document) rather - /// than on a slow CI box. - #[test] - #[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"] - fn the_hundred_megabyte_probes() { - use std::time::Instant; - let text = netlist(100 * 1024 * 1024); - let bytes = text.len(); - - let clock = Instant::now(); - let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text); - let open = clock.elapsed(); - - let lines = doc.line_index.line_count(); - let middle = lines / 2; - let viewport = Range { - start: Position { line: middle, character: 0 }, - end: Position { line: middle + 60, character: 0 }, - }; - // Twice: the first call is where any accidental one-off whole-file - // work would hide. - let clock = Instant::now(); - let first = window(&doc, viewport); - let first_window = clock.elapsed(); - let clock = Instant::now(); - let again = window(&doc, viewport); - let second_window = clock.elapsed(); - assert_eq!(first.tokens.len(), again.tokens.len()); - assert!(!first.tokens.is_empty(), "the window really did lex something"); - - // The worst case for both scans: the name is declared in the *last* - // line of the file, so the answer is only found after a whole pass. - let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32; - let clock = Instant::now(); - let found = definition(&doc, tail); - let definition_scan = clock.elapsed(); - assert!(found.is_some()); - - let clock = Instant::now(); - let refs = references(&doc, tail, true); - let reference_scan = clock.elapsed(); - assert!(!refs.is_empty()); - - // And the shape that is worst for the search itself: a short name - // that occurs as a *prefix* of a million others, so the whole-word - // filter runs on every one of them. - let common = doc.text.find("net1)").expect("a net use") as u32; - let clock = Instant::now(); - let many = references(&doc, common, true); - let capped_scan = clock.elapsed(); - - eprintln!( - "100 MB probe: {bytes} bytes, {lines} lines\n \ - open (line index only): {open:?}\n \ - semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \ - definition scan (declared in the last line): {definition_scan:?}\n \ - references scan (2 hits, whole file): {reference_scan:?}\n \ - references scan (short name, {} hits among a million prefixes): {capped_scan:?}", - many.len() - ); - - assert!(open.as_millis() < 5_000, "opening cost {open:?}"); - assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}"); - assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}"); - assert!( - definition_scan.as_millis() < 1_000, - "the definition scan cost {definition_scan:?}" - ); - assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}"); - assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}"); - } - - /// What the fast path is worth, measured rather than asserted: the same - /// buffer through [`Document::new`] and through [`Document::large`]. - /// - /// Ten megabytes rather than a hundred, because the point is the *ratio* - /// and because a 100 MB full analysis is minutes and gigabytes — which is - /// itself the finding, and is why the threshold exists. - #[test] - #[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"] - fn the_full_pipeline_probe_says_what_the_fast_path_saves() { - use std::time::Instant; - let text = netlist(10 * 1024 * 1024); - let clock = Instant::now(); - let fast = Document::large(None, text.clone()); - let fast_open = clock.elapsed(); - - let clock = Instant::now(); - let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default()); - let full_open = clock.elapsed(); - - eprintln!( - "10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \ - ({} tokens) — {:.0}x", - fast.tokens.len(), - full.tokens.len(), - full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE) - ); - assert!(fast_open < full_open, "the fast path is the fast one"); - } - - #[test] - fn every_declarator_is_a_real_keyword() { - for word in DECLARATORS { - assert!( - vlog_parser::KEYWORDS.contains(&word), - "{word} is not a keyword the lexer knows" - ); - } - } - - /// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far - /// longer than [`BACKSCAN`], packed with thousands of short tokens rather - /// than one long one — a wide bus concatenation or a one-line generated - /// port list, both ordinary netlist shapes. `window()` itself only ever - /// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by - /// construction. But colouring the window also converts every token's byte - /// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion - /// used to scan from the **start of the token's line** every time: on an - /// ordinary file a few dozen bytes of work, on a window that is all one - /// line O(line length) per token, i.e. **O(tokens²)**. Measured at - /// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below - /// (release) — 4x the time for 2x the tokens, the signature of a quadratic - /// wall rather than the "bounded, however big the file is" cost the - /// feature README promises. - /// - /// `tokens::flatten` now converts through `Positions::walker` - /// (`convert.rs`), which measures each line once however many offsets fall - /// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for - /// 2x, and 596x faster at the top. - /// - /// The bound is on the **shape** of the cost, not its size: the fastest - /// of five timings at each size, and the largest size (8x the tokens of - /// the smallest) may cost at most [`GROWTH_SLACK`] times 8x the smallest. - /// Linear is ~8x; the quadratic version is ~64x (73x in the release - /// numbers above). A wall-clock ceiling was here first and failed on the - /// CPU-capped Linux runner in debug, where everything is ~15x slower but - /// still 2x for 2x; a ratio holds on any machine. Shown to trip, with the - /// per-call converter put back into `tokens::flatten`, in - /// `docs/features/linux-test-portability/README.md`. - #[test] - fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() { - let sizes = [5_000u32, 10_000, 20_000, 40_000]; - let docs: Vec = sizes - .iter() - .map(|&count| { - // One line: `module m; wire a0,a1,...,last;` — realistic in - // shape (a wide declaration), synthetic only in how wide. - let mut text = String::from("module m; wire "); - for n in 0..count { - text.push_str(&format!("a{n},")); - } - text.push_str("last;\nendmodule\n"); - large(&text) - }) - .collect(); - for doc in &docs { - assert!(!window(doc, range(0, 1)).tokens.is_empty()); - } - assert_grows_linearly(&sizes, "colouring tokens on one line", || { - fastest_of_five(&docs, |doc| { - let clock = Instant::now(); - let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1)); - let elapsed = clock.elapsed(); - assert!(!data.is_empty(), "the window really did colour something"); - elapsed - }) - }); - } - - /// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other* - /// fast-path consumer of `Positions`: `references`' hits still have to - /// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one - /// `Positions::range` each. `large::references` itself was always linear; - /// the wall was entirely in turning up to [`REFERENCE_LIMIT`] hits on one - /// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s** - /// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms. - /// - /// `large_scan` now walks the hits with one `Positions::walker`, which - /// they are already in ascending order for. This runs at an eighth of the - /// original probe's line lengths so it can live in the normal suite. The - /// hits and the line both grow with `width`, so the walker's work (each - /// byte of the line once) is linear in it and the per-hit rescan's (the - /// line once per hit) quadratic; the bound is the same shape check as the - /// colour test's above, and shown to trip the same way. - #[test] - fn references_on_one_giant_line_locate_their_hits_in_linear_time() { - let sizes = [100u32, 200, 400, 800]; - let docs: Vec<(Document, Vec)> = sizes - .iter() - .map(|&width| { - // One line: `wire sig;` filler `sig` filler `sig` ... — - // `width` occurrences of the needle spread over one line, all - // comfortably under REFERENCE_LIMIT so the cap is not what is - // being timed. - let mut text = String::from("wire sig;"); - for _ in 0..width { - text.push_str(&" filler_word ".repeat(250)); - text.push_str("sig"); - } - text.push('\n'); - let doc = large(&text); - let hits = references(&doc, 5, true); - assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use"); - (doc, hits) - }) - .collect(); - assert_grows_linearly(&sizes, "locating hits on one line", || { - fastest_of_five(&docs, |(doc, hits)| { - let positions = doc.positions(); - let clock = Instant::now(); - // Exactly what `Server::large_scan` does with them. - let mut walker = positions.walker(); - for hit in hits { - std::hint::black_box(walker.range(*hit)); - } - clock.elapsed() - }) - }); - } - - /// How much faster than its input a linear-time test's cost may grow - /// before it fails: 3x, so 24x for an 8x input, where linear measures - /// ~8x (macOS and the Linux runner alike) and quadratic ~64x. - const GROWTH_SLACK: f64 = 3.0; - - /// The fastest of five timings of `run` on each input. The rounds go over - /// all the inputs in turn, so a burst of load from the tests running - /// beside this one slows one sample of each size rather than every sample - /// of one. Five, not three: QA saw 18.2x of the 24x limit at three under - /// 2x CPU oversubscription, and more rounds is the margin that does not - /// loosen what the test can see. - fn fastest_of_five(inputs: &[T], mut run: impl FnMut(&T) -> Duration) -> Vec { - let mut fastest = vec![Duration::MAX; inputs.len()]; - for _ in 0..5 { - for (best, input) in fastest.iter_mut().zip(inputs) { - *best = (*best).min(run(input)); - } - } - fastest - } - - /// How many times a measurement over [`GROWTH_SLACK`] is taken again - /// before the test fails. Load from the tests running beside this one - /// can stretch one whole measurement (the Linux runner read 24.9x of the - /// 24x limit once, with 1.35x between two neighbouring sizes); a - /// quadratic conversion measures ~64x every time, so asking again - /// loosens nothing the test can see. - const ATTEMPTS: usize = 3; - - /// Fails unless the cost at the largest size is within [`GROWTH_SLACK`] - /// of linear growth from the smallest, in one of [`ATTEMPTS`] measurements. - #[track_caller] - fn assert_grows_linearly( - sizes: &[u32], - what: &str, - mut measure: impl FnMut() -> Vec, - ) { - let (first, last) = (sizes[0], sizes[sizes.len() - 1]); - let input = f64::from(last) / f64::from(first); - let mut seen = Vec::new(); - for _ in 0..ATTEMPTS { - let costs = measure(); - for (size, cost) in sizes.iter().zip(&costs) { - eprintln!("{what}: {size} → {cost:?}"); - } - let growth = costs[costs.len() - 1].as_secs_f64() - / costs[0].as_secs_f64().max(f64::MIN_POSITIVE); - if growth <= GROWTH_SLACK * input { - return; - } - seen.push((growth, costs)); - } - panic!( - "{what}: {input}x the input cost more than {GROWTH_SLACK}x linear in each of \ - {ATTEMPTS} measurements ({seen:?}) — the quadratic conversion is back" - ); - } -} +pub(crate) mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/large/tests.rs b/crates/lucisv_server/src/large/tests.rs new file mode 100644 index 0000000..7a94590 --- /dev/null +++ b/crates/lucisv_server/src/large/tests.rs @@ -0,0 +1,534 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use lsp_types::{Position, Range}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +/// A fast-path document over `text`. +fn large(text: &str) -> Document { + Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string()) +} + +fn range(from: u32, to: u32) -> Range { + Range { start: Position { line: from, character: 0 }, end: Position { line: to, character: 0 } } +} + +/// The text of every token a window produced, in order. +fn words(doc: &Document, window: &Window) -> Vec { + window + .tokens + .iter() + .filter(|t| t.kind != vlog_parser::token::TokenKind::Eof) + .map(|t| doc.text[t.span.as_range()].to_string()) + .collect() +} + +// ------------------------------------------------------------------ +// the window +// ------------------------------------------------------------------ + +#[test] +fn a_window_lexes_its_own_lines_and_reports_document_offsets() { + let doc = large("module a;\nwire b;\nwire c;\nendmodule\n"); + let window = window(&doc, range(1, 2)); + assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]); + // The spans are the document's, not the slice's: the first token is + // `wire` on line 1, which starts at byte 10. + assert_eq!(window.tokens[0].span.start, 10); +} + +#[test] +fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() { + let doc = large("module a;\nwire b;\n"); + let mid = Range { + start: Position { line: 1, character: 4 }, + end: Position { line: 1, character: 6 }, + }; + assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]); +} + +#[test] +fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() { + let doc = large("module a;\nendmodule\n"); + assert!(words(&doc, &window(&doc, range(900, 999))).is_empty()); +} + +#[test] +fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() { + let doc = large("/* a\n b\n c */ wire d;\nwire e;\n"); + // Lines 1..3: the window opens on ` b`, which is inside the comment + // opened on line 0, so the tail up to `*/` is a comment span and the + // lexer only saw what followed it. + let window = window(&doc, range(1, 3)); + assert_eq!(window.comments.len(), 1); + let comment = &doc.text[window.comments[0].as_range()]; + assert!(comment.ends_with("*/"), "{comment:?}"); + assert!(comment.starts_with(" b"), "{comment:?}"); + assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]); +} + +#[test] +fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() { + let mut text = String::from("/* opener\n"); + for _ in 0..40 { + text.push_str(" still a comment\n"); + } + text.push_str("*/\nwire a;\n"); + let doc = large(&text); + let window = window(&doc, range(10, 20)); + assert!(window.tokens.is_empty()); + assert_eq!(window.comments.len(), 1); +} + +#[test] +fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() { + // A block comment opened further back than BACKSCAN: the decision + // cannot be made, and the documented answer is "code". + let mut text = String::from("/* opener\n"); + text.push_str(&" filler filler filler filler\n".repeat(4000)); + assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget"); + text.push_str("wire a;\n"); + let doc = large(&text); + let last = doc.line_index.line_count() - 2; + let window = window(&doc, range(last, last)); + assert!(window.comments.is_empty(), "no comment was detected"); + assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code"); +} + +#[test] +fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() { + let doc = large("wire a;\nwire b;\n/* an unterminated banner\n"); + let window = window(&doc, range(0, 2)); + assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]); + assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment"); + assert!(doc.text[window.comments[0].as_range()].starts_with("/*")); +} + +#[test] +fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() { + let doc = large("wire a;\n$display(\"unterminated\n"); + let window = window(&doc, range(0, 1)); + assert_eq!(words(&doc, &window), ["wire", "a", ";"]); + assert!(window.comments.is_empty(), "an unterminated string is not a comment"); +} + +#[test] +fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() { + let doc = large("$display(\"unterminated\nwire a;\n"); + let window = window(&doc, range(0, 0)); + assert!(window.tokens.is_empty()); + assert!(window.comments.is_empty()); +} + +#[test] +fn a_window_is_capped_however_much_the_client_asks_for() { + // Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking + // for the whole document must still lex at most MAX_WINDOW of it. + let text = "wire a;\n".repeat(200_000); + assert!(text.len() as u32 > MAX_WINDOW, "the premise"); + let doc = large(&text); + let window = window(&doc, range(0, doc.line_index.line_count())); + let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); + assert!(last <= MAX_WINDOW, "lexed past the cap: {last}"); + assert!(last > MAX_WINDOW - 64, "and up to it: {last}"); +} + +#[test] +fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() { + let mut text = String::from("wire "); + text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000)); + text.push_str(";\n"); + let doc = large(&text); + let window = window(&doc, range(0, 0)); + // It still answers, and it did not read the whole line. + let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); + assert!(last <= MAX_WINDOW, "{last}"); +} + +#[test] +fn an_empty_buffer_answers_an_empty_window() { + let doc = large(""); + let window = window(&doc, range(0, 10)); + assert!(window.tokens.is_empty() || words(&doc, &window).is_empty()); + assert!(window.comments.is_empty()); +} + +/// QA attack: a buffer of nothing but newlines. Every line is empty, so +/// every byte offset the code touches (line starts, line ends, the +/// backward scan's window) coincides with several others — the shape most +/// likely to trip an off-by-one into an out-of-range slice. +#[test] +fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() { + let doc = large(&"\n".repeat(5_000)); + for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] { + let window = window(&doc, range(from, to)); + // Only the EOF token, which every `tokenize` call ends with even + // over blank input — no real token, and no panic getting there. + assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}"); + } +} + +/// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary +/// byte of its line (`convert.rs`'s own rule), so a window boundary lands +/// right before a `\r` rather than a `\n` — this pins that the window +/// still lexes the same tokens CRLF or not, and that the trailing `\r` on +/// each line does not get coloured as part of the token before it. +#[test] +fn a_crlf_netlist_windows_the_same_as_its_lf_twin() { + let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n"; + let doc = large(lf); + let window = window(&doc, range(1, 2)); + assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]); + // No token swallowed the `\r`: every token's text is exactly itself. + for token in &window.tokens { + let text = &doc.text[token.span.as_range()]; + assert!(!text.contains('\r'), "a token ate the line ending: {text:?}"); + } +} + +// ------------------------------------------------------------------ +// the shrink helper on its own +// ------------------------------------------------------------------ + +#[test] +fn lex_reports_how_much_of_the_slice_it_used() { + let (tokens, used) = lex("wire a;\n"); + assert!(!tokens.is_empty()); + assert_eq!(used, 8); + let (tokens, used) = lex("wire a;\n/* open"); + assert!(!tokens.is_empty()); + assert_eq!(used, 8, "the comment line was dropped"); +} + +#[test] +fn line_start_counts_lines_from_one() { + assert_eq!(line_start("a\nb\nc", 1), Some(0)); + assert_eq!(line_start("a\nb\nc", 2), Some(2)); + assert_eq!(line_start("a\nb\nc", 3), Some(4)); + assert_eq!(line_start("a\nb\nc", 4), None); +} + +// ------------------------------------------------------------------ +// definition and references +// ------------------------------------------------------------------ + +const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \ + .b(sig_b));\n assign sig_a = sig_b;\nendmodule\n"; + +/// The offset of the `n`-th occurrence of `needle`. +fn at(text: &str, needle: &str, n: usize) -> u32 { + text.match_indices(needle).nth(n).expect("occurrence").0 as u32 +} + +#[test] +fn a_declaration_is_found_by_the_keyword_before_it() { + let doc = large(NETLIST); + let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration"); + assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line"); + assert_eq!(&NETLIST[found.as_range()], "sig_a"); +} + +#[test] +fn a_name_no_keyword_introduces_has_no_definition() { + let doc = large(NETLIST); + assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name"); +} + +#[test] +fn a_cursor_that_is_not_on_a_word_answers_nothing() { + let doc = large(NETLIST); + let space = NETLIST.find(" wire").expect("indent") as u32; + assert!(definition(&doc, space).is_none()); + assert!(references(&doc, space, true).is_empty()); +} + +#[test] +fn references_are_whole_word_and_in_order() { + let doc = large(NETLIST); + let found = references(&doc, at(NETLIST, "sig_a", 0), true); + assert_eq!(found.len(), 3, "declaration, connection, assignment"); + assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start)); + // `sig_a` is not found inside `sig_ab`. + let doc = large("wire sig_ab;\nwire sig_a;\n"); + assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1); +} + +#[test] +fn excluding_the_declaration_drops_exactly_the_declaration() { + let doc = large(NETLIST); + let with = references(&doc, at(NETLIST, "sig_a", 1), true); + let without = references(&doc, at(NETLIST, "sig_a", 1), false); + assert_eq!(without.len(), with.len() - 1); + assert!(!without.contains(&with[0])); +} + +#[test] +fn the_reference_list_is_capped() { + let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500)); + let doc = large(&text); + assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT); +} + +// ------------------------------------------------------------------ +// the 100 MB probes +// ------------------------------------------------------------------ + +/// A netlist-shaped buffer of about `bytes` bytes. +/// +/// Instantiation lines, which is what a synthesized netlist really is, with +/// a declaration and a comment every so often so the scans have something +/// to find and the windows have something to colour. +fn netlist(bytes: usize) -> String { + let mut text = String::with_capacity(bytes + 4096); + text.push_str("module netlist_top;\n wire needle;\n"); + let mut n = 0u64; + while text.len() < bytes { + text.push_str(&format!(" sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n", n + 1)); + if n.is_multiple_of(500) { + text.push_str(" /* a banner comment, so the windows are not all code */\n"); + text.push_str(" wire net_local;\n"); + } + n += 1; + } + // A second declaration at the far end: a scan for it is the worst + // case, since the answer is the last thing in the file. + text.push_str(" wire tail_needle;\nendmodule\n"); + text +} + +/// **The measurement the feature README quotes.** Ignored by default: it +/// builds a 100 MB buffer, which is not something `cargo test` should do +/// on every run. Run it as +/// `cargo test -p lucisv_server --release -- --ignored --nocapture +/// large::tests::the_hundred_megabyte_probes`. +/// +/// The bounds asserted are deliberately loose — an order of magnitude over +/// what the numbers actually are on the machine this was written on — so +/// the probe fails on a regression in *kind* (someone made the open path +/// scan the file twice, someone made the window lex the document) rather +/// than on a slow CI box. +#[test] +#[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"] +fn the_hundred_megabyte_probes() { + use std::time::Instant; + let text = netlist(100 * 1024 * 1024); + let bytes = text.len(); + + let clock = Instant::now(); + let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text); + let open = clock.elapsed(); + + let lines = doc.line_index.line_count(); + let middle = lines / 2; + let viewport = Range { + start: Position { line: middle, character: 0 }, + end: Position { line: middle + 60, character: 0 }, + }; + // Twice: the first call is where any accidental one-off whole-file + // work would hide. + let clock = Instant::now(); + let first = window(&doc, viewport); + let first_window = clock.elapsed(); + let clock = Instant::now(); + let again = window(&doc, viewport); + let second_window = clock.elapsed(); + assert_eq!(first.tokens.len(), again.tokens.len()); + assert!(!first.tokens.is_empty(), "the window really did lex something"); + + // The worst case for both scans: the name is declared in the *last* + // line of the file, so the answer is only found after a whole pass. + let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32; + let clock = Instant::now(); + let found = definition(&doc, tail); + let definition_scan = clock.elapsed(); + assert!(found.is_some()); + + let clock = Instant::now(); + let refs = references(&doc, tail, true); + let reference_scan = clock.elapsed(); + assert!(!refs.is_empty()); + + // And the shape that is worst for the search itself: a short name + // that occurs as a *prefix* of a million others, so the whole-word + // filter runs on every one of them. + let common = doc.text.find("net1)").expect("a net use") as u32; + let clock = Instant::now(); + let many = references(&doc, common, true); + let capped_scan = clock.elapsed(); + + eprintln!( + "100 MB probe: {bytes} bytes, {lines} lines\n \ + open (line index only): {open:?}\n \ + semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \ + definition scan (declared in the last line): {definition_scan:?}\n \ + references scan (2 hits, whole file): {reference_scan:?}\n \ + references scan (short name, {} hits among a million prefixes): {capped_scan:?}", + many.len() + ); + + assert!(open.as_millis() < 5_000, "opening cost {open:?}"); + assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}"); + assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}"); + assert!(definition_scan.as_millis() < 1_000, "the definition scan cost {definition_scan:?}"); + assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}"); + assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}"); +} + +/// What the fast path is worth, measured rather than asserted: the same +/// buffer through [`Document::new`] and through [`Document::large`]. +/// +/// Ten megabytes rather than a hundred, because the point is the *ratio* +/// and because a 100 MB full analysis is minutes and gigabytes — which is +/// itself the finding, and is why the threshold exists. +#[test] +#[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"] +fn the_full_pipeline_probe_says_what_the_fast_path_saves() { + use std::time::Instant; + let text = netlist(10 * 1024 * 1024); + let clock = Instant::now(); + let fast = Document::large(None, text.clone()); + let fast_open = clock.elapsed(); + + let clock = Instant::now(); + let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default()); + let full_open = clock.elapsed(); + + eprintln!( + "10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \ + ({} tokens) — {:.0}x", + fast.tokens.len(), + full.tokens.len(), + full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE) + ); + assert!(fast_open < full_open, "the fast path is the fast one"); +} + +#[test] +fn every_declarator_is_a_real_keyword() { + for word in DECLARATORS { + assert!(vlog_parser::KEYWORDS.contains(&word), "{word} is not a keyword the lexer knows"); + } +} + +/// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far +/// longer than [`BACKSCAN`], packed with thousands of short tokens rather +/// than one long one — a wide bus concatenation or a one-line generated +/// port list, both ordinary netlist shapes. `window()` itself only ever +/// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by +/// construction. But colouring the window also converts every token's byte +/// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion +/// used to scan from the **start of the token's line** every time: on an +/// ordinary file a few dozen bytes of work, on a window that is all one +/// line O(line length) per token, i.e. **O(tokens²)**. Measured at +/// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below +/// (release) — 4x the time for 2x the tokens, the signature of a quadratic +/// wall rather than the "bounded, however big the file is" cost the +/// feature README promises. +/// +/// `tokens::flatten` now converts through `Positions::walker` +/// (`convert.rs`), which measures each line once however many offsets fall +/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for +/// 2x, and 596x faster at the top. +/// +/// The bound is on the **shape** of the cost, not its size: the fastest +/// of five timings at each size, and the largest size (8x the tokens of +/// the smallest) may cost at most [`GROWTH_SLACK`] times 8x the smallest. +/// Linear is ~8x; the quadratic version is ~64x (73x in the release +/// numbers above). A wall-clock ceiling was here first and failed on the +/// CPU-capped Linux runner in debug, where everything is ~15x slower but +/// still 2x for 2x; a ratio holds on any machine. Shown to trip, with the +/// per-call converter put back into `tokens::flatten`, in +/// `docs/features/linux-test-portability/README.md`. +#[test] +fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() { + let sizes = [5_000u32, 10_000, 20_000, 40_000]; + let docs: Vec = sizes + .iter() + .map(|&count| { + // One line: `module m; wire a0,a1,...,last;` — realistic in + // shape (a wide declaration), synthetic only in how wide. + let mut text = String::from("module m; wire "); + for n in 0..count { + text.push_str(&format!("a{n},")); + } + text.push_str("last;\nendmodule\n"); + large(&text) + }) + .collect(); + for doc in &docs { + assert!(!window(doc, range(0, 1)).tokens.is_empty()); + } + assert_grows_linearly(&sizes, "colouring tokens on one line", || { + fastest_of_five(&docs, |doc| { + let clock = Instant::now(); + let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1)); + let elapsed = clock.elapsed(); + assert!(!data.is_empty(), "the window really did colour something"); + elapsed + }) + }); +} + +/// How much faster than its input a linear-time test's cost may grow +/// before it fails: 3x, so 24x for an 8x input, where linear measures +/// ~8x (macOS and the Linux runner alike) and quadratic ~64x. +const GROWTH_SLACK: f64 = 3.0; + +/// The fastest of five timings of `run` on each input. The rounds go over +/// all the inputs in turn, so a burst of load from the tests running +/// beside this one slows one sample of each size rather than every sample +/// of one. Five, not three: QA saw 18.2x of the 24x limit at three under +/// 2x CPU oversubscription, and more rounds is the margin that does not +/// loosen what the test can see. +pub(crate) fn fastest_of_five( + inputs: &[T], + mut run: impl FnMut(&T) -> Duration, +) -> Vec { + let mut fastest = vec![Duration::MAX; inputs.len()]; + for _ in 0..5 { + for (best, input) in fastest.iter_mut().zip(inputs) { + *best = (*best).min(run(input)); + } + } + fastest +} + +/// How many times a measurement over [`GROWTH_SLACK`] is taken again +/// before the test fails. Load from the tests running beside this one +/// can stretch one whole measurement (the Linux runner read 24.9x of the +/// 24x limit once, with 1.35x between two neighbouring sizes); a +/// quadratic conversion measures ~64x every time, so asking again +/// loosens nothing the test can see. +const ATTEMPTS: usize = 3; + +/// Fails unless the cost at the largest size is within [`GROWTH_SLACK`] +/// of linear growth from the smallest, in one of [`ATTEMPTS`] measurements. +#[track_caller] +pub(crate) fn assert_grows_linearly( + sizes: &[u32], + what: &str, + mut measure: impl FnMut() -> Vec, +) { + let (first, last) = (sizes[0], sizes[sizes.len() - 1]); + let input = f64::from(last) / f64::from(first); + let mut seen = Vec::new(); + for _ in 0..ATTEMPTS { + let costs = measure(); + for (size, cost) in sizes.iter().zip(&costs) { + eprintln!("{what}: {size} → {cost:?}"); + } + let growth = + costs[costs.len() - 1].as_secs_f64() / costs[0].as_secs_f64().max(f64::MIN_POSITIVE); + if growth <= GROWTH_SLACK * input { + return; + } + seen.push((growth, costs)); + } + panic!( + "{what}: {input}x the input cost more than {GROWTH_SLACK}x linear in each of \ + {ATTEMPTS} measurements ({seen:?}) — the quadratic conversion is back" + ); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/lens.rs b/crates/lucisv_server/src/lens.rs index 7798cf9..92b53d1 100644 --- a/crates/lucisv_server/src/lens.rs +++ b/crates/lucisv_server/src/lens.rs @@ -135,631 +135,6 @@ fn title(sites: usize) -> String { } #[cfg(test)] -mod tests { - use super::*; - use crate::uri::path_to_uri; - use lsp_types::CallHierarchyItem; - use std::fs; - use std::path::PathBuf; - - /// A scratch workspace root, removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_lens_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).expect("mkdir"); - } - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - /// A workspace over `files`, with the first of them opened as a buffer. - fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { - let tree = Tree::new(name); - let mut first = None; - for (rel, text) in files { - let path = tree.write(rel, text); - if first.is_none() { - first = Some((path, *text)); - } - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let (path, text) = first.expect("at least one file"); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - (tree, ws, uri) - } - - /// Every lens of a buffer as `(title, command, start line, start column)`. - fn shape(lenses: &[CodeLens]) -> Vec<(String, String, u32, u32)> { - lenses - .iter() - .map(|lens| { - let command = lens.command.as_ref().expect("every lens carries a command"); - ( - command.title.clone(), - command.command.clone(), - lens.range.start.line, - lens.range.start.character, - ) - }) - .collect() - } - - /// Just the titles, for the tests that only care what the user reads. - fn titles(lenses: &[CodeLens]) -> Vec { - lenses - .iter() - .map(|lens| lens.command.as_ref().map_or(String::new(), |c| c.title.clone())) - .collect() - } - - const SUB: &str = "module sub (input logic clk);\nendmodule\n"; - const TOP: &str = "\ -module top; - sub u_a (.clk(1'b0)); - sub u_b (.clk(1'b1)); -endmodule -"; - const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; - - // ------------------------------------------------------------------ - // the count - // ------------------------------------------------------------------ - - #[test] - fn a_lens_counts_every_instantiation_in_the_workspace() { - // Three sites across two other files, on a declaration in this one. - let (_tree, ws, uri) = - workspace("count", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); - let lenses = code_lenses(&ws, &uri).expect("an open buffer"); - assert_eq!(titles(&lenses), ["3 instantiations"], "two in top.sv, one in o.sv"); - } - - #[test] - fn the_title_counts_in_the_users_own_arithmetic() { - let alone = "module lonely;\nendmodule\n"; - let (_tree, ws, uri) = workspace("zero", &[("lonely.sv", alone)]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); - - let one = "module top;\n lonely u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("one", &[("lonely.sv", alone), ("top.sv", one)]); - assert_eq!( - titles(&code_lenses(&ws, &uri).expect("open")), - ["1 instantiation"], - "not `1 instantiations`" - ); - - let two = "module top;\n lonely u1 ();\n lonely u2 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("two", &[("lonely.sv", alone), ("top.sv", two)]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); - } - - #[test] - fn the_count_is_exactly_what_incoming_calls_would_list() { - // The whole contract between this feature and the hierarchy: a user - // who reads "3 instantiations" and then opens the call hierarchy must - // be shown three sites. - let (_tree, ws, uri) = - workspace("agree", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!(lenses.len(), 1); - - let item = CallHierarchyItem { - name: "sub".to_string(), - kind: lsp_types::SymbolKind::MODULE, - tags: None, - detail: None, - uri: uri.clone(), - range: lenses[0].range, - selection_range: lenses[0].range, - data: None, - }; - let listed: usize = - hierarchy::incoming(&ws, &item).iter().map(|call| call.from_ranges.len()).sum(); - assert_eq!(titles(&lenses), [format!("{listed} instantiations")]); - assert_eq!(listed, 3, "and the number itself is the one we meant"); - // And the command shows exactly those sites. - assert_eq!(execute(&ws, &[Value::String("sub".to_string())]).expect("runs").len(), listed); - } - - #[test] - fn an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it() { - // The same rule `callHierarchy/incomingCalls` applies: a site with no - // enclosing module has no caller to report, so it is nobody's edge. - let (_tree, ws, uri) = - workspace("filescope", &[("sub.sv", SUB), ("loose.sv", "sub u_loose ();\n")]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); - } - - // ------------------------------------------------------------------ - // which declarations get a lens, and where it sits - // ------------------------------------------------------------------ - - #[test] - fn the_lens_sits_on_the_declarations_own_name() { - // The client draws a lens on the line *above* `range.start`, so the - // name span is what puts it over the header and nowhere else. - let (_tree, ws, uri) = workspace("span", &[("sub.sv", SUB), ("top.sv", TOP)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!( - shape(&lenses), - [("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7)], - "column 7 is `sub`, not the `module` keyword" - ); - assert_eq!(lenses[0].range.end.character, 10, "the name only"); - } - - #[test] - fn an_interface_is_a_module_declaration_and_gets_its_own_lens() { - let bus = "interface bus;\n logic clk;\nendinterface\n"; - let user = "module top;\n bus u_bus ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("iface", &[("bus.sv", bus), ("top.sv", user)]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); - } - - #[test] - fn every_module_in_a_file_gets_its_own_lens_in_source_order() { - let many = "\ -module first; -endmodule - -module second; -endmodule - -module third; -endmodule -"; - let uses = "module top;\n third u3 ();\n first u1 ();\n third u3b ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("many", &[("many.sv", many), ("top.sv", uses)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!( - shape(&lenses), - [ - ("1 instantiation".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7), - ("no instantiations".to_string(), String::new(), 3, 7), - ("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 6, 7), - ], - "source order, one per declaration" - ); - } - - #[test] - fn a_module_nothing_instantiates_gets_a_lens_that_does_not_click() { - let (_tree, ws, uri) = - workspace("noclick", &[("lonely.sv", "module lonely;\nendmodule\n")]); - let lenses = code_lenses(&ws, &uri).expect("open"); - let command = lenses[0].command.as_ref().expect("a command"); - assert_eq!(command.title, "no instantiations"); - assert_eq!(command.command, "", "display-only: there is nothing to open"); - assert_eq!(command.arguments, None, "and nothing to pass"); - } - - #[test] - fn a_clickable_lens_carries_the_module_name_as_its_only_argument() { - let (_tree, ws, uri) = workspace("args", &[("sub.sv", SUB), ("top.sv", TOP)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - let command = lenses[0].command.as_ref().expect("a command"); - assert_eq!(command.command, SHOW_INSTANTIATIONS); - assert_eq!(command.arguments, Some(vec![Value::String("sub".to_string())])); - } - - #[test] - fn no_lens_is_ever_left_for_a_resolve_to_fill_in() { - // `resolveProvider: false` is advertised, so a lens without a command - // would be a lens the client can never complete. - let (_tree, ws, uri) = workspace("complete", &[("sub.sv", SUB), ("top.sv", TOP)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert!(lenses.iter().all(|lens| lens.command.is_some() && lens.data.is_none())); - } - - // ------------------------------------------------------------------ - // the refusals - // ------------------------------------------------------------------ - - #[test] - fn a_buffer_this_server_was_never_shown_has_no_lenses_at_all() { - let (tree, ws, _) = workspace("closed", &[("sub.sv", SUB)]); - let never = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); - assert!(code_lenses(&ws, &never).is_none(), "null, not an empty list"); - } - - #[test] - fn a_buffer_that_declares_no_module_gets_an_empty_list() { - let (_tree, ws, uri) = workspace("nomodules", &[("p.sv", "package p;\nendpackage\n")]); - assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new()); - } - - #[test] - fn a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic() { - let junk = ")))) not verilog ((((\n@@@ endmodule : ;\n"; - let (_tree, ws, uri) = workspace("junk", &[("junk.sv", junk)]); - assert_eq!( - code_lenses(&ws, &uri).expect("open"), - Vec::new(), - "total, whatever it parses to" - ); - } - - #[test] - fn a_declaration_the_parser_could_not_name_gets_no_lens() { - // `module ;` recovers into a declaration with an empty name span, - // which is a lens with no line to sit on. - let broken = "module ;\nendmodule\n\nmodule fine;\nendmodule\n"; - let (_tree, ws, uri) = workspace("unnamed", &[("broken.sv", broken)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert!( - lenses.iter().all(|lens| lens.range.start.line == 3), - "only the named declaration: {lenses:#?}" - ); - } - - // ------------------------------------------------------------------ - // the command - // ------------------------------------------------------------------ - - #[test] - fn the_command_answers_one_location_per_site() { - let (_tree, ws, _) = - workspace("sites", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); - let locations = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); - let shape: Vec<(String, u32, u32)> = locations - .iter() - .map(|at| { - ( - at.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), - at.range.start.line, - at.range.start.character, - ) - }) - .collect(); - assert_eq!( - shape, - [ - ("o.sv".to_string(), 1, 2), - ("top.sv".to_string(), 1, 2), - ("top.sv".to_string(), 2, 2), - ], - "every site, sorted by file then position" - ); - } - - #[test] - fn the_command_answers_nothing_for_a_module_nothing_instantiates() { - let (_tree, ws, _) = workspace("nosites", &[("lonely.sv", "module lonely;\nendmodule\n")]); - assert_eq!(execute(&ws, &[Value::String("lonely".to_string())]), Ok(Vec::new())); - assert_eq!( - execute(&ws, &[Value::String("never-heard-of-it".to_string())]), - Ok(Vec::new()), - "a name the workspace does not declare is not an error either" - ); - } - - #[test] - fn the_command_declines_arguments_it_cannot_read() { - let (_tree, ws, _) = workspace("badargs", &[("sub.sv", SUB)]); - for arguments in [vec![], vec![Value::Null], vec![Value::String(String::new())]] { - let message = execute(&ws, &arguments).expect_err("declined"); - assert!(message.contains("module name"), "{message}"); - } - } - - #[test] - fn the_command_list_is_what_the_server_advertises() { - assert_eq!(commands(), vec![SHOW_INSTANTIATIONS]); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): count-honesty shapes the fixture above never - // exercises — a multi-instance statement, self-recursion, name - // collisions (within one file and across files), generate replication - // and an `ifdef`-guarded instantiation. None of these turned out to - // disagree with `hierarchy::incoming` — they can't, since `lens.rs` and - // `hierarchy::incoming` both bottom out in the same - // `hierarchy::callers_of_each` — but the *number itself* is worth - // pinning so a future change to what counts as a "site" is visible here - // too, not just in `hierarchy.rs`. See QA log in - // `docs/features/code-lens/README.md`. - // ------------------------------------------------------------------ - - #[test] - fn qa_corpus_counts_agree_with_grep_derived_ground_truth() { - // `corpus/common_cells/src/cdc_fifo_gray.sv` declares three modules. - // Ground truth by hand, `grep -rnE '\bNAME\b' corpus --include='*.sv' - // --include='*.svh'`, read line by line to exclude the declaration - // itself and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has - // several, e.g. line 56's "In contrast to the cdc_fifo_gray - // version..."): - // - `cdc_fifo_gray` — one real instantiation, - // `common_cells/test/cdc_fifo_tb.sv:49` (`i_dut`). - // - `cdc_fifo_gray_src` — one, `cdc_fifo_gray.sv:130`, inside - // `cdc_fifo_gray` itself (`_src_clearable` is a different name - // and does not match `\bcdc_fifo_gray_src\b`). - // - `cdc_fifo_gray_dst` — one, `cdc_fifo_gray.sv:145`, likewise. - // Skipped like the other corpus tests when `corpus/` is not checked - // out (`tools/corpus_fetch.sh`). - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); - let Ok(text) = fs::read_to_string(&file) else { - eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&file).expect("uri"); - ws.set_document(uri.clone(), text); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!( - titles(&lenses), - ["1 instantiation", "1 instantiation", "1 instantiation"], - "cdc_fifo_gray, cdc_fifo_gray_src, cdc_fifo_gray_dst, in that source order: {lenses:#?}" - ); - } - - #[test] - fn qa_a_multi_instance_statement_is_one_site_not_two() { - // `sub u1 (), u2 ();` is ONE `Instantiation` AST node carrying TWO - // `Instance` entries — physically two instantiations of `sub` in the - // design. This is not a code-lens decision: `hierarchy.rs`'s own - // documented assumption ("One `Instantiation` is one call site, - // however many instances it declares") already settles it, the same - // way `textDocument/references` reports the module name once. Pinned - // here too so a change to that policy is visible in both features. - let top = "module top;\n sub u1 (), u2 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_multi", &[("sub.sv", SUB), ("top.sv", top)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!(titles(&lenses), ["1 instantiation"], "one AST node, not two instances"); - let locs = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); - assert_eq!(locs.len(), 1, "one location for the one site: {locs:#?}"); - } - - #[test] - fn qa_a_module_that_instantiates_itself_counts_its_own_instantiation() { - // Self-recursion (illegal to elaborate, legal text) is handled the - // same way `hierarchy.rs` handles an `a -> b -> a` cycle: each - // request answers one hop, so there is nothing here that could ever - // recurse or hang. - let text = "module m;\n m u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_recursive", &[("m.sv", text)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!(titles(&lenses), ["1 instantiation"]); - let locs = execute(&ws, &[Value::String("m".to_string())]).expect("runs"); - assert_eq!(locs.len(), 1); - } - - #[test] - fn qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both() { - // The census is by name (documented in this README's Assumptions): - // an instantiation of `m` cannot say which of two `module m` - // declarations it meant, so both lenses read the workspace-wide - // total rather than a partitioned one. Same limitation - // `callHierarchy/incomingCalls` already has, for the same reason. - let m_a = "module m;\n logic a;\nendmodule\n"; - let m_b = "module m;\n logic b;\nendmodule\n"; - let user = "module top;\n m u1 ();\nendmodule\n"; - let (_tree, ws, uri_a) = - workspace("qa_collide_a", &[("a/m.sv", m_a), ("b/m.sv", m_b), ("top.sv", user)]); - assert_eq!(titles(&code_lenses(&ws, &uri_a).expect("open a/m.sv")), ["1 instantiation"]); - - // Same workspace, opening the OTHER declaration instead: same total. - let mut ws_b = Workspace::default(); - let tree_b = Tree::new("qa_collide_b"); - tree_b.write("a/m.sv", m_a); - let path_b = tree_b.write("b/m.sv", m_b); - tree_b.write("top.sv", user); - ws_b.open_whole_workspace(vec![tree_b.path.clone()]); - let uri_b = path_to_uri(&path_b).expect("uri"); - ws_b.set_document(uri_b.clone(), m_b.to_string()); - assert_eq!( - titles(&code_lenses(&ws_b, &uri_b).expect("open b/m.sv")), - ["1 instantiation"], - "the other declaration reads the same total, not zero" - ); - } - - #[test] - fn qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count() { - // The tolerant parser accepts `module m; endmodule module m; - // endmodule` in one file (real SystemVerilog forbids it, but this is - // reachable through broken input). The batch in - // `hierarchy::callers_of_each` is asked `["m", "m"]` — two indices, - // not deduplicated — so this also pins that duplicate names in one - // batch do not alias or corrupt each other's answer. - let text = "module m;\nendmodule\n\nmodule m;\nendmodule\n"; - let user = "module top;\n m u1 ();\nendmodule\n"; - let (_tree, ws, uri) = workspace("qa_dup_same_file", &[("m.sv", text), ("top.sv", user)]); - let lenses = code_lenses(&ws, &uri).expect("open"); - assert_eq!(lenses.len(), 2, "one lens per declaration"); - assert_eq!(titles(&lenses), ["1 instantiation", "1 instantiation"]); - } - - #[test] - fn qa_a_generate_replicated_instantiation_counts_the_written_statement_once() { - // `generate for` is not elaborated: the AST has exactly one - // `Instantiation` node inside the loop body regardless of the - // genvar's range, matching `hierarchy.rs`'s own documented handling - // of the identical shape (`incoming_calls_reach_generate_regions_...` - // in `hierarchy.rs`). Four elaborated instances at synthesis time, - // one textual site here — the lens counts text, not hardware. - let sub = "module sub;\nendmodule\n"; - let top = "\ -module top; - generate - for (genvar i = 0; i < 4; i++) begin : g - sub u1 (); - end - endgenerate -endmodule -"; - let (_tree, ws, uri) = workspace("qa_generate", &[("sub.sv", sub), ("top.sv", top)]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); - } - - #[test] - fn qa_an_ifdef_guarded_instantiation_counts_both_arms() { - // Inherited from `hierarchy.rs`, disclosed there as an Assumption: - // the parser does not evaluate `` `ifdef``/`` `else``, so both arms - // land as ordinary `Instantiation` items and both are counted, even - // though only one is ever really built. Pinned here too since the - // lens is a second, more prominent surface for the same policy. - let sub = "module sub;\nendmodule\n"; - let top = "\ -module top; -`ifdef FOO - sub u1 (); -`endif - sub u2 (); -endmodule -"; - let (_tree, ws, uri) = workspace("qa_ifdef", &[("sub.sv", sub), ("top.sv", top)]); - assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); - } - - // ------------------------------------------------------------------ - // the performance claim, measured - // ------------------------------------------------------------------ - - /// The number the round's Handshake was filed for, measured: what a whole - /// file's lenses cost before the edge table (a walk of every in-scope - /// file, re-read and re-parsed) and what they cost after (a lookup). - /// - /// `#[ignore]`d like the other measurement probes in this crate — it prints - /// a number rather than asserting one, and the assertion that must hold is - /// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk` - /// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`. - #[test] - #[ignore] - fn qa_perf_lens_lookup_against_the_walk_it_replaced() { - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); - let Ok(text) = fs::read_to_string(&file) else { - eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&file).expect("uri"); - ws.set_document(uri.clone(), text); - let _ = code_lenses(&ws, &uri); - - let mut lenses = std::time::Duration::ZERO; - let mut walk = std::time::Duration::ZERO; - for _ in 0..3 { - let started = std::time::Instant::now(); - let _ = code_lenses(&ws, &uri).expect("open"); - lenses = lenses.max(started.elapsed()); - // What `callers_of_each` used to begin with, every request. - let started = std::time::Instant::now(); - let _ = ws.sources(); - walk = walk.max(started.elapsed()); - } - eprintln!( - "codeLens over {} files: {lenses:?} for the whole file; one workspace walk \ - (what the old census re-read on every request) is {walk:?}", - ws.index().files().len() - ); - } - - /// What a whole file's lenses cost over the real corpus, against what one - /// workspace walk costs. - /// - /// **Superseded this round (incremental-index, 2026-08-27):** - /// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted - /// `whole_file < one_name * 2` — that asking about three modules cost about - /// what asking about one did, because both were *one walk* of the whole - /// workspace. There is no walk any more: the count is a lookup in the - /// index's instantiation-edge table, and the only I/O left is reading the - /// handful of files that really do instantiate one of the three. Both sides - /// of that ratio are now microseconds dominated by a file read each, so the - /// ratio pins noise. The property worth pinning is the stronger one this - /// round bought: **a whole file's lenses cost a small fraction of one - /// workspace walk**, measured here rather than asserted. - /// - /// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`), - /// like the other corpus tests. The budget is deliberately loose: a debug - /// build on a loaded machine is the worst case this ever runs in, and this - /// exists to catch an order-of-magnitude regression — a lens handler that - /// went back to re-reading the workspace would fail it by two. - #[test] - fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() { - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - // A real file declaring three modules, so the batch has something to - // amortize over. - let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); - let Ok(text) = fs::read_to_string(&file) else { - eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&file).expect("uri"); - ws.set_document(uri.clone(), text); - - // Warm, then the worst of three, for the whole file and for one name; - // and the best of three for the walk it used to be, so the comparison - // is stacked against the claim rather than for it. - let _ = code_lenses(&ws, &uri); - let mut whole_file = std::time::Duration::ZERO; - let mut one_name = std::time::Duration::ZERO; - let mut walk = std::time::Duration::MAX; - let mut count = 0; - for _ in 0..3 { - let started = std::time::Instant::now(); - let lenses = code_lenses(&ws, &uri).expect("open"); - whole_file = whole_file.max(started.elapsed()); - count = lenses.len(); - let started = std::time::Instant::now(); - let _ = sites_of(&ws, "cdc_fifo_gray"); - one_name = one_name.max(started.elapsed()); - let started = std::time::Instant::now(); - let _ = ws.sources(); - walk = walk.min(started.elapsed()); - } - eprintln!( - "corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \ - (one name alone: {one_name:?}; one workspace walk: {walk:?})", - ws.index().files().len(), - ); - assert!(count >= 3, "the file declares three modules: {count}"); - assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}"); - assert!( - whole_file * 10 < walk, - "the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \ - {walk:?} for one walk of the workspace" - ); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/lens/tests.rs b/crates/lucisv_server/src/lens/tests.rs new file mode 100644 index 0000000..46caeaa --- /dev/null +++ b/crates/lucisv_server/src/lens/tests.rs @@ -0,0 +1,616 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use lsp_types::CallHierarchyItem; +use std::fs; +use std::path::PathBuf; + +/// A scratch workspace root, removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = + std::env::temp_dir().join(format!("lucisv_server_lens_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("mkdir"); + } + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +/// A workspace over `files`, with the first of them opened as a buffer. +fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + let mut first = None; + for (rel, text) in files { + let path = tree.write(rel, text); + if first.is_none() { + first = Some((path, *text)); + } + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let (path, text) = first.expect("at least one file"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + (tree, ws, uri) +} + +/// Every lens of a buffer as `(title, command, start line, start column)`. +fn shape(lenses: &[CodeLens]) -> Vec<(String, String, u32, u32)> { + lenses + .iter() + .map(|lens| { + let command = lens.command.as_ref().expect("every lens carries a command"); + ( + command.title.clone(), + command.command.clone(), + lens.range.start.line, + lens.range.start.character, + ) + }) + .collect() +} + +/// Just the titles, for the tests that only care what the user reads. +fn titles(lenses: &[CodeLens]) -> Vec { + lenses + .iter() + .map(|lens| lens.command.as_ref().map_or(String::new(), |c| c.title.clone())) + .collect() +} + +const SUB: &str = "module sub (input logic clk);\nendmodule\n"; +const TOP: &str = "\ +module top; + sub u_a (.clk(1'b0)); + sub u_b (.clk(1'b1)); +endmodule +"; +const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + +// ------------------------------------------------------------------ +// the count +// ------------------------------------------------------------------ + +#[test] +fn a_lens_counts_every_instantiation_in_the_workspace() { + // Three sites across two other files, on a declaration in this one. + let (_tree, ws, uri) = workspace("count", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let lenses = code_lenses(&ws, &uri).expect("an open buffer"); + assert_eq!(titles(&lenses), ["3 instantiations"], "two in top.sv, one in o.sv"); +} + +#[test] +fn the_title_counts_in_the_users_own_arithmetic() { + let alone = "module lonely;\nendmodule\n"; + let (_tree, ws, uri) = workspace("zero", &[("lonely.sv", alone)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); + + let one = "module top;\n lonely u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("one", &[("lonely.sv", alone), ("top.sv", one)]); + assert_eq!( + titles(&code_lenses(&ws, &uri).expect("open")), + ["1 instantiation"], + "not `1 instantiations`" + ); + + let two = "module top;\n lonely u1 ();\n lonely u2 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("two", &[("lonely.sv", alone), ("top.sv", two)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); +} + +#[test] +fn the_count_is_exactly_what_incoming_calls_would_list() { + // The whole contract between this feature and the hierarchy: a user + // who reads "3 instantiations" and then opens the call hierarchy must + // be shown three sites. + let (_tree, ws, uri) = workspace("agree", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(lenses.len(), 1); + + let item = CallHierarchyItem { + name: "sub".to_string(), + kind: lsp_types::SymbolKind::MODULE, + tags: None, + detail: None, + uri: uri.clone(), + range: lenses[0].range, + selection_range: lenses[0].range, + data: None, + }; + let listed: usize = + hierarchy::incoming(&ws, &item).iter().map(|call| call.from_ranges.len()).sum(); + assert_eq!(titles(&lenses), [format!("{listed} instantiations")]); + assert_eq!(listed, 3, "and the number itself is the one we meant"); + // And the command shows exactly those sites. + assert_eq!(execute(&ws, &[Value::String("sub".to_string())]).expect("runs").len(), listed); +} + +#[test] +fn an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it() { + // The same rule `callHierarchy/incomingCalls` applies: a site with no + // enclosing module has no caller to report, so it is nobody's edge. + let (_tree, ws, uri) = + workspace("filescope", &[("sub.sv", SUB), ("loose.sv", "sub u_loose ();\n")]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]); +} + +// ------------------------------------------------------------------ +// which declarations get a lens, and where it sits +// ------------------------------------------------------------------ + +#[test] +fn the_lens_sits_on_the_declarations_own_name() { + // The client draws a lens on the line *above* `range.start`, so the + // name span is what puts it over the header and nowhere else. + let (_tree, ws, uri) = workspace("span", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + shape(&lenses), + [("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7)], + "column 7 is `sub`, not the `module` keyword" + ); + assert_eq!(lenses[0].range.end.character, 10, "the name only"); +} + +#[test] +fn an_interface_is_a_module_declaration_and_gets_its_own_lens() { + let bus = "interface bus;\n logic clk;\nendinterface\n"; + let user = "module top;\n bus u_bus ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("iface", &[("bus.sv", bus), ("top.sv", user)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); +} + +#[test] +fn every_module_in_a_file_gets_its_own_lens_in_source_order() { + let many = "\ +module first; +endmodule + +module second; +endmodule + +module third; +endmodule +"; + let uses = "module top;\n third u3 ();\n first u1 ();\n third u3b ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("many", &[("many.sv", many), ("top.sv", uses)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + shape(&lenses), + [ + ("1 instantiation".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7), + ("no instantiations".to_string(), String::new(), 3, 7), + ("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 6, 7), + ], + "source order, one per declaration" + ); +} + +#[test] +fn a_module_nothing_instantiates_gets_a_lens_that_does_not_click() { + let (_tree, ws, uri) = workspace("noclick", &[("lonely.sv", "module lonely;\nendmodule\n")]); + let lenses = code_lenses(&ws, &uri).expect("open"); + let command = lenses[0].command.as_ref().expect("a command"); + assert_eq!(command.title, "no instantiations"); + assert_eq!(command.command, "", "display-only: there is nothing to open"); + assert_eq!(command.arguments, None, "and nothing to pass"); +} + +#[test] +fn a_clickable_lens_carries_the_module_name_as_its_only_argument() { + let (_tree, ws, uri) = workspace("args", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + let command = lenses[0].command.as_ref().expect("a command"); + assert_eq!(command.command, SHOW_INSTANTIATIONS); + assert_eq!(command.arguments, Some(vec![Value::String("sub".to_string())])); +} + +#[test] +fn no_lens_is_ever_left_for_a_resolve_to_fill_in() { + // `resolveProvider: false` is advertised, so a lens without a command + // would be a lens the client can never complete. + let (_tree, ws, uri) = workspace("complete", &[("sub.sv", SUB), ("top.sv", TOP)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert!(lenses.iter().all(|lens| lens.command.is_some() && lens.data.is_none())); +} + +// ------------------------------------------------------------------ +// the refusals +// ------------------------------------------------------------------ + +#[test] +fn a_buffer_this_server_was_never_shown_has_no_lenses_at_all() { + let (tree, ws, _) = workspace("closed", &[("sub.sv", SUB)]); + let never = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + assert!(code_lenses(&ws, &never).is_none(), "null, not an empty list"); +} + +#[test] +fn a_buffer_that_declares_no_module_gets_an_empty_list() { + let (_tree, ws, uri) = workspace("nomodules", &[("p.sv", "package p;\nendpackage\n")]); + assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new()); +} + +#[test] +fn a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic() { + let junk = ")))) not verilog ((((\n@@@ endmodule : ;\n"; + let (_tree, ws, uri) = workspace("junk", &[("junk.sv", junk)]); + assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new(), "total, whatever it parses to"); +} + +#[test] +fn a_declaration_the_parser_could_not_name_gets_no_lens() { + // `module ;` recovers into a declaration with an empty name span, + // which is a lens with no line to sit on. + let broken = "module ;\nendmodule\n\nmodule fine;\nendmodule\n"; + let (_tree, ws, uri) = workspace("unnamed", &[("broken.sv", broken)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert!( + lenses.iter().all(|lens| lens.range.start.line == 3), + "only the named declaration: {lenses:#?}" + ); +} + +// ------------------------------------------------------------------ +// the command +// ------------------------------------------------------------------ + +#[test] +fn the_command_answers_one_location_per_site() { + let (_tree, ws, _) = workspace("sites", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]); + let locations = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); + let shape: Vec<(String, u32, u32)> = locations + .iter() + .map(|at| { + ( + at.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + at.range.start.line, + at.range.start.character, + ) + }) + .collect(); + assert_eq!( + shape, + [("o.sv".to_string(), 1, 2), ("top.sv".to_string(), 1, 2), ("top.sv".to_string(), 2, 2),], + "every site, sorted by file then position" + ); +} + +#[test] +fn the_command_answers_nothing_for_a_module_nothing_instantiates() { + let (_tree, ws, _) = workspace("nosites", &[("lonely.sv", "module lonely;\nendmodule\n")]); + assert_eq!(execute(&ws, &[Value::String("lonely".to_string())]), Ok(Vec::new())); + assert_eq!( + execute(&ws, &[Value::String("never-heard-of-it".to_string())]), + Ok(Vec::new()), + "a name the workspace does not declare is not an error either" + ); +} + +#[test] +fn the_command_declines_arguments_it_cannot_read() { + let (_tree, ws, _) = workspace("badargs", &[("sub.sv", SUB)]); + for arguments in [vec![], vec![Value::Null], vec![Value::String(String::new())]] { + let message = execute(&ws, &arguments).expect_err("declined"); + assert!(message.contains("module name"), "{message}"); + } +} + +#[test] +fn the_command_list_is_what_the_server_advertises() { + assert_eq!(commands(), vec![SHOW_INSTANTIATIONS]); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): count-honesty shapes the fixture above never +// exercises — a multi-instance statement, self-recursion, name +// collisions (within one file and across files), generate replication +// and an `ifdef`-guarded instantiation. None of these turned out to +// disagree with `hierarchy::incoming` — they can't, since `lens.rs` and +// `hierarchy::incoming` both bottom out in the same +// `hierarchy::callers_of_each` — but the *number itself* is worth +// pinning so a future change to what counts as a "site" is visible here +// too, not just in `hierarchy.rs`. See QA log in +// `docs/features/code-lens/README.md`. +// ------------------------------------------------------------------ + +#[test] +fn qa_corpus_counts_agree_with_grep_derived_ground_truth() { + // `corpus/common_cells/src/cdc_fifo_gray.sv` declares three modules. + // Ground truth by hand, `grep -rnE '\bNAME\b' corpus --include='*.sv' + // --include='*.svh'`, read line by line to exclude the declaration + // itself and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has + // several, e.g. line 56's "In contrast to the cdc_fifo_gray + // version..."): + // - `cdc_fifo_gray` — one real instantiation, + // `common_cells/test/cdc_fifo_tb.sv:49` (`i_dut`). + // - `cdc_fifo_gray_src` — one, `cdc_fifo_gray.sv:130`, inside + // `cdc_fifo_gray` itself (`_src_clearable` is a different name + // and does not match `\bcdc_fifo_gray_src\b`). + // - `cdc_fifo_gray_dst` — one, `cdc_fifo_gray.sv:145`, likewise. + // Skipped like the other corpus tests when `corpus/` is not checked + // out (`tools/corpus_fetch.sh`). + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); + let Ok(text) = fs::read_to_string(&file) else { + eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!( + titles(&lenses), + ["1 instantiation", "1 instantiation", "1 instantiation"], + "cdc_fifo_gray, cdc_fifo_gray_src, cdc_fifo_gray_dst, in that source order: {lenses:#?}" + ); +} + +#[test] +fn qa_a_multi_instance_statement_is_one_site_not_two() { + // `sub u1 (), u2 ();` is ONE `Instantiation` AST node carrying TWO + // `Instance` entries — physically two instantiations of `sub` in the + // design. This is not a code-lens decision: `hierarchy.rs`'s own + // documented assumption ("One `Instantiation` is one call site, + // however many instances it declares") already settles it, the same + // way `textDocument/references` reports the module name once. Pinned + // here too so a change to that policy is visible in both features. + let top = "module top;\n sub u1 (), u2 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_multi", &[("sub.sv", SUB), ("top.sv", top)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(titles(&lenses), ["1 instantiation"], "one AST node, not two instances"); + let locs = execute(&ws, &[Value::String("sub".to_string())]).expect("runs"); + assert_eq!(locs.len(), 1, "one location for the one site: {locs:#?}"); +} + +#[test] +fn qa_a_module_that_instantiates_itself_counts_its_own_instantiation() { + // Self-recursion (illegal to elaborate, legal text) is handled the + // same way `hierarchy.rs` handles an `a -> b -> a` cycle: each + // request answers one hop, so there is nothing here that could ever + // recurse or hang. + let text = "module m;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_recursive", &[("m.sv", text)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(titles(&lenses), ["1 instantiation"]); + let locs = execute(&ws, &[Value::String("m".to_string())]).expect("runs"); + assert_eq!(locs.len(), 1); +} + +#[test] +fn qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both() { + // The census is by name (documented in this README's Assumptions): + // an instantiation of `m` cannot say which of two `module m` + // declarations it meant, so both lenses read the workspace-wide + // total rather than a partitioned one. Same limitation + // `callHierarchy/incomingCalls` already has, for the same reason. + let m_a = "module m;\n logic a;\nendmodule\n"; + let m_b = "module m;\n logic b;\nendmodule\n"; + let user = "module top;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri_a) = + workspace("qa_collide_a", &[("a/m.sv", m_a), ("b/m.sv", m_b), ("top.sv", user)]); + assert_eq!(titles(&code_lenses(&ws, &uri_a).expect("open a/m.sv")), ["1 instantiation"]); + + // Same workspace, opening the OTHER declaration instead: same total. + let mut ws_b = Workspace::default(); + let tree_b = Tree::new("qa_collide_b"); + tree_b.write("a/m.sv", m_a); + let path_b = tree_b.write("b/m.sv", m_b); + tree_b.write("top.sv", user); + ws_b.open_whole_workspace(vec![tree_b.path.clone()]); + let uri_b = path_to_uri(&path_b).expect("uri"); + ws_b.set_document(uri_b.clone(), m_b.to_string()); + assert_eq!( + titles(&code_lenses(&ws_b, &uri_b).expect("open b/m.sv")), + ["1 instantiation"], + "the other declaration reads the same total, not zero" + ); +} + +#[test] +fn qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count() { + // The tolerant parser accepts `module m; endmodule module m; + // endmodule` in one file (real SystemVerilog forbids it, but this is + // reachable through broken input). The batch in + // `hierarchy::callers_of_each` is asked `["m", "m"]` — two indices, + // not deduplicated — so this also pins that duplicate names in one + // batch do not alias or corrupt each other's answer. + let text = "module m;\nendmodule\n\nmodule m;\nendmodule\n"; + let user = "module top;\n m u1 ();\nendmodule\n"; + let (_tree, ws, uri) = workspace("qa_dup_same_file", &[("m.sv", text), ("top.sv", user)]); + let lenses = code_lenses(&ws, &uri).expect("open"); + assert_eq!(lenses.len(), 2, "one lens per declaration"); + assert_eq!(titles(&lenses), ["1 instantiation", "1 instantiation"]); +} + +#[test] +fn qa_a_generate_replicated_instantiation_counts_the_written_statement_once() { + // `generate for` is not elaborated: the AST has exactly one + // `Instantiation` node inside the loop body regardless of the + // genvar's range, matching `hierarchy.rs`'s own documented handling + // of the identical shape (`incoming_calls_reach_generate_regions_...` + // in `hierarchy.rs`). Four elaborated instances at synthesis time, + // one textual site here — the lens counts text, not hardware. + let sub = "module sub;\nendmodule\n"; + let top = "\ +module top; + generate + for (genvar i = 0; i < 4; i++) begin : g + sub u1 (); + end + endgenerate +endmodule +"; + let (_tree, ws, uri) = workspace("qa_generate", &[("sub.sv", sub), ("top.sv", top)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]); +} + +#[test] +fn qa_an_ifdef_guarded_instantiation_counts_both_arms() { + // Inherited from `hierarchy.rs`, disclosed there as an Assumption: + // the parser does not evaluate `` `ifdef``/`` `else``, so both arms + // land as ordinary `Instantiation` items and both are counted, even + // though only one is ever really built. Pinned here too since the + // lens is a second, more prominent surface for the same policy. + let sub = "module sub;\nendmodule\n"; + let top = "\ +module top; +`ifdef FOO + sub u1 (); +`endif + sub u2 (); +endmodule +"; + let (_tree, ws, uri) = workspace("qa_ifdef", &[("sub.sv", sub), ("top.sv", top)]); + assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]); +} + +// ------------------------------------------------------------------ +// the performance claim, measured +// ------------------------------------------------------------------ + +/// The number the round's Handshake was filed for, measured: what a whole +/// file's lenses cost before the edge table (a walk of every in-scope +/// file, re-read and re-parsed) and what they cost after (a lookup). +/// +/// `#[ignore]`d like the other measurement probes in this crate — it prints +/// a number rather than asserting one, and the assertion that must hold is +/// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk` +/// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`. +#[test] +#[ignore = "perf measurement over corpus/, printed not asserted; run with --ignored --nocapture"] +fn qa_perf_lens_lookup_against_the_walk_it_replaced() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); + let Ok(text) = fs::read_to_string(&file) else { + eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text); + let _ = code_lenses(&ws, &uri); + + let mut lenses = std::time::Duration::ZERO; + let mut walk = std::time::Duration::ZERO; + for _ in 0..3 { + let started = std::time::Instant::now(); + let _ = code_lenses(&ws, &uri).expect("open"); + lenses = lenses.max(started.elapsed()); + // What `callers_of_each` used to begin with, every request. + let started = std::time::Instant::now(); + let _ = ws.sources(); + walk = walk.max(started.elapsed()); + } + eprintln!( + "codeLens over {} files: {lenses:?} for the whole file; one workspace walk \ + (what the old census re-read on every request) is {walk:?}", + ws.index().files().len() + ); +} + +/// What a whole file's lenses cost over the real corpus, against what one +/// workspace walk costs. +/// +/// **Superseded this round (incremental-index, 2026-08-27):** +/// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted +/// `whole_file < one_name * 2` — that asking about three modules cost about +/// what asking about one did, because both were *one walk* of the whole +/// workspace. There is no walk any more: the count is a lookup in the +/// index's instantiation-edge table, and the only I/O left is reading the +/// handful of files that really do instantiate one of the three. Both sides +/// of that ratio are now microseconds dominated by a file read each, so the +/// ratio pins noise. The property worth pinning is the stronger one this +/// round bought: **a whole file's lenses cost a small fraction of one +/// workspace walk**, measured here rather than asserted. +/// +/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`), +/// like the other corpus tests. The budget is deliberately loose: a debug +/// build on a loaded machine is the worst case this ever runs in, and this +/// exists to catch an order-of-magnitude regression — a lens handler that +/// went back to re-reading the workspace would fail it by two. +#[test] +fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + // A real file declaring three modules, so the batch has something to + // amortize over. + let file = corpus.join("common_cells/src/cdc_fifo_gray.sv"); + let Ok(text) = fs::read_to_string(&file) else { + eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text); + + // Warm, then the worst of three, for the whole file and for one name; + // and the best of three for the walk it used to be, so the comparison + // is stacked against the claim rather than for it. + let _ = code_lenses(&ws, &uri); + let mut whole_file = std::time::Duration::ZERO; + let mut one_name = std::time::Duration::ZERO; + let mut walk = std::time::Duration::MAX; + let mut count = 0; + for _ in 0..3 { + let started = std::time::Instant::now(); + let lenses = code_lenses(&ws, &uri).expect("open"); + whole_file = whole_file.max(started.elapsed()); + count = lenses.len(); + let started = std::time::Instant::now(); + let _ = sites_of(&ws, "cdc_fifo_gray"); + one_name = one_name.max(started.elapsed()); + let started = std::time::Instant::now(); + let _ = ws.sources(); + walk = walk.min(started.elapsed()); + } + eprintln!( + "corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \ + (one name alone: {one_name:?}; one workspace walk: {walk:?})", + ws.index().files().len(), + ); + assert!(count >= 3, "the file declares three modules: {count}"); + assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}"); + assert!( + whole_file * 10 < walk, + "the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \ + {walk:?} for one walk of the workspace" + ); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/linked.rs b/crates/lucisv_server/src/linked.rs index 1999424..7b9af74 100644 --- a/crates/lucisv_server/src/linked.rs +++ b/crates/lucisv_server/src/linked.rs @@ -282,636 +282,6 @@ fn prefix_labelled_end(stmt: &Stmt) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use vlog_semantic::WorkspaceIndex; - - fn doc_of(text: &str) -> Document { - Document::new(None, text.to_string(), &WorkspaceIndex::default()) - } - - /// The byte offset of `needle`'s first occurrence. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - /// The byte offset just past `prefix` — how a fixture points at a name - /// whose own spelling occurs earlier in the text (`m` of `module m`). - fn at_after(text: &str, prefix: &str) -> u32 { - at(text, prefix) + prefix.len() as u32 - } - - /// The byte offset just past the *last* `prefix`. Every fixture below - /// writes its closing label as the file's last `": "`, so this is where - /// that label starts. - fn at_last_after(text: &str, prefix: &str) -> u32 { - text.rfind(prefix).expect("needle present") as u32 + prefix.len() as u32 - } - - /// The answer's ranges as `(line, start character, end character)`, which - /// is enough to say which occurrence each one is. - fn linked(text: &str, offset: u32) -> Option> { - let doc = doc_of(text); - let answer = linked_editing_ranges(&doc, offset)?; - assert_eq!( - answer.word_pattern.as_deref(), - Some(WORD_PATTERN), - "every answer carries the SV word pattern" - ); - Some( - answer - .ranges - .iter() - .map(|r| (r.start.line, r.start.character, r.end.character)) - .collect(), - ) - } - - // ------------------------------------------------------------------ - // every construct that ships - // ------------------------------------------------------------------ - - #[test] - fn every_labeled_construct_links_its_two_names() { - // Each fixture writes its name twice and nowhere else, and its closing - // label is the last `": "` in the text. - let cases = [ - ("module m;\nendmodule : m\n", "module ", "module"), - ("macromodule m;\nendmodule : m\n", "macromodule ", "macromodule"), - ("interface bus_if;\nendinterface : bus_if\n", "interface ", "interface"), - ("package p;\nendpackage : p\n", "package ", "package"), - ("class c;\nendclass : c\n", "class ", "class"), - ("module m;\n function f;\n endfunction : f\nendmodule\n", "function ", "function"), - ("module m;\n task t;\n endtask : t\nendmodule\n", "task ", "task"), - ( - "module m;\n initial begin : blk\n end : blk\nendmodule\n", - "begin : ", - "named begin", - ), - ("module m;\n initial fork : frk\n join : frk\nendmodule\n", "fork : ", "named fork"), - ( - concat!( - "module m;\n", - " generate\n", - " for (genvar i = 0; i < 2; i++) begin : g\n", - " wire w;\n", - " end : g\n", - " endgenerate\n", - "endmodule\n", - ), - "begin : ", - "generate block", - ), - ( - "interface i;\n clocking cb @(posedge clk);\n endclocking : cb\nendinterface\n", - "clocking ", - "clocking", - ), - ( - "module m;\n initial pre : begin\n end : pre\nendmodule\n", - "initial ", - "prefix-labelled begin", - ), - ]; - for (text, header, what) in cases { - let from_label = linked(text, at_last_after(text, ": ")) - .unwrap_or_else(|| panic!("{what}: the closing label answered nothing at all")); - assert_eq!(from_label.len(), 2, "{what}: exactly two ranges"); - let from_header = linked(text, at_after(text, header)) - .unwrap_or_else(|| panic!("{what}: the header name answered nothing")); - assert_eq!(from_label, from_header, "{what}: both directions answer the same pair"); - } - } - - // ------------------------------------------------------------------ - // where the cursor is - // ------------------------------------------------------------------ - - #[test] - fn the_cursor_may_sit_anywhere_in_either_name() { - let text = "module wide;\nendmodule : wide\n"; - let header = at_after(text, "module "); - let label = at_last_after(text, ": "); - let expected = linked(text, header).expect("the header answers"); - assert_eq!(expected, vec![(0, 7, 11), (1, 12, 16)]); - for (offset, what) in [ - (header, "header start"), - (header + 2, "header middle"), - (header + 4, "header end, one past the last byte"), - (label, "label start"), - (label + 2, "label middle"), - (label + 4, "label end, one past the last byte"), - ] { - assert_eq!(linked(text, offset).as_ref(), Some(&expected), "{what}"); - } - } - - #[test] - fn a_position_beside_the_names_answers_nothing() { - let text = "module m;\nendmodule : m\n"; - assert!(linked(text, 0).is_none(), "the `module` keyword itself"); - assert!(linked(text, at(text, " m;")).is_none(), "the space before the name"); - assert!(linked(text, at(text, ";") + 1).is_none(), "past the semicolon"); - assert!(linked(text, at(text, "endmodule")).is_none(), "the closing keyword"); - } - - #[test] - fn a_position_past_the_end_of_the_file_answers_nothing() { - let text = "module m;\nendmodule : m\n"; - assert!(linked(text, text.len() as u32).is_none()); - assert!(linked(text, text.len() as u32 + 1_000).is_none()); - } - - #[test] - fn an_empty_buffer_answers_nothing() { - assert!(linked("", 0).is_none()); - } - - // ------------------------------------------------------------------ - // the two refusals - // ------------------------------------------------------------------ - - #[test] - fn an_unlabeled_closer_links_nothing() { - // The label is optional in SV, and its absence is not an invitation to - // create one: there is no second range, so there is no answer. - for (text, header) in [ - ("module m;\nendmodule\n", "module "), - ("package p;\nendpackage\n", "package "), - ("class c;\nendclass\n", "class "), - ("module m;\n function f;\n endfunction\nendmodule\n", "function "), - ("module m;\n task t;\n endtask\nendmodule\n", "task "), - ("module m;\n initial begin : blk\n end\nendmodule\n", "begin : "), - ] { - assert!(linked(text, at_after(text, header)).is_none(), "{text:?} must link nothing"); - } - } - - #[test] - fn a_mismatched_label_links_nothing() { - // Broken code. Linking the two would rewrite one half into the other - // on the next keystroke — an edit the user never asked for — and the - // spec requires the ranges to hold identical text anyway. - let text = "module m;\nendmodule : wrong\n"; - assert!(linked(text, at_after(text, "module ")).is_none(), "from the header"); - assert!(linked(text, at(text, "wrong")).is_none(), "and from the label"); - } - - #[test] - fn a_label_differing_only_in_case_links_nothing() { - let text = "module Data;\nendmodule : data\n"; - assert!(linked(text, at(text, "Data")).is_none()); - assert!(linked(text, at(text, "data")).is_none()); - } - - #[test] - fn an_escaped_identifier_links_nothing() { - // `\odd.name ` is an identifier whose extent depends on a trailing - // space, which no word pattern can describe. Both halves matching does - // not make it safe to hand a client. - let text = "module \\odd.name ;\nendmodule : \\odd.name \n"; - let doc = doc_of(text); - let mut pairs = Vec::new(); - items_pairs(&doc.tree.items, &mut pairs); - assert_eq!(pairs.len(), 1, "premise: the tree really did record the pair"); - assert!(linked(text, at(text, "\\odd.name")).is_none(), "from the header"); - assert!( - linked(text, text.rfind("\\odd.name").expect("label") as u32).is_none(), - "and back" - ); - } - - #[test] - fn is_simple_identifier_accepts_exactly_the_word_pattern() { - for good in ["m", "_x", "a1", "foo$bar", "A_b$9", "_"] { - assert!(is_simple_identifier(good), "{good} is a plain SV identifier"); - } - for bad in ["", "1a", "$x", "\\odd.name", "a b", "a.b", "é"] { - assert!(!is_simple_identifier(bad), "{bad:?} is not"); - } - } - - // ------------------------------------------------------------------ - // nesting — the pair must be the syntactic one - // ------------------------------------------------------------------ - - #[test] - fn nested_blocks_answer_their_own_pair() { - let text = concat!( - "module m;\n", - " initial begin : outer\n", - " begin : inner\n", - " x = 1;\n", - " end : inner\n", - " end : outer\n", - "endmodule\n", - ); - let outer = linked(text, at(text, "outer")).expect("the outer header answers"); - assert_eq!(outer, vec![(1, 18, 23), (5, 8, 13)], "line 1 header, line 5 label"); - let inner = linked(text, at(text, "inner")).expect("the inner header answers"); - assert_eq!(inner, vec![(2, 12, 17), (4, 10, 15)], "line 2 header, line 4 label"); - } - - #[test] - fn identical_names_at_different_nesting_pair_syntactically() { - // The evil fixture: four byte-identical names, two pairs. A - // nearest-same-text rule would pair the outer header with the *inner* - // label, because that one is nearer. The pair comes off the AST node, - // so it cannot. - let text = concat!( - "module m;\n", - " initial begin : x\n", - " begin : x\n", - " y = 1;\n", - " end : x\n", - " end : x\n", - "endmodule\n", - ); - let outer_header = at_after(text, "begin : "); - let inner_header = - text.match_indices("begin : ").nth(1).expect("the inner block").0 as u32 + 8; - let outer = linked(text, outer_header).expect("the outer header answers"); - assert_eq!(outer, vec![(1, 18, 19), (5, 8, 9)], "outer header pairs with the OUTER end"); - let inner = linked(text, inner_header).expect("the inner header answers"); - assert_eq!(inner, vec![(2, 12, 13), (4, 10, 11)], "inner header pairs with the INNER end"); - assert_ne!(outer, inner); - // And from each closing label, back to the same two pairs. - let inner_label = text.match_indices("end : ").next().expect("the inner end").0 as u32 + 6; - let outer_label = at_last_after(text, "end : "); - assert_eq!(linked(text, inner_label), Some(inner)); - assert_eq!(linked(text, outer_label), Some(outer)); - } - - #[test] - fn a_module_and_the_function_inside_it_are_separate_pairs() { - // The function is deliberately named `m` too. - let text = "module m;\n function m;\n endfunction : m\nendmodule : m\n"; - let module = linked(text, at_after(text, "module ")).expect("the module header answers"); - assert_eq!(module, vec![(0, 7, 8), (3, 12, 13)], "module header, endmodule label"); - let function = - linked(text, at_after(text, "function ")).expect("the function header answers"); - assert_eq!(function, vec![(1, 11, 12), (2, 16, 17)], "function header, endfunction label"); - assert_ne!(module, function); - } - - #[test] - fn a_class_method_pairs_inside_its_class() { - let text = "class c;\n function void f();\n endfunction : f\nendclass : c\n"; - let class = linked(text, at_after(text, "class ")).expect("the class answers"); - assert_eq!(class, vec![(0, 6, 7), (3, 11, 12)]); - let method = linked(text, at(text, "f()")).expect("the method answers"); - assert_eq!(method, vec![(1, 16, 17), (2, 16, 17)]); - } - - #[test] - fn a_named_block_inside_a_generate_for_pairs() { - let text = concat!( - "module m;\n", - " generate\n", - " for (genvar i = 0; i < 2; i++) begin : g\n", - " initial begin : inner\n", - " end : inner\n", - " end : g\n", - " endgenerate\n", - "endmodule\n", - ); - let gen = linked(text, at(text, "g\n")).expect("the generate label answers"); - assert_eq!(gen, vec![(2, 43, 44), (5, 10, 11)]); - let inner = linked(text, at(text, "inner")).expect("the inner block answers"); - assert_eq!(inner, vec![(3, 22, 27), (4, 12, 17)]); - assert_ne!(gen, inner); - } - - // ------------------------------------------------------------------ - // UTF-16 positions - // ------------------------------------------------------------------ - - #[test] - fn a_multibyte_comment_before_the_name_does_not_shift_it() { - // SV identifiers are ASCII, but everything around them need not be. - // The characters are counted in UTF-16 units, so `é` (2 bytes, 1 unit) - // and `🎉` (4 bytes, 2 units) must not move the name's column. - let text = "// café 🎉\nmodule m;\nendmodule : m\n"; - let ranges = linked(text, at_after(text, "module ")).expect("the header answers"); - assert_eq!(ranges, vec![(1, 7, 8), (2, 12, 13)]); - } - - #[test] - fn a_multibyte_comment_on_the_same_line_keeps_the_columns_honest() { - let text = "module m; // 🎉 party\nendmodule : m // café\n"; - let ranges = linked(text, at_last_after(text, ": ")).expect("the label answers"); - assert_eq!(ranges, vec![(0, 7, 8), (1, 12, 13)]); - } - - // ------------------------------------------------------------------ - // buffers that do not parse - // ------------------------------------------------------------------ - - #[test] - fn a_buffer_that_does_not_lex_answers_nothing() { - let text = "module m;\n wire a; /* unterminated\n"; - let doc = doc_of(text); - assert!(doc.tokens.is_empty(), "premise: the lexer gave up"); - assert!(linked_editing_ranges(&doc, at_after(text, "module ")).is_none()); - } - - #[test] - fn a_half_typed_construct_answers_nothing_rather_than_guessing() { - let text = "module m;\n initial begin : blk\nendmodule\n"; - assert!(linked(text, at(text, "blk")).is_none(), "no closing label was written"); - } - - #[test] - fn a_pair_written_after_a_broken_item_still_answers() { - // Error recovery keeps the items it could parse, so a mistake early in - // the file must not un-link everything below it. - let text = "module a;\n @@@ ;\nendmodule\nmodule b;\nendmodule : b\n"; - let ranges = linked(text, at_after(text, "module b")).expect("the second module answers"); - assert_eq!(ranges.len(), 2); - } - - // ------------------------------------------------------------------ - // the answer's own shape - // ------------------------------------------------------------------ - - #[test] - fn the_two_ranges_hold_identical_text_and_never_overlap() { - let text = "module top;\n initial begin : blk\n end : blk\nendmodule : top\n"; - let doc = doc_of(text); - for offset in [at(text, "top") + 1, at(text, "blk") + 1] { - let answer = linked_editing_ranges(&doc, offset).expect("a pair"); - assert_eq!(answer.ranges.len(), 2); - let (first, second) = (answer.ranges[0], answer.ranges[1]); - assert!( - (first.end.line, first.end.character) < (second.start.line, second.start.character), - "the header comes first and the two do not overlap: {answer:?}" - ); - assert_eq!( - first.end.character - first.start.character, - second.end.character - second.start.character, - "identical length" - ); - } - } - - // ------------------------------------------------------------------ - // QA (2026-08-26) — the prefix-label gate, and the ranges' exact bytes - // ------------------------------------------------------------------ - - /// Every offset in `0..=text.len()` answers without panicking, and every - /// `Some` answer holds two identical-text, non-overlapping ranges. The - /// blanket check the targeted tests below narrow in on one fixture at a - /// time — kept here because a tolerant-parser fixture is exactly the kind - /// of input where a hand-picked offset can miss what a sweep finds. - fn assert_total_and_sane(text: &str) { - let doc = doc_of(text); - for offset in 0..=text.len() as u32 { - let Some(answer) = linked_editing_ranges(&doc, offset) else { continue }; - assert_eq!(answer.ranges.len(), 2, "{text:?} at {offset}: {answer:?}"); - assert_eq!( - answer.word_pattern.as_deref(), - Some(WORD_PATTERN), - "{text:?} at {offset}: word pattern missing" - ); - let (a, b) = (answer.ranges[0], answer.ranges[1]); - let (before, after) = - if (a.start.line, a.start.character) <= (b.start.line, b.start.character) { - (a, b) - } else { - (b, a) - }; - assert!( - (before.end.line, before.end.character) - <= (after.start.line, after.start.character), - "{text:?} at {offset}: ranges overlap: {answer:?}" - ); - } - } - - #[test] - fn a_block_named_both_ways_answers_only_the_blocks_own_pair() { - // `x : begin : y ... end : y` is illegal SV (IEEE 1800 §9.3.5: a block - // is named one way or the other), but the tolerant parser accepts it - // — the block wrote its own label, so `Labeled`'s prefix-label gate - // (`prefix_labelled_end`, only fires when the block wrote no label of - // its own) must stay silent and the block's own (y, y) pair, not a - // fabricated (x, y), must be what answers. - let text = "module m;\n initial x : begin : y\n z = 1;\n end : y\nendmodule\n"; - assert_total_and_sane(text); - let y_pair = linked(text, at(text, "y")).expect("the block's own label pairs"); - assert_eq!(y_pair.len(), 2); - assert_eq!(linked(text, text.rfind('y').expect("closing y") as u32), Some(y_pair)); - // `x` is not part of any pair: the prefix label was correctly not - // linked to anything. - assert!(linked(text, at(text, "x")).is_none(), "the unused prefix label links nothing"); - } - - #[test] - fn a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched() { - // `x : begin ... end : y` — the block wrote no label of its own, so - // the prefix-label gate does fire and pushes (x, y). The two names - // differ, so this must still answer null, the same as any other - // mismatch — the gate firing is not itself a promise of a match. - let text = "module m;\n initial x : begin\n z = 1;\n end : y\nendmodule\n"; - assert_total_and_sane(text); - assert!(linked(text, at(text, "x")).is_none(), "mismatched prefix pair: from x"); - assert!(linked(text, at(text, "y")).is_none(), "mismatched prefix pair: from y"); - } - - #[test] - fn a_stray_second_end_label_after_the_block_already_closed_is_inert() { - // Two `end : x` for one `begin : x`. The first one closes the block; - // the second is leftover tokens the item-level recovery has to make - // sense of on its own. Whatever it becomes, it must not create a - // second, wrong pairing, and it must not make the walk panic. - let text = "module m;\n initial begin : x\n z = 1;\n end : x\n end : x\nendmodule\n"; - assert_total_and_sane(text); - let doc = doc_of(text); - let mut pairs = Vec::new(); - items_pairs(&doc.tree.items, &mut pairs); - assert_eq!(pairs.len(), 1, "the stray `end : x` must not mint a second pair"); - // The pair that does exist closes on the FIRST `end : x`, not the - // second — the leftover tokens answer nothing at all. - let first_end = text.find("end : x").expect("first end"); - let second_end = text.rfind("end : x").expect("second end"); - assert_ne!(first_end, second_end); - assert!( - linked(text, second_end as u32 + 6).is_none(), - "the leftover end : x links nothing" - ); - } - - #[test] - fn broken_and_unclosed_labeled_constructs_never_panic() { - for text in [ - "module m;\n initial begin : blk\n z = 1;\nendmodule\n", // `end` missing - "module m;\n initial begin : blk\n z = 1;\n", // no closer at all, EOF - "module m;\n initial begin : \n end : \nendmodule\n", // label written, no name - "module m;\n initial begin :\n end\nendmodule\n", // colon, no name, no close label - ] { - assert_total_and_sane(text); - } - } - - #[test] - fn adjacent_closing_labels_never_bleed_into_each_other() { - // `endfunction : f` immediately followed by `endmodule : m` on the - // next line: the "name spans never touch" claim, checked at the exact - // boundary a lexer could in principle blur. - let text = "module m;\n function f;\n endfunction : f\nendmodule : m\n"; - assert_total_and_sane(text); - let f = linked(text, at(text, "f;")).expect("the function pairs"); - let m = linked(text, at_after(text, "module ")).expect("the module pairs"); - assert_ne!(f, m); - } - - /// The ranges cover exactly the identifier's bytes — never the `:`, never - /// the surrounding whitespace or a comment written between them. An - /// off-by-one here would let a client's keystroke land on the colon. - #[test] - fn ranges_cover_exactly_the_identifier_never_the_colon_or_comment() { - let cases: [(&str, &str, &str); 3] = [ - ("module m;\nendmodule : /*c*/ m\n", "module ", "m"), - ("module m;\n initial begin:x\n end:x\nendmodule\n", "begin:", "x"), - ("module m;\n initial begin :\n x\n end :\n x\nendmodule\n", "begin :\n ", "x"), - ]; - for (text, header_prefix, want) in cases { - let doc = doc_of(text); - let answer = linked_editing_ranges(&doc, at_after(text, header_prefix)) - .unwrap_or_else(|| panic!("{text:?}: the header answers")); - let positions = doc.positions(); - // Decode each `Range` back to a byte span via the same - // `Positions::offset` the server itself uses to turn a client - // position into an offset, and check it covers exactly the name - // — not the colon, not a space, not the comment beside it. - for range in &answer.ranges { - let start = positions.offset(range.start) as usize; - let end = positions.offset(range.end) as usize; - assert_eq!(&text[start..end], want, "{text:?}: range {range:?}"); - } - } - } - - // ------------------------------------------------------------------ - // corpus sweep — real RTL, every offset, machine-checked invariants - // ------------------------------------------------------------------ - - /// Every offset of a handful of real corpus files that write closing - /// labels: totality (no panic), and every `Some` answer's two ranges hold - /// identical text and do not overlap. Skipped when `corpus/` is not - /// checked out, like every other corpus test in this crate. - #[test] - fn a_corpus_sweep_of_labeled_constructs_is_total_and_sane() { - let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let files = [ - "common_cells/src/lzc.sv", - "common_cells/src/rr_arb_tree.sv", - "common_cells/src/popcount.sv", - "common_cells/src/cdc_reset_ctrlr.sv", - "common_cells/src/deprecated/rrarbiter.sv", - "common_cells/src/deprecated/prioarbiter.sv", - "common_cells/src/stream_fifo_optimal_wrap.sv", - "common_cells/src/stream_throttle.sv", - "ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv", - "ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_monitor.sv", - "opentitan/hw/ip/uart/dv/env/seq_lib/uart_base_vseq.sv", - ]; - let mut files_checked = 0; - let mut pairs_found = 0; - for name in files { - let path = corpus.join(name); - let Ok(text) = std::fs::read_to_string(&path) else { - eprintln!("{} not checked out — skipping", path.display()); - continue; - }; - assert!( - text.contains("end") && text.contains(':'), - "{}: premise, this file should write a closing label", - path.display() - ); - let doc = doc_of(&text); - let mut file_pairs = Vec::new(); - items_pairs(&doc.tree.items, &mut file_pairs); - pairs_found += file_pairs.len(); - let positions = doc.positions(); - for offset in 0..=text.len() as u32 { - let Some(answer) = linked_editing_ranges(&doc, offset) else { continue }; - assert_eq!(answer.ranges.len(), 2, "{}: {answer:?}", path.display()); - let (a, b) = (answer.ranges[0], answer.ranges[1]); - let a_text = - &text[positions.offset(a.start) as usize..positions.offset(a.end) as usize]; - let b_text = - &text[positions.offset(b.start) as usize..positions.offset(b.end) as usize]; - assert_eq!( - a_text, - b_text, - "{}: at {offset}, ranges hold different text", - path.display() - ); - assert!( - is_simple_identifier(a_text), - "{}: at {offset}, {a_text:?} is not a plain identifier", - path.display() - ); - assert!( - (a.end.line, a.end.character) <= (b.start.line, b.start.character) - || (b.end.line, b.end.character) <= (a.start.line, a.start.character), - "{}: at {offset}, ranges overlap: {answer:?}", - path.display() - ); - } - files_checked += 1; - } - assert!(files_checked > 5, "the corpus really is checked out: {files_checked} files"); - assert!( - pairs_found > 10, - "these files really do write closing labels: {pairs_found} pairs" - ); - } - - #[test] - fn a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing() { - let text = "module m;\n initial begin : blk\n end : blk\nendmodule\n"; - for (offset, what) in [ - (at(text, ": blk"), "the colon before the header's `blk`"), - (at(text, ": blk") + 1, "the space after that colon"), - (at(text, " end"), "the indentation before `end`, between the two names"), - ] { - // A position strictly on the colon or on whitespace — never on a - // letter of `blk` itself — answers nothing, even with `blk` - // close by on both sides. - assert!(linked(text, offset).is_none(), "{what}: {offset}"); - } - } - - #[test] - fn a_walk_of_a_whole_file_finds_every_construct_once() { - let text = concat!( - "package p;\n", - "endpackage : p\n", - "module m;\n", - " function f;\n", - " endfunction : f\n", - " task t;\n", - " endtask : t\n", - " initial begin : blk\n", - " end : blk\n", - "endmodule : m\n", - ); - let doc = doc_of(text); - let mut pairs = Vec::new(); - items_pairs(&doc.tree.items, &mut pairs); - assert_eq!(pairs.len(), 5, "package, module, function, task, named begin"); - // And every one of them is reachable from either of its own names. - for pair in &pairs { - assert!(linked_editing_ranges(&doc, pair.open.start).is_some()); - assert!(linked_editing_ranges(&doc, pair.close.start).is_some()); - } - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/linked/tests.rs b/crates/lucisv_server/src/linked/tests.rs new file mode 100644 index 0000000..d4abeee --- /dev/null +++ b/crates/lucisv_server/src/linked/tests.rs @@ -0,0 +1,611 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use vlog_semantic::WorkspaceIndex; + +fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) +} + +/// The byte offset of `needle`'s first occurrence. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// The byte offset just past `prefix` — how a fixture points at a name +/// whose own spelling occurs earlier in the text (`m` of `module m`). +fn at_after(text: &str, prefix: &str) -> u32 { + at(text, prefix) + prefix.len() as u32 +} + +/// The byte offset just past the *last* `prefix`. Every fixture below +/// writes its closing label as the file's last `": "`, so this is where +/// that label starts. +fn at_last_after(text: &str, prefix: &str) -> u32 { + text.rfind(prefix).expect("needle present") as u32 + prefix.len() as u32 +} + +/// The answer's ranges as `(line, start character, end character)`, which +/// is enough to say which occurrence each one is. +fn linked(text: &str, offset: u32) -> Option> { + let doc = doc_of(text); + let answer = linked_editing_ranges(&doc, offset)?; + assert_eq!( + answer.word_pattern.as_deref(), + Some(WORD_PATTERN), + "every answer carries the SV word pattern" + ); + Some(answer.ranges.iter().map(|r| (r.start.line, r.start.character, r.end.character)).collect()) +} + +// ------------------------------------------------------------------ +// every construct that ships +// ------------------------------------------------------------------ + +#[test] +fn every_labeled_construct_links_its_two_names() { + // Each fixture writes its name twice and nowhere else, and its closing + // label is the last `": "` in the text. + let cases = [ + ("module m;\nendmodule : m\n", "module ", "module"), + ("macromodule m;\nendmodule : m\n", "macromodule ", "macromodule"), + ("interface bus_if;\nendinterface : bus_if\n", "interface ", "interface"), + ("package p;\nendpackage : p\n", "package ", "package"), + ("class c;\nendclass : c\n", "class ", "class"), + ("module m;\n function f;\n endfunction : f\nendmodule\n", "function ", "function"), + ("module m;\n task t;\n endtask : t\nendmodule\n", "task ", "task"), + ("module m;\n initial begin : blk\n end : blk\nendmodule\n", "begin : ", "named begin"), + ("module m;\n initial fork : frk\n join : frk\nendmodule\n", "fork : ", "named fork"), + ( + concat!( + "module m;\n", + " generate\n", + " for (genvar i = 0; i < 2; i++) begin : g\n", + " wire w;\n", + " end : g\n", + " endgenerate\n", + "endmodule\n", + ), + "begin : ", + "generate block", + ), + ( + "interface i;\n clocking cb @(posedge clk);\n endclocking : cb\nendinterface\n", + "clocking ", + "clocking", + ), + ( + "module m;\n initial pre : begin\n end : pre\nendmodule\n", + "initial ", + "prefix-labelled begin", + ), + ]; + for (text, header, what) in cases { + let from_label = linked(text, at_last_after(text, ": ")) + .unwrap_or_else(|| panic!("{what}: the closing label answered nothing at all")); + assert_eq!(from_label.len(), 2, "{what}: exactly two ranges"); + let from_header = linked(text, at_after(text, header)) + .unwrap_or_else(|| panic!("{what}: the header name answered nothing")); + assert_eq!(from_label, from_header, "{what}: both directions answer the same pair"); + } +} + +// ------------------------------------------------------------------ +// where the cursor is +// ------------------------------------------------------------------ + +#[test] +fn the_cursor_may_sit_anywhere_in_either_name() { + let text = "module wide;\nendmodule : wide\n"; + let header = at_after(text, "module "); + let label = at_last_after(text, ": "); + let expected = linked(text, header).expect("the header answers"); + assert_eq!(expected, vec![(0, 7, 11), (1, 12, 16)]); + for (offset, what) in [ + (header, "header start"), + (header + 2, "header middle"), + (header + 4, "header end, one past the last byte"), + (label, "label start"), + (label + 2, "label middle"), + (label + 4, "label end, one past the last byte"), + ] { + assert_eq!(linked(text, offset).as_ref(), Some(&expected), "{what}"); + } +} + +#[test] +fn a_position_beside_the_names_answers_nothing() { + let text = "module m;\nendmodule : m\n"; + assert!(linked(text, 0).is_none(), "the `module` keyword itself"); + assert!(linked(text, at(text, " m;")).is_none(), "the space before the name"); + assert!(linked(text, at(text, ";") + 1).is_none(), "past the semicolon"); + assert!(linked(text, at(text, "endmodule")).is_none(), "the closing keyword"); +} + +#[test] +fn a_position_past_the_end_of_the_file_answers_nothing() { + let text = "module m;\nendmodule : m\n"; + assert!(linked(text, text.len() as u32).is_none()); + assert!(linked(text, text.len() as u32 + 1_000).is_none()); +} + +#[test] +fn an_empty_buffer_answers_nothing() { + assert!(linked("", 0).is_none()); +} + +// ------------------------------------------------------------------ +// the two refusals +// ------------------------------------------------------------------ + +#[test] +fn an_unlabeled_closer_links_nothing() { + // The label is optional in SV, and its absence is not an invitation to + // create one: there is no second range, so there is no answer. + for (text, header) in [ + ("module m;\nendmodule\n", "module "), + ("package p;\nendpackage\n", "package "), + ("class c;\nendclass\n", "class "), + ("module m;\n function f;\n endfunction\nendmodule\n", "function "), + ("module m;\n task t;\n endtask\nendmodule\n", "task "), + ("module m;\n initial begin : blk\n end\nendmodule\n", "begin : "), + ] { + assert!(linked(text, at_after(text, header)).is_none(), "{text:?} must link nothing"); + } +} + +#[test] +fn a_mismatched_label_links_nothing() { + // Broken code. Linking the two would rewrite one half into the other + // on the next keystroke — an edit the user never asked for — and the + // spec requires the ranges to hold identical text anyway. + let text = "module m;\nendmodule : wrong\n"; + assert!(linked(text, at_after(text, "module ")).is_none(), "from the header"); + assert!(linked(text, at(text, "wrong")).is_none(), "and from the label"); +} + +#[test] +fn a_label_differing_only_in_case_links_nothing() { + let text = "module Data;\nendmodule : data\n"; + assert!(linked(text, at(text, "Data")).is_none()); + assert!(linked(text, at(text, "data")).is_none()); +} + +#[test] +fn an_escaped_identifier_links_nothing() { + // `\odd.name ` is an identifier whose extent depends on a trailing + // space, which no word pattern can describe. Both halves matching does + // not make it safe to hand a client. + let text = "module \\odd.name ;\nendmodule : \\odd.name \n"; + let doc = doc_of(text); + let mut pairs = Vec::new(); + items_pairs(&doc.tree.items, &mut pairs); + assert_eq!(pairs.len(), 1, "premise: the tree really did record the pair"); + assert!(linked(text, at(text, "\\odd.name")).is_none(), "from the header"); + assert!(linked(text, text.rfind("\\odd.name").expect("label") as u32).is_none(), "and back"); +} + +#[test] +fn is_simple_identifier_accepts_exactly_the_word_pattern() { + for good in ["m", "_x", "a1", "foo$bar", "A_b$9", "_"] { + assert!(is_simple_identifier(good), "{good} is a plain SV identifier"); + } + for bad in ["", "1a", "$x", "\\odd.name", "a b", "a.b", "é"] { + assert!(!is_simple_identifier(bad), "{bad:?} is not"); + } +} + +// ------------------------------------------------------------------ +// nesting — the pair must be the syntactic one +// ------------------------------------------------------------------ + +#[test] +fn nested_blocks_answer_their_own_pair() { + let text = concat!( + "module m;\n", + " initial begin : outer\n", + " begin : inner\n", + " x = 1;\n", + " end : inner\n", + " end : outer\n", + "endmodule\n", + ); + let outer = linked(text, at(text, "outer")).expect("the outer header answers"); + assert_eq!(outer, vec![(1, 18, 23), (5, 8, 13)], "line 1 header, line 5 label"); + let inner = linked(text, at(text, "inner")).expect("the inner header answers"); + assert_eq!(inner, vec![(2, 12, 17), (4, 10, 15)], "line 2 header, line 4 label"); +} + +#[test] +fn identical_names_at_different_nesting_pair_syntactically() { + // The evil fixture: four byte-identical names, two pairs. A + // nearest-same-text rule would pair the outer header with the *inner* + // label, because that one is nearer. The pair comes off the AST node, + // so it cannot. + let text = concat!( + "module m;\n", + " initial begin : x\n", + " begin : x\n", + " y = 1;\n", + " end : x\n", + " end : x\n", + "endmodule\n", + ); + let outer_header = at_after(text, "begin : "); + let inner_header = text.match_indices("begin : ").nth(1).expect("the inner block").0 as u32 + 8; + let outer = linked(text, outer_header).expect("the outer header answers"); + assert_eq!(outer, vec![(1, 18, 19), (5, 8, 9)], "outer header pairs with the OUTER end"); + let inner = linked(text, inner_header).expect("the inner header answers"); + assert_eq!(inner, vec![(2, 12, 13), (4, 10, 11)], "inner header pairs with the INNER end"); + assert_ne!(outer, inner); + // And from each closing label, back to the same two pairs. + let inner_label = text.match_indices("end : ").next().expect("the inner end").0 as u32 + 6; + let outer_label = at_last_after(text, "end : "); + assert_eq!(linked(text, inner_label), Some(inner)); + assert_eq!(linked(text, outer_label), Some(outer)); +} + +#[test] +fn a_module_and_the_function_inside_it_are_separate_pairs() { + // The function is deliberately named `m` too. + let text = "module m;\n function m;\n endfunction : m\nendmodule : m\n"; + let module = linked(text, at_after(text, "module ")).expect("the module header answers"); + assert_eq!(module, vec![(0, 7, 8), (3, 12, 13)], "module header, endmodule label"); + let function = linked(text, at_after(text, "function ")).expect("the function header answers"); + assert_eq!(function, vec![(1, 11, 12), (2, 16, 17)], "function header, endfunction label"); + assert_ne!(module, function); +} + +#[test] +fn a_class_method_pairs_inside_its_class() { + let text = "class c;\n function void f();\n endfunction : f\nendclass : c\n"; + let class = linked(text, at_after(text, "class ")).expect("the class answers"); + assert_eq!(class, vec![(0, 6, 7), (3, 11, 12)]); + let method = linked(text, at(text, "f()")).expect("the method answers"); + assert_eq!(method, vec![(1, 16, 17), (2, 16, 17)]); +} + +#[test] +fn a_named_block_inside_a_generate_for_pairs() { + let text = concat!( + "module m;\n", + " generate\n", + " for (genvar i = 0; i < 2; i++) begin : g\n", + " initial begin : inner\n", + " end : inner\n", + " end : g\n", + " endgenerate\n", + "endmodule\n", + ); + let gen = linked(text, at(text, "g\n")).expect("the generate label answers"); + assert_eq!(gen, vec![(2, 43, 44), (5, 10, 11)]); + let inner = linked(text, at(text, "inner")).expect("the inner block answers"); + assert_eq!(inner, vec![(3, 22, 27), (4, 12, 17)]); + assert_ne!(gen, inner); +} + +// ------------------------------------------------------------------ +// UTF-16 positions +// ------------------------------------------------------------------ + +#[test] +fn a_multibyte_comment_before_the_name_does_not_shift_it() { + // SV identifiers are ASCII, but everything around them need not be. + // The characters are counted in UTF-16 units, so `é` (2 bytes, 1 unit) + // and `🎉` (4 bytes, 2 units) must not move the name's column. + let text = "// café 🎉\nmodule m;\nendmodule : m\n"; + let ranges = linked(text, at_after(text, "module ")).expect("the header answers"); + assert_eq!(ranges, vec![(1, 7, 8), (2, 12, 13)]); +} + +#[test] +fn a_multibyte_comment_on_the_same_line_keeps_the_columns_honest() { + let text = "module m; // 🎉 party\nendmodule : m // café\n"; + let ranges = linked(text, at_last_after(text, ": ")).expect("the label answers"); + assert_eq!(ranges, vec![(0, 7, 8), (1, 12, 13)]); +} + +// ------------------------------------------------------------------ +// buffers that do not parse +// ------------------------------------------------------------------ + +#[test] +fn a_buffer_that_does_not_lex_answers_nothing() { + let text = "module m;\n wire a; /* unterminated\n"; + let doc = doc_of(text); + assert!(doc.tokens.is_empty(), "premise: the lexer gave up"); + assert!(linked_editing_ranges(&doc, at_after(text, "module ")).is_none()); +} + +#[test] +fn a_half_typed_construct_answers_nothing_rather_than_guessing() { + let text = "module m;\n initial begin : blk\nendmodule\n"; + assert!(linked(text, at(text, "blk")).is_none(), "no closing label was written"); +} + +#[test] +fn a_pair_written_after_a_broken_item_still_answers() { + // Error recovery keeps the items it could parse, so a mistake early in + // the file must not un-link everything below it. + let text = "module a;\n @@@ ;\nendmodule\nmodule b;\nendmodule : b\n"; + let ranges = linked(text, at_after(text, "module b")).expect("the second module answers"); + assert_eq!(ranges.len(), 2); +} + +// ------------------------------------------------------------------ +// the answer's own shape +// ------------------------------------------------------------------ + +#[test] +fn the_two_ranges_hold_identical_text_and_never_overlap() { + let text = "module top;\n initial begin : blk\n end : blk\nendmodule : top\n"; + let doc = doc_of(text); + for offset in [at(text, "top") + 1, at(text, "blk") + 1] { + let answer = linked_editing_ranges(&doc, offset).expect("a pair"); + assert_eq!(answer.ranges.len(), 2); + let (first, second) = (answer.ranges[0], answer.ranges[1]); + assert!( + (first.end.line, first.end.character) < (second.start.line, second.start.character), + "the header comes first and the two do not overlap: {answer:?}" + ); + assert_eq!( + first.end.character - first.start.character, + second.end.character - second.start.character, + "identical length" + ); + } +} + +// ------------------------------------------------------------------ +// QA (2026-08-26) — the prefix-label gate, and the ranges' exact bytes +// ------------------------------------------------------------------ + +/// Every offset in `0..=text.len()` answers without panicking, and every +/// `Some` answer holds two identical-text, non-overlapping ranges. The +/// blanket check the targeted tests below narrow in on one fixture at a +/// time — kept here because a tolerant-parser fixture is exactly the kind +/// of input where a hand-picked offset can miss what a sweep finds. +fn assert_total_and_sane(text: &str) { + let doc = doc_of(text); + for offset in 0..=text.len() as u32 { + let Some(answer) = linked_editing_ranges(&doc, offset) else { continue }; + assert_eq!(answer.ranges.len(), 2, "{text:?} at {offset}: {answer:?}"); + assert_eq!( + answer.word_pattern.as_deref(), + Some(WORD_PATTERN), + "{text:?} at {offset}: word pattern missing" + ); + let (a, b) = (answer.ranges[0], answer.ranges[1]); + let (before, after) = + if (a.start.line, a.start.character) <= (b.start.line, b.start.character) { + (a, b) + } else { + (b, a) + }; + assert!( + (before.end.line, before.end.character) <= (after.start.line, after.start.character), + "{text:?} at {offset}: ranges overlap: {answer:?}" + ); + } +} + +#[test] +fn a_block_named_both_ways_answers_only_the_blocks_own_pair() { + // `x : begin : y ... end : y` is illegal SV (IEEE 1800 §9.3.5: a block + // is named one way or the other), but the tolerant parser accepts it + // — the block wrote its own label, so `Labeled`'s prefix-label gate + // (`prefix_labelled_end`, only fires when the block wrote no label of + // its own) must stay silent and the block's own (y, y) pair, not a + // fabricated (x, y), must be what answers. + let text = "module m;\n initial x : begin : y\n z = 1;\n end : y\nendmodule\n"; + assert_total_and_sane(text); + let y_pair = linked(text, at(text, "y")).expect("the block's own label pairs"); + assert_eq!(y_pair.len(), 2); + assert_eq!(linked(text, text.rfind('y').expect("closing y") as u32), Some(y_pair)); + // `x` is not part of any pair: the prefix label was correctly not + // linked to anything. + assert!(linked(text, at(text, "x")).is_none(), "the unused prefix label links nothing"); +} + +#[test] +fn a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched() { + // `x : begin ... end : y` — the block wrote no label of its own, so + // the prefix-label gate does fire and pushes (x, y). The two names + // differ, so this must still answer null, the same as any other + // mismatch — the gate firing is not itself a promise of a match. + let text = "module m;\n initial x : begin\n z = 1;\n end : y\nendmodule\n"; + assert_total_and_sane(text); + assert!(linked(text, at(text, "x")).is_none(), "mismatched prefix pair: from x"); + assert!(linked(text, at(text, "y")).is_none(), "mismatched prefix pair: from y"); +} + +#[test] +fn a_stray_second_end_label_after_the_block_already_closed_is_inert() { + // Two `end : x` for one `begin : x`. The first one closes the block; + // the second is leftover tokens the item-level recovery has to make + // sense of on its own. Whatever it becomes, it must not create a + // second, wrong pairing, and it must not make the walk panic. + let text = "module m;\n initial begin : x\n z = 1;\n end : x\n end : x\nendmodule\n"; + assert_total_and_sane(text); + let doc = doc_of(text); + let mut pairs = Vec::new(); + items_pairs(&doc.tree.items, &mut pairs); + assert_eq!(pairs.len(), 1, "the stray `end : x` must not mint a second pair"); + // The pair that does exist closes on the FIRST `end : x`, not the + // second — the leftover tokens answer nothing at all. + let first_end = text.find("end : x").expect("first end"); + let second_end = text.rfind("end : x").expect("second end"); + assert_ne!(first_end, second_end); + assert!(linked(text, second_end as u32 + 6).is_none(), "the leftover end : x links nothing"); +} + +#[test] +fn broken_and_unclosed_labeled_constructs_never_panic() { + for text in [ + "module m;\n initial begin : blk\n z = 1;\nendmodule\n", // `end` missing + "module m;\n initial begin : blk\n z = 1;\n", // no closer at all, EOF + "module m;\n initial begin : \n end : \nendmodule\n", // label written, no name + "module m;\n initial begin :\n end\nendmodule\n", // colon, no name, no close label + ] { + assert_total_and_sane(text); + } +} + +#[test] +fn adjacent_closing_labels_never_bleed_into_each_other() { + // `endfunction : f` immediately followed by `endmodule : m` on the + // next line: the "name spans never touch" claim, checked at the exact + // boundary a lexer could in principle blur. + let text = "module m;\n function f;\n endfunction : f\nendmodule : m\n"; + assert_total_and_sane(text); + let f = linked(text, at(text, "f;")).expect("the function pairs"); + let m = linked(text, at_after(text, "module ")).expect("the module pairs"); + assert_ne!(f, m); +} + +/// The ranges cover exactly the identifier's bytes — never the `:`, never +/// the surrounding whitespace or a comment written between them. An +/// off-by-one here would let a client's keystroke land on the colon. +#[test] +fn ranges_cover_exactly_the_identifier_never_the_colon_or_comment() { + let cases: [(&str, &str, &str); 3] = [ + ("module m;\nendmodule : /*c*/ m\n", "module ", "m"), + ("module m;\n initial begin:x\n end:x\nendmodule\n", "begin:", "x"), + ("module m;\n initial begin :\n x\n end :\n x\nendmodule\n", "begin :\n ", "x"), + ]; + for (text, header_prefix, want) in cases { + let doc = doc_of(text); + let answer = linked_editing_ranges(&doc, at_after(text, header_prefix)) + .unwrap_or_else(|| panic!("{text:?}: the header answers")); + let positions = doc.positions(); + // Decode each `Range` back to a byte span via the same + // `Positions::offset` the server itself uses to turn a client + // position into an offset, and check it covers exactly the name + // — not the colon, not a space, not the comment beside it. + for range in &answer.ranges { + let start = positions.offset(range.start) as usize; + let end = positions.offset(range.end) as usize; + assert_eq!(&text[start..end], want, "{text:?}: range {range:?}"); + } + } +} + +// ------------------------------------------------------------------ +// corpus sweep — real RTL, every offset, machine-checked invariants +// ------------------------------------------------------------------ + +/// Every offset of a handful of real corpus files that write closing +/// labels: totality (no panic), and every `Some` answer's two ranges hold +/// identical text and do not overlap. Skipped when `corpus/` is not +/// checked out, like every other corpus test in this crate. +#[test] +fn a_corpus_sweep_of_labeled_constructs_is_total_and_sane() { + let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let files = [ + "common_cells/src/lzc.sv", + "common_cells/src/rr_arb_tree.sv", + "common_cells/src/popcount.sv", + "common_cells/src/cdc_reset_ctrlr.sv", + "common_cells/src/deprecated/rrarbiter.sv", + "common_cells/src/deprecated/prioarbiter.sv", + "common_cells/src/stream_fifo_optimal_wrap.sv", + "common_cells/src/stream_throttle.sv", + "ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv", + "ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_monitor.sv", + "opentitan/hw/ip/uart/dv/env/seq_lib/uart_base_vseq.sv", + ]; + let mut files_checked = 0; + let mut pairs_found = 0; + for name in files { + let path = corpus.join(name); + let Ok(text) = std::fs::read_to_string(&path) else { + eprintln!("{} not checked out — skipping", path.display()); + continue; + }; + assert!( + text.contains("end") && text.contains(':'), + "{}: premise, this file should write a closing label", + path.display() + ); + let doc = doc_of(&text); + let mut file_pairs = Vec::new(); + items_pairs(&doc.tree.items, &mut file_pairs); + pairs_found += file_pairs.len(); + let positions = doc.positions(); + for offset in 0..=text.len() as u32 { + let Some(answer) = linked_editing_ranges(&doc, offset) else { continue }; + assert_eq!(answer.ranges.len(), 2, "{}: {answer:?}", path.display()); + let (a, b) = (answer.ranges[0], answer.ranges[1]); + let a_text = + &text[positions.offset(a.start) as usize..positions.offset(a.end) as usize]; + let b_text = + &text[positions.offset(b.start) as usize..positions.offset(b.end) as usize]; + assert_eq!( + a_text, + b_text, + "{}: at {offset}, ranges hold different text", + path.display() + ); + assert!( + is_simple_identifier(a_text), + "{}: at {offset}, {a_text:?} is not a plain identifier", + path.display() + ); + assert!( + (a.end.line, a.end.character) <= (b.start.line, b.start.character) + || (b.end.line, b.end.character) <= (a.start.line, a.start.character), + "{}: at {offset}, ranges overlap: {answer:?}", + path.display() + ); + } + files_checked += 1; + } + assert!(files_checked > 5, "the corpus really is checked out: {files_checked} files"); + assert!(pairs_found > 10, "these files really do write closing labels: {pairs_found} pairs"); +} + +#[test] +fn a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing() { + let text = "module m;\n initial begin : blk\n end : blk\nendmodule\n"; + for (offset, what) in [ + (at(text, ": blk"), "the colon before the header's `blk`"), + (at(text, ": blk") + 1, "the space after that colon"), + (at(text, " end"), "the indentation before `end`, between the two names"), + ] { + // A position strictly on the colon or on whitespace — never on a + // letter of `blk` itself — answers nothing, even with `blk` + // close by on both sides. + assert!(linked(text, offset).is_none(), "{what}: {offset}"); + } +} + +#[test] +fn a_walk_of_a_whole_file_finds_every_construct_once() { + let text = concat!( + "package p;\n", + "endpackage : p\n", + "module m;\n", + " function f;\n", + " endfunction : f\n", + " task t;\n", + " endtask : t\n", + " initial begin : blk\n", + " end : blk\n", + "endmodule : m\n", + ); + let doc = doc_of(text); + let mut pairs = Vec::new(); + items_pairs(&doc.tree.items, &mut pairs); + assert_eq!(pairs.len(), 5, "package, module, function, task, named begin"); + // And every one of them is reachable from either of its own names. + for pair in &pairs { + assert!(linked_editing_ranges(&doc, pair.open.start).is_some()); + assert!(linked_editing_ranges(&doc, pair.close.start).is_some()); + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 58020e7..f01e12c 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -712,2701 +712,6 @@ fn occurrences( } #[cfg(test)] -mod tests { - use super::*; - use crate::perf::mean; - use std::fs; - use std::path::{Path, PathBuf}; - use std::str::FromStr; - - fn document(text: &str) -> (Workspace, Uri) { - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - (ws, uri) - } - - /// The byte offset of the first occurrence of `needle` in `text`. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - fn temp_dir(tag: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("lucisv_server_nav_{tag}_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("temp dir"); - dir - } - - #[test] - fn a_use_jumps_to_its_declaration_in_the_same_file() { - let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; - let (ws, uri) = document(text); - let offset = at(text, "assign a") + 7; - let locations = definition(&ws, &uri, offset); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0].range.start.line, 1, "the `wire a;` line"); - assert_eq!(locations[0].range.start.character, 7); - } - - #[test] - fn the_cursor_on_a_declaration_resolves_to_itself() { - let text = "module m;\n wire a;\nendmodule\n"; - let (ws, uri) = document(text); - let locations = definition(&ws, &uri, at(text, "wire a") + 5); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0].range.start.line, 1); - } - - /// A qualified type name is two references, each addressable on its own - /// half: the parser spans `pkg::t` and `DataType::segments` splits it, so - /// F12 on the *item* lands on the typedef rather than on the package. - #[test] - fn a_scoped_type_name_jumps_from_its_item_half() { - let text = "\ -package pkg; - typedef logic [1:0] t; -endpackage -module m; - pkg::t x; -endmodule -"; - let (ws, uri) = document(text); - let item = definition(&ws, &uri, at(text, "pkg::t x") + 5); - assert_eq!(item.len(), 1, "the typedef"); - assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line"); - assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword"); - let unit = definition(&ws, &uri, at(text, "pkg::t x")); - assert_eq!(unit.len(), 1, "the package"); - assert_eq!(unit[0].range.start.line, 0); - } - - /// `bus_if.mp bus` — the interface is the type, so the head range is what - /// F12 answers from; the modport tail is a member of it. - #[test] - fn an_interface_port_type_jumps_from_its_head() { - let text = "\ -interface bus_if; - logic clk; - modport mp (input clk); -endinterface -module m (bus_if.mp bus); -endmodule -"; - let (ws, uri) = document(text); - let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2); - assert_eq!(head.len(), 1, "the interface"); - assert_eq!(head[0].range.start.line, 0); - assert_eq!(head[0].range.start.character, 10, "the interface name"); - let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7); - assert_eq!(tail.len(), 1, "the modport"); - assert_eq!(tail[0].range.start.line, 2); - } - - #[test] - fn a_macro_use_jumps_to_its_define_in_the_same_file() { - let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n"; - let (ws, uri) = document(text); - let locations = definition(&ws, &uri, at(text, "`WIDTH-1") + 2); - assert_eq!(locations.len(), 1, "the `define` this file wrote"); - assert_eq!(locations[0].range.start.line, 0); - assert_eq!(locations[0].range.start.character, 8, "the name, not the backtick"); - } - - #[test] - fn a_macro_nothing_defines_has_no_definition() { - // `uvm_info` with no UVM in the index: the same empty answer a name - // nothing declares gets, and no invented location. - let text = "module m;\n initial `uvm_info(\"x\", \"y\", UVM_LOW)\nendmodule\n"; - let (ws, uri) = document(text); - assert!(definition(&ws, &uri, at(text, "`uvm_info") + 2).is_empty()); - } - - #[test] - fn a_macro_use_jumps_across_files_to_the_define() { - let dir = temp_dir("macro_xfile"); - fs::write(dir.join("defs.svh"), "`define BUS_W 32\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n logic [`BUS_W-1:0] bus;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "`BUS_W") + 2); - assert_eq!(locations.len(), 1, "the one file that defines it"); - assert!(locations[0].uri.as_str().ends_with("defs.svh"), "{:?}", locations[0].uri); - assert_eq!(locations[0].range.start.line, 0); - } - - #[test] - fn two_defines_of_one_macro_are_narrowed_by_the_include_graph() { - let dir = temp_dir("macro_narrow"); - fs::write(dir.join("a.svh"), "`define MODE 1\n").expect("write"); - fs::write(dir.join("b.svh"), "`define MODE 2\n").expect("write"); - let top_path = dir.join("top.sv"); - // Only `a.svh` is reachable from this file, so only its definition is - // offered — the narrowing `hover` already does, shared. - let top_text = "`include \"a.svh\"\nmodule top;\n logic [`MODE:0] m;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "`MODE:0") + 2); - assert_eq!(locations.len(), 1, "the include graph picks one: {locations:?}"); - assert!(locations[0].uri.as_str().ends_with("a.svh"), "{:?}", locations[0].uri); - } - - #[test] - fn a_define_inside_a_fragment_file_is_still_a_jump_target() { - // A `.svh` that is a *fragment* — no module, no package — is indexed - // for its defines like any other file (`fragment-mode`). - let dir = temp_dir("macro_fragment"); - fs::write(dir.join("frag.svh"), "CUSTOM_1,\n`define TAIL 7\nCUSTOM_2\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n logic [`TAIL:0] t;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "`TAIL") + 2); - assert_eq!(locations.len(), 1, "the fragment's define: {locations:?}"); - assert!(locations[0].uri.as_str().ends_with("frag.svh"), "{:?}", locations[0].uri); - assert_eq!(locations[0].range.start.line, 1); - } - - #[test] - fn a_name_nothing_declares_has_no_definition() { - let text = "module m;\n assign x = 1;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(definition(&ws, &uri, at(text, "x")).is_empty()); - } - - #[test] - fn references_finds_every_use_and_honors_include_declaration() { - let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; - let (ws, uri) = document(text); - let offset = at(text, "wire a") + 5; - - let without = references(&ws, &uri, offset, false); - assert_eq!(without.len(), 2, "two uses"); - assert_eq!(without[0].range.start.line, 2); - assert_eq!(without[1].range.start.line, 3); - - let with = references(&ws, &uri, offset, true); - assert_eq!(with.len(), 3, "the declaration is added"); - assert_eq!(with[0].range.start.line, 1, "declaration sorts first"); - } - - #[test] - fn references_work_from_a_use_as_well_as_from_the_declaration() { - let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; - let (ws, uri) = document(text); - let from_use = references(&ws, &uri, at(text, "assign a") + 7, false); - assert_eq!(from_use.len(), 2); - } - - #[test] - fn reference_positions_are_utf16() { - let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n"; - let (ws, uri) = document(text); - let locations = references(&ws, &uri, at(text, "wire a") + 5, false); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0].range.start.character, 9); - assert_eq!(locations[0].range.end.character, 10); - } - - #[test] - fn an_instantiation_jumps_into_another_file() { - let dir = temp_dir("xfile"); - let sub = dir.join("sub.sv"); - fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "sub u_sub")); - assert_eq!(locations.len(), 1, "the module in sub.sv"); - assert_eq!(locations[0].uri, path_to_uri(&sub).expect("uri")); - assert_eq!(locations[0].range.start.line, 0); - assert_eq!(locations[0].range.start.character, 7, "the name `sub`"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_cross_file_definition_reads_no_file() { - // The jump above, asked again for what it *costs*: the target module's - // range is in the index (`DeclPositions`), so nothing opens `sub.sv`. - // Pinned through the view cache, which is where a read would land. - let dir = temp_dir("no_read"); - let sub = dir.join("sub.sv"); - fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "sub u_sub")); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer"); - assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views()); - - // `workspace/symbol` answers the same way, over the same index. - let hits = crate::symbols::workspace_symbols(&ws, "sub"); - assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}"); - assert!(ws.held_views().is_empty(), "nor did the symbol search"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_ambiguous_workspace_name_returns_every_location() { - let dir = temp_dir("ambig"); - for name in ["a.sv", "b.sv"] { - fs::write(dir.join(name), "module dup;\nendmodule\n").expect("write"); - } - let top_path = dir.join("top.sv"); - let top_text = "module top;\n dup u (.*);\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "dup u")); - assert_eq!(locations.len(), 2, "both declarations, not a guess"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_include_line_jumps_into_the_file_it_names() { - // Go-to-definition's third case, and the one that answers where the - // other two have no identifier to work with. - let dir = temp_dir("include"); - let defs = dir.join("defs.svh"); - fs::write(&defs, "`define W 8\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "`include \"defs.svh\"\nmodule top;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "defs.svh")); - assert_eq!(locations.len(), 1); - assert_eq!(locations[0].uri, path_to_uri(&defs).expect("uri")); - assert_eq!(locations[0].range.start.line, 0, "the top of the included file"); - assert_eq!(locations[0].range.end.character, 0); - - // And a cursor on the module below is unaffected by any of this. - assert!(definition(&ws, &uri, at(top_text, "module top") + 7).len() == 1); - - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // cross-file references - // ------------------------------------------------------------------ - - const SUB: &str = "module sub (input logic clk);\nendmodule\n"; - const TOP: &str = "module top;\n sub u_a (.clk(1'b0));\n sub u_b (.clk(1'b1));\nendmodule\n"; - const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; - - /// A three-file workspace, with `which` opened as a buffer. - fn instantiated(tag: &str, which: &str) -> (PathBuf, Workspace, Uri) { - let dir = temp_dir(tag); - for (name, text) in [("sub.sv", SUB), ("top.sv", TOP), ("other.sv", OTHER)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let path = dir.join(which); - let uri = path_to_uri(&path).expect("uri"); - let text = fs::read_to_string(&path).expect("read"); - ws.set_document(uri.clone(), text); - (dir, ws, uri) - } - - /// Every location as `(file name, line)`. - fn places(locations: &[Location]) -> Vec<(String, u32)> { - locations - .iter() - .map(|l| { - let name = l.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(); - (name, l.range.start.line) - }) - .collect() - } - - #[test] - fn a_modules_references_come_from_every_file_that_instantiates_it() { - let (dir, ws, uri) = instantiated("xrefs_decl", "sub.sv"); - let found = references(&ws, &uri, at(SUB, "sub"), true); - assert_eq!( - places(&found), - vec![ - ("other.sv".to_string(), 1), - ("sub.sv".to_string(), 0), - ("top.sv".to_string(), 1), - ("top.sv".to_string(), 2), - ], - "the declaration plus three instantiations" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn references_from_an_instantiation_answer_the_same_set() { - let (dir, ws, uri) = instantiated("xrefs_use", "top.sv"); - let found = references(&ws, &uri, at(TOP, "sub u_b"), true); - assert_eq!( - places(&found), - vec![ - ("other.sv".to_string(), 1), - ("sub.sv".to_string(), 0), - ("top.sv".to_string(), 1), - ("top.sv".to_string(), 2), - ], - "renaming from here would touch exactly these" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn indexed_references_equal_the_refactor_walk_they_replace() { - let (dir, ws, uri) = instantiated("xrefs_equivalence", "top.sv"); - let offset = at(TOP, "sub u_b"); - let indexed = references(&ws, &uri, offset, true); - let path = dir.join("top.sv"); - let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true) - .expect("the existing refactor walk answers"); - // The oracle's spans are walked over the current texts of the very - // files it read, so there is no index-time claim to guard. - let walked = locations(&ws, walked, None); - - assert_eq!(indexed, walked); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() { - // A harder equivalence case than the one above: `W` is a module (a - // *unit*, filed in `units`) and, spelled identically, a package - // member (filed in `members`) — the prefilter's one string compare - // must not let either bucket answer for the other. `top.sv` is also - // edited live after opening, so the overlay's answer has to come from - // the unsaved buffer, not the file `find_references`'s own oracle - // would otherwise re-read from disk. - let dir = temp_dir("xrefs_equivalence_unit_and_member"); - let w_mod = "module W;\nendmodule\n"; - let w_pkg = "package p;\n localparam W = 4;\nendpackage\n"; - let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n"; - for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri"); - // An unsaved edit: a second live instantiation of `W`, not yet saved. - let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n"; - ws.set_document(top_uri, top_live.to_string()); - let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri"); - ws.set_document(w_uri.clone(), w_mod.to_string()); - let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri"); - ws.set_document(p_uri.clone(), w_pkg.to_string()); - - // The module `W`: its declaration and both live instantiations, never - // the package member spelled the same way. - let module_offset = at(w_mod, "W"); - let indexed_module = references(&ws, &w_uri, module_offset, true); - let walked_module = - vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true) - .expect("the walk answers"); - assert_eq!(indexed_module, locations(&ws, walked_module, None)); - assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member"); - - // The package member `W`: its declaration and the one qualified use, - // never the module. - let member_offset = at(w_pkg, "W"); - let indexed_member = references(&ws, &p_uri, member_offset, true); - let walked_member = - vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true) - .expect("the walk answers"); - assert_eq!(indexed_member, locations(&ws, walked_member, None)); - assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - #[ignore = "manual indexed-navigation latency probe"] - fn qa_indexed_references_latency_over_a_large_workspace() { - let dir = temp_dir("xrefs_latency"); - let sub_path = dir.join("sub.sv"); - fs::write(&sub_path, SUB).expect("write declaration"); - for i in 0..4 { - fs::write( - dir.join(format!("use_{i}.sv")), - format!("module use_{i}; sub u (); endmodule\n"), - ) - .expect("write use"); - } - for i in 0..815 { - fs::write( - dir.join(format!("unrelated_{i}.sv")), - format!("module unrelated_{i}; logic signal_{i}; endmodule\n"), - ) - .expect("write unrelated source"); - } - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&sub_path).expect("uri"); - ws.set_document(uri.clone(), SUB.to_string()); - assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); - - let requests = 200; - let start = std::time::Instant::now(); - for _ in 0..requests { - assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); - } - let indexed = start.elapsed(); - - let start = std::time::Instant::now(); - let walked = vlog_refactor::find_references(&ws.sources(), &sub_path, at(SUB, "sub"), true) - .expect("old walk"); - let old = start.elapsed(); - assert_eq!(walked.len(), 5); - eprintln!( - "indexed references: {:.3} ms/request over 820 files; old walk: {:.3} ms/request", - indexed.as_secs_f64() * 1_000.0 / f64::from(requests), - old.as_secs_f64() * 1_000.0, - ); - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // latency probes for a big open buffer - // - // `#[ignore]`d, asserting nothing about duration — the house shape from - // `perf.rs`, whose `mean` they borrow so every number in this repo is - // taken the same way. The numbers they print are recorded in - // `docs/features/references-nav/README.md`. - // - // cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \ - // --nocapture --test-threads=1 - // ------------------------------------------------------------------ - - /// A declaration small enough that nothing about it is the measurement. - const PROBE_SUB: &str = - "module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n"; - - /// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an - /// assign, a register and its update — then `instances` instantiations of - /// `sub`. Every block declares two names and uses four, so ten thousand - /// blocks is a forty-thousand-line file carrying tens of thousands of - /// locally resolved references: exactly the buffer the open-document - /// overlay in `indexed_references` has to walk past to answer anything. - /// - /// One `acc` is used by every block, so the file also carries a *local* - /// name with thousands of occurrences — the worst case for the in-file - /// fallback, which converts one span at a time. - /// - /// Its own generator rather than `perf::generated_module`'s, because that - /// one instantiates nothing and a probe about instantiations needs some. - fn generated_top(blocks: usize, instances: usize) -> String { - let mut src = String::from( - "module top (\n input logic clk,\n input logic rst_n,\n \ - input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \ - wire acc;\n assign acc = rst_n;\n", - ); - for n in 0..blocks { - src.push_str(&format!( - " wire [31:0] w_{n};\n \ - assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \ - reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n" - )); - } - for n in 0..instances { - src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n")); - } - src.push_str(" assign data_out = data_in;\nendmodule\n"); - src - } - - /// Both directions of a cross-file references request, with a big buffer - /// open — the owner's report of 2026-08-28, measured. - #[test] - #[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"] - fn qa_references_latency_with_a_big_open_top() { - use std::hint::black_box; - - let dir = temp_dir("refs_big_top"); - let top_text = generated_top(10_000, 4); - let sub_path = dir.join("sub.sv"); - let top_path = dir.join("top.sv"); - fs::write(&sub_path, PROBE_SUB).expect("write"); - fs::write(&top_path, &top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top_uri = path_to_uri(&top_path).expect("uri"); - let sub_uri = path_to_uri(&sub_path).expect("uri"); - ws.set_document(top_uri.clone(), top_text.clone()); - ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); - - let use_site = at(&top_text, "sub u_0"); - let declaration = at(PROBE_SUB, "sub"); - let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3; - let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4; - let references_in_top = - ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open"); - - // The answers, before any timing: a measurement of a request that - // answered nothing is worthless. - assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances"); - assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five"); - assert_eq!(definition(&ws, &top_uri, use_site).len(), 1); - assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only"); - assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere"); - - let runs = 20; - let from_use = mean(runs, || { - black_box(references(&ws, &top_uri, black_box(use_site), true)); - }); - let from_declaration = mean(runs, || { - black_box(references(&ws, &sub_uri, black_box(declaration), true)); - }); - let to_definition = mean(runs, || { - black_box(definition(&ws, &top_uri, black_box(use_site))); - }); - let in_file = mean(runs, || { - black_box(references(&ws, &top_uri, black_box(local), true)); - }); - let in_file_common = mean(runs, || { - black_box(references(&ws, &top_uri, black_box(common), true)); - }); - let highlights = mean(runs, || { - let doc = ws.document(&top_uri).expect("open"); - black_box(document_highlights(doc, black_box(common))); - }); - - eprintln!( - "big open top ({} KB, {references_in_top} references): \ - references from the use site {from_use:?}, \ - from the declaration {from_declaration:?}, \ - definition from the use site {to_definition:?}, \ - references on a local wire used 3× (the in-file fallback) {in_file:?}, \ - on one used 10 001× {in_file_common:?}, \ - documentHighlight on that one {highlights:?}", - top_text.len() / 1000, - ); - let _ = fs::remove_dir_all(&dir); - } - - /// The other half of the owner's report: what jumping *into* a file costs - /// when the folder it lives in was not in the index's scope yet. - #[test] - #[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"] - fn qa_didopen_latency_when_a_new_folder_widens_the_scope() { - use std::hint::black_box; - - let dir = temp_dir("didopen_scope"); - fs::create_dir_all(dir.join("rtl")).expect("rtl dir"); - fs::create_dir_all(dir.join("lib")).expect("lib dir"); - for n in 0..400 { - fs::write( - dir.join("rtl").join(format!("m{n}.sv")), - format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"), - ) - .expect("write"); - } - fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write"); - let top_text = generated_top(10_000, 4); - let top_path = dir.join("rtl").join("top.sv"); - fs::write(&top_path, &top_text).expect("write"); - - // The default rung: the folder scope. Nothing is in scope until a - // buffer is opened, so the first `didOpen` is itself a widening. - let mut ws = Workspace::default(); - ws.open_roots(vec![dir.clone()]); - let top_uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(top_uri.clone(), top_text.clone()); - ws.rebuild_index(); - let covered = ws.index().files().len(); - - // A `didOpen` the scope already covers: one `Document::new` and a - // publish, and `server.rs` runs no rescan at all. - let sibling = dir.join("rtl").join("m0.sv"); - let sibling_uri = path_to_uri(&sibling).expect("uri"); - let sibling_text = fs::read_to_string(&sibling).expect("read"); - let inside = mean(20, || { - ws.set_document(sibling_uri.clone(), sibling_text.clone()); - }); - - // A `didOpen` in a folder the scope does not cover: the same - // `Document::new`, and then the whole rescan `server.rs` runs when - // `scope_dirs()` moved — which re-reads and re-parses every file in - // the widened scope. Until 2026-08-28 the open big buffer was one of - // them; it now goes in from the analysis it already holds, which is - // what the last two pairs of numbers below are about - // (`docs/features/index-scope/README.md`). - let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri"); - let widening = mean(5, || { - ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); - black_box(ws.rebuild_index()); - }); - let rescan = mean(5, || { - black_box(ws.rebuild_index()); - }); - // Where the buffer's share goes, on the same buffer: what a rescan - // used to pay for one open file — a whole parse for the index facts, - // then a second lex for the completion words — against what it pays - // since 2026-08-28, which is the two walks over the analysis and the - // token stream the buffer already holds. - let (reparse, reused, relex, rewords) = { - let doc = ws.document(&top_uri).expect("open"); - ( - mean(3, || { - black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text)); - }), - mean(3, || { - black_box(doc.facts(top_path.clone())); - }), - mean(3, || { - let tokens = vlog_parser::tokenize(&top_text).expect("it lexes"); - black_box(crate::candidates::words_of_tokens(&tokens)); - }), - mean(3, || { - black_box(doc.words()); - }), - ) - }; - - // The same rescan with the big buffer closed, so its share of the - // rescan is a subtraction rather than a guess. - ws.close_document(&top_uri); - let without = mean(5, || { - black_box(ws.rebuild_index()); - }); - - eprintln!( - "didOpen with a {} KB buffer already open, {covered} files in scope: \ - a file the scope already covers {inside:?}; \ - one in a new folder (didOpen + rescan) {widening:?}; \ - the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \ - That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \ - words {relex:?} re-lexed vs {rewords:?} reused", - top_text.len() / 1000, - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn include_declaration_drops_the_declaration_and_nothing_else() { - let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv"); - let found = references(&ws, &uri, at(SUB, "sub"), false); - assert_eq!( - places(&found), - vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_package_members_references_come_from_every_import_site() { - let dir = temp_dir("xrefs_pkg"); - let pkg = "package p;\n localparam WIDTH = 8;\nendpackage\n"; - let a = "module a;\n import p::*;\n wire [WIDTH-1:0] x;\nendmodule\n"; - let b = "module b;\n wire [p::WIDTH-1:0] y;\nendmodule\n"; - for (name, text) in [("p.sv", pkg), ("a.sv", a), ("b.sv", b)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&dir.join("p.sv")).expect("uri"); - ws.set_document(uri.clone(), pkg.to_string()); - - let found = references(&ws, &uri, at(pkg, "WIDTH"), false); - assert_eq!(places(&found), vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1)]); - - // And from one of the use sites, the same answer plus the declaration. - let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); - ws.set_document(a_uri.clone(), a.to_string()); - let from_use = references(&ws, &a_uri, at(a, "WIDTH-1"), true); - assert_eq!( - places(&from_use), - vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1), ("p.sv".to_string(), 1)] - ); - let _ = fs::remove_dir_all(&dir); - } - - /// The gate, asserted directly. Since §64.1 a module's net **is** a name - /// another file can spell (`u_m.a`), so the gate admits it — that - /// assertion flipped, and the two truths this test was written to protect - /// did not: - /// - /// * `other.sv`'s own `a` is a different signal and is never listed; - /// * a name the index holds **nowhere** still never asks the workspace — - /// a generate-block-scoped net, whose scope is the block's and not the - /// module's, and an undeclared `b`, which is no symbol at all. - /// - /// And the cost argument is unchanged, which is why the gate is still - /// worth having: admitting a name buys two map probes plus the - /// name-prefiltered pass over the *open* buffers, and never a project - /// read. What the gate saves is those probes for every name that could - /// not have left the file anyway. - #[test] - fn a_local_signal_never_asks_the_workspace() { - let dir = temp_dir("xrefs_local"); - let text = "\ -module m; - wire a; - assign a = 1; - assign b = a; - if (1) begin : g - wire gen_only; - assign gen_only = a; - end -endmodule -"; - fs::write(dir.join("m.sv"), text).expect("write"); - fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&dir.join("m.sv")).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - let doc = ws.document(&uri).expect("open"); - - assert!( - leaves_this_file(&ws, doc, at(text, "wire a") + 5), - "a module's net is on its hierarchical surface, so `u_m.a` could name it" - ); - assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit"); - assert!( - leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5), - "and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`" - ); - assert!( - !leaves_this_file(&ws, doc, at(text, "assign b") + 7), - "and an undeclared name is no symbol at all" - ); - - let found = references(&ws, &uri, at(text, "wire a") + 5, true); - assert_eq!( - places(&found), - vec![ - ("m.sv".to_string(), 1), - ("m.sv".to_string(), 2), - ("m.sv".to_string(), 3), - ("m.sv".to_string(), 6), - ], - "this file only — `other.sv`'s own `a` is a different signal" - ); - // No file was read to answer that: `other.sv` holds a same-named net - // and was never opened, which `held_views` is the witness for. - assert!(ws.held_views().is_empty(), "no project read: {:?}", ws.held_views()); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_name_declared_in_two_files_degrades_references_to_the_in_file_answer() { - // The gate says yes (the index holds `dup` as a unit), but the - // collection refuses it as ambiguous — exactly like a rename would. - // `references` is read-only, so it falls back to what this file - // alone can say, rather than an empty list or a protocol error. - let dir = temp_dir("xrefs_ambiguous"); - let text = "module dup;\n wire w;\nendmodule\n"; - fs::write(dir.join("a.sv"), text).expect("write"); - fs::write(dir.join("b.sv"), text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let a_path = dir.join("a.sv"); - let uri = path_to_uri(&a_path).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - let doc = ws.document(&uri).expect("open"); - - assert!(leaves_this_file(&ws, doc, at(text, "dup")), "dup is a unit the index holds"); - - let found = references(&ws, &uri, at(text, "dup"), true); - assert_eq!(found.len(), 1, "the in-file declaration only, not empty and not an error"); - assert_eq!(found[0].uri, uri); - assert_eq!(found[0].range.start.line, 0); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_port_is_reachable_from_a_connection_in_another_file() { - // A module's ports are exactly what the index exports for it, so a - // `.clk(...)` connection elsewhere is a reference to this port. - let (dir, ws, uri) = instantiated("xrefs_port", "sub.sv"); - let found = references(&ws, &uri, at(SUB, "clk"), false); - assert_eq!( - places(&found), - vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] - ); - let _ = fs::remove_dir_all(&dir); - } - - /// TODO §63.1 QA, closed by §64.1. A `bind`'s connection expressions - /// elaborate in the target's scope (IEEE 1800 §23.11), and the index - /// records that reach on the target's hierarchical surface - /// (`resolve::in_bind_target`, `FACTS_FORMAT` 20). `definition` from the - /// bind file's expression half jumps to the target's net, never to - /// `aes_reseed_if`'s `.port` half of the same name — the overlay's - /// `Resolution::ExternalCandidate` carries the real `Def` straight - /// through, unremapped. - /// - /// `references` now sees it from **both** directions. It could not until - /// `leaves_this_file` and `indexed_def_in_file` stopped asking - /// `WorkspaceIndex::member` — the *connection* surface, ports and - /// parameters — about a declaration that lives on the **hierarchical** - /// surface only (`workspace/hierarchy.rs`, 2026-09-05). The two locations - /// this test was written to demand are the ones it asserts now: the bind - /// file's expression half seen from the declaration, and `aes.sv`'s own - /// `assign idle_o = entropy_masking_req;` seen from the bind file. The - /// same fix serves a plain (non-`bind`) tail, which was never a - /// bind-specific hole — see - /// `a_hierarchical_nets_references_reach_every_file_that_names_it`. - #[test] - fn a_binds_connection_expression_is_reachable_by_definition_and_by_references() { - let dir = temp_dir("xrefs_bind_wire"); - let aes = "module aes (input logic clk_i, output logic idle_o);\n \ - logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; - let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; - let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ - .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; - for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] - { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let aes_uri = path_to_uri(&dir.join("aes.sv")).expect("uri"); - ws.set_document(aes_uri.clone(), aes.to_string()); - let bind_uri = path_to_uri(&dir.join("aes_bind.sv")).expect("uri"); - ws.set_document(bind_uri.clone(), bind_file.to_string()); - - // The expression half's `definition` is the target's net, not the - // checker's `.port` of the same name. - let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; - let locations = definition(&ws, &bind_uri, expr_offset); - assert_eq!( - places(&locations), - vec![("aes.sv".to_string(), 1)], - "the expression half names `aes`'s net: {locations:?}" - ); - - // Both directions answer one set: the declaration, `aes.sv`'s own use - // of it, and the bind file's expression half. - let everywhere = vec![ - ("aes.sv".to_string(), 1), - ("aes.sv".to_string(), 2), - ("aes_bind.sv".to_string(), 2), - ]; - let found = references(&ws, &aes_uri, at(aes, "entropy_masking_req"), true); - assert_eq!(places(&found), everywhere, "from the declaration: {found:?}"); - let from_bind = references(&ws, &bind_uri, expr_offset, true); - assert_eq!(places(&from_bind), everywhere, "from the bind file: {from_bind:?}"); - - // And with `aes.sv` closed, which is how a DV engineer reads a bind - // file: its own in-file use comes from the one re-analysis - // `declaring_file_uses` runs, not from a posting that does not exist. - ws.close_document(&aes_uri); - let closed = references(&ws, &bind_uri, expr_offset, true); - assert_eq!(places(&closed), everywhere, "with the declaring file shut: {closed:?}"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() { - // The name prefilter's risk case, asserted from both sides: two - // modules declare a port `clk`, both files are open, and each port's - // references are its own. A prefilter that let a spelling stand in for - // an identity would merge these two answers. - let dir = temp_dir("xrefs_same_name"); - let sub = "module sub (input logic clk);\nendmodule\n"; - let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n"; - let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n"; - for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let mut uri_of = |name: &str, text: &str| { - let uri = path_to_uri(&dir.join(name)).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - uri - }; - let sub_uri = uri_of("sub.sv", sub); - uri_of("top.sv", top); - let other_uri = uri_of("other.sv", other); - - assert_eq!( - places(&references(&ws, &sub_uri, at(sub, "clk"), true)), - vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], - "`sub`'s port: its declaration and the connection to it" - ); - assert_eq!( - places(&references(&ws, &other_uri, at(other, "clk"), true)), - vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)], - "`other`'s port: its declaration and its own use" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn two_packages_declaring_one_name_keep_their_references_apart() { - // The same attack through the member table rather than the port table: - // `p::WIDTH` and `q::WIDTH` spell one name and are two declarations, - // and the file using both is open. - let dir = temp_dir("xrefs_two_packages"); - let p = "package p;\n localparam WIDTH = 8;\nendpackage\n"; - let q = "package q;\n localparam WIDTH = 16;\nendpackage\n"; - let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n"; - for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); - ws.set_document(a_uri.clone(), a.to_string()); - let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri"); - ws.set_document(p_uri.clone(), p.to_string()); - - assert_eq!( - places(&references(&ws, &p_uri, at(p, "WIDTH"), true)), - vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)], - "`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol" - ); - // And from the use side, the same set. - assert_eq!( - places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)), - vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)] - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn every_in_file_occurrence_is_converted_against_its_own_line() { - // The in-file fallback converts its spans with one walker now. A - // walker handed an out-of-order span answers a stale column, so the - // shape that would catch it: many occurrences, each on a line with a - // wide character before it, plus one on the same line as another. - let mut text = String::from("module m;\n wire a;\n"); - for n in 0..20 { - text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n")); - } - text.push_str("endmodule\n"); - let (ws, uri) = document(&text); - let found = references(&ws, &uri, at(&text, "wire a") + 5, true); - assert_eq!(found.len(), 41, "the declaration and two uses per block"); - - let doc = ws.document(&uri).expect("open"); - let positions = doc.positions(); - for location in &found { - let line = location.range.start.line as usize; - let offset = positions.offset(location.range.start); - assert_eq!( - text.get(offset as usize..offset as usize + 1), - Some("a"), - "line {line} must point at the name" - ); - assert_eq!(location.range.end.character, location.range.start.character + 1); - } - - // documentHighlight walks the same list and must agree with it. - let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol"); - let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect(); - assert_eq!(ranges, found.iter().map(|l| l.range).collect::>()); - } - - #[test] - fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() { - let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv"); - let edited = "module top;\n\n sub only_now ();\nendmodule\n"; - ws.set_document(uri.clone(), edited.to_string()); - - let found = references(&ws, &uri, at(edited, "sub only_now"), false); - assert_eq!( - places(&found), - vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 2)], - "the new live use replaces both saved top.sv uses" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_unsaved_declaration_move_is_reported_at_its_live_span() { - let (dir, mut ws, uri) = instantiated("xrefs_unsaved_decl", "sub.sv"); - let edited = "// moved down\n\nmodule sub (input logic clk);\nendmodule\n"; - ws.set_document(uri.clone(), edited.to_string()); - - let found = references(&ws, &uri, at(edited, "module sub") + 7, true); - assert!( - places(&found).contains(&("sub.sv".to_string(), 2)), - "the declaration comes from the live buffer, not its saved offset" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_untitled_buffer_still_answers_from_itself() { - // No path means no place in the index and nothing to hand the engine, - // so the in-file answer is the whole answer. - let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - let found = references(&ws, &uri, at(text, "wire a") + 5, true); - assert_eq!(found.len(), 2); - assert_eq!(found[0].uri, uri, "reported against the buffer itself"); - } - - // ------------------------------------------------------------------ - // documentHighlight - // ------------------------------------------------------------------ - - #[test] - fn a_signal_highlights_its_declaration_and_every_use() { - let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - let found = document_highlights(doc, at(text, "assign a") + 7).expect("a symbol"); - let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); - assert_eq!(lines, vec![1, 2, 3], "the declaration first, then both uses"); - assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); - } - - #[test] - fn highlighting_works_from_the_declaration_as_well() { - let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); - assert_eq!(found.len(), 2); - assert_eq!(found[0].range.start.line, 1); - } - - #[test] - fn highlight_ranges_are_utf16() { - let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n"; - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); - assert_eq!(found[0].range.start.character, 7); - assert_eq!(found[1].range.start.character, 9); - } - - #[test] - fn a_position_on_no_symbol_declines_rather_than_answering_nothing() { - // `None`, not an empty list: an empty list tells the editor to stop - // drawing its own word highlighting. - let text = "module m;\n wire a;\nendmodule\n"; - let (ws, uri) = document(text); - let doc = ws.document(&uri).expect("open"); - assert!(document_highlights(doc, at(text, "wire")).is_none(), "a keyword"); - assert!(document_highlights(doc, 0).is_none(), "the `module` keyword"); - } - - /// `performance.md` §7, reproduced: `documentHighlight` answered nothing - /// at every opentitan position tried — an instantiated module's name, a - /// port connection — while `references` at the same positions answered. - /// Both names are declared in *another* file, which is the whole of what - /// the two handlers used to disagree about. - #[test] - fn a_cross_file_name_highlights_its_uses_in_this_file() { - let dir = temp_dir("highlight_cross"); - fs::write( - dir.join("sub.sv"), - "module sub (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n", - ) - .expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "\ -module top; - logic clk, rst; - sub u_0 (.clk_i(clk), .rst_ni(rst)); - sub u_1 (.clk_i(clk), .rst_ni(rst)); -endmodule -"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - let doc = ws.document(&uri).expect("open"); - - // The module name at an instantiation: both instantiations, and - // nothing from the *other* module's file — this is one file's answer. - let module = at(top_text, "sub u_0"); - assert_eq!(references(&ws, &uri, module, true).len(), 3, "premise: references answers"); - let found = document_highlights(doc, module).expect("the instantiated module"); - let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); - assert_eq!(lines, vec![2, 3], "both instantiations of `sub`"); - assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); - - // A port connection: the `.clk_i` of both instantiations, and not the - // `clk` they are wired to, which is a different symbol. - let port = at(top_text, ".clk_i") + 1; - assert!(!references(&ws, &uri, port, true).is_empty(), "premise: references answers"); - let found = document_highlights(doc, port).expect("the connected port"); - let starts: Vec<(u32, u32)> = - found.iter().map(|h| (h.range.start.line, h.range.start.character)).collect(); - assert_eq!(starts, vec![(2, 12), (3, 12)], "both `.clk_i` connections"); - - let _ = fs::remove_dir_all(&dir); - } - - /// QA (performance wave Lane B, 2026-08-28): an instantiated module whose - /// name two files declare is ambiguous at the workspace layer. - /// `references` gives up on an ambiguous external target outright - /// (`indexed_target` only ever builds one from `Definition::External([def])` - /// — exactly one candidate — so an ambiguous use never reaches - /// `indexed_references`, and `in_file_references` needs a *local* symbol, - /// which an external use does not have; the net result is an empty - /// answer, unchanged by this round). `document_highlights` does not - /// inherit that caution: `external_occurrences` groups by the overlay's - /// whole answer, ambiguous sets included, so it answers here where - /// `references` does not. Recorded rather than asserted as a bug — LSP - /// does not require the two to agree, and answering something reasonable - /// beats the editor's own word-highlighter falling back to nothing — but - /// it is a real divergence the lead should see before calling the two - /// "cross-checked". - #[test] - fn an_ambiguous_instantiation_highlights_where_references_gives_up() { - let dir = temp_dir("highlight_ambiguous"); - let dup = "module dup (input logic clk_i);\nendmodule\n"; - fs::write(dir.join("a.sv"), dup).expect("write"); - fs::write(dir.join("b.sv"), dup).expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "\ -module top; - logic clk; - dup u_0 (.clk_i(clk)); - dup u_1 (.clk_i(clk)); -endmodule -"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - let doc = ws.document(&uri).expect("open"); - - let module = at(top_text, "dup u_0"); - assert!(leaves_this_file(&ws, doc, module), "dup is a unit the index holds"); - assert!( - references(&ws, &uri, module, true).is_empty(), - "references declines an ambiguous external target rather than guessing" - ); - let found = document_highlights(doc, module).expect("highlight groups the ambiguous use"); - let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); - assert_eq!(lines, vec![2, 3], "both instantiations, grouped by the same ambiguous def set"); - - let _ = fs::remove_dir_all(&dir); - } - - /// Two uses of the *same name* that are ambiguous between *different* - /// def sets must not be grouped into one highlight — the def-set - /// comparison in `external_occurrences`, not the name match alone, is - /// what keeps them apart. `dup_a` and `dup_b` are each declared in two - /// files (so a connection to either is ambiguous), and both happen to - /// export a port with the identical name `same_port` — so the two - /// connections below share one `reference.name` but must resolve against - /// disjoint ambiguous sets (`dup_a`'s two files vs. `dup_b`'s two files). - #[test] - fn two_uses_ambiguous_between_different_def_sets_do_not_group() { - let dir = temp_dir("highlight_ambiguous_disjoint"); - let dup_a = "module dup_a (input logic same_port);\nendmodule\n"; - let dup_b = "module dup_b (input logic same_port);\nendmodule\n"; - fs::write(dir.join("a1.sv"), dup_a).expect("write"); - fs::write(dir.join("a2.sv"), dup_a).expect("write"); - fs::write(dir.join("b1.sv"), dup_b).expect("write"); - fs::write(dir.join("b2.sv"), dup_b).expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "\ -module top; - logic clk; - dup_a u_a (.same_port(clk)); - dup_b u_b (.same_port(clk)); -endmodule -"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - let doc = ws.document(&uri).expect("open"); - - let first = at(top_text, "same_port(clk));\n dup_b") + 1; - let second = at(top_text, "same_port(clk));\nendmodule") + 1; - // Premise: both connections are genuinely ambiguous externals (no - // local `same_port`, and the workspace really does hold two - // candidates for each), i.e. this exercises the def-set comparison - // and not some earlier decline. - let first_found = - document_highlights(doc, first).expect("dup_a's connection is ambiguous, not empty"); - let second_found = - document_highlights(doc, second).expect("dup_b's connection is ambiguous, not empty"); - let first_lines: Vec = first_found.iter().map(|h| h.range.start.line).collect(); - let second_lines: Vec = second_found.iter().map(|h| h.range.start.line).collect(); - assert_eq!(first_lines, vec![2], "dup_a's port only, despite sharing a name with dup_b's"); - assert_eq!(second_lines, vec![3], "dup_b's port only, despite sharing a name with dup_a's"); - - let _ = fs::remove_dir_all(&dir); - } - - /// A use the overlay never answered — its `defs()` is empty, e.g. a - /// package member the index does not hold — must decline like any other - /// unanswered position, not fall through to some other file's namesake. - #[test] - fn an_unanswered_external_use_declines_rather_than_guessing() { - let dir = temp_dir("highlight_unanswered"); - let top_path = dir.join("top.sv"); - // `missing_pkg` is never declared anywhere in the workspace, so the - // import itself is the only thing the index can say nothing about; - // `NOPE` is a member reference the overlay tries and fails to place. - let top_text = "module top;\n import missing_pkg::*;\n wire [NOPE-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - let doc = ws.document(&uri).expect("open"); - - let use_pos = at(top_text, "NOPE") + 1; - assert!(document_highlights(doc, use_pos).is_none(), "unresolved, so decline"); - - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // TODO §64.1 — the hierarchical member surface - // ------------------------------------------------------------------ - - /// `leaf` declares a net only a hierarchical path can reach, plus a port - /// and a parameter that a connection list can, so one fixture answers both - /// "did the widening land" and "did the connection answers move". - const LEAF: &str = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - logic sig; - assign sig = clk_i; -endmodule -"; - /// One level up: `u_leaf.sig`. - const SINGLE: &str = "\ -module single; - leaf u_leaf (.clk_i(1'b0)); - wire v; - assign v = u_leaf.sig; -endmodule -"; - /// Two levels up, through `mid`'s own instance. - const MID: &str = "\ -module mid; - leaf u_leaf (.clk_i(1'b0)); -endmodule -"; - const TWO_LEVEL: &str = "\ -module top; - mid u_mid (); - wire w; - assign w = u_mid.u_leaf.sig; -endmodule -"; - - /// The four-file hierarchical workspace, with the named files opened as - /// buffers holding exactly their on-disk text. - fn hierarchical(tag: &str, open: &[&str]) -> (PathBuf, Workspace) { - let dir = temp_dir(tag); - for (name, text) in - [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] - { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - for name in open { - let path = dir.join(name); - let uri = path_to_uri(&path).expect("uri"); - let text = fs::read_to_string(&path).expect("read"); - ws.set_document(uri, text); - } - (dir, ws) - } - - fn uri_in(dir: &Path, name: &str) -> Uri { - path_to_uri(&dir.join(name)).expect("uri") - } - - /// The byte offset of `leaf`'s net declaration, its one-level tail and its - /// two-level tail — the three positions the sweep below asks from. - fn sig_positions() -> (u32, u32, u32) { - ( - at(LEAF, "logic sig") + 6, - at(SINGLE, "u_leaf.sig;") + 7, - at(TWO_LEVEL, "u_mid.u_leaf.sig") + 13, - ) - } - - /// The declaration, its own in-file use, and both cross-file tails. - fn every_place_naming_sig() -> Vec<(String, u32)> { - vec![ - ("leaf.sv".to_string(), 1), - ("leaf.sv".to_string(), 2), - ("single.sv".to_string(), 3), - ("top.sv".to_string(), 3), - ] - } - - /// Cases (b) and (c): asked **from the declaration** of a net that only a - /// hierarchical path can reach, with `includeDeclaration` both ways. - #[test] - fn a_hierarchical_nets_references_reach_every_file_that_names_it() { - let (dir, ws) = hierarchical("hier_from_decl", &["leaf.sv", "single.sv", "top.sv"]); - let leaf_uri = uri_in(&dir, "leaf.sv"); - let (decl, _, _) = sig_positions(); - - assert_eq!( - places(&references(&ws, &leaf_uri, decl, true)), - every_place_naming_sig(), - "the declaration, its own use, the one-level tail and the two-level one" - ); - assert_eq!( - places(&references(&ws, &leaf_uri, decl, false)), - every_place_naming_sig()[1..].to_vec(), - "`includeDeclaration: false` drops the declaration and nothing else" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (h): asked **from a tail**, the answer must include the declaring - /// buffer's own in-file use — the half `indexed_def_in_file` could not - /// re-identify. Both tails answer the same set, from one and from two - /// levels up. - #[test] - fn a_hierarchical_nets_references_from_a_tail_include_the_declaring_files_own_uses() { - let (dir, ws) = hierarchical("hier_from_tail", &["leaf.sv", "single.sv", "top.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let top_uri = uri_in(&dir, "top.sv"); - let (_, one, two) = sig_positions(); - - assert_eq!( - places(&references(&ws, &single_uri, one, true)), - every_place_naming_sig(), - "from `u_leaf.sig`" - ); - assert_eq!( - places(&references(&ws, &top_uri, two, true)), - every_place_naming_sig(), - "from `u_mid.u_leaf.sig` — the same declaration, so the same set" - ); - assert_eq!( - places(&references(&ws, &single_uri, one, false)), - every_place_naming_sig()[1..].to_vec(), - "and the declaration is the only thing `includeDeclaration` drops" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (i). The index posts no `Local` fact for a hierarchical-only - /// declaration, so with `leaf.sv` **closed** neither the postings nor the - /// open-buffer overlay can supply its own `assign sig = clk_i;`. An answer - /// that silently omitted it would be worse than the single-file fallback, - /// because it looks complete. - #[test] - fn a_hierarchical_nets_own_uses_are_found_with_its_declaring_file_closed() { - let (dir, ws) = hierarchical("hier_closed", &["single.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, one, _) = sig_positions(); - - assert_eq!( - places(&references(&ws, &single_uri, one, true)), - every_place_naming_sig(), - "`leaf.sv` is closed and `top.sv` too, and both are still listed" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// `definition` and `documentHighlight` over the same three positions. - /// Neither reads the reachability gate — `definition` goes through the - /// overlay and `documentHighlight` is a *document* answer by contract - /// (`docs/features/references-nav/README.md`, 2026-08-28) — so both are - /// pinned here to stay exactly what they were. - #[test] - fn definition_and_document_highlight_over_a_hierarchical_tail_are_unchanged() { - let (dir, ws) = hierarchical("hier_def_highlight", &["leaf.sv", "single.sv", "top.sv"]); - let leaf_uri = uri_in(&dir, "leaf.sv"); - let single_uri = uri_in(&dir, "single.sv"); - let top_uri = uri_in(&dir, "top.sv"); - let (decl, one, two) = sig_positions(); - - let declaration = vec![("leaf.sv".to_string(), 1)]; - assert_eq!(places(&definition(&ws, &leaf_uri, decl)), declaration, "itself"); - assert_eq!(places(&definition(&ws, &single_uri, one)), declaration, "from one level up"); - assert_eq!(places(&definition(&ws, &top_uri, two)), declaration, "from two"); - - let lines = |uri: &Uri, offset: u32| { - let doc = ws.document(uri).expect("open"); - document_highlights(doc, offset) - .map(|found| found.iter().map(|h| h.range.start.line).collect::>()) - }; - assert_eq!(lines(&leaf_uri, decl), Some(vec![1, 2]), "this file's two spans"); - assert_eq!(lines(&single_uri, one), Some(vec![3]), "the tail, in its own file only"); - assert_eq!(lines(&top_uri, two), Some(vec![3]), "same, two levels up"); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (d). The connection surface is a *prefix* of the hierarchical one - /// (`hierarchy::member` returns the connection records whole whenever they - /// are non-empty), so a port and a parameter of the very same module must - /// answer exactly what they answered before the widening. - #[test] - fn a_port_and_a_parameter_of_the_same_unit_keep_their_connection_answers() { - let (dir, ws) = hierarchical("hier_port", &["leaf.sv", "single.sv", "top.sv"]); - let leaf_uri = uri_in(&dir, "leaf.sv"); - - assert_eq!( - places(&references(&ws, &leaf_uri, at(LEAF, "clk_i)"), true)), - vec![ - ("leaf.sv".to_string(), 0), - ("leaf.sv".to_string(), 2), - ("mid.sv".to_string(), 1), - ("single.sv".to_string(), 1), - ], - "the port: its declaration, its own use, and both `.clk_i(...)` connections" - ); - assert_eq!( - places(&references(&ws, &leaf_uri, at(LEAF, "W = 1"), true)), - vec![("leaf.sv".to_string(), 0)], - "the parameter: declared, never named again anywhere" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// A **class** member stays on the connection answer — the attack case - /// §49's QA asked for, re-asked here because the widening is one call - /// away from it. A class has one surface, so `member_in` cannot move it. - #[test] - fn a_class_member_keeps_its_connection_answer() { - let dir = temp_dir("hier_class"); - let pkg = "\ -package cp; - class c; - int fld; - function void f(); - fld = 1; - endfunction - endclass -endpackage -"; - let user = "module cuser;\n cp::c h;\n initial h.fld = 2;\nendmodule\n"; - for (name, text) in [("cp.sv", pkg), ("cuser.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let pkg_uri = uri_in(&dir, "cp.sv"); - ws.set_document(pkg_uri.clone(), pkg.to_string()); - let user_uri = uri_in(&dir, "cuser.sv"); - ws.set_document(user_uri, user.to_string()); - - assert_eq!( - places(&references(&ws, &pkg_uri, at(pkg, "int fld") + 4, true)), - vec![("cp.sv".to_string(), 2), ("cp.sv".to_string(), 4), ("cuser.sv".to_string(), 2)], - "the field, its use in the method, and the handle access in the other file" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// A net declared inside a **generate block**. Until TODO §65.1 it was on - /// neither surface and this pinned the honest single-file answer; a named - /// block is now on its module's hierarchical surface and its members under - /// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate - /// says yes and `u_g.g.gsig` in the other file is one of the references. - #[test] - fn a_generate_block_scoped_net_is_found_through_the_instance_path() { - let dir = temp_dir("hier_generate"); - let leaf = "\ -module gleaf; - if (1) begin : g - wire gsig; - assign gsig = 1'b0; - end -endmodule -"; - let user = - "module guser;\n gleaf u_g ();\n wire z;\n assign z = u_g.g.gsig;\nendmodule\n"; - for (name, text) in [("gleaf.sv", leaf), ("guser.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let leaf_uri = uri_in(&dir, "gleaf.sv"); - ws.set_document(leaf_uri.clone(), leaf.to_string()); - let user_uri = uri_in(&dir, "guser.sv"); - ws.set_document(user_uri, user.to_string()); - - let decl = at(leaf, "wire gsig") + 5; - let doc = ws.document(&leaf_uri).expect("open"); - assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically"); - assert_eq!( - places(&references(&ws, &leaf_uri, decl, true)), - vec![ - ("gleaf.sv".to_string(), 2), - ("gleaf.sv".to_string(), 3), - ("guser.sv".to_string(), 3) - ], - "this file and `u_g.g.gsig`" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// A net in one unit and a **port of the same name in another** — each - /// keeps its own answer. The widening is per unit, so `sb`'s net gaining - /// its cross-file tail must not pull `sa`'s port along, and `sa`'s port - /// must answer exactly what it did. - #[test] - fn a_net_and_a_like_named_port_in_another_unit_keep_their_answers_apart() { - let dir = temp_dir("hier_shadow"); - let with_port = - "module sa (input logic shared);\n wire x;\n assign x = shared;\nendmodule\n"; - let with_net = "module sb;\n logic shared;\n assign shared = 1'b0;\nendmodule\n"; - let user = "\ -module suse; - sa u_a (.shared(1'b1)); - sb u_b (); - wire q; - assign q = u_b.shared; -endmodule -"; - for (name, text) in [("sa.sv", with_port), ("sb.sv", with_net), ("suse.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let port_uri = uri_in(&dir, "sa.sv"); - ws.set_document(port_uri.clone(), with_port.to_string()); - let net_uri = uri_in(&dir, "sb.sv"); - ws.set_document(net_uri.clone(), with_net.to_string()); - let user_uri = uri_in(&dir, "suse.sv"); - ws.set_document(user_uri, user.to_string()); - - assert_eq!( - places(&references(&ws, &port_uri, at(with_port, "logic shared") + 6, true)), - vec![("sa.sv".to_string(), 0), ("sa.sv".to_string(), 2), ("suse.sv".to_string(), 1)], - "`sa`'s port: unchanged, and never `sb`'s net" - ); - assert_eq!( - places(&references(&ws, &net_uri, at(with_net, "logic shared") + 6, true)), - vec![("sb.sv".to_string(), 1), ("sb.sv".to_string(), 2), ("suse.sv".to_string(), 4)], - "`sb`'s net: its own file plus the `u_b.shared` tail, and never `sa`'s connection" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (f) as it actually exists. `vlog_semantic` records **one symbol - /// per name per scope** — a second declaration of a name already declared - /// becomes a `Duplicate` and a reference to the first — so "a name that is - /// both a parameter and an internal net of one unit" is one symbol, one - /// index record, and one surface: the first declaration's. The - /// single-record rule (`defs.len() != 1`) therefore never sees two records - /// for one `(unit, name)` from one file, and both cursor positions answer - /// the same complete set. Asserted rather than argued, because the - /// alternative — two records, the port silently winning — is what §64.1 - /// asked to be ruled out. - #[test] - fn a_name_declared_twice_in_one_unit_is_one_symbol_and_one_record() { - let dir = temp_dir("hier_redeclared"); - let both = "\ -module pboth #(parameter int q = 1) (); - wire q; - assign q = 1'b0; -endmodule -"; - let user = - "module puse;\n pboth #(.q(2)) u_p ();\n wire s;\n assign s = u_p.q;\nendmodule\n"; - for (name, text) in [("pboth.sv", both), ("puse.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let both_uri = uri_in(&dir, "pboth.sv"); - ws.set_document(both_uri.clone(), both.to_string()); - let user_uri = uri_in(&dir, "puse.sv"); - ws.set_document(user_uri, user.to_string()); - - let everywhere = vec![ - ("pboth.sv".to_string(), 0), - ("pboth.sv".to_string(), 1), - ("pboth.sv".to_string(), 2), - ("puse.sv".to_string(), 1), - ("puse.sv".to_string(), 3), - ]; - assert_eq!( - places(&references(&ws, &both_uri, at(both, "int q") + 4, true)), - everywhere, - "from the parameter" - ); - assert_eq!( - places(&references(&ws, &both_uri, at(both, "wire q") + 5, true)), - everywhere, - "and from the redeclaration, which is a use of it" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Two files declaring one module, each with a net of one name: the gate - /// now admits the net, and the **single-record rule** refuses it — two - /// `Def`s for `(dleaf, dsig)` is exactly the ambiguity `defs.len() != 1` - /// has always declined. So the answer is the in-file one, as before, and - /// the tail that cannot be placed answers nothing rather than guessing. - #[test] - fn two_modules_of_one_name_keep_a_hierarchical_net_on_the_in_file_answer() { - let dir = temp_dir("hier_two_modules"); - let leaf = "module dleaf;\n logic dsig;\n assign dsig = 1'b0;\nendmodule\n"; - let user = "module duse;\n dleaf u_d ();\n wire r;\n assign r = u_d.dsig;\nendmodule\n"; - for (name, text) in [("a.sv", leaf), ("b.sv", leaf), ("duse.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let a_uri = uri_in(&dir, "a.sv"); - ws.set_document(a_uri.clone(), leaf.to_string()); - let user_uri = uri_in(&dir, "duse.sv"); - ws.set_document(user_uri.clone(), user.to_string()); - - assert_eq!( - places(&references(&ws, &a_uri, at(leaf, "logic dsig") + 6, true)), - vec![("a.sv".to_string(), 1), ("a.sv".to_string(), 2)], - "`a.sv`'s own answer — `b.sv`'s `dsig` is another declaration" - ); - assert_eq!( - places(&references(&ws, &user_uri, at(user, "u_d.dsig") + 4, true)), - Vec::new(), - "the tail is ambiguous between two `dleaf`s, so nothing is claimed" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (g). An `untitled:` buffer is in no index and has no path to hand - /// over, so the gate declines before any surface question is asked — the - /// widening cannot reach it. - #[test] - fn an_untitled_buffer_never_asks_the_workspace() { - let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(untitled.clone(), LEAF.to_string()); - let doc = ws.document(&untitled).expect("open"); - let (decl, _, _) = sig_positions(); - - assert!(!leaves_this_file(&ws, doc, decl), "no path, no index entry"); - let found = references(&ws, &untitled, decl, true); - assert_eq!( - found.iter().map(|l| l.range.start.line).collect::>(), - vec![1, 2], - "its own two spans, reported against the `untitled:` uri" - ); - assert!(found.iter().all(|l| l.uri == untitled)); - } - - // ------------------------------------------------------------------ - // TODO §64.1 — QA attacks (task-d8afe80f) - // ------------------------------------------------------------------ - - /// The disk edit shared by the three findings below: three comment lines - /// pushed in above `leaf`'s net declaration, keeping the net's name, kind - /// and owner so every identity check downstream still finds it. - const LEAF_MOVED: &str = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - // one - // two - // three - logic sig; - assign sig = clk_i; -endmodule -"; - - /// Every `leaf.sv` line in an answer, in the order it came — the three - /// stale-file findings all turn on which lines of the *closed declaring - /// file* a request reports. - fn leaf_lines(found: &[Location]) -> Vec { - found - .iter() - .filter(|l| l.uri.as_str().ends_with("leaf.sv")) - .map(|l| l.range.start.line) - .collect() - } - - /// **FINDING 1**, QA's scenario, now fixed. `declaring_file_uses` used to - /// read the declaring file through `ws.file_view` — a *cache*, dropped - /// only on `set_document`/`close_document`/`update_one`/ - /// `rebuild_index_with`/`begin_widen`, none of which an external edit to a - /// closed file is — while `locations` renders every closed-file span - /// against `Workspace::text_of`, which never caches. Two reads of one path - /// in one request, free to disagree, and the older offsets landed on the - /// newer bytes: QA saw `leaf.sv`'s "own use" reported at line `3` - /// (`// two`). The path now reads **once, fresh**, with `text_of`, and - /// hands those same bytes to `locations`. - /// - /// Worked out from `LEAF_MOVED` above, which is `LEAF` with three comment - /// lines pushed in under the header: line `4` is ` logic sig;` and line - /// `5` is ` assign sig = clk_i;`. Both come from the re-analysis of the - /// fresh text — the declaration too, because a file this request just - /// re-analysed knows where the declaration is *now* and the index-time - /// span is only the last resort. - #[test] - fn qa_finding_1_a_disk_edited_closed_declaring_file_reports_its_live_spans() { - let (dir, ws) = hierarchical("hier_stale_disk_1", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - // One request first, which is what used to prime the view cache: - // `leaf.sv` is closed, so this walks `declaring_file_uses`. - let before = references(&ws, &top_uri, two, true); - assert_eq!(places(&before), every_place_naming_sig(), "sanity: correct before any edit"); - - fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); - - let after = references(&ws, &top_uri, two, true); - assert_eq!( - leaf_lines(&after), - vec![4, 5], - "the declaration and its own use, both at their live lines" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// **FINDING 2**, now fixed, and the half that needed no primed cache at - /// all. The `include_declaration` tail used to fall straight to - /// `target.declaration_span` — a span fixed at the last index rebuild — - /// for a closed file, and `locations` rendered it against a fresh read - /// with no check that the two still agreed: QA saw the declaration at - /// line `1` (`// one`). It is now taken from the same re-analysis that - /// supplies the uses, so a single fresh request answers `4` and `5` from - /// `LEAF_MOVED`'s own text. - #[test] - fn qa_finding_2_one_fresh_request_reports_the_live_declaration_line() { - let (dir, ws) = hierarchical("hier_stale_disk_2", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); - - let after = references(&ws, &top_uri, two, true); - assert_eq!( - leaf_lines(&after), - vec![4, 5], - "declaration 4, own use 5 — nothing on this path caches" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// **FINDING 3**, the pre-existing half, now an honest omission. Asked - /// from `single.sv`'s `.clk_i(1'b0)` connection, the target is a **port**: - /// on the connection surface, its uses already posted, so no re-analysis - /// of the declaring file runs and every `leaf.sv` span in the answer is an - /// index-time claim about bytes nobody pinned. The guard now decides each - /// one against the text it is about to be rendered in: - /// - /// * the declaration, `clk_i` in the module header — `LEAF_MOVED` inserts - /// its three lines *below* the header, so line `0` is untouched, the - /// recorded span still spells `clk_i`, and it is reported (correctly, at - /// `0`); - /// * the posted use, `clk_i` in `assign sig = clk_i;` — that line is now - /// line `5` and the recorded span points into `// two`, which does not - /// spell `clk_i`, so it is **dropped**. - /// - /// QA saw `[0, 3]`: the `3` was the wrong line this guard exists to - /// refuse. The right answer is not to invent `5` either — nothing - /// re-analysed this file, so the request does not know `5`; it knows only - /// that what it held is no longer true. - #[test] - fn qa_finding_3_a_stale_index_span_in_a_closed_file_is_dropped_not_misreported() { - let (dir, ws) = hierarchical("hier_stale_disk_3", &["single.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; - - // Sanity: before the edit, both `leaf.sv` spans are true and reported. - assert_eq!( - leaf_lines(&references(&ws, &single_uri, clk_offset, true)), - vec![0, 2], - "the header's port and its own use, before any edit" - ); - - fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); - - let after = references(&ws, &single_uri, clk_offset, true); - assert_eq!( - leaf_lines(&after), - vec![0], - "the unmoved header still spells `clk_i`; the moved use is omitted, not misreported" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// The guard itself, attacked the way `hover.rs`'s own QA attacked it: a - /// disk edit that leaves a recorded span still *covering* the name, as a - /// **prefix** of a longer identifier. - /// - /// `leafp` declares one port and uses it nowhere, so the only `leafp.sv` - /// span in the answer is the index-time declaration span — `clk_i` in the - /// header. The edit renames the port to `clk_i2` and changes nothing - /// before it, so that span's bytes still read exactly `clk_i` and a - /// length-and-content check alone would emit it, under the old name, on a - /// line that now declares something else. `spells_exactly` requires the - /// character immediately outside the span not to continue an identifier, - /// which is what turns this prefix match back into a miss. - #[test] - fn qa_a_stale_span_that_now_spells_a_longer_name_is_dropped() { - let dir = temp_dir("hier_stale_prefix"); - let leaf = "module leafp (input logic clk_i);\nendmodule\n"; - let user = "module userp;\n leafp u_p (.clk_i(1'b0));\nendmodule\n"; - for (name, text) in [("leafp.sv", leaf), ("userp.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let user_uri = uri_in(&dir, "userp.sv"); - ws.set_document(user_uri.clone(), user.to_string()); - let offset = at(user, ".clk_i(1'b0)") + 1; - - assert_eq!( - places(&references(&ws, &user_uri, offset, true)), - vec![("leafp.sv".to_string(), 0), ("userp.sv".to_string(), 1)], - "sanity: the declaration and the connection, before the edit" - ); - - // The same header, one longer name, nothing before it moved. - fs::write(dir.join("leafp.sv"), "module leafp (input logic clk_i2);\nendmodule\n") - .expect("write"); - - assert_eq!( - places(&references(&ws, &user_uri, offset, true)), - vec![("userp.sv".to_string(), 1)], - "the prefix match is refused: the connection only, no invented declaration" - ); - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // Re-check round, 2026-09-12 — the rework's guard and one-read invariant - // ------------------------------------------------------------------ - - /// Re-check item 2(a): a disk edit that moves only the **use**, leaving - /// the declaration's own line untouched. The target is hierarchical-only, - /// so `declaring_file_uses` always re-analyses the whole file regardless - /// of what moved — both spans must come out live and correct, not just - /// the one that happened to move. - #[test] - fn qa_recheck_a_disk_edit_that_moves_only_the_use_is_still_fully_reanalysed() { - let (dir, ws) = hierarchical("hier_recheck_use_only", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - let moved_use_only = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - logic sig; - // one - // two - assign sig = clk_i; -endmodule -"; - fs::write(dir.join("leaf.sv"), moved_use_only).expect("write"); - - let after = references(&ws, &top_uri, two, true); - assert_eq!( - leaf_lines(&after), - vec![1, 4], - "declaration unmoved at 1, its own use moved to 4 — both live and correct" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Re-check item 2(b): the closed declaring file is **deleted** after the - /// index was built, with no rescan. `declaring_file_uses`'s `text_of` - /// read fails (`?` short-circuits to `None`), and the `include_declaration` - /// fallback's own `ws.text_of` read in `closed_locations` fails the same - /// way — no text, no panic, an honest omission of *that file* rather than - /// a guess. `single.sv` is untouched and perfectly readable, so its own - /// posted tail still answers normally — only `leaf.sv` itself vanishes - /// from the set. - #[test] - fn qa_recheck_a_deleted_closed_declaring_file_is_an_honest_omission_not_a_panic() { - let (dir, ws) = hierarchical("hier_recheck_deleted", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - fs::remove_file(dir.join("leaf.sv")).expect("delete"); - - let after = references(&ws, &top_uri, two, true); - assert!( - leaf_lines(&after).is_empty(), - "leaf.sv cannot be read at all, so it is omitted, not guessed at: {:?}", - leaf_lines(&after) - ); - assert_eq!( - places(&after), - vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], - "single.sv (untouched, still readable) and the live top.sv buffer, no panic, no crash" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Re-check item 2(c): a stale index-time span that, reinterpreted - /// against the edited disk text, no longer lands on a `char` boundary at - /// all — a multi-byte character straddling the exact byte offset the - /// index recorded. `spells_exactly`/`span_text` use `str::get`, which - /// answers `None` off a boundary rather than panicking; this is the - /// direct attack on that, on the **port** shape (finding 3's case, an - /// index-time span with no re-analysis to save it). - #[test] - fn qa_recheck_a_stale_span_off_a_utf8_boundary_does_not_panic() { - let (dir, ws) = hierarchical("hier_recheck_utf8", &["single.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; - - // The old, index-time byte offset of `clk_i`'s own use in `LEAF` - // (inside `assign sig = clk_i;`, the second occurrence). - let old_use_offset = LEAF.rfind("clk_i").expect("second occurrence"); - - // A new `leaf.sv` in which that same raw byte offset lands on the - // second byte of a 4-byte emoji — never a `char` boundary. - let mut edited = "a".repeat(old_use_offset.saturating_sub(1)); - edited.push('🎉'); - edited.push_str("\nmodule leaf (input logic clk_i2);\nendmodule\n"); - assert!( - !edited.is_char_boundary(old_use_offset), - "test bug: byte {old_use_offset} must land mid-character" - ); - fs::write(dir.join("leaf.sv"), &edited).expect("write"); - - // Must not panic. The header itself changed too (`clk_i` -> `clk_i2` - // and garbage before it), so nothing about `leaf.sv` need survive — - // the only requirement is that answering does not crash the server. - let after = references(&ws, &single_uri, clk_offset, true); - assert!(leaf_lines(&after).is_empty(), "garbage text spells nothing: {:?}", after); - let _ = fs::remove_dir_all(&dir); - } - - /// Re-check item 2(d): **two** closed files in one answer — `leaf.sv` - /// (the declaring file, fully re-analysed) and `single.sv` (a posted - /// `External` cross-file site, never re-analysed, guarded the same way a - /// port's own use is) — asked from a third, open file. An edit to one - /// must not affect the other's answer, and each is rendered against its - /// own, independently-read text. - #[test] - fn qa_recheck_two_closed_files_in_one_answer_are_independent() { - let (dir, ws) = hierarchical("hier_recheck_two_closed", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - assert_eq!( - places(&references(&ws, &top_uri, two, true)), - every_place_naming_sig(), - "leaf.sv re-analysed, single.sv posted-only, top.sv live — before any edit" - ); - - // Move `single.sv`'s own tail down by two lines; `leaf.sv` untouched. - let single_moved = "\ -module single; - // one - // two - leaf u_leaf (.clk_i(1'b0)); - wire v; - assign v = u_leaf.sig; -endmodule -"; - fs::write(dir.join("single.sv"), single_moved).expect("write"); - - let after = references(&ws, &top_uri, two, true); - assert_eq!( - leaf_lines(&after), - vec![1, 2], - "leaf.sv is untouched and unaffected by single.sv's own edit" - ); - let single_lines: Vec = after - .iter() - .filter(|l| l.uri.as_str().ends_with("single.sv")) - .map(|l| l.range.start.line) - .collect(); - // `single.sv`'s own tail is a posted `External` site, never - // re-analysed (only the *declaring* file is) — so it is exactly the - // finding-3 shape one file over: the moved span no longer spells - // `sig` and is dropped, an honest omission, not misreported at its - // old line (3) nor invented at its new one (5). - assert!( - single_lines.is_empty(), - "single.sv's own tail moved and is not re-analysed, so it is dropped: {single_lines:?}" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// QA finding 4 (re-check round), fixed. The direction the closed-file - /// guard did not cover: an **open** buffer whose live text no longer - /// declares the name. `leaf.sv` is open with `sig` renamed away - /// (unsaved); the request comes from `single.sv`'s tail, which still - /// resolves to the original `Def`. `declaring_file_uses` declines (the - /// file is open) and the live lookup finds nothing (no symbol is named - /// `sig` in the buffer any more), so the only span left is the - /// index-time one — and `locations` renders an open document with no - /// guard. Before the fix that stale 3-byte span was reported at line 1, - /// columns 8..11: a strict *prefix* of the live token `sig2` (8..12), the - /// very shape `spells_exactly` refuses for a closed file - /// (`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`). - /// `declaration_site` now asks the same question of the live buffer and - /// omits the declaration: `leaf.sv` does not appear at all, and every - /// other location is unchanged. - #[test] - fn qa_recheck_a_renamed_open_buffers_stale_declaration_is_omitted_not_misreported() { - let (dir, ws) = hierarchical("hier_recheck_open_stale", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let leaf_uri = uri_in(&dir, "leaf.sv"); - let (_, one, _) = sig_positions(); - - // Sanity: with the buffer holding its on-disk text, the answer is - // complete, declaration included. - assert_eq!( - places(&references(&ws, &single_uri, one, true)), - every_place_naming_sig(), - "before the rename: the full answer" - ); - - // Rename `sig` away in the live, unsaved `leaf.sv` buffer. The index - // still holds the original `Def` for `sig`, at the same offsets. - let renamed = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - logic sig2; - assign sig2 = clk_i; -endmodule -"; - let mut ws = ws; - ws.set_document(leaf_uri, renamed.to_string()); - - // Asked from `single.sv`'s tail, which still names the original - // declaration by its persisted `Def`. - let after = references(&ws, &single_uri, one, true); - assert_eq!( - places(&after), - vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], - "leaf.sv is honestly omitted — no stale prefix of `sig2` — and the two tails stay: {after:?}" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// The control for the guard above: an open buffer with an unsaved edit - /// **above** the declaration, which still spells `sig` and has only - /// moved. The live-symbol path answers first (`indexed_def_for_symbol` - /// matches logically — path, owner, name, kind — not positionally), so - /// the declaration is reported at its live line and the guard never - /// fires. The index-time span, rendered blind, would have pointed into - /// the header line; dropped by the guard, it would be missing. Either - /// way the live line `3` at `sig`'s own columns is the only right answer, - /// and it is the one the request gives with `includeDeclaration` on and - /// not without it. - #[test] - fn an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line() { - let (dir, ws) = hierarchical("hier_open_edit_above", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let leaf_uri = uri_in(&dir, "leaf.sv"); - let (_, one, _) = sig_positions(); - - let edited = "\ -// pushed -// down -module leaf #(parameter int W = 1) (input logic clk_i); - logic sig; - assign sig = clk_i; -endmodule -"; - let mut ws = ws; - ws.set_document(leaf_uri, edited.to_string()); - - let with = references(&ws, &single_uri, one, true); - let leaf_spans: Vec<(u32, u32, u32)> = with - .iter() - .filter(|l| l.uri.as_str().ends_with("leaf.sv")) - .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) - .collect(); - assert_eq!( - leaf_spans, - vec![(3, 8, 11), (4, 9, 12)], - "the live declaration and the live use, both shifted down two lines: {with:?}" - ); - assert_eq!( - places(&with), - vec![ - ("leaf.sv".to_string(), 3), - ("leaf.sv".to_string(), 4), - ("single.sv".to_string(), 3), - ("top.sv".to_string(), 3), - ], - "and nothing else moved" - ); - - let without = references(&ws, &single_uri, one, false); - assert_eq!( - places(&without), - vec![ - ("leaf.sv".to_string(), 4), - ("single.sv".to_string(), 3), - ("top.sv".to_string(), 3), - ], - "line 3 is the declaration: it goes when includeDeclaration is off" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Re-check (coordinator's follow-up): an escaped port name - /// (`\my-clk `), reachable before §64.1 too (connection surface). The - /// declaration is an index-time span like any port's, so it goes through - /// `closed_locations`'s `spells_exactly` guard — which must recognise the - /// escaped name (backslash and all) rather than silently dropping every - /// closed-file location for it. - #[test] - fn qa_recheck_an_escaped_port_name_survives_the_guard() { - let dir = temp_dir("qa_escaped_port"); - let sub = "module sub (input logic \\my-clk );\nendmodule\n"; - let top = "module top;\n sub u (.\\my-clk (1'b0));\nendmodule\n"; - for (name, text) in [("sub.sv", sub), ("top.sv", top)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top_uri = uri_in(&dir, "top.sv"); - ws.set_document(top_uri.clone(), top.to_string()); - let offset = at(top, "\\my-clk (1'b0)") + 1; - - let found = references(&ws, &top_uri, offset, true); - assert_eq!( - places(&found), - vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], - "sub.sv's declaration must survive the guard, escaped name and all" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Re-check: the hierarchical twin of the escaped-name attack above — an - /// escaped **net**, hierarchical-only, closed declaring file. This one - /// goes through the *re-analysis* path (`declaring_file_uses`) rather - /// than the guard directly, so it is really testing whether the parser - /// and `Semantics::symbols_named` round-trip an escaped name at all - /// under re-analysis. - #[test] - fn qa_recheck_an_escaped_net_survives_the_closed_file_reanalysis() { - let dir = temp_dir("qa_escaped_net"); - let leaf = "module eleaf;\n logic \\my-sig ;\n assign \\my-sig = 1'b0;\nendmodule\n"; - let top = "module etop;\n eleaf u_leaf ();\n wire w;\n assign w = u_leaf.\\my-sig ;\nendmodule\n"; - for (name, text) in [("eleaf.sv", leaf), ("etop.sv", top)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let top_uri = uri_in(&dir, "etop.sv"); - ws.set_document(top_uri.clone(), top.to_string()); - let offset = at(top, "u_leaf.\\my-sig") + 8; - - let found = references(&ws, &top_uri, offset, true); - assert_eq!( - places(&found), - vec![("eleaf.sv".to_string(), 1), ("eleaf.sv".to_string(), 2), ("etop.sv".to_string(), 3)], - "eleaf.sv's declaration and its own use, escaped name and all, via the closed-file repair" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (a), sharpened: an **indexed generate array**, not just a named - /// block. The array index changes how many instances of the scope exist, - /// not which scope `gsig` belongs to — which since TODO §65.1 is exactly - /// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found. - #[test] - fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() { - let dir = temp_dir("qa_generate_for"); - let leaf = "\ -module gfleaf; - for (genvar i = 0; i < 2; i++) begin : gen - wire gsig; - assign gsig = 1'b0; - end -endmodule -"; - let user = - "module gfuser;\n gfleaf u_g ();\n wire z;\n assign z = u_g.gen[0].gsig;\nendmodule\n"; - for (name, text) in [("gfleaf.sv", leaf), ("gfuser.sv", user)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let leaf_uri = uri_in(&dir, "gfleaf.sv"); - ws.set_document(leaf_uri.clone(), leaf.to_string()); - let user_uri = uri_in(&dir, "gfuser.sv"); - ws.set_document(user_uri, user.to_string()); - - let decl = at(leaf, "wire gsig") + 5; - let doc = ws.document(&leaf_uri).expect("open"); - assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too"); - assert_eq!( - places(&references(&ws, &leaf_uri, decl, true)), - vec![ - ("gfleaf.sv".to_string(), 2), - ("gfleaf.sv".to_string(), 3), - ("gfuser.sv".to_string(), 3) - ], - "this file and `u_g.gen[0].gsig`" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// An interface's signal, reached through a virtual-interface handle - /// (`vif.data`) from another file. Interface members are on the - /// **connection** surface already (`hierarchy.rs`, 2026-09-01), so - /// `member_in(…, Hierarchical)` answers exactly what `member` always did - /// — confirmed, not merely assumed unchanged. - #[test] - fn qa_an_interface_signal_through_a_virtual_interface_handle_is_unchanged() { - let dir = temp_dir("qa_interface"); - let iface = "interface bus_if;\n logic data;\nendinterface\n"; - let agent = "\ -class agent; - virtual bus_if vif; - function void f(); - vif.data = 1; - endfunction -endclass -"; - for (name, text) in [("bus_if.sv", iface), ("agent.sv", agent)] { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let iface_uri = uri_in(&dir, "bus_if.sv"); - ws.set_document(iface_uri.clone(), iface.to_string()); - let agent_uri = uri_in(&dir, "agent.sv"); - ws.set_document(agent_uri, agent.to_string()); - - assert_eq!( - places(&references(&ws, &iface_uri, at(iface, "logic data") + 6, true)), - vec![("agent.sv".to_string(), 3), ("bus_if.sv".to_string(), 1)], - "the interface signal, from the declaration" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (k). `documentHighlight` from the declaration and from the bind - /// file's connection: a *document* answer by contract regardless of - /// cross-file reachability (`references-nav`, 2026-08-28) — same-file - /// only, non-empty, unchanged by this lane. - #[test] - fn qa_document_highlight_over_the_bind_fixture_stays_same_file_only() { - let dir = temp_dir("qa_bind_highlight"); - let aes = "module aes (input logic clk_i, output logic idle_o);\n \ - logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; - let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; - let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ - .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; - for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] - { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let aes_uri = uri_in(&dir, "aes.sv"); - ws.set_document(aes_uri.clone(), aes.to_string()); - let bind_uri = uri_in(&dir, "aes_bind.sv"); - ws.set_document(bind_uri.clone(), bind_file.to_string()); - - let decl_doc = ws.document(&aes_uri).expect("open"); - let decl_highlights = document_highlights(decl_doc, at(aes, "entropy_masking_req") + 4) - .expect("highlights from the declaration"); - assert_eq!( - decl_highlights.iter().map(|h| h.range.start.line).collect::>(), - vec![1, 2], - "aes.sv's own two lines, never the bind file" - ); - - let bind_doc = ws.document(&bind_uri).expect("open"); - let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; - let bind_highlights = - document_highlights(bind_doc, expr_offset).expect("highlights from the bind file"); - assert_eq!( - bind_highlights.iter().map(|h| h.range.start.line).collect::>(), - vec![2], - "the bind file's own connection line only, never aes.sv" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (e), completed. `leaf.sv` closed, `top.sv` open: references from - /// the tail already include `leaf.sv`'s own in-file uses (the - /// closed-file repair). Then `leaf.sv` is **opened** with an unsaved - /// edit above the declaration: the answer must reflect the live, - /// shifted spans, not the ones the closed-file repair (or the index) - /// last computed. - #[test] - fn qa_reopening_the_declaring_file_with_an_unsaved_edit_gives_live_spans() { - let (dir, mut ws) = hierarchical("hier_reopen_live", &["top.sv"]); - let top_uri = uri_in(&dir, "top.sv"); - let (_, _, two) = sig_positions(); - - let closed = references(&ws, &top_uri, two, true); - assert_eq!( - places(&closed), - every_place_naming_sig(), - "closed: the repair supplies leaf.sv" - ); - - // Open `leaf.sv` with two lines pushed in above the declaration, - // never saved. - let leaf_uri = uri_in(&dir, "leaf.sv"); - let edited = "\ -// pushed -// down -module leaf #(parameter int W = 1) (input logic clk_i); - logic sig; - assign sig = clk_i; -endmodule -"; - ws.set_document(leaf_uri, edited.to_string()); - - let live = references(&ws, &top_uri, two, true); - let leaf_lines: Vec = live - .iter() - .filter(|l| l.uri.as_str().ends_with("leaf.sv")) - .map(|l| l.range.start.line) - .collect(); - assert_eq!(leaf_lines, vec![3, 4], "the live, shifted spans — not the closed-file ones"); - let _ = fs::remove_dir_all(&dir); - } - - /// Oracle helper: `vlog_refactor::find_references`'s answer, as - /// `(file name, line)` — the same shape `places` gives `references`'s - /// own answer, so the two can be compared directly. - fn oracle_places( - files: &[(PathBuf, String)], - file: &Path, - offset: u32, - include_declaration: bool, - ) -> Vec<(String, u32)> { - let found = vlog_refactor::find_references(files, file, offset, include_declaration) - .expect("the oracle resolves it"); - let mut out: Vec<(String, u32)> = found - .iter() - .map(|(path, span)| { - let text = - files.iter().find(|(p, _)| p == path).map(|(_, t)| t.as_str()).unwrap_or(""); - let line = text[..span.start as usize].matches('\n').count() as u32; - (path.file_name().unwrap().to_string_lossy().to_string(), line) - }) - .collect(); - out.sort(); - out - } - - /// Equivalence with the whole-scope oracle (charter item 4): the plain - /// hierarchical tail. `references` must equal what a rename would edit, - /// now that the indexed path answers this shape at all. - #[test] - fn qa_references_agrees_with_the_rename_oracle_over_a_plain_tail() { - let (dir, ws) = hierarchical("hier_oracle_tail", &["leaf.sv", "single.sv", "top.sv"]); - let leaf_uri = uri_in(&dir, "leaf.sv"); - let (decl, _, _) = sig_positions(); - - let mut got = places(&references(&ws, &leaf_uri, decl, true)); - got.sort(); - - let files: Vec<(PathBuf, String)> = - [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] - .into_iter() - .map(|(name, text)| (dir.join(name), text.to_string())) - .collect(); - let oracle = oracle_places(&files, &dir.join("leaf.sv"), decl, true); - - assert_eq!(got, oracle, "references must equal what a rename would edit"); - let _ = fs::remove_dir_all(&dir); - } - - /// Equivalence with the oracle over the **bind** fixture. - #[test] - fn qa_references_agrees_with_the_rename_oracle_over_the_bind_fixture() { - let dir = temp_dir("qa_oracle_bind"); - let aes = "module aes (input logic clk_i, output logic idle_o);\n \ - logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; - let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; - let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ - .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; - for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] - { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let aes_uri = uri_in(&dir, "aes.sv"); - ws.set_document(aes_uri.clone(), aes.to_string()); - let bind_uri = uri_in(&dir, "aes_bind.sv"); - ws.set_document(bind_uri, bind_file.to_string()); - - let offset = at(aes, "entropy_masking_req"); - let mut got = places(&references(&ws, &aes_uri, offset, true)); - got.sort(); - - let files: Vec<(PathBuf, String)> = - [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] - .into_iter() - .map(|(name, text)| (dir.join(name), text.to_string())) - .collect(); - let oracle = oracle_places(&files, &dir.join("aes.sv"), offset, true); - - assert_eq!(got, oracle, "references must equal what a rename would edit, bind included"); - let _ = fs::remove_dir_all(&dir); - } - - /// Case (h) + equivalence: the **instance name** itself. Does the - /// instance segment of a hierarchical tail count as a reference, and - /// does `references` answer the same set a rename would edit? - #[test] - fn qa_an_instance_names_references_agree_with_the_rename_oracle() { - let (dir, ws) = - hierarchical("hier_oracle_instance", &["leaf.sv", "single.sv", "mid.sv", "top.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let offset = at(SINGLE, "u_leaf"); - - let mut got = places(&references(&ws, &single_uri, offset, true)); - got.sort(); - - let files: Vec<(PathBuf, String)> = - [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] - .into_iter() - .map(|(name, text)| (dir.join(name), text.to_string())) - .collect(); - let oracle = oracle_places(&files, &dir.join("single.sv"), offset, true); - - assert_eq!(got, oracle, "the instance name: same set a rename would edit"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_package_import_resolves_into_the_packages_file() { - let dir = temp_dir("pkg"); - let pkg = dir.join("p_pkg.sv"); - fs::write(&pkg, "package p;\n localparam WIDTH = 8;\nendpackage\n").expect("write"); - let top_path = dir.join("top.sv"); - let top_text = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\nendmodule\n"; - fs::write(&top_path, top_text).expect("write"); - - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), top_text.to_string()); - - let locations = definition(&ws, &uri, at(top_text, "WIDTH-1")); - assert_eq!(locations.len(), 1, "WIDTH is declared in p_pkg.sv"); - assert_eq!(locations[0].uri, path_to_uri(&pkg).expect("uri")); - assert_eq!(locations[0].range.start.line, 1); - - let _ = fs::remove_dir_all(&dir); - } - - // ------------------------------------------------------------------ - // Final QA (2026-09-12): the declaration-site ladder, rung by rung. - // Rung (a) is the control test above; the prefix half of rung (c) is the - // flipped finding-4 test; rungs (e) and (f) with the declaration on are - // `qa_finding_2` and `qa_finding_3`. - // ------------------------------------------------------------------ - - /// The `leaf.sv` spans of an answer as `(line, start col, end col)`. - fn leaf_spans(found: &[Location]) -> Vec<(u32, u32, u32)> { - found - .iter() - .filter(|l| l.uri.as_str().ends_with("leaf.sv")) - .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) - .collect() - } - - /// Rung (b): an open buffer whose live lookup fails while the index-time - /// span still spells the name at the same bytes. `logic sig;` becomes - /// `wire sig;` — one byte longer keyword, one space fewer, so nothing - /// moves — and `logic` is `Var` where `wire` is `Net` (`bind/decl.rs`), - /// so `indexed_def_in_file`'s kind filter rejects the live symbol and the - /// live path finds nothing. The fallback span reads exactly `sig` at line - /// 1, columns 8..11, and is emitted; the buffer's own use resolves to the - /// rejected live symbol and is (consistently) not listed; and with - /// `includeDeclaration: false` the fallback is never consulted. - #[test] - fn qa_final_b_a_failed_live_lookup_with_the_name_still_in_place_emits_the_index_span() { - let (dir, mut ws) = hierarchical("hier_final_b", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, one, _) = sig_positions(); - let rekinded = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - wire sig; - assign sig = clk_i; -endmodule -"; - assert_eq!(at(rekinded, "sig;"), at(LEAF, "sig;"), "the edit moves nothing"); - ws.set_document(uri_in(&dir, "leaf.sv"), rekinded.to_string()); - - let with = references(&ws, &single_uri, one, true); - assert_eq!( - leaf_spans(&with), - vec![(1, 8, 11)], - "the index-time span, still `sig`: {with:?}" - ); - assert_eq!( - places(&with), - vec![ - ("leaf.sv".to_string(), 1), - ("single.sv".to_string(), 3), - ("top.sv".to_string(), 3) - ], - "nothing else changes" - ); - let without = references(&ws, &single_uri, one, false); - assert_eq!( - places(&without), - vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], - "includeDeclaration: false never reaches the fallback" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Rung (c), the suffix half: `logic sig;` becomes `wire _sig;`, so bytes - /// 8..11 of line 1 still read `sig` but the byte before them is `_`, a - /// name character. No live symbol is named `sig`, the fallback is a - /// suffix of `_sig`, and `spells_exactly` refuses it: `leaf.sv` is absent. - #[test] - fn qa_final_c_an_index_span_now_a_suffix_of_a_longer_live_name_is_dropped() { - let (dir, mut ws) = hierarchical("hier_final_c", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, one, _) = sig_positions(); - let suffixed = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - wire _sig; - assign _sig = clk_i; -endmodule -"; - let o = at(LEAF, "sig;") as usize; - assert_eq!(&suffixed[o..o + 3], "sig", "the old bytes still read `sig`"); - assert_eq!(&suffixed[o - 1..o], "_", "as the tail of `_sig`"); - ws.set_document(uri_in(&dir, "leaf.sv"), suffixed.to_string()); - - let after = references(&ws, &single_uri, one, true); - assert_eq!( - places(&after), - vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], - "a suffix match is a miss: {after:?}" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Rung (d): the index-time span starts inside a multi-byte character of - /// the live text. Line 1 becomes a comment of two four-byte emoji placed - /// so the span's start byte is the last byte of the first one, and the - /// declaration below is renamed away so the live path finds nothing. - /// `spells_exactly` slices with `str::get`, which is `None` off a - /// boundary: no panic, and `leaf.sv` is omitted. - #[test] - fn qa_final_d_an_open_buffers_span_off_a_utf8_boundary_is_dropped_without_a_panic() { - let (dir, mut ws) = hierarchical("hier_final_d", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, one, _) = sig_positions(); - let emoji = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - // \u{1F642}\u{1F642} - logic sig2; - assign sig2 = clk_i; -endmodule -"; - let o = at(LEAF, "sig;") as usize; - assert!(!emoji.is_char_boundary(o), "the span starts mid-character"); - ws.set_document(uri_in(&dir, "leaf.sv"), emoji.to_string()); - - let after = references(&ws, &single_uri, one, true); - assert_eq!( - places(&after), - vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], - "off a boundary is a miss, not a panic: {after:?}" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// Rung (g) on the closed rungs: `includeDeclaration: false` emits no - /// declaration whether the closed declaring file is re-analysed (rung (e), - /// a hierarchical-only net, its live declaration known) or postings-only - /// (rung (f), a port, its index-time span guarded once) — before and - /// after a disk edit that moves the declaration. The open rungs are pinned - /// the same way by the control test and by rung (b). - #[test] - fn qa_final_g_include_declaration_false_emits_no_declaration_on_the_closed_rungs() { - let (dir, ws) = hierarchical("hier_final_g", &["single.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, sig, _) = sig_positions(); - let clk = at(SINGLE, ".clk_i(1'b0)") + 1; - - assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![2]); - assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), vec![2]); - - fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); - // (e): the re-analysis knows the live declaration (4) and the live - // use (5); without the declaration only the use is left. - assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, true)), vec![4, 5]); - assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![5]); - // (f): the header's port survives its guard (0); the moved use does - // not; without the declaration nothing in `leaf.sv` is left. - assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, true)), vec![0]); - assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), Vec::::new()); - let _ = fs::remove_dir_all(&dir); - } - - /// Observation, pinned rather than argued: the fallback is a textual - /// claim, on an open buffer exactly as on a closed file. A buffer whose - /// declaration is gone but where a *different* `sig` — here an undeclared - /// gate output — now sits at the very same bytes is reported as the - /// declaration. The token is a whole, exact `sig`, so `spells_exactly` - /// is right to accept it; whether that occurrence *is* the declaration is - /// a question the guard was never meant to answer, and the lead's to rule - /// on. - #[test] - fn qa_final_observation_a_different_exact_sig_at_the_old_bytes_is_reported() { - let (dir, mut ws) = hierarchical("hier_final_obs", &["single.sv", "leaf.sv"]); - let single_uri = uri_in(&dir, "single.sv"); - let (_, one, _) = sig_positions(); - let reused = "\ -module leaf #(parameter int W = 1) (input logic clk_i); - buf b(sig, clk_i); -endmodule -"; - let o = at(LEAF, "sig;") as usize; - assert_eq!(&reused[o..o + 3], "sig"); - assert_eq!(&reused[o - 1..o + 4], "(sig,"); - ws.set_document(uri_in(&dir, "leaf.sv"), reused.to_string()); - - let after = references(&ws, &single_uri, one, true); - assert_eq!(leaf_spans(&after), vec![(1, 8, 11)], "{after:?}"); - let _ = fs::remove_dir_all(&dir); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/nav/tests.rs b/crates/lucisv_server/src/nav/tests.rs new file mode 100644 index 0000000..c5c780a --- /dev/null +++ b/crates/lucisv_server/src/nav/tests.rs @@ -0,0 +1,2668 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::perf::mean; +use std::fs; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +fn document(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) +} + +/// The byte offset of the first occurrence of `needle` in `text`. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lucisv_server_nav_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir +} + +#[test] +fn a_use_jumps_to_its_declaration_in_the_same_file() { + let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let offset = at(text, "assign a") + 7; + let locations = definition(&ws, &uri, offset); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].range.start.line, 1, "the `wire a;` line"); + assert_eq!(locations[0].range.start.character, 7); +} + +#[test] +fn the_cursor_on_a_declaration_resolves_to_itself() { + let text = "module m;\n wire a;\nendmodule\n"; + let (ws, uri) = document(text); + let locations = definition(&ws, &uri, at(text, "wire a") + 5); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].range.start.line, 1); +} + +/// A qualified type name is two references, each addressable on its own +/// half: the parser spans `pkg::t` and `DataType::segments` splits it, so +/// F12 on the *item* lands on the typedef rather than on the package. +#[test] +fn a_scoped_type_name_jumps_from_its_item_half() { + let text = "\ +package pkg; + typedef logic [1:0] t; +endpackage +module m; + pkg::t x; +endmodule +"; + let (ws, uri) = document(text); + let item = definition(&ws, &uri, at(text, "pkg::t x") + 5); + assert_eq!(item.len(), 1, "the typedef"); + assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line"); + assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword"); + let unit = definition(&ws, &uri, at(text, "pkg::t x")); + assert_eq!(unit.len(), 1, "the package"); + assert_eq!(unit[0].range.start.line, 0); +} + +/// `bus_if.mp bus` — the interface is the type, so the head range is what +/// F12 answers from; the modport tail is a member of it. +#[test] +fn an_interface_port_type_jumps_from_its_head() { + let text = "\ +interface bus_if; + logic clk; + modport mp (input clk); +endinterface +module m (bus_if.mp bus); +endmodule +"; + let (ws, uri) = document(text); + let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2); + assert_eq!(head.len(), 1, "the interface"); + assert_eq!(head[0].range.start.line, 0); + assert_eq!(head[0].range.start.character, 10, "the interface name"); + let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7); + assert_eq!(tail.len(), 1, "the modport"); + assert_eq!(tail[0].range.start.line, 2); +} + +#[test] +fn a_macro_use_jumps_to_its_define_in_the_same_file() { + let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let locations = definition(&ws, &uri, at(text, "`WIDTH-1") + 2); + assert_eq!(locations.len(), 1, "the `define` this file wrote"); + assert_eq!(locations[0].range.start.line, 0); + assert_eq!(locations[0].range.start.character, 8, "the name, not the backtick"); +} + +#[test] +fn a_macro_nothing_defines_has_no_definition() { + // `uvm_info` with no UVM in the index: the same empty answer a name + // nothing declares gets, and no invented location. + let text = "module m;\n initial `uvm_info(\"x\", \"y\", UVM_LOW)\nendmodule\n"; + let (ws, uri) = document(text); + assert!(definition(&ws, &uri, at(text, "`uvm_info") + 2).is_empty()); +} + +#[test] +fn a_macro_use_jumps_across_files_to_the_define() { + let dir = temp_dir("macro_xfile"); + fs::write(dir.join("defs.svh"), "`define BUS_W 32\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n logic [`BUS_W-1:0] bus;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`BUS_W") + 2); + assert_eq!(locations.len(), 1, "the one file that defines it"); + assert!(locations[0].uri.as_str().ends_with("defs.svh"), "{:?}", locations[0].uri); + assert_eq!(locations[0].range.start.line, 0); +} + +#[test] +fn two_defines_of_one_macro_are_narrowed_by_the_include_graph() { + let dir = temp_dir("macro_narrow"); + fs::write(dir.join("a.svh"), "`define MODE 1\n").expect("write"); + fs::write(dir.join("b.svh"), "`define MODE 2\n").expect("write"); + let top_path = dir.join("top.sv"); + // Only `a.svh` is reachable from this file, so only its definition is + // offered — the narrowing `hover` already does, shared. + let top_text = "`include \"a.svh\"\nmodule top;\n logic [`MODE:0] m;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`MODE:0") + 2); + assert_eq!(locations.len(), 1, "the include graph picks one: {locations:?}"); + assert!(locations[0].uri.as_str().ends_with("a.svh"), "{:?}", locations[0].uri); +} + +#[test] +fn a_define_inside_a_fragment_file_is_still_a_jump_target() { + // A `.svh` that is a *fragment* — no module, no package — is indexed + // for its defines like any other file (`fragment-mode`). + let dir = temp_dir("macro_fragment"); + fs::write(dir.join("frag.svh"), "CUSTOM_1,\n`define TAIL 7\nCUSTOM_2\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n logic [`TAIL:0] t;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`TAIL") + 2); + assert_eq!(locations.len(), 1, "the fragment's define: {locations:?}"); + assert!(locations[0].uri.as_str().ends_with("frag.svh"), "{:?}", locations[0].uri); + assert_eq!(locations[0].range.start.line, 1); +} + +#[test] +fn a_name_nothing_declares_has_no_definition() { + let text = "module m;\n assign x = 1;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(definition(&ws, &uri, at(text, "x")).is_empty()); +} + +#[test] +fn references_finds_every_use_and_honors_include_declaration() { + let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + let (ws, uri) = document(text); + let offset = at(text, "wire a") + 5; + + let without = references(&ws, &uri, offset, false); + assert_eq!(without.len(), 2, "two uses"); + assert_eq!(without[0].range.start.line, 2); + assert_eq!(without[1].range.start.line, 3); + + let with = references(&ws, &uri, offset, true); + assert_eq!(with.len(), 3, "the declaration is added"); + assert_eq!(with[0].range.start.line, 1, "declaration sorts first"); +} + +#[test] +fn references_work_from_a_use_as_well_as_from_the_declaration() { + let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + let (ws, uri) = document(text); + let from_use = references(&ws, &uri, at(text, "assign a") + 7, false); + assert_eq!(from_use.len(), 2); +} + +#[test] +fn reference_positions_are_utf16() { + let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let locations = references(&ws, &uri, at(text, "wire a") + 5, false); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].range.start.character, 9); + assert_eq!(locations[0].range.end.character, 10); +} + +#[test] +fn an_instantiation_jumps_into_another_file() { + let dir = temp_dir("xfile"); + let sub = dir.join("sub.sv"); + fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "sub u_sub")); + assert_eq!(locations.len(), 1, "the module in sub.sv"); + assert_eq!(locations[0].uri, path_to_uri(&sub).expect("uri")); + assert_eq!(locations[0].range.start.line, 0); + assert_eq!(locations[0].range.start.character, 7, "the name `sub`"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_cross_file_definition_reads_no_file() { + // The jump above, asked again for what it *costs*: the target module's + // range is in the index (`DeclPositions`), so nothing opens `sub.sv`. + // Pinned through the view cache, which is where a read would land. + let dir = temp_dir("no_read"); + let sub = dir.join("sub.sv"); + fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "sub u_sub")); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer"); + assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views()); + + // `workspace/symbol` answers the same way, over the same index. + let hits = crate::symbols::workspace_symbols(&ws, "sub"); + assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}"); + assert!(ws.held_views().is_empty(), "nor did the symbol search"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_ambiguous_workspace_name_returns_every_location() { + let dir = temp_dir("ambig"); + for name in ["a.sv", "b.sv"] { + fs::write(dir.join(name), "module dup;\nendmodule\n").expect("write"); + } + let top_path = dir.join("top.sv"); + let top_text = "module top;\n dup u (.*);\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "dup u")); + assert_eq!(locations.len(), 2, "both declarations, not a guess"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_include_line_jumps_into_the_file_it_names() { + // Go-to-definition's third case, and the one that answers where the + // other two have no identifier to work with. + let dir = temp_dir("include"); + let defs = dir.join("defs.svh"); + fs::write(&defs, "`define W 8\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \"defs.svh\"\nmodule top;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "defs.svh")); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].uri, path_to_uri(&defs).expect("uri")); + assert_eq!(locations[0].range.start.line, 0, "the top of the included file"); + assert_eq!(locations[0].range.end.character, 0); + + // And a cursor on the module below is unaffected by any of this. + assert!(definition(&ws, &uri, at(top_text, "module top") + 7).len() == 1); + + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// cross-file references +// ------------------------------------------------------------------ + +const SUB: &str = "module sub (input logic clk);\nendmodule\n"; +const TOP: &str = "module top;\n sub u_a (.clk(1'b0));\n sub u_b (.clk(1'b1));\nendmodule\n"; +const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n"; + +/// A three-file workspace, with `which` opened as a buffer. +fn instantiated(tag: &str, which: &str) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in [("sub.sv", SUB), ("top.sv", TOP), ("other.sv", OTHER)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let path = dir.join(which); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri.clone(), text); + (dir, ws, uri) +} + +/// Every location as `(file name, line)`. +fn places(locations: &[Location]) -> Vec<(String, u32)> { + locations + .iter() + .map(|l| { + let name = l.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(); + (name, l.range.start.line) + }) + .collect() +} + +#[test] +fn a_modules_references_come_from_every_file_that_instantiates_it() { + let (dir, ws, uri) = instantiated("xrefs_decl", "sub.sv"); + let found = references(&ws, &uri, at(SUB, "sub"), true); + assert_eq!( + places(&found), + vec![ + ("other.sv".to_string(), 1), + ("sub.sv".to_string(), 0), + ("top.sv".to_string(), 1), + ("top.sv".to_string(), 2), + ], + "the declaration plus three instantiations" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn references_from_an_instantiation_answer_the_same_set() { + let (dir, ws, uri) = instantiated("xrefs_use", "top.sv"); + let found = references(&ws, &uri, at(TOP, "sub u_b"), true); + assert_eq!( + places(&found), + vec![ + ("other.sv".to_string(), 1), + ("sub.sv".to_string(), 0), + ("top.sv".to_string(), 1), + ("top.sv".to_string(), 2), + ], + "renaming from here would touch exactly these" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn indexed_references_equal_the_refactor_walk_they_replace() { + let (dir, ws, uri) = instantiated("xrefs_equivalence", "top.sv"); + let offset = at(TOP, "sub u_b"); + let indexed = references(&ws, &uri, offset, true); + let path = dir.join("top.sv"); + let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true) + .expect("the existing refactor walk answers"); + // The oracle's spans are walked over the current texts of the very + // files it read, so there is no index-time claim to guard. + let walked = locations(&ws, walked, None); + + assert_eq!(indexed, walked); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() { + // A harder equivalence case than the one above: `W` is a module (a + // *unit*, filed in `units`) and, spelled identically, a package + // member (filed in `members`) — the prefilter's one string compare + // must not let either bucket answer for the other. `top.sv` is also + // edited live after opening, so the overlay's answer has to come from + // the unsaved buffer, not the file `find_references`'s own oracle + // would otherwise re-read from disk. + let dir = temp_dir("xrefs_equivalence_unit_and_member"); + let w_mod = "module W;\nendmodule\n"; + let w_pkg = "package p;\n localparam W = 4;\nendpackage\n"; + let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n"; + for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri"); + // An unsaved edit: a second live instantiation of `W`, not yet saved. + let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n"; + ws.set_document(top_uri, top_live.to_string()); + let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri"); + ws.set_document(w_uri.clone(), w_mod.to_string()); + let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri"); + ws.set_document(p_uri.clone(), w_pkg.to_string()); + + // The module `W`: its declaration and both live instantiations, never + // the package member spelled the same way. + let module_offset = at(w_mod, "W"); + let indexed_module = references(&ws, &w_uri, module_offset, true); + let walked_module = + vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true) + .expect("the walk answers"); + assert_eq!(indexed_module, locations(&ws, walked_module, None)); + assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member"); + + // The package member `W`: its declaration and the one qualified use, + // never the module. + let member_offset = at(w_pkg, "W"); + let indexed_member = references(&ws, &p_uri, member_offset, true); + let walked_member = + vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true) + .expect("the walk answers"); + assert_eq!(indexed_member, locations(&ws, walked_member, None)); + assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +#[ignore = "manual indexed-navigation latency probe"] +fn qa_indexed_references_latency_over_a_large_workspace() { + let dir = temp_dir("xrefs_latency"); + let sub_path = dir.join("sub.sv"); + fs::write(&sub_path, SUB).expect("write declaration"); + for i in 0..4 { + fs::write( + dir.join(format!("use_{i}.sv")), + format!("module use_{i}; sub u (); endmodule\n"), + ) + .expect("write use"); + } + for i in 0..815 { + fs::write( + dir.join(format!("unrelated_{i}.sv")), + format!("module unrelated_{i}; logic signal_{i}; endmodule\n"), + ) + .expect("write unrelated source"); + } + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&sub_path).expect("uri"); + ws.set_document(uri.clone(), SUB.to_string()); + assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); + + let requests = 200; + let start = std::time::Instant::now(); + for _ in 0..requests { + assert_eq!(references(&ws, &uri, at(SUB, "sub"), true).len(), 5); + } + let indexed = start.elapsed(); + + let start = std::time::Instant::now(); + let walked = vlog_refactor::find_references(&ws.sources(), &sub_path, at(SUB, "sub"), true) + .expect("old walk"); + let old = start.elapsed(); + assert_eq!(walked.len(), 5); + eprintln!( + "indexed references: {:.3} ms/request over 820 files; old walk: {:.3} ms/request", + indexed.as_secs_f64() * 1_000.0 / f64::from(requests), + old.as_secs_f64() * 1_000.0, + ); + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// latency probes for a big open buffer +// +// `#[ignore]`d, asserting nothing about duration — the house shape from +// `perf.rs`, whose `mean` they borrow so every number in this repo is +// taken the same way. The numbers they print are recorded in +// `docs/features/references-nav/README.md`. +// +// cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \ +// --nocapture --test-threads=1 +// ------------------------------------------------------------------ + +/// A declaration small enough that nothing about it is the measurement. +const PROBE_SUB: &str = "module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n"; + +/// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an +/// assign, a register and its update — then `instances` instantiations of +/// `sub`. Every block declares two names and uses four, so ten thousand +/// blocks is a forty-thousand-line file carrying tens of thousands of +/// locally resolved references: exactly the buffer the open-document +/// overlay in `indexed_references` has to walk past to answer anything. +/// +/// One `acc` is used by every block, so the file also carries a *local* +/// name with thousands of occurrences — the worst case for the in-file +/// fallback, which converts one span at a time. +/// +/// Its own generator rather than `perf::generated_module`'s, because that +/// one instantiates nothing and a probe about instantiations needs some. +fn generated_top(blocks: usize, instances: usize) -> String { + let mut src = String::from( + "module top (\n input logic clk,\n input logic rst_n,\n \ + input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \ + wire acc;\n assign acc = rst_n;\n", + ); + for n in 0..blocks { + src.push_str(&format!( + " wire [31:0] w_{n};\n \ + assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \ + reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n" + )); + } + for n in 0..instances { + src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n")); + } + src.push_str(" assign data_out = data_in;\nendmodule\n"); + src +} + +/// Both directions of a cross-file references request, with a big buffer +/// open — the owner's report of 2026-08-28, measured. +#[test] +#[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"] +fn qa_references_latency_with_a_big_open_top() { + use std::hint::black_box; + + let dir = temp_dir("refs_big_top"); + let top_text = generated_top(10_000, 4); + let sub_path = dir.join("sub.sv"); + let top_path = dir.join("top.sv"); + fs::write(&sub_path, PROBE_SUB).expect("write"); + fs::write(&top_path, &top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = path_to_uri(&top_path).expect("uri"); + let sub_uri = path_to_uri(&sub_path).expect("uri"); + ws.set_document(top_uri.clone(), top_text.clone()); + ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); + + let use_site = at(&top_text, "sub u_0"); + let declaration = at(PROBE_SUB, "sub"); + let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3; + let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4; + let references_in_top = + ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open"); + + // The answers, before any timing: a measurement of a request that + // answered nothing is worthless. + assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances"); + assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five"); + assert_eq!(definition(&ws, &top_uri, use_site).len(), 1); + assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only"); + assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere"); + + let runs = 20; + let from_use = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(use_site), true)); + }); + let from_declaration = mean(runs, || { + black_box(references(&ws, &sub_uri, black_box(declaration), true)); + }); + let to_definition = mean(runs, || { + black_box(definition(&ws, &top_uri, black_box(use_site))); + }); + let in_file = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(local), true)); + }); + let in_file_common = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(common), true)); + }); + let highlights = mean(runs, || { + let doc = ws.document(&top_uri).expect("open"); + black_box(document_highlights(doc, black_box(common))); + }); + + eprintln!( + "big open top ({} KB, {references_in_top} references): \ + references from the use site {from_use:?}, \ + from the declaration {from_declaration:?}, \ + definition from the use site {to_definition:?}, \ + references on a local wire used 3× (the in-file fallback) {in_file:?}, \ + on one used 10 001× {in_file_common:?}, \ + documentHighlight on that one {highlights:?}", + top_text.len() / 1000, + ); + let _ = fs::remove_dir_all(&dir); +} + +/// The other half of the owner's report: what jumping *into* a file costs +/// when the folder it lives in was not in the index's scope yet. +#[test] +#[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"] +fn qa_didopen_latency_when_a_new_folder_widens_the_scope() { + use std::hint::black_box; + + let dir = temp_dir("didopen_scope"); + fs::create_dir_all(dir.join("rtl")).expect("rtl dir"); + fs::create_dir_all(dir.join("lib")).expect("lib dir"); + for n in 0..400 { + fs::write( + dir.join("rtl").join(format!("m{n}.sv")), + format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"), + ) + .expect("write"); + } + fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write"); + let top_text = generated_top(10_000, 4); + let top_path = dir.join("rtl").join("top.sv"); + fs::write(&top_path, &top_text).expect("write"); + + // The default rung: the folder scope. Nothing is in scope until a + // buffer is opened, so the first `didOpen` is itself a widening. + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let top_uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(top_uri.clone(), top_text.clone()); + ws.rebuild_index(); + let covered = ws.index().files().len(); + + // A `didOpen` the scope already covers: one `Document::new` and a + // publish, and `server.rs` runs no rescan at all. + let sibling = dir.join("rtl").join("m0.sv"); + let sibling_uri = path_to_uri(&sibling).expect("uri"); + let sibling_text = fs::read_to_string(&sibling).expect("read"); + let inside = mean(20, || { + ws.set_document(sibling_uri.clone(), sibling_text.clone()); + }); + + // A `didOpen` in a folder the scope does not cover: the same + // `Document::new`, and then the whole rescan `server.rs` runs when + // `scope_dirs()` moved — which re-reads and re-parses every file in + // the widened scope. Until 2026-08-28 the open big buffer was one of + // them; it now goes in from the analysis it already holds, which is + // what the last two pairs of numbers below are about + // (`docs/features/index-scope/README.md`). + let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri"); + let widening = mean(5, || { + ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); + black_box(ws.rebuild_index()); + }); + let rescan = mean(5, || { + black_box(ws.rebuild_index()); + }); + // Where the buffer's share goes, on the same buffer: what a rescan + // used to pay for one open file — a whole parse for the index facts, + // then a second lex for the completion words — against what it pays + // since 2026-08-28, which is the two walks over the analysis and the + // token stream the buffer already holds. + let (reparse, reused, relex, rewords) = { + let doc = ws.document(&top_uri).expect("open"); + ( + mean(3, || { + black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text)); + }), + mean(3, || { + black_box(doc.facts(top_path.clone())); + }), + mean(3, || { + let tokens = vlog_parser::tokenize(&top_text).expect("it lexes"); + black_box(crate::candidates::words_of_tokens(&tokens)); + }), + mean(3, || { + black_box(doc.words()); + }), + ) + }; + + // The same rescan with the big buffer closed, so its share of the + // rescan is a subtraction rather than a guess. + ws.close_document(&top_uri); + let without = mean(5, || { + black_box(ws.rebuild_index()); + }); + + eprintln!( + "didOpen with a {} KB buffer already open, {covered} files in scope: \ + a file the scope already covers {inside:?}; \ + one in a new folder (didOpen + rescan) {widening:?}; \ + the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \ + That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \ + words {relex:?} re-lexed vs {rewords:?} reused", + top_text.len() / 1000, + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn include_declaration_drops_the_declaration_and_nothing_else() { + let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv"); + let found = references(&ws, &uri, at(SUB, "sub"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_package_members_references_come_from_every_import_site() { + let dir = temp_dir("xrefs_pkg"); + let pkg = "package p;\n localparam WIDTH = 8;\nendpackage\n"; + let a = "module a;\n import p::*;\n wire [WIDTH-1:0] x;\nendmodule\n"; + let b = "module b;\n wire [p::WIDTH-1:0] y;\nendmodule\n"; + for (name, text) in [("p.sv", pkg), ("a.sv", a), ("b.sv", b)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&dir.join("p.sv")).expect("uri"); + ws.set_document(uri.clone(), pkg.to_string()); + + let found = references(&ws, &uri, at(pkg, "WIDTH"), false); + assert_eq!(places(&found), vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1)]); + + // And from one of the use sites, the same answer plus the declaration. + let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); + ws.set_document(a_uri.clone(), a.to_string()); + let from_use = references(&ws, &a_uri, at(a, "WIDTH-1"), true); + assert_eq!( + places(&from_use), + vec![("a.sv".to_string(), 2), ("b.sv".to_string(), 1), ("p.sv".to_string(), 1)] + ); + let _ = fs::remove_dir_all(&dir); +} + +/// The gate, asserted directly. Since §64.1 a module's net **is** a name +/// another file can spell (`u_m.a`), so the gate admits it — that +/// assertion flipped, and the two truths this test was written to protect +/// did not: +/// +/// * `other.sv`'s own `a` is a different signal and is never listed; +/// * a name the index holds **nowhere** still never asks the workspace — +/// a generate-block-scoped net, whose scope is the block's and not the +/// module's, and an undeclared `b`, which is no symbol at all. +/// +/// And the cost argument is unchanged, which is why the gate is still +/// worth having: admitting a name buys two map probes plus the +/// name-prefiltered pass over the *open* buffers, and never a project +/// read. What the gate saves is those probes for every name that could +/// not have left the file anyway. +#[test] +fn a_local_signal_never_asks_the_workspace() { + let dir = temp_dir("xrefs_local"); + let text = "\ +module m; + wire a; + assign a = 1; + assign b = a; + if (1) begin : g + wire gen_only; + assign gen_only = a; + end +endmodule +"; + fs::write(dir.join("m.sv"), text).expect("write"); + fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&dir.join("m.sv")).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let doc = ws.document(&uri).expect("open"); + + assert!( + leaves_this_file(&ws, doc, at(text, "wire a") + 5), + "a module's net is on its hierarchical surface, so `u_m.a` could name it" + ); + assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit"); + assert!( + leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5), + "and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`" + ); + assert!( + !leaves_this_file(&ws, doc, at(text, "assign b") + 7), + "and an undeclared name is no symbol at all" + ); + + let found = references(&ws, &uri, at(text, "wire a") + 5, true); + assert_eq!( + places(&found), + vec![ + ("m.sv".to_string(), 1), + ("m.sv".to_string(), 2), + ("m.sv".to_string(), 3), + ("m.sv".to_string(), 6), + ], + "this file only — `other.sv`'s own `a` is a different signal" + ); + // No file was read to answer that: `other.sv` holds a same-named net + // and was never opened, which `held_views` is the witness for. + assert!(ws.held_views().is_empty(), "no project read: {:?}", ws.held_views()); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_name_declared_in_two_files_degrades_references_to_the_in_file_answer() { + // The gate says yes (the index holds `dup` as a unit), but the + // collection refuses it as ambiguous — exactly like a rename would. + // `references` is read-only, so it falls back to what this file + // alone can say, rather than an empty list or a protocol error. + let dir = temp_dir("xrefs_ambiguous"); + let text = "module dup;\n wire w;\nendmodule\n"; + fs::write(dir.join("a.sv"), text).expect("write"); + fs::write(dir.join("b.sv"), text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let a_path = dir.join("a.sv"); + let uri = path_to_uri(&a_path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let doc = ws.document(&uri).expect("open"); + + assert!(leaves_this_file(&ws, doc, at(text, "dup")), "dup is a unit the index holds"); + + let found = references(&ws, &uri, at(text, "dup"), true); + assert_eq!(found.len(), 1, "the in-file declaration only, not empty and not an error"); + assert_eq!(found[0].uri, uri); + assert_eq!(found[0].range.start.line, 0); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_port_is_reachable_from_a_connection_in_another_file() { + // A module's ports are exactly what the index exports for it, so a + // `.clk(...)` connection elsewhere is a reference to this port. + let (dir, ws, uri) = instantiated("xrefs_port", "sub.sv"); + let found = references(&ws, &uri, at(SUB, "clk"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 1), ("top.sv".to_string(), 2),] + ); + let _ = fs::remove_dir_all(&dir); +} + +/// TODO §63.1 QA, closed by §64.1. A `bind`'s connection expressions +/// elaborate in the target's scope (IEEE 1800 §23.11), and the index +/// records that reach on the target's hierarchical surface +/// (`resolve::in_bind_target`, `FACTS_FORMAT` 20). `definition` from the +/// bind file's expression half jumps to the target's net, never to +/// `aes_reseed_if`'s `.port` half of the same name — the overlay's +/// `Resolution::ExternalCandidate` carries the real `Def` straight +/// through, unremapped. +/// +/// `references` now sees it from **both** directions. It could not until +/// `leaves_this_file` and `indexed_def_in_file` stopped asking +/// `WorkspaceIndex::member` — the *connection* surface, ports and +/// parameters — about a declaration that lives on the **hierarchical** +/// surface only (`workspace/hierarchy.rs`, 2026-09-05). The two locations +/// this test was written to demand are the ones it asserts now: the bind +/// file's expression half seen from the declaration, and `aes.sv`'s own +/// `assign idle_o = entropy_masking_req;` seen from the bind file. The +/// same fix serves a plain (non-`bind`) tail, which was never a +/// bind-specific hole — see +/// `a_hierarchical_nets_references_reach_every_file_that_names_it`. +#[test] +fn a_binds_connection_expression_is_reachable_by_definition_and_by_references() { + let dir = temp_dir("xrefs_bind_wire"); + let aes = "module aes (input logic clk_i, output logic idle_o);\n \ + logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; + let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; + let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ + .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; + for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let aes_uri = path_to_uri(&dir.join("aes.sv")).expect("uri"); + ws.set_document(aes_uri.clone(), aes.to_string()); + let bind_uri = path_to_uri(&dir.join("aes_bind.sv")).expect("uri"); + ws.set_document(bind_uri.clone(), bind_file.to_string()); + + // The expression half's `definition` is the target's net, not the + // checker's `.port` of the same name. + let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; + let locations = definition(&ws, &bind_uri, expr_offset); + assert_eq!( + places(&locations), + vec![("aes.sv".to_string(), 1)], + "the expression half names `aes`'s net: {locations:?}" + ); + + // Both directions answer one set: the declaration, `aes.sv`'s own use + // of it, and the bind file's expression half. + let everywhere = + vec![("aes.sv".to_string(), 1), ("aes.sv".to_string(), 2), ("aes_bind.sv".to_string(), 2)]; + let found = references(&ws, &aes_uri, at(aes, "entropy_masking_req"), true); + assert_eq!(places(&found), everywhere, "from the declaration: {found:?}"); + let from_bind = references(&ws, &bind_uri, expr_offset, true); + assert_eq!(places(&from_bind), everywhere, "from the bind file: {from_bind:?}"); + + // And with `aes.sv` closed, which is how a DV engineer reads a bind + // file: its own in-file use comes from the one re-analysis + // `declaring_file_uses` runs, not from a posting that does not exist. + ws.close_document(&aes_uri); + let closed = references(&ws, &bind_uri, expr_offset, true); + assert_eq!(places(&closed), everywhere, "with the declaring file shut: {closed:?}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() { + // The name prefilter's risk case, asserted from both sides: two + // modules declare a port `clk`, both files are open, and each port's + // references are its own. A prefilter that let a spelling stand in for + // an identity would merge these two answers. + let dir = temp_dir("xrefs_same_name"); + let sub = "module sub (input logic clk);\nendmodule\n"; + let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n"; + let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n"; + for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let mut uri_of = |name: &str, text: &str| { + let uri = path_to_uri(&dir.join(name)).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + uri + }; + let sub_uri = uri_of("sub.sv", sub); + uri_of("top.sv", top); + let other_uri = uri_of("other.sv", other); + + assert_eq!( + places(&references(&ws, &sub_uri, at(sub, "clk"), true)), + vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], + "`sub`'s port: its declaration and the connection to it" + ); + assert_eq!( + places(&references(&ws, &other_uri, at(other, "clk"), true)), + vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)], + "`other`'s port: its declaration and its own use" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn two_packages_declaring_one_name_keep_their_references_apart() { + // The same attack through the member table rather than the port table: + // `p::WIDTH` and `q::WIDTH` spell one name and are two declarations, + // and the file using both is open. + let dir = temp_dir("xrefs_two_packages"); + let p = "package p;\n localparam WIDTH = 8;\nendpackage\n"; + let q = "package q;\n localparam WIDTH = 16;\nendpackage\n"; + let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n"; + for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); + ws.set_document(a_uri.clone(), a.to_string()); + let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri"); + ws.set_document(p_uri.clone(), p.to_string()); + + assert_eq!( + places(&references(&ws, &p_uri, at(p, "WIDTH"), true)), + vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)], + "`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol" + ); + // And from the use side, the same set. + assert_eq!( + places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)), + vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)] + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn every_in_file_occurrence_is_converted_against_its_own_line() { + // The in-file fallback converts its spans with one walker now. A + // walker handed an out-of-order span answers a stale column, so the + // shape that would catch it: many occurrences, each on a line with a + // wide character before it, plus one on the same line as another. + let mut text = String::from("module m;\n wire a;\n"); + for n in 0..20 { + text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n")); + } + text.push_str("endmodule\n"); + let (ws, uri) = document(&text); + let found = references(&ws, &uri, at(&text, "wire a") + 5, true); + assert_eq!(found.len(), 41, "the declaration and two uses per block"); + + let doc = ws.document(&uri).expect("open"); + let positions = doc.positions(); + for location in &found { + let line = location.range.start.line as usize; + let offset = positions.offset(location.range.start); + assert_eq!( + text.get(offset as usize..offset as usize + 1), + Some("a"), + "line {line} must point at the name" + ); + assert_eq!(location.range.end.character, location.range.start.character + 1); + } + + // documentHighlight walks the same list and must agree with it. + let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol"); + let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect(); + assert_eq!(ranges, found.iter().map(|l| l.range).collect::>()); +} + +#[test] +fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() { + let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv"); + let edited = "module top;\n\n sub only_now ();\nendmodule\n"; + ws.set_document(uri.clone(), edited.to_string()); + + let found = references(&ws, &uri, at(edited, "sub only_now"), false); + assert_eq!( + places(&found), + vec![("other.sv".to_string(), 1), ("top.sv".to_string(), 2)], + "the new live use replaces both saved top.sv uses" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_declaration_move_is_reported_at_its_live_span() { + let (dir, mut ws, uri) = instantiated("xrefs_unsaved_decl", "sub.sv"); + let edited = "// moved down\n\nmodule sub (input logic clk);\nendmodule\n"; + ws.set_document(uri.clone(), edited.to_string()); + + let found = references(&ws, &uri, at(edited, "module sub") + 7, true); + assert!( + places(&found).contains(&("sub.sv".to_string(), 2)), + "the declaration comes from the live buffer, not its saved offset" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_untitled_buffer_still_answers_from_itself() { + // No path means no place in the index and nothing to hand the engine, + // so the in-file answer is the whole answer. + let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let found = references(&ws, &uri, at(text, "wire a") + 5, true); + assert_eq!(found.len(), 2); + assert_eq!(found[0].uri, uri, "reported against the buffer itself"); +} + +// ------------------------------------------------------------------ +// documentHighlight +// ------------------------------------------------------------------ + +#[test] +fn a_signal_highlights_its_declaration_and_every_use() { + let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "assign a") + 7).expect("a symbol"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![1, 2, 3], "the declaration first, then both uses"); + assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); +} + +#[test] +fn highlighting_works_from_the_declaration_as_well() { + let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); + assert_eq!(found.len(), 2); + assert_eq!(found[0].range.start.line, 1); +} + +#[test] +fn highlight_ranges_are_utf16() { + let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + let found = document_highlights(doc, at(text, "wire a") + 5).expect("a symbol"); + assert_eq!(found[0].range.start.character, 7); + assert_eq!(found[1].range.start.character, 9); +} + +#[test] +fn a_position_on_no_symbol_declines_rather_than_answering_nothing() { + // `None`, not an empty list: an empty list tells the editor to stop + // drawing its own word highlighting. + let text = "module m;\n wire a;\nendmodule\n"; + let (ws, uri) = document(text); + let doc = ws.document(&uri).expect("open"); + assert!(document_highlights(doc, at(text, "wire")).is_none(), "a keyword"); + assert!(document_highlights(doc, 0).is_none(), "the `module` keyword"); +} + +/// `performance.md` §7, reproduced: `documentHighlight` answered nothing +/// at every opentitan position tried — an instantiated module's name, a +/// port connection — while `references` at the same positions answered. +/// Both names are declared in *another* file, which is the whole of what +/// the two handlers used to disagree about. +#[test] +fn a_cross_file_name_highlights_its_uses_in_this_file() { + let dir = temp_dir("highlight_cross"); + fs::write( + dir.join("sub.sv"), + "module sub (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n", + ) + .expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk, rst; + sub u_0 (.clk_i(clk), .rst_ni(rst)); + sub u_1 (.clk_i(clk), .rst_ni(rst)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + // The module name at an instantiation: both instantiations, and + // nothing from the *other* module's file — this is one file's answer. + let module = at(top_text, "sub u_0"); + assert_eq!(references(&ws, &uri, module, true).len(), 3, "premise: references answers"); + let found = document_highlights(doc, module).expect("the instantiated module"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![2, 3], "both instantiations of `sub`"); + assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT))); + + // A port connection: the `.clk_i` of both instantiations, and not the + // `clk` they are wired to, which is a different symbol. + let port = at(top_text, ".clk_i") + 1; + assert!(!references(&ws, &uri, port, true).is_empty(), "premise: references answers"); + let found = document_highlights(doc, port).expect("the connected port"); + let starts: Vec<(u32, u32)> = + found.iter().map(|h| (h.range.start.line, h.range.start.character)).collect(); + assert_eq!(starts, vec![(2, 12), (3, 12)], "both `.clk_i` connections"); + + let _ = fs::remove_dir_all(&dir); +} + +/// QA (performance wave Lane B, 2026-08-28): an instantiated module whose +/// name two files declare is ambiguous at the workspace layer. +/// `references` gives up on an ambiguous external target outright +/// (`indexed_target` only ever builds one from `Definition::External([def])` +/// — exactly one candidate — so an ambiguous use never reaches +/// `indexed_references`, and `in_file_references` needs a *local* symbol, +/// which an external use does not have; the net result is an empty +/// answer, unchanged by this round). `document_highlights` does not +/// inherit that caution: `external_occurrences` groups by the overlay's +/// whole answer, ambiguous sets included, so it answers here where +/// `references` does not. Recorded rather than asserted as a bug — LSP +/// does not require the two to agree, and answering something reasonable +/// beats the editor's own word-highlighter falling back to nothing — but +/// it is a real divergence the lead should see before calling the two +/// "cross-checked". +#[test] +fn an_ambiguous_instantiation_highlights_where_references_gives_up() { + let dir = temp_dir("highlight_ambiguous"); + let dup = "module dup (input logic clk_i);\nendmodule\n"; + fs::write(dir.join("a.sv"), dup).expect("write"); + fs::write(dir.join("b.sv"), dup).expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk; + dup u_0 (.clk_i(clk)); + dup u_1 (.clk_i(clk)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let module = at(top_text, "dup u_0"); + assert!(leaves_this_file(&ws, doc, module), "dup is a unit the index holds"); + assert!( + references(&ws, &uri, module, true).is_empty(), + "references declines an ambiguous external target rather than guessing" + ); + let found = document_highlights(doc, module).expect("highlight groups the ambiguous use"); + let lines: Vec = found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(lines, vec![2, 3], "both instantiations, grouped by the same ambiguous def set"); + + let _ = fs::remove_dir_all(&dir); +} + +/// Two uses of the *same name* that are ambiguous between *different* +/// def sets must not be grouped into one highlight — the def-set +/// comparison in `external_occurrences`, not the name match alone, is +/// what keeps them apart. `dup_a` and `dup_b` are each declared in two +/// files (so a connection to either is ambiguous), and both happen to +/// export a port with the identical name `same_port` — so the two +/// connections below share one `reference.name` but must resolve against +/// disjoint ambiguous sets (`dup_a`'s two files vs. `dup_b`'s two files). +#[test] +fn two_uses_ambiguous_between_different_def_sets_do_not_group() { + let dir = temp_dir("highlight_ambiguous_disjoint"); + let dup_a = "module dup_a (input logic same_port);\nendmodule\n"; + let dup_b = "module dup_b (input logic same_port);\nendmodule\n"; + fs::write(dir.join("a1.sv"), dup_a).expect("write"); + fs::write(dir.join("a2.sv"), dup_a).expect("write"); + fs::write(dir.join("b1.sv"), dup_b).expect("write"); + fs::write(dir.join("b2.sv"), dup_b).expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "\ +module top; + logic clk; + dup_a u_a (.same_port(clk)); + dup_b u_b (.same_port(clk)); +endmodule +"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let first = at(top_text, "same_port(clk));\n dup_b") + 1; + let second = at(top_text, "same_port(clk));\nendmodule") + 1; + // Premise: both connections are genuinely ambiguous externals (no + // local `same_port`, and the workspace really does hold two + // candidates for each), i.e. this exercises the def-set comparison + // and not some earlier decline. + let first_found = + document_highlights(doc, first).expect("dup_a's connection is ambiguous, not empty"); + let second_found = + document_highlights(doc, second).expect("dup_b's connection is ambiguous, not empty"); + let first_lines: Vec = first_found.iter().map(|h| h.range.start.line).collect(); + let second_lines: Vec = second_found.iter().map(|h| h.range.start.line).collect(); + assert_eq!(first_lines, vec![2], "dup_a's port only, despite sharing a name with dup_b's"); + assert_eq!(second_lines, vec![3], "dup_b's port only, despite sharing a name with dup_a's"); + + let _ = fs::remove_dir_all(&dir); +} + +/// A use the overlay never answered — its `defs()` is empty, e.g. a +/// package member the index does not hold — must decline like any other +/// unanswered position, not fall through to some other file's namesake. +#[test] +fn an_unanswered_external_use_declines_rather_than_guessing() { + let dir = temp_dir("highlight_unanswered"); + let top_path = dir.join("top.sv"); + // `missing_pkg` is never declared anywhere in the workspace, so the + // import itself is the only thing the index can say nothing about; + // `NOPE` is a member reference the overlay tries and fails to place. + let top_text = "module top;\n import missing_pkg::*;\n wire [NOPE-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + let doc = ws.document(&uri).expect("open"); + + let use_pos = at(top_text, "NOPE") + 1; + assert!(document_highlights(doc, use_pos).is_none(), "unresolved, so decline"); + + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// TODO §64.1 — the hierarchical member surface +// ------------------------------------------------------------------ + +/// `leaf` declares a net only a hierarchical path can reach, plus a port +/// and a parameter that a connection list can, so one fixture answers both +/// "did the widening land" and "did the connection answers move". +const LEAF: &str = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; +/// One level up: `u_leaf.sig`. +const SINGLE: &str = "\ +module single; + leaf u_leaf (.clk_i(1'b0)); + wire v; + assign v = u_leaf.sig; +endmodule +"; +/// Two levels up, through `mid`'s own instance. +const MID: &str = "\ +module mid; + leaf u_leaf (.clk_i(1'b0)); +endmodule +"; +const TWO_LEVEL: &str = "\ +module top; + mid u_mid (); + wire w; + assign w = u_mid.u_leaf.sig; +endmodule +"; + +/// The four-file hierarchical workspace, with the named files opened as +/// buffers holding exactly their on-disk text. +fn hierarchical(tag: &str, open: &[&str]) -> (PathBuf, Workspace) { + let dir = temp_dir(tag); + for (name, text) in + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + for name in open { + let path = dir.join(name); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri, text); + } + (dir, ws) +} + +fn uri_in(dir: &Path, name: &str) -> Uri { + path_to_uri(&dir.join(name)).expect("uri") +} + +/// The byte offset of `leaf`'s net declaration, its one-level tail and its +/// two-level tail — the three positions the sweep below asks from. +fn sig_positions() -> (u32, u32, u32) { + ( + at(LEAF, "logic sig") + 6, + at(SINGLE, "u_leaf.sig;") + 7, + at(TWO_LEVEL, "u_mid.u_leaf.sig") + 13, + ) +} + +/// The declaration, its own in-file use, and both cross-file tails. +fn every_place_naming_sig() -> Vec<(String, u32)> { + vec![ + ("leaf.sv".to_string(), 1), + ("leaf.sv".to_string(), 2), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3), + ] +} + +/// Cases (b) and (c): asked **from the declaration** of a net that only a +/// hierarchical path can reach, with `includeDeclaration` both ways. +#[test] +fn a_hierarchical_nets_references_reach_every_file_that_names_it() { + let (dir, ws) = hierarchical("hier_from_decl", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (decl, _, _) = sig_positions(); + + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + every_place_naming_sig(), + "the declaration, its own use, the one-level tail and the two-level one" + ); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, false)), + every_place_naming_sig()[1..].to_vec(), + "`includeDeclaration: false` drops the declaration and nothing else" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (h): asked **from a tail**, the answer must include the declaring +/// buffer's own in-file use — the half `indexed_def_in_file` could not +/// re-identify. Both tails answer the same set, from one and from two +/// levels up. +#[test] +fn a_hierarchical_nets_references_from_a_tail_include_the_declaring_files_own_uses() { + let (dir, ws) = hierarchical("hier_from_tail", &["leaf.sv", "single.sv", "top.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let top_uri = uri_in(&dir, "top.sv"); + let (_, one, two) = sig_positions(); + + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "from `u_leaf.sig`" + ); + assert_eq!( + places(&references(&ws, &top_uri, two, true)), + every_place_naming_sig(), + "from `u_mid.u_leaf.sig` — the same declaration, so the same set" + ); + assert_eq!( + places(&references(&ws, &single_uri, one, false)), + every_place_naming_sig()[1..].to_vec(), + "and the declaration is the only thing `includeDeclaration` drops" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (i). The index posts no `Local` fact for a hierarchical-only +/// declaration, so with `leaf.sv` **closed** neither the postings nor the +/// open-buffer overlay can supply its own `assign sig = clk_i;`. An answer +/// that silently omitted it would be worse than the single-file fallback, +/// because it looks complete. +#[test] +fn a_hierarchical_nets_own_uses_are_found_with_its_declaring_file_closed() { + let (dir, ws) = hierarchical("hier_closed", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "`leaf.sv` is closed and `top.sv` too, and both are still listed" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// `definition` and `documentHighlight` over the same three positions. +/// Neither reads the reachability gate — `definition` goes through the +/// overlay and `documentHighlight` is a *document* answer by contract +/// (`docs/features/references-nav/README.md`, 2026-08-28) — so both are +/// pinned here to stay exactly what they were. +#[test] +fn definition_and_document_highlight_over_a_hierarchical_tail_are_unchanged() { + let (dir, ws) = hierarchical("hier_def_highlight", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let single_uri = uri_in(&dir, "single.sv"); + let top_uri = uri_in(&dir, "top.sv"); + let (decl, one, two) = sig_positions(); + + let declaration = vec![("leaf.sv".to_string(), 1)]; + assert_eq!(places(&definition(&ws, &leaf_uri, decl)), declaration, "itself"); + assert_eq!(places(&definition(&ws, &single_uri, one)), declaration, "from one level up"); + assert_eq!(places(&definition(&ws, &top_uri, two)), declaration, "from two"); + + let lines = |uri: &Uri, offset: u32| { + let doc = ws.document(uri).expect("open"); + document_highlights(doc, offset) + .map(|found| found.iter().map(|h| h.range.start.line).collect::>()) + }; + assert_eq!(lines(&leaf_uri, decl), Some(vec![1, 2]), "this file's two spans"); + assert_eq!(lines(&single_uri, one), Some(vec![3]), "the tail, in its own file only"); + assert_eq!(lines(&top_uri, two), Some(vec![3]), "same, two levels up"); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (d). The connection surface is a *prefix* of the hierarchical one +/// (`hierarchy::member` returns the connection records whole whenever they +/// are non-empty), so a port and a parameter of the very same module must +/// answer exactly what they answered before the widening. +#[test] +fn a_port_and_a_parameter_of_the_same_unit_keep_their_connection_answers() { + let (dir, ws) = hierarchical("hier_port", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + + assert_eq!( + places(&references(&ws, &leaf_uri, at(LEAF, "clk_i)"), true)), + vec![ + ("leaf.sv".to_string(), 0), + ("leaf.sv".to_string(), 2), + ("mid.sv".to_string(), 1), + ("single.sv".to_string(), 1), + ], + "the port: its declaration, its own use, and both `.clk_i(...)` connections" + ); + assert_eq!( + places(&references(&ws, &leaf_uri, at(LEAF, "W = 1"), true)), + vec![("leaf.sv".to_string(), 0)], + "the parameter: declared, never named again anywhere" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A **class** member stays on the connection answer — the attack case +/// §49's QA asked for, re-asked here because the widening is one call +/// away from it. A class has one surface, so `member_in` cannot move it. +#[test] +fn a_class_member_keeps_its_connection_answer() { + let dir = temp_dir("hier_class"); + let pkg = "\ +package cp; + class c; + int fld; + function void f(); + fld = 1; + endfunction + endclass +endpackage +"; + let user = "module cuser;\n cp::c h;\n initial h.fld = 2;\nendmodule\n"; + for (name, text) in [("cp.sv", pkg), ("cuser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let pkg_uri = uri_in(&dir, "cp.sv"); + ws.set_document(pkg_uri.clone(), pkg.to_string()); + let user_uri = uri_in(&dir, "cuser.sv"); + ws.set_document(user_uri, user.to_string()); + + assert_eq!( + places(&references(&ws, &pkg_uri, at(pkg, "int fld") + 4, true)), + vec![("cp.sv".to_string(), 2), ("cp.sv".to_string(), 4), ("cuser.sv".to_string(), 2)], + "the field, its use in the method, and the handle access in the other file" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A net declared inside a **generate block**. Until TODO §65.1 it was on +/// neither surface and this pinned the honest single-file answer; a named +/// block is now on its module's hierarchical surface and its members under +/// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate +/// says yes and `u_g.g.gsig` in the other file is one of the references. +#[test] +fn a_generate_block_scoped_net_is_found_through_the_instance_path() { + let dir = temp_dir("hier_generate"); + let leaf = "\ +module gleaf; + if (1) begin : g + wire gsig; + assign gsig = 1'b0; + end +endmodule +"; + let user = "module guser;\n gleaf u_g ();\n wire z;\n assign z = u_g.g.gsig;\nendmodule\n"; + for (name, text) in [("gleaf.sv", leaf), ("guser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let leaf_uri = uri_in(&dir, "gleaf.sv"); + ws.set_document(leaf_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "guser.sv"); + ws.set_document(user_uri, user.to_string()); + + let decl = at(leaf, "wire gsig") + 5; + let doc = ws.document(&leaf_uri).expect("open"); + assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically"); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3), ("guser.sv".to_string(), 3)], + "this file and `u_g.g.gsig`" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A net in one unit and a **port of the same name in another** — each +/// keeps its own answer. The widening is per unit, so `sb`'s net gaining +/// its cross-file tail must not pull `sa`'s port along, and `sa`'s port +/// must answer exactly what it did. +#[test] +fn a_net_and_a_like_named_port_in_another_unit_keep_their_answers_apart() { + let dir = temp_dir("hier_shadow"); + let with_port = "module sa (input logic shared);\n wire x;\n assign x = shared;\nendmodule\n"; + let with_net = "module sb;\n logic shared;\n assign shared = 1'b0;\nendmodule\n"; + let user = "\ +module suse; + sa u_a (.shared(1'b1)); + sb u_b (); + wire q; + assign q = u_b.shared; +endmodule +"; + for (name, text) in [("sa.sv", with_port), ("sb.sv", with_net), ("suse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let port_uri = uri_in(&dir, "sa.sv"); + ws.set_document(port_uri.clone(), with_port.to_string()); + let net_uri = uri_in(&dir, "sb.sv"); + ws.set_document(net_uri.clone(), with_net.to_string()); + let user_uri = uri_in(&dir, "suse.sv"); + ws.set_document(user_uri, user.to_string()); + + assert_eq!( + places(&references(&ws, &port_uri, at(with_port, "logic shared") + 6, true)), + vec![("sa.sv".to_string(), 0), ("sa.sv".to_string(), 2), ("suse.sv".to_string(), 1)], + "`sa`'s port: unchanged, and never `sb`'s net" + ); + assert_eq!( + places(&references(&ws, &net_uri, at(with_net, "logic shared") + 6, true)), + vec![("sb.sv".to_string(), 1), ("sb.sv".to_string(), 2), ("suse.sv".to_string(), 4)], + "`sb`'s net: its own file plus the `u_b.shared` tail, and never `sa`'s connection" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (f) as it actually exists. `vlog_semantic` records **one symbol +/// per name per scope** — a second declaration of a name already declared +/// becomes a `Duplicate` and a reference to the first — so "a name that is +/// both a parameter and an internal net of one unit" is one symbol, one +/// index record, and one surface: the first declaration's. The +/// single-record rule (`defs.len() != 1`) therefore never sees two records +/// for one `(unit, name)` from one file, and both cursor positions answer +/// the same complete set. Asserted rather than argued, because the +/// alternative — two records, the port silently winning — is what §64.1 +/// asked to be ruled out. +#[test] +fn a_name_declared_twice_in_one_unit_is_one_symbol_and_one_record() { + let dir = temp_dir("hier_redeclared"); + let both = "\ +module pboth #(parameter int q = 1) (); + wire q; + assign q = 1'b0; +endmodule +"; + let user = + "module puse;\n pboth #(.q(2)) u_p ();\n wire s;\n assign s = u_p.q;\nendmodule\n"; + for (name, text) in [("pboth.sv", both), ("puse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let both_uri = uri_in(&dir, "pboth.sv"); + ws.set_document(both_uri.clone(), both.to_string()); + let user_uri = uri_in(&dir, "puse.sv"); + ws.set_document(user_uri, user.to_string()); + + let everywhere = vec![ + ("pboth.sv".to_string(), 0), + ("pboth.sv".to_string(), 1), + ("pboth.sv".to_string(), 2), + ("puse.sv".to_string(), 1), + ("puse.sv".to_string(), 3), + ]; + assert_eq!( + places(&references(&ws, &both_uri, at(both, "int q") + 4, true)), + everywhere, + "from the parameter" + ); + assert_eq!( + places(&references(&ws, &both_uri, at(both, "wire q") + 5, true)), + everywhere, + "and from the redeclaration, which is a use of it" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Two files declaring one module, each with a net of one name: the gate +/// now admits the net, and the **single-record rule** refuses it — two +/// `Def`s for `(dleaf, dsig)` is exactly the ambiguity `defs.len() != 1` +/// has always declined. So the answer is the in-file one, as before, and +/// the tail that cannot be placed answers nothing rather than guessing. +#[test] +fn two_modules_of_one_name_keep_a_hierarchical_net_on_the_in_file_answer() { + let dir = temp_dir("hier_two_modules"); + let leaf = "module dleaf;\n logic dsig;\n assign dsig = 1'b0;\nendmodule\n"; + let user = "module duse;\n dleaf u_d ();\n wire r;\n assign r = u_d.dsig;\nendmodule\n"; + for (name, text) in [("a.sv", leaf), ("b.sv", leaf), ("duse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let a_uri = uri_in(&dir, "a.sv"); + ws.set_document(a_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "duse.sv"); + ws.set_document(user_uri.clone(), user.to_string()); + + assert_eq!( + places(&references(&ws, &a_uri, at(leaf, "logic dsig") + 6, true)), + vec![("a.sv".to_string(), 1), ("a.sv".to_string(), 2)], + "`a.sv`'s own answer — `b.sv`'s `dsig` is another declaration" + ); + assert_eq!( + places(&references(&ws, &user_uri, at(user, "u_d.dsig") + 4, true)), + Vec::new(), + "the tail is ambiguous between two `dleaf`s, so nothing is claimed" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (g). An `untitled:` buffer is in no index and has no path to hand +/// over, so the gate declines before any surface question is asked — the +/// widening cannot reach it. +#[test] +fn an_untitled_buffer_never_asks_the_workspace() { + let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(untitled.clone(), LEAF.to_string()); + let doc = ws.document(&untitled).expect("open"); + let (decl, _, _) = sig_positions(); + + assert!(!leaves_this_file(&ws, doc, decl), "no path, no index entry"); + let found = references(&ws, &untitled, decl, true); + assert_eq!( + found.iter().map(|l| l.range.start.line).collect::>(), + vec![1, 2], + "its own two spans, reported against the `untitled:` uri" + ); + assert!(found.iter().all(|l| l.uri == untitled)); +} + +// ------------------------------------------------------------------ +// TODO §64.1 — QA attacks (task-d8afe80f) +// ------------------------------------------------------------------ + +/// The disk edit shared by the three findings below: three comment lines +/// pushed in above `leaf`'s net declaration, keeping the net's name, kind +/// and owner so every identity check downstream still finds it. +const LEAF_MOVED: &str = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + // one + // two + // three + logic sig; + assign sig = clk_i; +endmodule +"; + +/// Every `leaf.sv` line in an answer, in the order it came — the three +/// stale-file findings all turn on which lines of the *closed declaring +/// file* a request reports. +fn leaf_lines(found: &[Location]) -> Vec { + found + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| l.range.start.line) + .collect() +} + +/// **FINDING 1**, QA's scenario, now fixed. `declaring_file_uses` used to +/// read the declaring file through `ws.file_view` — a *cache*, dropped +/// only on `set_document`/`close_document`/`update_one`/ +/// `rebuild_index_with`/`begin_widen`, none of which an external edit to a +/// closed file is — while `locations` renders every closed-file span +/// against `Workspace::text_of`, which never caches. Two reads of one path +/// in one request, free to disagree, and the older offsets landed on the +/// newer bytes: QA saw `leaf.sv`'s "own use" reported at line `3` +/// (`// two`). The path now reads **once, fresh**, with `text_of`, and +/// hands those same bytes to `locations`. +/// +/// Worked out from `LEAF_MOVED` above, which is `LEAF` with three comment +/// lines pushed in under the header: line `4` is ` logic sig;` and line +/// `5` is ` assign sig = clk_i;`. Both come from the re-analysis of the +/// fresh text — the declaration too, because a file this request just +/// re-analysed knows where the declaration is *now* and the index-time +/// span is only the last resort. +#[test] +fn qa_finding_1_a_disk_edited_closed_declaring_file_reports_its_live_spans() { + let (dir, ws) = hierarchical("hier_stale_disk_1", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + // One request first, which is what used to prime the view cache: + // `leaf.sv` is closed, so this walks `declaring_file_uses`. + let before = references(&ws, &top_uri, two, true); + assert_eq!(places(&before), every_place_naming_sig(), "sanity: correct before any edit"); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![4, 5], + "the declaration and its own use, both at their live lines" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// **FINDING 2**, now fixed, and the half that needed no primed cache at +/// all. The `include_declaration` tail used to fall straight to +/// `target.declaration_span` — a span fixed at the last index rebuild — +/// for a closed file, and `locations` rendered it against a fresh read +/// with no check that the two still agreed: QA saw the declaration at +/// line `1` (`// one`). It is now taken from the same re-analysis that +/// supplies the uses, so a single fresh request answers `4` and `5` from +/// `LEAF_MOVED`'s own text. +#[test] +fn qa_finding_2_one_fresh_request_reports_the_live_declaration_line() { + let (dir, ws) = hierarchical("hier_stale_disk_2", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![4, 5], + "declaration 4, own use 5 — nothing on this path caches" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// **FINDING 3**, the pre-existing half, now an honest omission. Asked +/// from `single.sv`'s `.clk_i(1'b0)` connection, the target is a **port**: +/// on the connection surface, its uses already posted, so no re-analysis +/// of the declaring file runs and every `leaf.sv` span in the answer is an +/// index-time claim about bytes nobody pinned. The guard now decides each +/// one against the text it is about to be rendered in: +/// +/// * the declaration, `clk_i` in the module header — `LEAF_MOVED` inserts +/// its three lines *below* the header, so line `0` is untouched, the +/// recorded span still spells `clk_i`, and it is reported (correctly, at +/// `0`); +/// * the posted use, `clk_i` in `assign sig = clk_i;` — that line is now +/// line `5` and the recorded span points into `// two`, which does not +/// spell `clk_i`, so it is **dropped**. +/// +/// QA saw `[0, 3]`: the `3` was the wrong line this guard exists to +/// refuse. The right answer is not to invent `5` either — nothing +/// re-analysed this file, so the request does not know `5`; it knows only +/// that what it held is no longer true. +#[test] +fn qa_finding_3_a_stale_index_span_in_a_closed_file_is_dropped_not_misreported() { + let (dir, ws) = hierarchical("hier_stale_disk_3", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; + + // Sanity: before the edit, both `leaf.sv` spans are true and reported. + assert_eq!( + leaf_lines(&references(&ws, &single_uri, clk_offset, true)), + vec![0, 2], + "the header's port and its own use, before any edit" + ); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &single_uri, clk_offset, true); + assert_eq!( + leaf_lines(&after), + vec![0], + "the unmoved header still spells `clk_i`; the moved use is omitted, not misreported" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// The guard itself, attacked the way `hover.rs`'s own QA attacked it: a +/// disk edit that leaves a recorded span still *covering* the name, as a +/// **prefix** of a longer identifier. +/// +/// `leafp` declares one port and uses it nowhere, so the only `leafp.sv` +/// span in the answer is the index-time declaration span — `clk_i` in the +/// header. The edit renames the port to `clk_i2` and changes nothing +/// before it, so that span's bytes still read exactly `clk_i` and a +/// length-and-content check alone would emit it, under the old name, on a +/// line that now declares something else. `spells_exactly` requires the +/// character immediately outside the span not to continue an identifier, +/// which is what turns this prefix match back into a miss. +#[test] +fn qa_a_stale_span_that_now_spells_a_longer_name_is_dropped() { + let dir = temp_dir("hier_stale_prefix"); + let leaf = "module leafp (input logic clk_i);\nendmodule\n"; + let user = "module userp;\n leafp u_p (.clk_i(1'b0));\nendmodule\n"; + for (name, text) in [("leafp.sv", leaf), ("userp.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let user_uri = uri_in(&dir, "userp.sv"); + ws.set_document(user_uri.clone(), user.to_string()); + let offset = at(user, ".clk_i(1'b0)") + 1; + + assert_eq!( + places(&references(&ws, &user_uri, offset, true)), + vec![("leafp.sv".to_string(), 0), ("userp.sv".to_string(), 1)], + "sanity: the declaration and the connection, before the edit" + ); + + // The same header, one longer name, nothing before it moved. + fs::write(dir.join("leafp.sv"), "module leafp (input logic clk_i2);\nendmodule\n") + .expect("write"); + + assert_eq!( + places(&references(&ws, &user_uri, offset, true)), + vec![("userp.sv".to_string(), 1)], + "the prefix match is refused: the connection only, no invented declaration" + ); + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// Re-check round, 2026-09-12 — the rework's guard and one-read invariant +// ------------------------------------------------------------------ + +/// Re-check item 2(a): a disk edit that moves only the **use**, leaving +/// the declaration's own line untouched. The target is hierarchical-only, +/// so `declaring_file_uses` always re-analyses the whole file regardless +/// of what moved — both spans must come out live and correct, not just +/// the one that happened to move. +#[test] +fn qa_recheck_a_disk_edit_that_moves_only_the_use_is_still_fully_reanalysed() { + let (dir, ws) = hierarchical("hier_recheck_use_only", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + let moved_use_only = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + // one + // two + assign sig = clk_i; +endmodule +"; + fs::write(dir.join("leaf.sv"), moved_use_only).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![1, 4], + "declaration unmoved at 1, its own use moved to 4 — both live and correct" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Re-check item 2(b): the closed declaring file is **deleted** after the +/// index was built, with no rescan. `declaring_file_uses`'s `text_of` +/// read fails (`?` short-circuits to `None`), and the `include_declaration` +/// fallback's own `ws.text_of` read in `closed_locations` fails the same +/// way — no text, no panic, an honest omission of *that file* rather than +/// a guess. `single.sv` is untouched and perfectly readable, so its own +/// posted tail still answers normally — only `leaf.sv` itself vanishes +/// from the set. +#[test] +fn qa_recheck_a_deleted_closed_declaring_file_is_an_honest_omission_not_a_panic() { + let (dir, ws) = hierarchical("hier_recheck_deleted", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + fs::remove_file(dir.join("leaf.sv")).expect("delete"); + + let after = references(&ws, &top_uri, two, true); + assert!( + leaf_lines(&after).is_empty(), + "leaf.sv cannot be read at all, so it is omitted, not guessed at: {:?}", + leaf_lines(&after) + ); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "single.sv (untouched, still readable) and the live top.sv buffer, no panic, no crash" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Re-check item 2(c): a stale index-time span that, reinterpreted +/// against the edited disk text, no longer lands on a `char` boundary at +/// all — a multi-byte character straddling the exact byte offset the +/// index recorded. `spells_exactly`/`span_text` use `str::get`, which +/// answers `None` off a boundary rather than panicking; this is the +/// direct attack on that, on the **port** shape (finding 3's case, an +/// index-time span with no re-analysis to save it). +#[test] +fn qa_recheck_a_stale_span_off_a_utf8_boundary_does_not_panic() { + let (dir, ws) = hierarchical("hier_recheck_utf8", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; + + // The old, index-time byte offset of `clk_i`'s own use in `LEAF` + // (inside `assign sig = clk_i;`, the second occurrence). + let old_use_offset = LEAF.rfind("clk_i").expect("second occurrence"); + + // A new `leaf.sv` in which that same raw byte offset lands on the + // second byte of a 4-byte emoji — never a `char` boundary. + let mut edited = "a".repeat(old_use_offset.saturating_sub(1)); + edited.push('🎉'); + edited.push_str("\nmodule leaf (input logic clk_i2);\nendmodule\n"); + assert!( + !edited.is_char_boundary(old_use_offset), + "test bug: byte {old_use_offset} must land mid-character" + ); + fs::write(dir.join("leaf.sv"), &edited).expect("write"); + + // Must not panic. The header itself changed too (`clk_i` -> `clk_i2` + // and garbage before it), so nothing about `leaf.sv` need survive — + // the only requirement is that answering does not crash the server. + let after = references(&ws, &single_uri, clk_offset, true); + assert!(leaf_lines(&after).is_empty(), "garbage text spells nothing: {:?}", after); + let _ = fs::remove_dir_all(&dir); +} + +/// Re-check item 2(d): **two** closed files in one answer — `leaf.sv` +/// (the declaring file, fully re-analysed) and `single.sv` (a posted +/// `External` cross-file site, never re-analysed, guarded the same way a +/// port's own use is) — asked from a third, open file. An edit to one +/// must not affect the other's answer, and each is rendered against its +/// own, independently-read text. +#[test] +fn qa_recheck_two_closed_files_in_one_answer_are_independent() { + let (dir, ws) = hierarchical("hier_recheck_two_closed", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + assert_eq!( + places(&references(&ws, &top_uri, two, true)), + every_place_naming_sig(), + "leaf.sv re-analysed, single.sv posted-only, top.sv live — before any edit" + ); + + // Move `single.sv`'s own tail down by two lines; `leaf.sv` untouched. + let single_moved = "\ +module single; + // one + // two + leaf u_leaf (.clk_i(1'b0)); + wire v; + assign v = u_leaf.sig; +endmodule +"; + fs::write(dir.join("single.sv"), single_moved).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![1, 2], + "leaf.sv is untouched and unaffected by single.sv's own edit" + ); + let single_lines: Vec = after + .iter() + .filter(|l| l.uri.as_str().ends_with("single.sv")) + .map(|l| l.range.start.line) + .collect(); + // `single.sv`'s own tail is a posted `External` site, never + // re-analysed (only the *declaring* file is) — so it is exactly the + // finding-3 shape one file over: the moved span no longer spells + // `sig` and is dropped, an honest omission, not misreported at its + // old line (3) nor invented at its new one (5). + assert!( + single_lines.is_empty(), + "single.sv's own tail moved and is not re-analysed, so it is dropped: {single_lines:?}" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// QA finding 4 (re-check round), fixed. The direction the closed-file +/// guard did not cover: an **open** buffer whose live text no longer +/// declares the name. `leaf.sv` is open with `sig` renamed away +/// (unsaved); the request comes from `single.sv`'s tail, which still +/// resolves to the original `Def`. `declaring_file_uses` declines (the +/// file is open) and the live lookup finds nothing (no symbol is named +/// `sig` in the buffer any more), so the only span left is the +/// index-time one — and `locations` renders an open document with no +/// guard. Before the fix that stale 3-byte span was reported at line 1, +/// columns 8..11: a strict *prefix* of the live token `sig2` (8..12), the +/// very shape `spells_exactly` refuses for a closed file +/// (`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`). +/// `declaration_site` now asks the same question of the live buffer and +/// omits the declaration: `leaf.sv` does not appear at all, and every +/// other location is unchanged. +#[test] +fn qa_recheck_a_renamed_open_buffers_stale_declaration_is_omitted_not_misreported() { + let (dir, ws) = hierarchical("hier_recheck_open_stale", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (_, one, _) = sig_positions(); + + // Sanity: with the buffer holding its on-disk text, the answer is + // complete, declaration included. + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "before the rename: the full answer" + ); + + // Rename `sig` away in the live, unsaved `leaf.sv` buffer. The index + // still holds the original `Def` for `sig`, at the same offsets. + let renamed = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig2; + assign sig2 = clk_i; +endmodule +"; + let mut ws = ws; + ws.set_document(leaf_uri, renamed.to_string()); + + // Asked from `single.sv`'s tail, which still names the original + // declaration by its persisted `Def`. + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "leaf.sv is honestly omitted — no stale prefix of `sig2` — and the two tails stay: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// The control for the guard above: an open buffer with an unsaved edit +/// **above** the declaration, which still spells `sig` and has only +/// moved. The live-symbol path answers first (`indexed_def_for_symbol` +/// matches logically — path, owner, name, kind — not positionally), so +/// the declaration is reported at its live line and the guard never +/// fires. The index-time span, rendered blind, would have pointed into +/// the header line; dropped by the guard, it would be missing. Either +/// way the live line `3` at `sig`'s own columns is the only right answer, +/// and it is the one the request gives with `includeDeclaration` on and +/// not without it. +#[test] +fn an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line() { + let (dir, ws) = hierarchical("hier_open_edit_above", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (_, one, _) = sig_positions(); + + let edited = "\ +// pushed +// down +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + let mut ws = ws; + ws.set_document(leaf_uri, edited.to_string()); + + let with = references(&ws, &single_uri, one, true); + let leaf_spans: Vec<(u32, u32, u32)> = with + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) + .collect(); + assert_eq!( + leaf_spans, + vec![(3, 8, 11), (4, 9, 12)], + "the live declaration and the live use, both shifted down two lines: {with:?}" + ); + assert_eq!( + places(&with), + vec![ + ("leaf.sv".to_string(), 3), + ("leaf.sv".to_string(), 4), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3), + ], + "and nothing else moved" + ); + + let without = references(&ws, &single_uri, one, false); + assert_eq!( + places(&without), + vec![("leaf.sv".to_string(), 4), ("single.sv".to_string(), 3), ("top.sv".to_string(), 3),], + "line 3 is the declaration: it goes when includeDeclaration is off" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Re-check (coordinator's follow-up): an escaped port name +/// (`\my-clk `), reachable before §64.1 too (connection surface). The +/// declaration is an index-time span like any port's, so it goes through +/// `closed_locations`'s `spells_exactly` guard — which must recognise the +/// escaped name (backslash and all) rather than silently dropping every +/// closed-file location for it. +#[test] +fn qa_recheck_an_escaped_port_name_survives_the_guard() { + let dir = temp_dir("qa_escaped_port"); + let sub = "module sub (input logic \\my-clk );\nendmodule\n"; + let top = "module top;\n sub u (.\\my-clk (1'b0));\nendmodule\n"; + for (name, text) in [("sub.sv", sub), ("top.sv", top)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = uri_in(&dir, "top.sv"); + ws.set_document(top_uri.clone(), top.to_string()); + let offset = at(top, "\\my-clk (1'b0)") + 1; + + let found = references(&ws, &top_uri, offset, true); + assert_eq!( + places(&found), + vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], + "sub.sv's declaration must survive the guard, escaped name and all" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Re-check: the hierarchical twin of the escaped-name attack above — an +/// escaped **net**, hierarchical-only, closed declaring file. This one +/// goes through the *re-analysis* path (`declaring_file_uses`) rather +/// than the guard directly, so it is really testing whether the parser +/// and `Semantics::symbols_named` round-trip an escaped name at all +/// under re-analysis. +#[test] +fn qa_recheck_an_escaped_net_survives_the_closed_file_reanalysis() { + let dir = temp_dir("qa_escaped_net"); + let leaf = "module eleaf;\n logic \\my-sig ;\n assign \\my-sig = 1'b0;\nendmodule\n"; + let top = + "module etop;\n eleaf u_leaf ();\n wire w;\n assign w = u_leaf.\\my-sig ;\nendmodule\n"; + for (name, text) in [("eleaf.sv", leaf), ("etop.sv", top)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = uri_in(&dir, "etop.sv"); + ws.set_document(top_uri.clone(), top.to_string()); + let offset = at(top, "u_leaf.\\my-sig") + 8; + + let found = references(&ws, &top_uri, offset, true); + assert_eq!( + places(&found), + vec![("eleaf.sv".to_string(), 1), ("eleaf.sv".to_string(), 2), ("etop.sv".to_string(), 3)], + "eleaf.sv's declaration and its own use, escaped name and all, via the closed-file repair" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (a), sharpened: an **indexed generate array**, not just a named +/// block. The array index changes how many instances of the scope exist, +/// not which scope `gsig` belongs to — which since TODO §65.1 is exactly +/// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found. +#[test] +fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() { + let dir = temp_dir("qa_generate_for"); + let leaf = "\ +module gfleaf; + for (genvar i = 0; i < 2; i++) begin : gen + wire gsig; + assign gsig = 1'b0; + end +endmodule +"; + let user = + "module gfuser;\n gfleaf u_g ();\n wire z;\n assign z = u_g.gen[0].gsig;\nendmodule\n"; + for (name, text) in [("gfleaf.sv", leaf), ("gfuser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let leaf_uri = uri_in(&dir, "gfleaf.sv"); + ws.set_document(leaf_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "gfuser.sv"); + ws.set_document(user_uri, user.to_string()); + + let decl = at(leaf, "wire gsig") + 5; + let doc = ws.document(&leaf_uri).expect("open"); + assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too"); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + vec![ + ("gfleaf.sv".to_string(), 2), + ("gfleaf.sv".to_string(), 3), + ("gfuser.sv".to_string(), 3) + ], + "this file and `u_g.gen[0].gsig`" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// An interface's signal, reached through a virtual-interface handle +/// (`vif.data`) from another file. Interface members are on the +/// **connection** surface already (`hierarchy.rs`, 2026-09-01), so +/// `member_in(…, Hierarchical)` answers exactly what `member` always did +/// — confirmed, not merely assumed unchanged. +#[test] +fn qa_an_interface_signal_through_a_virtual_interface_handle_is_unchanged() { + let dir = temp_dir("qa_interface"); + let iface = "interface bus_if;\n logic data;\nendinterface\n"; + let agent = "\ +class agent; + virtual bus_if vif; + function void f(); + vif.data = 1; + endfunction +endclass +"; + for (name, text) in [("bus_if.sv", iface), ("agent.sv", agent)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let iface_uri = uri_in(&dir, "bus_if.sv"); + ws.set_document(iface_uri.clone(), iface.to_string()); + let agent_uri = uri_in(&dir, "agent.sv"); + ws.set_document(agent_uri, agent.to_string()); + + assert_eq!( + places(&references(&ws, &iface_uri, at(iface, "logic data") + 6, true)), + vec![("agent.sv".to_string(), 3), ("bus_if.sv".to_string(), 1)], + "the interface signal, from the declaration" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (k). `documentHighlight` from the declaration and from the bind +/// file's connection: a *document* answer by contract regardless of +/// cross-file reachability (`references-nav`, 2026-08-28) — same-file +/// only, non-empty, unchanged by this lane. +#[test] +fn qa_document_highlight_over_the_bind_fixture_stays_same_file_only() { + let dir = temp_dir("qa_bind_highlight"); + let aes = "module aes (input logic clk_i, output logic idle_o);\n \ + logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; + let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; + let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ + .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; + for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let aes_uri = uri_in(&dir, "aes.sv"); + ws.set_document(aes_uri.clone(), aes.to_string()); + let bind_uri = uri_in(&dir, "aes_bind.sv"); + ws.set_document(bind_uri.clone(), bind_file.to_string()); + + let decl_doc = ws.document(&aes_uri).expect("open"); + let decl_highlights = document_highlights(decl_doc, at(aes, "entropy_masking_req") + 4) + .expect("highlights from the declaration"); + assert_eq!( + decl_highlights.iter().map(|h| h.range.start.line).collect::>(), + vec![1, 2], + "aes.sv's own two lines, never the bind file" + ); + + let bind_doc = ws.document(&bind_uri).expect("open"); + let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; + let bind_highlights = + document_highlights(bind_doc, expr_offset).expect("highlights from the bind file"); + assert_eq!( + bind_highlights.iter().map(|h| h.range.start.line).collect::>(), + vec![2], + "the bind file's own connection line only, never aes.sv" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (e), completed. `leaf.sv` closed, `top.sv` open: references from +/// the tail already include `leaf.sv`'s own in-file uses (the +/// closed-file repair). Then `leaf.sv` is **opened** with an unsaved +/// edit above the declaration: the answer must reflect the live, +/// shifted spans, not the ones the closed-file repair (or the index) +/// last computed. +#[test] +fn qa_reopening_the_declaring_file_with_an_unsaved_edit_gives_live_spans() { + let (dir, mut ws) = hierarchical("hier_reopen_live", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + let closed = references(&ws, &top_uri, two, true); + assert_eq!(places(&closed), every_place_naming_sig(), "closed: the repair supplies leaf.sv"); + + // Open `leaf.sv` with two lines pushed in above the declaration, + // never saved. + let leaf_uri = uri_in(&dir, "leaf.sv"); + let edited = "\ +// pushed +// down +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + ws.set_document(leaf_uri, edited.to_string()); + + let live = references(&ws, &top_uri, two, true); + let leaf_lines: Vec = live + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| l.range.start.line) + .collect(); + assert_eq!(leaf_lines, vec![3, 4], "the live, shifted spans — not the closed-file ones"); + let _ = fs::remove_dir_all(&dir); +} + +/// Oracle helper: `vlog_refactor::find_references`'s answer, as +/// `(file name, line)` — the same shape `places` gives `references`'s +/// own answer, so the two can be compared directly. +fn oracle_places( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, + include_declaration: bool, +) -> Vec<(String, u32)> { + let found = vlog_refactor::find_references(files, file, offset, include_declaration) + .expect("the oracle resolves it"); + let mut out: Vec<(String, u32)> = found + .iter() + .map(|(path, span)| { + let text = files.iter().find(|(p, _)| p == path).map(|(_, t)| t.as_str()).unwrap_or(""); + let line = text[..span.start as usize].matches('\n').count() as u32; + (path.file_name().unwrap().to_string_lossy().to_string(), line) + }) + .collect(); + out.sort(); + out +} + +/// Equivalence with the whole-scope oracle (charter item 4): the plain +/// hierarchical tail. `references` must equal what a rename would edit, +/// now that the indexed path answers this shape at all. +#[test] +fn qa_references_agrees_with_the_rename_oracle_over_a_plain_tail() { + let (dir, ws) = hierarchical("hier_oracle_tail", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (decl, _, _) = sig_positions(); + + let mut got = places(&references(&ws, &leaf_uri, decl, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("leaf.sv"), decl, true); + + assert_eq!(got, oracle, "references must equal what a rename would edit"); + let _ = fs::remove_dir_all(&dir); +} + +/// Equivalence with the oracle over the **bind** fixture. +#[test] +fn qa_references_agrees_with_the_rename_oracle_over_the_bind_fixture() { + let dir = temp_dir("qa_oracle_bind"); + let aes = "module aes (input logic clk_i, output logic idle_o);\n \ + logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; + let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; + let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ + .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; + for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let aes_uri = uri_in(&dir, "aes.sv"); + ws.set_document(aes_uri.clone(), aes.to_string()); + let bind_uri = uri_in(&dir, "aes_bind.sv"); + ws.set_document(bind_uri, bind_file.to_string()); + + let offset = at(aes, "entropy_masking_req"); + let mut got = places(&references(&ws, &aes_uri, offset, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("aes.sv"), offset, true); + + assert_eq!(got, oracle, "references must equal what a rename would edit, bind included"); + let _ = fs::remove_dir_all(&dir); +} + +/// Case (h) + equivalence: the **instance name** itself. Does the +/// instance segment of a hierarchical tail count as a reference, and +/// does `references` answer the same set a rename would edit? +#[test] +fn qa_an_instance_names_references_agree_with_the_rename_oracle() { + let (dir, ws) = + hierarchical("hier_oracle_instance", &["leaf.sv", "single.sv", "mid.sv", "top.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let offset = at(SINGLE, "u_leaf"); + + let mut got = places(&references(&ws, &single_uri, offset, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("single.sv"), offset, true); + + assert_eq!(got, oracle, "the instance name: same set a rename would edit"); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_package_import_resolves_into_the_packages_file() { + let dir = temp_dir("pkg"); + let pkg = dir.join("p_pkg.sv"); + fs::write(&pkg, "package p;\n localparam WIDTH = 8;\nendpackage\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "WIDTH-1")); + assert_eq!(locations.len(), 1, "WIDTH is declared in p_pkg.sv"); + assert_eq!(locations[0].uri, path_to_uri(&pkg).expect("uri")); + assert_eq!(locations[0].range.start.line, 1); + + let _ = fs::remove_dir_all(&dir); +} + +// ------------------------------------------------------------------ +// Final QA (2026-09-12): the declaration-site ladder, rung by rung. +// Rung (a) is the control test above; the prefix half of rung (c) is the +// flipped finding-4 test; rungs (e) and (f) with the declaration on are +// `qa_finding_2` and `qa_finding_3`. +// ------------------------------------------------------------------ + +/// The `leaf.sv` spans of an answer as `(line, start col, end col)`. +fn leaf_spans(found: &[Location]) -> Vec<(u32, u32, u32)> { + found + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) + .collect() +} + +/// Rung (b): an open buffer whose live lookup fails while the index-time +/// span still spells the name at the same bytes. `logic sig;` becomes +/// `wire sig;` — one byte longer keyword, one space fewer, so nothing +/// moves — and `logic` is `Var` where `wire` is `Net` (`bind/decl.rs`), +/// so `indexed_def_in_file`'s kind filter rejects the live symbol and the +/// live path finds nothing. The fallback span reads exactly `sig` at line +/// 1, columns 8..11, and is emitted; the buffer's own use resolves to the +/// rejected live symbol and is (consistently) not listed; and with +/// `includeDeclaration: false` the fallback is never consulted. +#[test] +fn qa_final_b_a_failed_live_lookup_with_the_name_still_in_place_emits_the_index_span() { + let (dir, mut ws) = hierarchical("hier_final_b", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let rekinded = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + wire sig; + assign sig = clk_i; +endmodule +"; + assert_eq!(at(rekinded, "sig;"), at(LEAF, "sig;"), "the edit moves nothing"); + ws.set_document(uri_in(&dir, "leaf.sv"), rekinded.to_string()); + + let with = references(&ws, &single_uri, one, true); + assert_eq!(leaf_spans(&with), vec![(1, 8, 11)], "the index-time span, still `sig`: {with:?}"); + assert_eq!( + places(&with), + vec![("leaf.sv".to_string(), 1), ("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "nothing else changes" + ); + let without = references(&ws, &single_uri, one, false); + assert_eq!( + places(&without), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "includeDeclaration: false never reaches the fallback" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Rung (c), the suffix half: `logic sig;` becomes `wire _sig;`, so bytes +/// 8..11 of line 1 still read `sig` but the byte before them is `_`, a +/// name character. No live symbol is named `sig`, the fallback is a +/// suffix of `_sig`, and `spells_exactly` refuses it: `leaf.sv` is absent. +#[test] +fn qa_final_c_an_index_span_now_a_suffix_of_a_longer_live_name_is_dropped() { + let (dir, mut ws) = hierarchical("hier_final_c", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let suffixed = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + wire _sig; + assign _sig = clk_i; +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert_eq!(&suffixed[o..o + 3], "sig", "the old bytes still read `sig`"); + assert_eq!(&suffixed[o - 1..o], "_", "as the tail of `_sig`"); + ws.set_document(uri_in(&dir, "leaf.sv"), suffixed.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "a suffix match is a miss: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Rung (d): the index-time span starts inside a multi-byte character of +/// the live text. Line 1 becomes a comment of two four-byte emoji placed +/// so the span's start byte is the last byte of the first one, and the +/// declaration below is renamed away so the live path finds nothing. +/// `spells_exactly` slices with `str::get`, which is `None` off a +/// boundary: no panic, and `leaf.sv` is omitted. +#[test] +fn qa_final_d_an_open_buffers_span_off_a_utf8_boundary_is_dropped_without_a_panic() { + let (dir, mut ws) = hierarchical("hier_final_d", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let emoji = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + // \u{1F642}\u{1F642} + logic sig2; + assign sig2 = clk_i; +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert!(!emoji.is_char_boundary(o), "the span starts mid-character"); + ws.set_document(uri_in(&dir, "leaf.sv"), emoji.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "off a boundary is a miss, not a panic: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// Rung (g) on the closed rungs: `includeDeclaration: false` emits no +/// declaration whether the closed declaring file is re-analysed (rung (e), +/// a hierarchical-only net, its live declaration known) or postings-only +/// (rung (f), a port, its index-time span guarded once) — before and +/// after a disk edit that moves the declaration. The open rungs are pinned +/// the same way by the control test and by rung (b). +#[test] +fn qa_final_g_include_declaration_false_emits_no_declaration_on_the_closed_rungs() { + let (dir, ws) = hierarchical("hier_final_g", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, sig, _) = sig_positions(); + let clk = at(SINGLE, ".clk_i(1'b0)") + 1; + + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![2]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), vec![2]); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + // (e): the re-analysis knows the live declaration (4) and the live + // use (5); without the declaration only the use is left. + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, true)), vec![4, 5]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![5]); + // (f): the header's port survives its guard (0); the moved use does + // not; without the declaration nothing in `leaf.sv` is left. + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, true)), vec![0]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), Vec::::new()); + let _ = fs::remove_dir_all(&dir); +} + +/// Observation, pinned rather than argued: the fallback is a textual +/// claim, on an open buffer exactly as on a closed file. A buffer whose +/// declaration is gone but where a *different* `sig` — here an undeclared +/// gate output — now sits at the very same bytes is reported as the +/// declaration. The token is a whole, exact `sig`, so `spells_exactly` +/// is right to accept it; whether that occurrence *is* the declaration is +/// a question the guard was never meant to answer, and the lead's to rule +/// on. +#[test] +fn qa_final_observation_a_different_exact_sig_at_the_old_bytes_is_reported() { + let (dir, mut ws) = hierarchical("hier_final_obs", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let reused = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + buf b(sig, clk_i); +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert_eq!(&reused[o..o + 3], "sig"); + assert_eq!(&reused[o - 1..o + 4], "(sig,"); + ws.set_document(uri_in(&dir, "leaf.sv"), reused.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!(leaf_spans(&after), vec![(1, 8, 11)], "{after:?}"); + let _ = fs::remove_dir_all(&dir); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/pairs.rs b/crates/lucisv_server/src/pairs.rs index 3b4f1ae..39c6f8a 100644 --- a/crates/lucisv_server/src/pairs.rs +++ b/crates/lucisv_server/src/pairs.rs @@ -572,1339 +572,6 @@ fn article(word: &str) -> &'static str { } #[cfg(test)] -mod tests { - use super::*; - use crate::state::Workspace; - use lsp_types::Uri; - use std::str::FromStr; - use vlog_parser::tokenize; - use vlog_semantic::WorkspaceIndex; - - /// The analysis of a source string, straight off the lexer — no parser - /// involved, which is the point: the matcher must stand on its own. - fn scopes(text: &str) -> ScopeAnalysis { - let tokens = tokenize(text).expect("the fixtures all lex"); - analyze(&tokens) - } - - /// The source text of every matched pair, as `open..close`. - fn matched(text: &str) -> Vec { - let analysis = scopes(text); - analysis - .pairs - .iter() - .map(|p| { - format!( - "{}..{}", - &text[p.open.start as usize..p.open.end as usize], - &text[p.close.start as usize..p.close.end as usize] - ) - }) - .collect() - } - - /// The keyword of every unclosed opener, in source order. - fn unclosed(text: &str) -> Vec<&'static str> { - scopes(text).unmatched_open.iter().map(|u| u.keyword).collect() - } - - #[test] - fn the_vendor_and_formal_blocks_are_scopes() { - // `vendor-formal-grammar`, 2026-09-02. A rule only fires on a - // `TokenKind::Keyword`, so `checker` and `config` became matchable - // the moment the lexer reserved them; `table` was a keyword all along - // and simply had no row. - assert_eq!( - matched("primitive p (q, a);\n table\n 0 : 1;\n endtable\nendprimitive\n"), - ["primitive..endprimitive", "table..endtable"] - ); - assert_eq!( - matched("checker c (logic a);\n checker d (logic b);\n endchecker\nendchecker\n"), - ["checker..endchecker", "checker..endchecker"] - ); - assert_eq!(matched("config cfg;\n design work.top;\nendconfig\n"), ["config..endconfig"]); - assert_eq!( - matched("module m;\n specify\n endspecify\nendmodule\n"), - ["module..endmodule", "specify..endspecify"] - ); - } - - #[test] - fn an_unclosed_vendor_block_is_reported_against_its_own_keyword() { - assert_eq!(unclosed("checker c (logic a);\n"), ["checker"]); - assert_eq!(unclosed("config cfg;\n"), ["config"]); - assert_eq!(orphan_closers("endchecker\n"), ["endchecker"]); - } - - /// The keyword of every closer that closed nothing. - fn orphan_closers(text: &str) -> Vec<&'static str> { - scopes(text).unmatched_close.iter().map(|u| u.keyword).collect() - } - - fn doc_of(text: &str) -> Document { - Document::new(None, text.to_string(), &WorkspaceIndex::default()) - } - - /// The byte offset of `needle` in `text`. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - // ------------------------------------------------------------------ - // the basics - // ------------------------------------------------------------------ - - #[test] - fn a_module_with_nested_begins_matches_every_pair() { - let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(analysis.pairs.len(), 3); - assert!(analysis.unmatched_open.is_empty()); - assert!(analysis.unmatched_close.is_empty()); - // Depth counts only the scopes the rainbow draws. The module is one of - // the nineteen it does not, so it is 0 and does not push the `begin` - // under it off colour 0. - let depths: Vec = analysis.pairs.iter().map(|p| p.depth).collect(); - assert_eq!(depths, vec![0, 0, 1], "module (uncounted), outer begin, inner begin"); - } - - #[test] - fn a_comment_or_a_string_never_counts_as_a_keyword() { - // Hard invariant of the whole approach: the lexer detaches comments - // and makes the literal one token, so neither can push or pop. - let text = "module m;\n // end endmodule\n initial begin\n /* begin */\n $display(\"end begin endmodule\");\n end\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(analysis.pairs.len(), 2, "the module and the one real begin"); - assert!(analysis.unmatched_open.is_empty()); - assert!(analysis.unmatched_close.is_empty()); - } - - #[test] - fn a_labeled_block_matches_on_the_keywords_alone() { - let text = "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(analysis.pairs.len(), 3); - assert!(analysis.unmatched_open.is_empty(), "labels are not part of the match"); - } - - #[test] - fn every_fork_flavour_joins() { - for closer in ["join", "join_any", "join_none"] { - let text = format!("module m;\n initial fork\n x = 1;\n {closer}\nendmodule\n"); - let analysis = scopes(&text); - assert_eq!(analysis.pairs.len(), 2, "module + fork, closed by {closer}"); - assert!(analysis.unmatched_open.is_empty(), "{closer} must close a fork"); - } - } - - #[test] - fn every_case_flavour_ends() { - for opener in ["case", "casex", "casez", "randcase"] { - let text = - format!("module m;\n initial {opener} (x)\n 1: y = 1;\n endcase\nendmodule\n"); - assert!(scopes(&text).unmatched_open.is_empty(), "{opener} must take endcase"); - } - } - - #[test] - fn the_named_scopes_all_pair_up() { - let cases = [ - ("module m;\nendmodule\n", "module"), - ("macromodule m;\nendmodule\n", "macromodule"), - ("package p;\nendpackage\n", "package"), - ("interface i;\nendinterface\n", "interface"), - ("program p;\nendprogram\n", "program"), - ("class c;\nendclass\n", "class"), - ("module m;\n function f;\n endfunction\nendmodule\n", "function"), - ("module m;\n task t;\n endtask\nendmodule\n", "task"), - ("module m;\n generate\n endgenerate\nendmodule\n", "generate"), - ("module m;\n specify\n endspecify\nendmodule\n", "specify"), - ("primitive p (o, i);\nendprimitive\n", "primitive"), - ("module m;\n property p;\n endproperty\nendmodule\n", "property"), - ("module m;\n sequence s;\n endsequence\nendmodule\n", "sequence"), - ("module m;\n clocking cb @(posedge clk);\n endclocking\nendmodule\n", "clocking"), - ("class c;\n covergroup cg;\n endgroup\nendclass\n", "covergroup"), - ]; - for (text, what) in cases { - let analysis = scopes(text); - assert!(analysis.unmatched_open.is_empty(), "{what} left something open"); - assert!(analysis.unmatched_close.is_empty(), "{what} left a stray closer"); - assert!(!analysis.pairs.is_empty(), "{what} matched nothing at all"); - } - } - - // ------------------------------------------------------------------ - // hazards: keywords that open nothing - // ------------------------------------------------------------------ - - #[test] - fn an_extern_prototype_opens_nothing() { - let text = "class c;\n extern function void f(int a);\n extern task t();\nendclass\n"; - assert!(unclosed(text).is_empty(), "prototypes have no body"); - assert_eq!(matched(text), vec!["class..endclass"]); - } - - #[test] - fn a_pure_virtual_method_opens_nothing() { - let text = "class c;\n pure virtual function int g();\nendclass\n"; - assert!(unclosed(text).is_empty()); - assert_eq!(matched(text), vec!["class..endclass"]); - } - - #[test] - fn a_dpi_import_or_export_opens_nothing() { - let text = "module m;\n import \"DPI-C\" function void c_init(input int a);\n import \"DPI-C\" context function int c_get();\n export \"DPI-C\" function f;\nendmodule\n"; - assert!(unclosed(text).is_empty(), "DPI declarations have no body"); - assert_eq!(matched(text), vec!["module..endmodule"]); - } - - #[test] - fn an_extern_module_header_opens_nothing() { - let text = "extern module m (input a);\nmodule m (input a);\nendmodule\n"; - assert!(unclosed(text).is_empty()); - assert_eq!(matched(text), vec!["module..endmodule"], "only the real one"); - } - - #[test] - fn a_package_import_does_not_swallow_the_next_declaration() { - // The prototype flag is dropped at the `;`, so an ordinary - // `import p::*;` must not suppress the function after it. - let text = "module m;\n import p::*;\n function f;\n endfunction\nendmodule\n"; - assert!(unclosed(text).is_empty()); - assert_eq!(matched(text), vec!["module..endmodule", "function..endfunction"]); - } - - #[test] - fn a_module_header_import_does_not_suppress_the_body() { - let text = "module m import p::*; (input a);\n initial begin\n end\nendmodule\n"; - assert!(unclosed(text).is_empty()); - assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); - } - - #[test] - fn a_typedef_class_is_a_forward_declaration() { - let text = "typedef class C;\nclass C;\n int x;\nendclass\n"; - assert!(unclosed(text).is_empty(), "the forward declaration opens nothing"); - assert_eq!(matched(text), vec!["class..endclass"], "only the real class"); - } - - #[test] - fn a_virtual_interface_member_is_a_type() { - let text = "class c;\n virtual interface bus_if vif;\n virtual bus_if v2;\nendclass\n"; - assert!(unclosed(text).is_empty(), "`virtual interface` is a type"); - assert_eq!(matched(text), vec!["class..endclass"]); - } - - #[test] - fn a_virtual_class_still_opens() { - let text = "virtual class C;\n int x;\nendclass\n"; - assert_eq!(matched(text), vec!["class..endclass"], "an abstract class has a body"); - } - - #[test] - fn an_interface_class_is_closed_by_endclass() { - // `interface class IC; ... endclass`: the `class` opens, the - // `interface` in front of it does not, or the `endclass` would find - // an `interface` frame on top of the stack and report both wrong. - let text = "interface class IC;\n pure virtual function void f();\nendclass\n"; - assert_eq!(matched(text), vec!["class..endclass"]); - assert!(unclosed(text).is_empty()); - assert!(orphan_closers(text).is_empty()); - } - - #[test] - fn a_generic_interface_port_opens_nothing() { - let text = "module m (interface bus, input logic clk);\nendmodule\n"; - assert_eq!(matched(text), vec!["module..endmodule"]); - assert!(unclosed(text).is_empty(), "a port is not a declaration"); - } - - #[test] - fn a_default_clocking_reference_opens_nothing() { - let text = "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n"; - assert!(unclosed(text).is_empty(), "`default clocking cb;` names an existing block"); - assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); - } - - #[test] - fn an_unnamed_default_clocking_block_still_opens() { - let text = "module m;\n default clocking @(posedge clk);\n endclocking\nendmodule\n"; - assert!(unclosed(text).is_empty()); - assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); - } - - #[test] - fn an_assertion_does_not_open_a_property() { - let text = "module m;\n a1: assert property (@(posedge clk) a |-> b);\n cover property (@(posedge clk) c);\n assume property (@(posedge clk) d);\nendmodule\n"; - assert!(unclosed(text).is_empty(), "`assert property (` opens nothing"); - assert_eq!(matched(text), vec!["module..endmodule"]); - } - - #[test] - fn a_property_declaration_does_open() { - let text = - "module m;\n property p;\n @(posedge clk) a |-> b;\n endproperty\nendmodule\n"; - assert_eq!(matched(text), vec!["module..endmodule", "property..endproperty"]); - } - - #[test] - fn disable_fork_and_wait_fork_are_statements() { - let text = "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n wait fork;\n end\nendmodule\n"; - assert!(unclosed(text).is_empty(), "`disable fork;` starts no fork"); - assert_eq!(matched(text), vec!["module..endmodule", "begin..end", "fork..join_any"]); - } - - #[test] - fn a_covergroup_sample_method_opens_nothing() { - // Found by sweeping the corpus, not by reading the LRM: seven of the - // 840 files that parse cleanly write this, and every one of them is a - // UVM coverage class. `with function sample(...)` names the - // covergroup's sample method in its header; the `endgroup` closes the - // lot, and there is no `endfunction` anywhere. - let text = "class c;\n covergroup cg with function sample(int lvl, bit rst);\n cp: coverpoint lvl;\n endgroup\n function new();\n endfunction\nendclass\n"; - assert!(unclosed(text).is_empty(), "the sample method has no body of its own"); - assert_eq!( - matched(text), - vec!["class..endclass", "covergroup..endgroup", "function..endfunction"], - "and the real function next to it still pairs" - ); - } - - #[test] - fn a_macro_invocation_is_invisible_to_the_matcher() { - // A macro body is not in this token stream, so a macro that expands to - // a whole block must neither open nor close anything. This is why the - // diagnostics below are gated on the parser having already failed. - let text = - "class c;\n `uvm_component_utils(c)\n `uvm_do_with(item, { a == 1; })\nendclass\n"; - assert_eq!(matched(text), vec!["class..endclass"]); - assert!(unclosed(text).is_empty()); - assert!(orphan_closers(text).is_empty()); - } - - // ------------------------------------------------------------------ - // hazards: mismatch recovery - // ------------------------------------------------------------------ - - #[test] - fn a_missing_end_points_at_the_innermost_unclosed_begin() { - let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n"; - let analysis = scopes(text); - // The one `end` closes the inner begin; the outer one is left open. - assert_eq!(analysis.unmatched_open.len(), 1); - assert_eq!(analysis.unmatched_open[0].keyword, "begin"); - assert_eq!(analysis.unmatched_open[0].expected, "end"); - assert_eq!( - analysis.unmatched_open[0].span.start, - at(text, "begin"), - "the `initial begin` on line 2, not the module and not the inner begin" - ); - // And the module still matched, which is the whole point of the - // recovery rule: one missing `end` must not lose `endmodule`. - assert!(matched(text).contains(&"module..endmodule".to_string())); - } - - #[test] - fn two_missing_ends_are_both_reported_in_source_order() { - let text = "module m;\n initial begin\n if (x) begin\n y = 1;\nendmodule\n"; - let analysis = scopes(text); - let keywords: Vec<_> = analysis.unmatched_open.iter().map(|u| u.keyword).collect(); - assert_eq!(keywords, vec!["begin", "begin"]); - assert!(analysis.unmatched_open[0].span.start < analysis.unmatched_open[1].span.start); - assert_eq!(matched(text), vec!["module..endmodule"]); - } - - #[test] - fn a_stray_end_matches_nothing_and_disturbs_nothing() { - let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(orphan_closers(text), vec!["end"], "the second `end` closes nothing"); - assert!(analysis.unmatched_open.is_empty(), "the stack must be left alone"); - assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); - } - - #[test] - fn a_wrong_closer_does_not_pop_the_frame_it_does_not_match() { - // `endmodule` while a `begin` is open: the begin is reported unclosed - // and the module still pairs. Popping blindly would pair `begin` with - // `endmodule` and then report the module unclosed — two lies for one - // missing keyword. - let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(matched(text), vec!["module..endmodule"]); - assert_eq!(analysis.unmatched_open.len(), 1); - assert_eq!(analysis.unmatched_open[0].keyword, "begin"); - } - - #[test] - fn an_endcase_with_no_case_is_an_orphan_closer() { - let text = "module m;\n initial begin\n endcase\n end\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(orphan_closers(text), vec!["endcase"]); - assert_eq!(analysis.unmatched_close[0].expected, "case", "it wanted a case"); - assert_eq!(matched(text), vec!["module..endmodule", "begin..end"], "nothing else moved"); - } - - #[test] - fn an_orphan_join_names_the_fork_it_wanted() { - let text = "module m;\n initial begin\n join_none\n end\nendmodule\n"; - let analysis = scopes(text); - assert_eq!(analysis.unmatched_close.len(), 1); - assert_eq!(analysis.unmatched_close[0].keyword, "join_none"); - assert_eq!(analysis.unmatched_close[0].expected, "fork"); - } - - #[test] - fn an_empty_stream_analyzes_to_nothing() { - let analysis = analyze(&[]); - assert!(analysis.pairs.is_empty()); - assert!(analysis.unmatched_open.is_empty()); - assert!(analysis.unmatched_close.is_empty()); - } - - #[test] - fn a_file_that_does_not_lex_has_no_tokens_and_no_pairs() { - // `Document::new` leaves `tokens` empty when the lexer gives up, so - // the matcher sees nothing rather than a truncated stream. - let doc = doc_of("module m;\n wire a; /* unterminated\n"); - assert!(doc.tokens.is_empty()); - assert!(analyze(&doc.tokens).pairs.is_empty()); - assert!(missing_end_diagnostics(&doc).is_empty(), "and says nothing about it"); - } - - // ------------------------------------------------------------------ - // the running counts on `Stack` - // ------------------------------------------------------------------ - - /// The pre-counter algorithm, kept here as an oracle: the same matcher - /// with `depth` scanned off the stack at every push, which is how the code - /// computed it before the running count replaced the scan. Returns - /// `(opener start, depth)` for every pair it closes. - /// - /// The old comment claimed the scan was "immune to the mismatch recovery - /// in `close`, which pops frames from the middle". That immunity is now - /// `Stack`'s job, so the claim is worth a second implementation to check - /// against rather than a hand-written expectation. - fn scanned_pairs(tokens: &[Token]) -> Vec<(u32, u32)> { - struct Slow { - rule: &'static Rule, - start: u32, - depth: u32, - } - let mut stack: Vec = Vec::new(); - let mut pairs: Vec<(u32, u32)> = Vec::new(); - let mut prototype = false; - for (i, token) in tokens.iter().enumerate() { - if token.is_sym(";") { - prototype = false; - continue; - } - if token.kind != TokenKind::Keyword { - continue; - } - let text = token.text.as_str(); - if PROTOTYPE_STARTERS.contains(&text) { - prototype = true; - continue; - } - if let Some((_, rule)) = opener_rule(text) { - if !prototype && opens_a_scope(tokens, i) { - let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32; - stack.push(Slow { rule, start: token.span.start, depth }); - } - } else if let Some(closer) = closer_keyword(text) { - let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else { - continue; - }; - stack.drain(index + 1..); - if let Some(frame) = stack.pop() { - pairs.push((frame.start, frame.depth)); - } - } - } - pairs.sort_unstable(); - pairs - } - - /// `analyze`'s own answer in the oracle's shape. - fn counted_pairs(tokens: &[Token]) -> Vec<(u32, u32)> { - let mut pairs: Vec<(u32, u32)> = - analyze(tokens).pairs.iter().map(|p| (p.open.start, p.depth)).collect(); - pairs.sort_unstable(); - pairs - } - - #[test] - fn the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack() { - // Every fixture puts rainbow and non-rainbow scopes in the same nest - // and then makes `close` remove frames from the middle, which is the - // only way a running counter can drift from a scan. - let cases = [ - ( - // A `join` that closes the `fork` below the top: the `begin` - // and the `case` above it are drained, and the `begin` after - // must land at depth 1 (inside the outer `begin` alone), not - // at 3. - concat!( - "module m;\n", - " initial begin\n", - " fork\n", - " begin\n", - " case (x)\n", - " join\n", - " begin\n", - " y = 1;\n", - " end\n", - " end\n", - "endmodule\n", - ), - "a join draining two rainbow frames out of the middle", - ), - ( - // The mirror: a non-rainbow frame closes with rainbow frames - // stacked on top of it, so the drain has to give back counts - // for frames that are not the one being closed. - concat!( - "module m;\n", - " case (x)\n", - " 1: begin\n", - " fork\n", - " endcase\n", - " initial begin\n", - " end\n", - "endmodule\n", - ), - "an endcase draining a begin and a fork above it", - ), - ( - // A closer that matches nothing must leave the counts exactly - // as it found them, or the `begin` after it shifts colour. - concat!( - "module m;\n", - " initial begin\n", - " begin\n", - " join_none\n", - " begin\n", - " end\n", - " end\n", - " end\n", - "endmodule\n", - ), - "a stray join_none between two pushes", - ), - ( - // Recovery twice over, with the outer scopes still closing. - concat!( - "module m;\n", - " function f;\n", - " fork\n", - " begin\n", - " case (y)\n", - " endfunction\n", - " task t;\n", - " begin\n", - " fork\n", - " begin\n", - " end\n", - " join\n", - " end\n", - " endtask\n", - "endmodule\n", - ), - "two recoveries in one file", - ), - ]; - for (text, what) in cases { - let tokens = tokenize(text).expect("the fixtures all lex"); - let counted = counted_pairs(&tokens); - assert!(!counted.is_empty(), "{what}: the fixture matched nothing at all"); - assert_eq!(counted, scanned_pairs(&tokens), "{what}: the counter drifted from a scan"); - } - // And on every fixture the rest of this module already uses, so a - // drift anywhere in the corpus of shapes above fails here too. - for text in [ - "module m;\n initial begin\n fork\n begin\n end\n join\n end\nendmodule\n", - "module m;\n initial begin\n case (x)\n 1: begin\n end\n endcase\n end\nendmodule\n", - "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n", - ] { - let tokens = tokenize(text).expect("lexes"); - assert_eq!(counted_pairs(&tokens), scanned_pairs(&tokens), "{text}"); - } - } - - #[test] - fn analysis_is_linear_in_nesting_depth_not_quadratic() { - // Two of these three shapes were O(n²) until the running counts landed: - // the depth of a push was scanned off the whole stack, and a closer - // that matched no frame scanned the whole stack to find that out. The - // third is not a shape that was ever slow — it is here so that the - // per-rule counts have to be *given back*, not merely taken: a drain - // that forgets to decrement leaves the guard permanently answering - // "maybe", which quietly restores the second quadratic. - // - // The budget is wall clock, which is coarse on purpose. Measured on - // the dev machine (debug build) at this N: the three shapes cost 5 ms, - // 41 ms and 44 ms with the counts, against roughly 7 s, 17 s and 15 s - // for the quadratic version of each. Two seconds is therefore ~45× - // the honest cost — room for a machine several times slower than this - // one, under load — while still being a small fraction of what any of - // the three quadratics needs. - const N: usize = 30_000; - const BUDGET: std::time::Duration = std::time::Duration::from_secs(2); - - let deep = "begin\n".repeat(N); - let tokens = tokenize(&deep).expect("lexes"); - let started = std::time::Instant::now(); - let analysis = analyze(&tokens); - let elapsed = started.elapsed(); - assert_eq!(analysis.unmatched_open.len(), N, "premise: all {N} really are open at once"); - assert!(elapsed < BUDGET, "{N} nested begins took {elapsed:?}"); - - // `endcase` can close nothing on a stack of `begin`s, so every one of - // them is the no-match case. - let mut stray = "begin\n".repeat(N); - stray.push_str(&"endcase\n".repeat(N)); - let tokens = tokenize(&stray).expect("lexes"); - let started = std::time::Instant::now(); - let analysis = analyze(&tokens); - let elapsed = started.elapsed(); - assert_eq!(analysis.unmatched_close.len(), N, "premise: none of them matched"); - assert_eq!(analysis.unmatched_open.len(), N, "premise: and none of the begins closed"); - assert!(elapsed < BUDGET, "{N} never-matching closers took {elapsed:?}"); - - // `endcase` closes the `case` at the bottom and drains N `begin`s out - // of the middle on the way — so by the time the N `case`s below the - // `end`s are on the stack, no `begin` is open and every `end` must be - // declined without a scan. It is declined either way; the question is - // whether the counts remember that the drained `begin`s are gone. - let mut given_back = String::from("case (x)\n"); - given_back.push_str(&"begin\n".repeat(N)); - given_back.push_str("endcase\n"); - given_back.push_str(&"case (x)\n".repeat(N)); - given_back.push_str(&"end\n".repeat(N)); - let tokens = tokenize(&given_back).expect("lexes"); - let started = std::time::Instant::now(); - let analysis = analyze(&tokens); - let elapsed = started.elapsed(); - assert_eq!(analysis.pairs.len(), 1, "premise: only the outer case/endcase pairs"); - assert_eq!(analysis.unmatched_open.len(), 2 * N, "premise: N drained begins, N open cases"); - assert_eq!(analysis.unmatched_close.len(), N, "premise: no end can close a case"); - assert!(elapsed < BUDGET, "{N} closers over drained frames took {elapsed:?}"); - } - - // ------------------------------------------------------------------ - // QA (2026-08-25, perf fix) — independent full-fidelity differential - // check against the pre-`Stack` algorithm. Kept as a permanent - // regression test, unlike the dev's own oracle - // (`the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack`), - // which only compares `(open start, depth)`: this one diffs every field - // of `ScopeAnalysis` — both unmatched lists included — and adds - // adversarial fixtures the dev's own tests do not cover (shared-closer - // priority, deep mixed-rainbow drains with more pushes/closes - // afterward, prototype interleavings, closers before any opener) plus a - // fixed-seed fuzz sweep. - // ------------------------------------------------------------------ - - /// HEAD's `Frame`, transcribed from `git show HEAD:.../pairs.rs`, before - /// `Stack` existed. - struct OldFrame { - rule: &'static Rule, - span: TextRange, - depth: u32, - } - - /// HEAD's `close`, transcribed verbatim (modulo the `Vec` type). - fn old_close( - analysis: &mut ScopeAnalysis, - stack: &mut Vec, - closer: &'static str, - span: TextRange, - ) { - let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else { - analysis.unmatched_close.push(Unmatched { - span, - keyword: closer, - expected: opener_of(closer), - }); - return; - }; - for frame in stack.drain(index + 1..) { - analysis.unmatched_open.push(Unmatched { - span: frame.span, - keyword: frame.rule.open, - expected: frame.rule.close[0], - }); - } - if let Some(frame) = stack.pop() { - analysis.pairs.push(Pair { - open: frame.span, - close: span, - keyword: frame.rule.open, - depth: frame.depth, - }); - } - } - - /// HEAD's `analyze`, transcribed verbatim (modulo `opener_rule`'s new - /// `(usize, &Rule)` signature, whose index this oracle ignores). - fn old_analyze(tokens: &[Token]) -> ScopeAnalysis { - let mut analysis = ScopeAnalysis::default(); - let mut stack: Vec = Vec::new(); - let mut prototype = false; - for (i, token) in tokens.iter().enumerate() { - if token.is_sym(";") { - prototype = false; - continue; - } - if token.kind != TokenKind::Keyword { - continue; - } - let text = token.text.as_str(); - if PROTOTYPE_STARTERS.contains(&text) { - prototype = true; - continue; - } - if let Some((_, rule)) = opener_rule(text) { - if !prototype && opens_a_scope(tokens, i) { - let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32; - stack.push(OldFrame { rule, span: token.span, depth }); - } - } else if let Some(closer) = closer_keyword(text) { - old_close(&mut analysis, &mut stack, closer, token.span); - } - } - for frame in stack { - analysis.unmatched_open.push(Unmatched { - span: frame.span, - keyword: frame.rule.open, - expected: frame.rule.close[0], - }); - } - analysis.pairs.sort_by_key(|p| p.open.start); - analysis.unmatched_open.sort_by_key(|u| u.span.start); - analysis.unmatched_close.sort_by_key(|u| u.span.start); - analysis - } - - /// Every field of `ScopeAnalysis` that matters, in one comparable value — - /// not just `(open start, depth)` the dev's own oracle checks. - #[allow(clippy::type_complexity)] - fn qa_fingerprint( - a: &ScopeAnalysis, - ) -> ( - Vec<(u32, u32, &'static str, u32)>, - Vec<(u32, &'static str, &'static str)>, - Vec<(u32, &'static str, &'static str)>, - ) { - ( - a.pairs.iter().map(|p| (p.open.start, p.close.start, p.keyword, p.depth)).collect(), - a.unmatched_open.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(), - a.unmatched_close.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(), - ) - } - - fn qa_assert_identical(text: &str, what: &str) { - let tokens = tokenize(text).unwrap_or_else(|e| panic!("{what}: fixture must lex: {e:?}")); - let old = qa_fingerprint(&old_analyze(&tokens)); - let new = qa_fingerprint(&analyze(&tokens)); - assert_eq!(old, new, "{what}: old and new algorithms disagree on:\n{text:?}"); - } - - #[test] - fn qa_old_and_new_algorithms_agree_field_for_field() { - // Empty input. - qa_assert_identical("", "empty input"); - - // Every closer keyword, alone and before any opener at all — every - // closer in RULES, not just `end`. - for rule in RULES { - for closer in rule.close { - qa_assert_identical(closer, &format!("bare closer {closer}")); - qa_assert_identical( - &format!("{closer} {closer} {closer}"), - &format!("three bare {closer} in a row"), - ); - } - } - - // Shared-closer priority: several rules accept the same closer - // keyword. `endcase` is accepted by case/casex/casez/randcase (4 - // rules); `endmodule` by module/macromodule (2). Nest mismatched - // openers that share a closer and confirm both algorithms pick the - // same *topmost* frame (the `rposition` scan's priority), not merely - // "some frame that fits". - qa_assert_identical( - "case casex casez randcase endcase endcase endcase endcase", - "endcase closes topmost-first across 4 sharing rules", - ); - qa_assert_identical( - "module macromodule endmodule endmodule", - "endmodule closes topmost-first across 2 sharing rules", - ); - qa_assert_identical( - "module begin fork case casex endcase join begin end endmodule", - "a shared-closer rule interleaved with rainbow frames, drained and not", - ); - - // Interleaved rainbow / non-rainbow scopes, closers reaching deep - // below the top and draining a mix of both kinds, with more - // pushing/closing continuing afterward (so a stale count would show - // up on the *next* pair, not just the one being closed). - qa_assert_identical( - "begin fork case begin fork begin join begin end endcase begin end join end begin end end", - "deep mixed drain (join draining case+begin+fork) then more begins after", - ); - qa_assert_identical( - "module function task begin fork case endcase join endtask endfunction begin end endmodule", - "drain across 3 non-rainbow frames and 2 rainbow frames in one closer, then a fresh pair after", - ); - qa_assert_identical( - "begin begin begin endcase begin end end end end", - "a non-matching closer (endcase) between two begins changes nothing, more begins follow", - ); - - // Prototype mode interleaved with opens and closes: the flag must - // drop at the next `;` regardless of what real scopes are doing - // around it. - qa_assert_identical( - "extern function ; begin fork join end pure task ; begin end import function ; class endclass", - "prototype starters interleaved with real opens/closes", - ); - qa_assert_identical( - "begin extern module ; fork join end typedef class ; begin end", - "a prototype flag raised and dropped while a rainbow frame is already open", - ); - - // Unmatched closers of every flavor stacked back to back with no - // openers anywhere, then a real pair afterward. - qa_assert_identical( - "end join join_any join_none endcase endmodule endfunction begin end", - "a run of unmatched closers of every closer family, then one real pair", - ); - - // Closers before any opener, mixed with a later real pair. - qa_assert_identical( - "end end join begin end", - "closers before any opener, then a real pair", - ); - - // A small xorshift PRNG (no external dependency, per CLAUDE.md) over - // a vocabulary that exercises every `opens_a_scope` guard - // (interface/property/sequence/clocking/fork/function) as well as - // plain opens, closes, prototype starters and `;`. - let vocab: Vec<&str> = RULES - .iter() - .flat_map(|r| std::iter::once(r.open).chain(r.close.iter().copied())) - .chain(PROTOTYPE_STARTERS.iter().copied()) - .chain([ - "with", "disable", "wait", "virtual", "class", "(", ",", "@", "posedge", "x", "cb", - ";", - ]) - .collect(); - - let mut state: u64 = 0x2545_F491_4F6C_DD1D; - let mut next = || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - - for round in 0..500u32 { - let len = 10 + (next() % 40) as usize; - let mut text = String::new(); - for _ in 0..len { - let word = vocab[(next() as usize) % vocab.len()]; - text.push_str(word); - text.push(' '); - } - // Not every random token soup lexes (e.g. a lone `@` needs - // nothing special, but skip anything the lexer itself rejects — - // this test is about matcher agreement, not lexer coverage). - if let Ok(tokens) = tokenize(&text) { - let old = qa_fingerprint(&old_analyze(&tokens)); - let new = qa_fingerprint(&analyze(&tokens)); - assert_eq!(old, new, "fuzz round {round}: old and new disagree on:\n{text:?}"); - } - } - } - - // ------------------------------------------------------------------ - // documentHighlight - // ------------------------------------------------------------------ - - #[test] - fn the_cursor_on_begin_highlights_its_own_end() { - let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; - let doc = doc_of(text); - let outer = at(text, "begin"); - let found = highlights(&doc, outer).expect("a pair"); - assert_eq!(found.len(), 2); - assert_eq!(found[0].range.start.line, 1, "the outer begin"); - assert_eq!(found[1].range.start.line, 5, "and the outer end, not the inner one"); - assert_eq!(found[0].kind, Some(DocumentHighlightKind::TEXT)); - } - - #[test] - fn the_cursor_on_end_highlights_its_own_begin() { - let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; - let doc = doc_of(text); - let inner_end = at(text, " end"); - let found = highlights(&doc, inner_end + 4).expect("a pair"); - assert_eq!(found[0].range.start.line, 2, "the inner begin"); - assert_eq!(found[1].range.start.line, 4, "the inner end"); - } - - #[test] - fn the_cursor_at_either_edge_of_the_keyword_still_matches() { - let text = "module m;\n initial begin\n end\nendmodule\n"; - let doc = doc_of(text); - let begin = at(text, "begin"); - for (offset, where_) in [(begin, "first byte"), (begin + 5, "just past the last")] { - let found = highlights(&doc, offset).expect(where_); - assert_eq!(found.len(), 2, "cursor at the {where_}"); - } - assert!(highlights(&doc, begin - 1).is_none(), "the space before is not the keyword"); - } - - #[test] - fn a_multibyte_comment_before_the_keyword_does_not_shift_the_range() { - // The `é` is 2 bytes and 1 UTF-16 unit; a byte-based range would put - // the highlight one column late. - let text = "module m;\n // é\n initial begin\n end\nendmodule\n"; - let doc = doc_of(text); - let found = highlights(&doc, at(text, "begin")).expect("a pair"); - assert_eq!(found[0].range.start.line, 2); - assert_eq!(found[0].range.start.character, 10, "in UTF-16 units"); - assert_eq!(found[0].range.end.character, 15); - } - - #[test] - fn the_cursor_on_an_unmatched_keyword_highlights_nothing() { - // Not "everything that looks like an `end`" — `None` lets the editor - // fall back to its own word highlighting. - let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; - let doc = doc_of(text); - assert!(highlights(&doc, at(text, "begin")).is_none(), "the begin never closed"); - let stray = "module m;\n end\nendmodule\n"; - let doc = doc_of(stray); - assert!(highlights(&doc, at(stray, "end\n")).is_none(), "the end opened nothing"); - } - - #[test] - fn the_cursor_somewhere_else_entirely_highlights_nothing() { - let text = "module m;\n wire a;\nendmodule\n"; - let doc = doc_of(text); - assert!(highlights(&doc, at(text, "wire")).is_none()); - } - - // ------------------------------------------------------------------ - // lucisv/scopePairs - // ------------------------------------------------------------------ - - #[test] - fn scope_pairs_carries_only_block_delimiters() { - // The module, the class and the case are all matched by the engine and - // all dropped here: the rainbow is for the `begin` ladder. - let text = "module m;\n initial begin\n case (x)\n 1: y = 1;\n endcase\n end\n function f;\n endfunction\nendmodule\n"; - let doc = doc_of(text); - let sent = scope_pairs(&doc); - assert_eq!(sent.pairs.len(), 1, "only the begin/end survives the filter"); - assert_eq!(sent.pairs[0].open.start.line, 1); - assert_eq!(sent.pairs[0].close.start.line, 5); - // The engine itself still saw all four. - assert_eq!(analyze(&doc.tokens).pairs.len(), 4); - } - - #[test] - fn scope_pairs_depths_nest_and_forks_are_included() { - let text = "module top;\n initial begin\n if (a) begin\n b = 1;\n end\n end\n initial fork\n c = 1;\n join\nendmodule\n"; - let doc = doc_of(text); - let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); - // The module does not count, so the outer begin is 0; the begin inside - // it is 1; the fork is the outer begin's sibling, so 0 again. - assert_eq!(depths, vec![0, 1, 0]); - } - - #[test] - fn a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows() { - // The M5 bug, as the user reported it: "for blocks that don't have - // begin/end, like inside of a case statement, I can see an invisible - // begin/end being highlighted." The `case` was counted but never - // drawn, so the `begin` inside it came out one colour deeper than its - // sibling outside — a phantom level with no keyword on screen. - let text = concat!( - "module m;\n", - " initial begin\n", // depth 0 - " x = 1;\n", - " end\n", - " always_comb begin\n", // depth 0 — the sibling to match - " case (y)\n", // hidden: must not count - " 1: begin\n", // depth 1, NOT 2 - " z = 1;\n", - " end\n", - " endcase\n", - " end\n", - "endmodule\n", - ); - let doc = doc_of(text); - let sent = scope_pairs(&doc); - let depths: Vec = sent.pairs.iter().map(|p| p.depth).collect(); - assert_eq!(depths, vec![0, 0, 1], "the two outer begins are siblings"); - assert_eq!(sent.pairs.len(), 3, "the case itself is still not on the wire"); - } - - #[test] - fn no_hidden_scope_counts_toward_the_depth() { - // Every scope kind the rainbow filters out, one at a time, wrapping a - // `begin` that must still come out at depth 0. A new entry in `RULES` - // that forgets to stay out of `RAINBOW_KEYWORDS` fails here. - let cases = [ - ("module m;\n initial begin\n end\nendmodule\n", "module"), - ( - "package p;\n function f;\n begin\n end\n endfunction\nendpackage\n", - "package+function", - ), - ( - "module m;\n generate\n if (A) begin\n end\n endgenerate\nendmodule\n", - "generate", - ), - ("module m;\n task t;\n begin\n end\n endtask\nendmodule\n", "task"), - ( - "class c;\n function new();\n begin\n end\n endfunction\nendclass\n", - "class+function", - ), - ("interface i;\n initial begin\n end\nendinterface\n", "interface"), - ("program p;\n initial begin\n end\nendprogram\n", "program"), - ( - "module m;\n specify\n if (a) begin\n end\n endspecify\nendmodule\n", - "specify", - ), - ]; - for (text, what) in cases { - let doc = doc_of(text); - let sent = scope_pairs(&doc); - assert_eq!(sent.pairs.len(), 1, "{what}: exactly one begin on the wire"); - assert_eq!(sent.pairs[0].depth, 0, "{what} must not count toward depth"); - } - } - - #[test] - fn only_begins_and_forks_stack_up_the_colours() { - // A begin in a fork in a begin is three distinct levels, because all - // three are drawn. - let text = "module m;\n initial begin\n fork\n begin\n x = 1;\n end\n join\n end\nendmodule\n"; - let doc = doc_of(text); - let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); - assert_eq!(depths, vec![0, 1, 2], "begin, fork, begin"); - } - - #[test] - fn the_depth_counter_and_the_wire_filter_read_the_same_list() { - // The invariant that keeps the M5 bug from coming back: a scope is - // counted if and only if it is sent. Asserted over the whole rule - // table rather than by re-reading the const. - for rule in RULES { - let counted = is_rainbow(rule.open); - let text = format!("module m;\n {} \nendmodule\n", rule.open); - let _ = doc_of(&text); // never panics on any opener, closed or not - assert_eq!( - counted, - RAINBOW_KEYWORDS.contains(&rule.open), - "`{}` must be counted exactly when it is sent", - rule.open - ); - } - assert_eq!(RAINBOW_KEYWORDS, ["begin", "fork"], "the set the extension was built for"); - } - - #[test] - fn scope_pairs_ranges_are_utf16_and_cover_the_keyword() { - let text = "module m;\n // é ✓\n initial begin\n end\nendmodule\n"; - let doc = doc_of(text); - let sent = scope_pairs(&doc); - assert_eq!(sent.pairs.len(), 1); - let open = sent.pairs[0].open; - assert_eq!(open.start.line, 2); - assert_eq!(open.start.character, 10, "the `begin`, in UTF-16 units"); - assert_eq!(open.end.character, 15, "and it covers the whole keyword"); - assert_eq!(sent.pairs[0].close.start.line, 3); - } - - #[test] - fn scope_pairs_omits_a_pair_that_never_closed() { - // Half a pair is nothing to *colour by depth* — it has none — so it - // stays out of `pairs` and goes on the wire as `unmatched` instead. - let text = "module m;\n initial begin\n if (x) begin\n end\nendmodule\n"; - let doc = doc_of(text); - let sent = scope_pairs(&doc); - assert_eq!(sent.pairs.len(), 1, "only the inner begin closed"); - assert_eq!(sent.pairs[0].open.start.line, 2); - assert_eq!(sent.unmatched.len(), 1, "the outer begin is reported, not dropped"); - assert_eq!(sent.unmatched[0].start.line, 1); - } - - #[test] - fn scope_pairs_of_a_file_with_no_blocks_is_empty_not_absent() { - let doc = doc_of("module m;\n wire a;\nendmodule\n"); - let sent = scope_pairs(&doc); - assert!(sent.pairs.is_empty()); - assert!(sent.unmatched.is_empty()); - let json = serde_json::to_value(&sent).expect("serializes"); - assert_eq!( - json, - serde_json::json!({ "pairs": [], "unmatched": [] }), - "the shape is stable" - ); - } - - // ------------------------------------------------------------------ - // lucisv/scopePairs — unmatched block delimiters - // ------------------------------------------------------------------ - - /// The unmatched ranges of a buffer as `(line, character)` starts. - fn unmatched_starts(text: &str) -> Vec<(u32, u32)> { - scope_pairs(&doc_of(text)) - .unmatched - .iter() - .map(|r| (r.start.line, r.start.character)) - .collect() - } - - #[test] - fn an_opener_that_never_closes_is_reported_as_unmatched() { - // The 0.3.1 bug's own shape: three nested `begin`s in a task, the - // outermost one missing its `end`. Before this, the wire said nothing - // about it and the extension painted it with no decoration at all. - let text = concat!( - "module m;\n", - " task t;\n", - " begin\n", // line 2 — never closes - " begin\n", // line 3 — closes on line 6 - " begin\n", - " end\n", - " end\n", - " endtask\n", - "endmodule\n", - ); - assert_eq!(unmatched_starts(text), vec![(2, 4)], "the `begin` that lost its `end`"); - // And the pairs that *did* close still carry the depth they always - // did: an unmatched frame is still an enclosing scope. - let depths: Vec = scope_pairs(&doc_of(text)).pairs.iter().map(|p| p.depth).collect(); - assert_eq!(depths, vec![1, 2], "the two inner begins, unshifted"); - } - - #[test] - fn a_closer_that_opens_nothing_is_reported_as_unmatched() { - let text = "module m;\n initial begin\n end\n end\nendmodule\n"; - assert_eq!(unmatched_starts(text), vec![(3, 2)], "the second `end` closes nothing"); - assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 1, "the real pair is untouched"); - } - - #[test] - fn a_balanced_file_reports_nothing_unmatched() { - let text = - "module m;\n initial begin\n fork\n x = 1;\n join\n end\nendmodule\n"; - assert!(scope_pairs(&doc_of(text)).unmatched.is_empty()); - assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 2); - } - - #[test] - fn a_keyword_is_never_both_paired_and_unmatched() { - // The two lists are painted with different colours, so an overlap - // would be two decorations fighting over one keyword. - let text = concat!( - "module m;\n", - " initial begin\n", - " begin\n", - " end\n", - " end\n", - " initial begin\n", - " end\n", - " end\n", - " initial fork\n", - "endmodule\n", - ); - let sent = scope_pairs(&doc_of(text)); - let paired: Vec = sent.pairs.iter().flat_map(|p| [p.open, p.close]).collect(); - assert_eq!(paired.len(), 6, "three pairs"); - assert_eq!(sent.unmatched.len(), 2, "the stray `end` and the unclosed `fork`"); - for lonely in &sent.unmatched { - assert!(!paired.contains(lonely), "{lonely:?} is on both lists"); - } - } - - #[test] - fn unmatched_carries_only_block_delimiters() { - // Same filter as `pairs`: the rainbow does not draw `module` or - // `function`, so it does not report their halves either. - let text = "module m;\n function f;\n begin\n"; - let sent = scope_pairs(&doc_of(text)); - assert!(sent.pairs.is_empty()); - assert_eq!(sent.unmatched.len(), 1, "the begin only, not the module or the function"); - assert_eq!(sent.unmatched[0].start.line, 2); - // The engine itself still saw all three unclosed. - assert_eq!(analyze(&doc_of(text).tokens).unmatched_open.len(), 3); - } - - #[test] - fn an_unmatched_join_is_reported_but_an_unmatched_endcase_is_not() { - // `unmatched_close` carries the closer; the filter asks about the - // *opener* it wanted, which is what `expected` holds. - assert_eq!(unmatched_starts("module m;\n join\nendmodule\n"), vec![(1, 2)]); - assert!(unmatched_starts("module m;\n endcase\nendmodule\n").is_empty()); - } - - #[test] - fn the_scope_pairs_wire_shape_is_what_the_extension_reads() { - // Pinned against the Handshakes section of the feature README: the - // extension indexes `pairs[].depth % 6`, paints `unmatched` in its - // error colour, and hands every range straight to the client's Range - // converter. - let doc = doc_of("module m;\n initial begin\n end\n begin\nendmodule\n"); - let json = serde_json::to_value(scope_pairs(&doc)).expect("serializes"); - assert_eq!( - json, - serde_json::json!({ - "pairs": [{ - "open": { - "start": { "line": 1, "character": 10 }, - "end": { "line": 1, "character": 15 } - }, - "close": { - "start": { "line": 2, "character": 2 }, - "end": { "line": 2, "character": 5 } - }, - "depth": 0 - }], - "unmatched": [{ - "start": { "line": 3, "character": 2 }, - "end": { "line": 3, "character": 7 } - }] - }) - ); - } - - // ------------------------------------------------------------------ - // missing-closer diagnostics, and the gate - // ------------------------------------------------------------------ - - #[test] - fn a_missing_end_warns_at_the_begin_that_lost_it() { - let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; - let doc = doc_of(text); - assert!(!doc.diagnostics.is_empty(), "premise: the parser must have failed"); - let warnings = missing_end_diagnostics(&doc); - assert_eq!(warnings.len(), 1); - assert_eq!(warnings[0].severity, Some(DiagnosticSeverity::WARNING)); - assert_eq!(warnings[0].source.as_deref(), Some("lucisv")); - assert_eq!(warnings[0].range.start.line, 1, "the `initial begin` line"); - assert_eq!(warnings[0].message, "`begin` has no matching `end` — is an `end` missing?"); - } - - #[test] - fn a_missing_join_names_join_and_not_end() { - let text = "module m;\n initial fork\n x = 1;\nendmodule\n"; - let doc = doc_of(text); - let warnings = missing_end_diagnostics(&doc); - assert_eq!(warnings.len(), 1); - assert_eq!(warnings[0].message, "`fork` has no matching `join` — is a `join` missing?"); - } - - #[test] - fn an_orphan_closer_warns_on_itself() { - let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; - let doc = doc_of(text); - assert!(!doc.diagnostics.is_empty(), "premise: the stray end breaks the parse"); - let warnings = missing_end_diagnostics(&doc); - assert!( - warnings.iter().any(|w| w.message == "`end` has no matching `begin`"), - "got {warnings:#?}" - ); - } - - #[test] - fn the_gate_alone_suppresses_the_warnings() { - // The precise claim: the *only* reason a clean-parsing buffer stays - // quiet is the gate. Clearing the parse diagnostics on a buffer the - // matcher does find unbalanced must not change the answer. - let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; - let mut doc = doc_of(text); - assert_eq!(missing_end_diagnostics(&doc).len(), 1, "premise: it warns"); - doc.diagnostics.clear(); - assert!(!analyze(&doc.tokens).unmatched_open.is_empty(), "still unbalanced"); - assert!(missing_end_diagnostics(&doc).is_empty(), "the gate must shut"); - } - - #[test] - fn a_file_that_parses_is_never_told_it_is_unbalanced() { - // Every hazard above, as a whole buffer the parser accepts. - let clean = [ - "module m;\n initial begin\n x = 1;\n end\nendmodule\n", - "class c;\n extern function void f(int a);\n pure virtual function int g();\nendclass\n", - "typedef class C;\nclass C;\n int x;\nendclass\n", - "class c;\n virtual interface bus_if vif;\nendclass\n", - "module m;\n import \"DPI-C\" function void c_init(input int a);\nendmodule\n", - "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n", - "module m;\n a1: assert property (@(posedge clk) a |-> b);\nendmodule\n", - "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n end\nendmodule\n", - "class c;\n covergroup cg;\n coverpoint x;\n endgroup\nendclass\n", - "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n", - ]; - for text in clean { - let doc = doc_of(text); - assert!(doc.diagnostics.is_empty(), "premise: this must parse — {text}"); - assert!(missing_end_diagnostics(&doc).is_empty(), "warned about {text}"); - // Stronger than the gate: the matcher itself must agree. - let analysis = analyze(&doc.tokens); - assert!(analysis.unmatched_open.is_empty(), "phantom unclosed scope in {text}"); - assert!(analysis.unmatched_close.is_empty(), "phantom stray closer in {text}"); - } - } - - #[test] - fn a_lint_warning_does_not_open_the_gate() { - // The gate reads the *parse* diagnostics. A file that only violates a - // lint rule parses fine and must stay quiet. - let doc = doc_of("module m;\n\twire a;\nendmodule\n"); - assert!(doc.diagnostics.is_empty(), "premise: a tab is not a parse error"); - assert!(missing_end_diagnostics(&doc).is_empty()); - } - - #[test] - fn the_warnings_are_capped() { - // Twenty-five stray `end`s. Flat on purpose: nesting them instead - // would charge the *parser's* recursion, and a test thread's 2 MiB - // stack is not the 8 MiB `docs/features/recursion-limit/README.md` - // requires — the cap under test here is this module's, not that one's. - let mut text = String::from("module m;\n initial begin\n x = 1;\n end\n"); - for _ in 0..25 { - text.push_str(" end\n"); - } - text.push_str("endmodule\n"); - let doc = doc_of(&text); - assert!(!doc.diagnostics.is_empty(), "premise: stray `end`s do not parse"); - assert_eq!(analyze(&doc.tokens).unmatched_close.len(), 25, "the matcher sees them all"); - assert_eq!(missing_end_diagnostics(&doc).len(), MAX_WARNINGS, "the publish is capped"); - } - - #[test] - fn the_published_list_carries_the_pair_warning() { - // The wiring, not the engine: `diagnostics::all` must include these. - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), "module m;\n initial begin\n x = 1;\nendmodule\n".into()); - let published = crate::diagnostics::all(ws.document(&uri).expect("open")); - assert!( - published.iter().any(|d| d.message.contains("has no matching `end`")), - "got {published:#?}" - ); - assert_eq!( - published[0].severity, - Some(DiagnosticSeverity::ERROR), - "the parse error still leads" - ); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/pairs/tests.rs b/crates/lucisv_server/src/pairs/tests.rs new file mode 100644 index 0000000..fdadf0a --- /dev/null +++ b/crates/lucisv_server/src/pairs/tests.rs @@ -0,0 +1,1321 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::state::Workspace; +use lsp_types::Uri; +use std::str::FromStr; +use vlog_parser::tokenize; +use vlog_semantic::WorkspaceIndex; + +/// The analysis of a source string, straight off the lexer — no parser +/// involved, which is the point: the matcher must stand on its own. +fn scopes(text: &str) -> ScopeAnalysis { + let tokens = tokenize(text).expect("the fixtures all lex"); + analyze(&tokens) +} + +/// The source text of every matched pair, as `open..close`. +fn matched(text: &str) -> Vec { + let analysis = scopes(text); + analysis + .pairs + .iter() + .map(|p| { + format!( + "{}..{}", + &text[p.open.start as usize..p.open.end as usize], + &text[p.close.start as usize..p.close.end as usize] + ) + }) + .collect() +} + +/// The keyword of every unclosed opener, in source order. +fn unclosed(text: &str) -> Vec<&'static str> { + scopes(text).unmatched_open.iter().map(|u| u.keyword).collect() +} + +#[test] +fn the_vendor_and_formal_blocks_are_scopes() { + // `vendor-formal-grammar`, 2026-09-02. A rule only fires on a + // `TokenKind::Keyword`, so `checker` and `config` became matchable + // the moment the lexer reserved them; `table` was a keyword all along + // and simply had no row. + assert_eq!( + matched("primitive p (q, a);\n table\n 0 : 1;\n endtable\nendprimitive\n"), + ["primitive..endprimitive", "table..endtable"] + ); + assert_eq!( + matched("checker c (logic a);\n checker d (logic b);\n endchecker\nendchecker\n"), + ["checker..endchecker", "checker..endchecker"] + ); + assert_eq!(matched("config cfg;\n design work.top;\nendconfig\n"), ["config..endconfig"]); + assert_eq!( + matched("module m;\n specify\n endspecify\nendmodule\n"), + ["module..endmodule", "specify..endspecify"] + ); +} + +#[test] +fn an_unclosed_vendor_block_is_reported_against_its_own_keyword() { + assert_eq!(unclosed("checker c (logic a);\n"), ["checker"]); + assert_eq!(unclosed("config cfg;\n"), ["config"]); + assert_eq!(orphan_closers("endchecker\n"), ["endchecker"]); +} + +/// The keyword of every closer that closed nothing. +fn orphan_closers(text: &str) -> Vec<&'static str> { + scopes(text).unmatched_close.iter().map(|u| u.keyword).collect() +} + +fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) +} + +/// The byte offset of `needle` in `text`. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +// ------------------------------------------------------------------ +// the basics +// ------------------------------------------------------------------ + +#[test] +fn a_module_with_nested_begins_matches_every_pair() { + let text = + "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 3); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); + // Depth counts only the scopes the rainbow draws. The module is one of + // the nineteen it does not, so it is 0 and does not push the `begin` + // under it off colour 0. + let depths: Vec = analysis.pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 0, 1], "module (uncounted), outer begin, inner begin"); +} + +#[test] +fn a_comment_or_a_string_never_counts_as_a_keyword() { + // Hard invariant of the whole approach: the lexer detaches comments + // and makes the literal one token, so neither can push or pop. + let text = "module m;\n // end endmodule\n initial begin\n /* begin */\n $display(\"end begin endmodule\");\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 2, "the module and the one real begin"); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); +} + +#[test] +fn a_labeled_block_matches_on_the_keywords_alone() { + let text = "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 3); + assert!(analysis.unmatched_open.is_empty(), "labels are not part of the match"); +} + +#[test] +fn every_fork_flavour_joins() { + for closer in ["join", "join_any", "join_none"] { + let text = format!("module m;\n initial fork\n x = 1;\n {closer}\nendmodule\n"); + let analysis = scopes(&text); + assert_eq!(analysis.pairs.len(), 2, "module + fork, closed by {closer}"); + assert!(analysis.unmatched_open.is_empty(), "{closer} must close a fork"); + } +} + +#[test] +fn every_case_flavour_ends() { + for opener in ["case", "casex", "casez", "randcase"] { + let text = + format!("module m;\n initial {opener} (x)\n 1: y = 1;\n endcase\nendmodule\n"); + assert!(scopes(&text).unmatched_open.is_empty(), "{opener} must take endcase"); + } +} + +#[test] +fn the_named_scopes_all_pair_up() { + let cases = [ + ("module m;\nendmodule\n", "module"), + ("macromodule m;\nendmodule\n", "macromodule"), + ("package p;\nendpackage\n", "package"), + ("interface i;\nendinterface\n", "interface"), + ("program p;\nendprogram\n", "program"), + ("class c;\nendclass\n", "class"), + ("module m;\n function f;\n endfunction\nendmodule\n", "function"), + ("module m;\n task t;\n endtask\nendmodule\n", "task"), + ("module m;\n generate\n endgenerate\nendmodule\n", "generate"), + ("module m;\n specify\n endspecify\nendmodule\n", "specify"), + ("primitive p (o, i);\nendprimitive\n", "primitive"), + ("module m;\n property p;\n endproperty\nendmodule\n", "property"), + ("module m;\n sequence s;\n endsequence\nendmodule\n", "sequence"), + ("module m;\n clocking cb @(posedge clk);\n endclocking\nendmodule\n", "clocking"), + ("class c;\n covergroup cg;\n endgroup\nendclass\n", "covergroup"), + ]; + for (text, what) in cases { + let analysis = scopes(text); + assert!(analysis.unmatched_open.is_empty(), "{what} left something open"); + assert!(analysis.unmatched_close.is_empty(), "{what} left a stray closer"); + assert!(!analysis.pairs.is_empty(), "{what} matched nothing at all"); + } +} + +// ------------------------------------------------------------------ +// hazards: keywords that open nothing +// ------------------------------------------------------------------ + +#[test] +fn an_extern_prototype_opens_nothing() { + let text = "class c;\n extern function void f(int a);\n extern task t();\nendclass\n"; + assert!(unclosed(text).is_empty(), "prototypes have no body"); + assert_eq!(matched(text), vec!["class..endclass"]); +} + +#[test] +fn a_pure_virtual_method_opens_nothing() { + let text = "class c;\n pure virtual function int g();\nendclass\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["class..endclass"]); +} + +#[test] +fn a_dpi_import_or_export_opens_nothing() { + let text = "module m;\n import \"DPI-C\" function void c_init(input int a);\n import \"DPI-C\" context function int c_get();\n export \"DPI-C\" function f;\nendmodule\n"; + assert!(unclosed(text).is_empty(), "DPI declarations have no body"); + assert_eq!(matched(text), vec!["module..endmodule"]); +} + +#[test] +fn an_extern_module_header_opens_nothing() { + let text = "extern module m (input a);\nmodule m (input a);\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule"], "only the real one"); +} + +#[test] +fn a_package_import_does_not_swallow_the_next_declaration() { + // The prototype flag is dropped at the `;`, so an ordinary + // `import p::*;` must not suppress the function after it. + let text = "module m;\n import p::*;\n function f;\n endfunction\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "function..endfunction"]); +} + +#[test] +fn a_module_header_import_does_not_suppress_the_body() { + let text = "module m import p::*; (input a);\n initial begin\n end\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); +} + +#[test] +fn a_typedef_class_is_a_forward_declaration() { + let text = "typedef class C;\nclass C;\n int x;\nendclass\n"; + assert!(unclosed(text).is_empty(), "the forward declaration opens nothing"); + assert_eq!(matched(text), vec!["class..endclass"], "only the real class"); +} + +#[test] +fn a_virtual_interface_member_is_a_type() { + let text = "class c;\n virtual interface bus_if vif;\n virtual bus_if v2;\nendclass\n"; + assert!(unclosed(text).is_empty(), "`virtual interface` is a type"); + assert_eq!(matched(text), vec!["class..endclass"]); +} + +#[test] +fn a_virtual_class_still_opens() { + let text = "virtual class C;\n int x;\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"], "an abstract class has a body"); +} + +#[test] +fn an_interface_class_is_closed_by_endclass() { + // `interface class IC; ... endclass`: the `class` opens, the + // `interface` in front of it does not, or the `endclass` would find + // an `interface` frame on top of the stack and report both wrong. + let text = "interface class IC;\n pure virtual function void f();\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"]); + assert!(unclosed(text).is_empty()); + assert!(orphan_closers(text).is_empty()); +} + +#[test] +fn a_generic_interface_port_opens_nothing() { + let text = "module m (interface bus, input logic clk);\nendmodule\n"; + assert_eq!(matched(text), vec!["module..endmodule"]); + assert!(unclosed(text).is_empty(), "a port is not a declaration"); +} + +#[test] +fn a_default_clocking_reference_opens_nothing() { + let text = "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`default clocking cb;` names an existing block"); + assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); +} + +#[test] +fn an_unnamed_default_clocking_block_still_opens() { + let text = "module m;\n default clocking @(posedge clk);\n endclocking\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); +} + +#[test] +fn an_assertion_does_not_open_a_property() { + let text = "module m;\n a1: assert property (@(posedge clk) a |-> b);\n cover property (@(posedge clk) c);\n assume property (@(posedge clk) d);\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`assert property (` opens nothing"); + assert_eq!(matched(text), vec!["module..endmodule"]); +} + +#[test] +fn a_property_declaration_does_open() { + let text = "module m;\n property p;\n @(posedge clk) a |-> b;\n endproperty\nendmodule\n"; + assert_eq!(matched(text), vec!["module..endmodule", "property..endproperty"]); +} + +#[test] +fn disable_fork_and_wait_fork_are_statements() { + let text = "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n wait fork;\n end\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`disable fork;` starts no fork"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end", "fork..join_any"]); +} + +#[test] +fn a_covergroup_sample_method_opens_nothing() { + // Found by sweeping the corpus, not by reading the LRM: seven of the + // 840 files that parse cleanly write this, and every one of them is a + // UVM coverage class. `with function sample(...)` names the + // covergroup's sample method in its header; the `endgroup` closes the + // lot, and there is no `endfunction` anywhere. + let text = "class c;\n covergroup cg with function sample(int lvl, bit rst);\n cp: coverpoint lvl;\n endgroup\n function new();\n endfunction\nendclass\n"; + assert!(unclosed(text).is_empty(), "the sample method has no body of its own"); + assert_eq!( + matched(text), + vec!["class..endclass", "covergroup..endgroup", "function..endfunction"], + "and the real function next to it still pairs" + ); +} + +#[test] +fn a_macro_invocation_is_invisible_to_the_matcher() { + // A macro body is not in this token stream, so a macro that expands to + // a whole block must neither open nor close anything. This is why the + // diagnostics below are gated on the parser having already failed. + let text = "class c;\n `uvm_component_utils(c)\n `uvm_do_with(item, { a == 1; })\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"]); + assert!(unclosed(text).is_empty()); + assert!(orphan_closers(text).is_empty()); +} + +// ------------------------------------------------------------------ +// hazards: mismatch recovery +// ------------------------------------------------------------------ + +#[test] +fn a_missing_end_points_at_the_innermost_unclosed_begin() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n"; + let analysis = scopes(text); + // The one `end` closes the inner begin; the outer one is left open. + assert_eq!(analysis.unmatched_open.len(), 1); + assert_eq!(analysis.unmatched_open[0].keyword, "begin"); + assert_eq!(analysis.unmatched_open[0].expected, "end"); + assert_eq!( + analysis.unmatched_open[0].span.start, + at(text, "begin"), + "the `initial begin` on line 2, not the module and not the inner begin" + ); + // And the module still matched, which is the whole point of the + // recovery rule: one missing `end` must not lose `endmodule`. + assert!(matched(text).contains(&"module..endmodule".to_string())); +} + +#[test] +fn two_missing_ends_are_both_reported_in_source_order() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\nendmodule\n"; + let analysis = scopes(text); + let keywords: Vec<_> = analysis.unmatched_open.iter().map(|u| u.keyword).collect(); + assert_eq!(keywords, vec!["begin", "begin"]); + assert!(analysis.unmatched_open[0].span.start < analysis.unmatched_open[1].span.start); + assert_eq!(matched(text), vec!["module..endmodule"]); +} + +#[test] +fn a_stray_end_matches_nothing_and_disturbs_nothing() { + let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(orphan_closers(text), vec!["end"], "the second `end` closes nothing"); + assert!(analysis.unmatched_open.is_empty(), "the stack must be left alone"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); +} + +#[test] +fn a_wrong_closer_does_not_pop_the_frame_it_does_not_match() { + // `endmodule` while a `begin` is open: the begin is reported unclosed + // and the module still pairs. Popping blindly would pair `begin` with + // `endmodule` and then report the module unclosed — two lies for one + // missing keyword. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(matched(text), vec!["module..endmodule"]); + assert_eq!(analysis.unmatched_open.len(), 1); + assert_eq!(analysis.unmatched_open[0].keyword, "begin"); +} + +#[test] +fn an_endcase_with_no_case_is_an_orphan_closer() { + let text = "module m;\n initial begin\n endcase\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(orphan_closers(text), vec!["endcase"]); + assert_eq!(analysis.unmatched_close[0].expected, "case", "it wanted a case"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"], "nothing else moved"); +} + +#[test] +fn an_orphan_join_names_the_fork_it_wanted() { + let text = "module m;\n initial begin\n join_none\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.unmatched_close.len(), 1); + assert_eq!(analysis.unmatched_close[0].keyword, "join_none"); + assert_eq!(analysis.unmatched_close[0].expected, "fork"); +} + +#[test] +fn an_empty_stream_analyzes_to_nothing() { + let analysis = analyze(&[]); + assert!(analysis.pairs.is_empty()); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); +} + +#[test] +fn a_file_that_does_not_lex_has_no_tokens_and_no_pairs() { + // `Document::new` leaves `tokens` empty when the lexer gives up, so + // the matcher sees nothing rather than a truncated stream. + let doc = doc_of("module m;\n wire a; /* unterminated\n"); + assert!(doc.tokens.is_empty()); + assert!(analyze(&doc.tokens).pairs.is_empty()); + assert!(missing_end_diagnostics(&doc).is_empty(), "and says nothing about it"); +} + +// ------------------------------------------------------------------ +// the running counts on `Stack` +// ------------------------------------------------------------------ + +/// The pre-counter algorithm, kept here as an oracle: the same matcher +/// with `depth` scanned off the stack at every push, which is how the code +/// computed it before the running count replaced the scan. Returns +/// `(opener start, depth)` for every pair it closes. +/// +/// The old comment claimed the scan was "immune to the mismatch recovery +/// in `close`, which pops frames from the middle". That immunity is now +/// `Stack`'s job, so the claim is worth a second implementation to check +/// against rather than a hand-written expectation. +fn scanned_pairs(tokens: &[Token]) -> Vec<(u32, u32)> { + struct Slow { + rule: &'static Rule, + start: u32, + depth: u32, + } + let mut stack: Vec = Vec::new(); + let mut pairs: Vec<(u32, u32)> = Vec::new(); + let mut prototype = false; + for (i, token) in tokens.iter().enumerate() { + if token.is_sym(";") { + prototype = false; + continue; + } + if token.kind != TokenKind::Keyword { + continue; + } + let text = token.text.as_str(); + if PROTOTYPE_STARTERS.contains(&text) { + prototype = true; + continue; + } + if let Some((_, rule)) = opener_rule(text) { + if !prototype && opens_a_scope(tokens, i) { + let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32; + stack.push(Slow { rule, start: token.span.start, depth }); + } + } else if let Some(closer) = closer_keyword(text) { + let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else { + continue; + }; + stack.drain(index + 1..); + if let Some(frame) = stack.pop() { + pairs.push((frame.start, frame.depth)); + } + } + } + pairs.sort_unstable(); + pairs +} + +/// `analyze`'s own answer in the oracle's shape. +fn counted_pairs(tokens: &[Token]) -> Vec<(u32, u32)> { + let mut pairs: Vec<(u32, u32)> = + analyze(tokens).pairs.iter().map(|p| (p.open.start, p.depth)).collect(); + pairs.sort_unstable(); + pairs +} + +#[test] +fn the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack() { + // Every fixture puts rainbow and non-rainbow scopes in the same nest + // and then makes `close` remove frames from the middle, which is the + // only way a running counter can drift from a scan. + let cases = [ + ( + // A `join` that closes the `fork` below the top: the `begin` + // and the `case` above it are drained, and the `begin` after + // must land at depth 1 (inside the outer `begin` alone), not + // at 3. + concat!( + "module m;\n", + " initial begin\n", + " fork\n", + " begin\n", + " case (x)\n", + " join\n", + " begin\n", + " y = 1;\n", + " end\n", + " end\n", + "endmodule\n", + ), + "a join draining two rainbow frames out of the middle", + ), + ( + // The mirror: a non-rainbow frame closes with rainbow frames + // stacked on top of it, so the drain has to give back counts + // for frames that are not the one being closed. + concat!( + "module m;\n", + " case (x)\n", + " 1: begin\n", + " fork\n", + " endcase\n", + " initial begin\n", + " end\n", + "endmodule\n", + ), + "an endcase draining a begin and a fork above it", + ), + ( + // A closer that matches nothing must leave the counts exactly + // as it found them, or the `begin` after it shifts colour. + concat!( + "module m;\n", + " initial begin\n", + " begin\n", + " join_none\n", + " begin\n", + " end\n", + " end\n", + " end\n", + "endmodule\n", + ), + "a stray join_none between two pushes", + ), + ( + // Recovery twice over, with the outer scopes still closing. + concat!( + "module m;\n", + " function f;\n", + " fork\n", + " begin\n", + " case (y)\n", + " endfunction\n", + " task t;\n", + " begin\n", + " fork\n", + " begin\n", + " end\n", + " join\n", + " end\n", + " endtask\n", + "endmodule\n", + ), + "two recoveries in one file", + ), + ]; + for (text, what) in cases { + let tokens = tokenize(text).expect("the fixtures all lex"); + let counted = counted_pairs(&tokens); + assert!(!counted.is_empty(), "{what}: the fixture matched nothing at all"); + assert_eq!(counted, scanned_pairs(&tokens), "{what}: the counter drifted from a scan"); + } + // And on every fixture the rest of this module already uses, so a + // drift anywhere in the corpus of shapes above fails here too. + for text in [ + "module m;\n initial begin\n fork\n begin\n end\n join\n end\nendmodule\n", + "module m;\n initial begin\n case (x)\n 1: begin\n end\n endcase\n end\nendmodule\n", + "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n", + ] { + let tokens = tokenize(text).expect("lexes"); + assert_eq!(counted_pairs(&tokens), scanned_pairs(&tokens), "{text}"); + } +} + +#[test] +fn analysis_is_linear_in_nesting_depth_not_quadratic() { + // Two of these three shapes were O(n²) until the running counts landed: + // the depth of a push was scanned off the whole stack, and a closer + // that matched no frame scanned the whole stack to find that out. The + // third is not a shape that was ever slow — it is here so that the + // per-rule counts have to be *given back*, not merely taken: a drain + // that forgets to decrement leaves the guard permanently answering + // "maybe", which quietly restores the second quadratic. + // + // The budget is wall clock, which is coarse on purpose. Measured on + // the dev machine (debug build) at this N: the three shapes cost 5 ms, + // 41 ms and 44 ms with the counts, against roughly 7 s, 17 s and 15 s + // for the quadratic version of each. Two seconds is therefore ~45× + // the honest cost — room for a machine several times slower than this + // one, under load — while still being a small fraction of what any of + // the three quadratics needs. + const N: usize = 30_000; + const BUDGET: std::time::Duration = std::time::Duration::from_secs(2); + + let deep = "begin\n".repeat(N); + let tokens = tokenize(&deep).expect("lexes"); + let started = std::time::Instant::now(); + let analysis = analyze(&tokens); + let elapsed = started.elapsed(); + assert_eq!(analysis.unmatched_open.len(), N, "premise: all {N} really are open at once"); + assert!(elapsed < BUDGET, "{N} nested begins took {elapsed:?}"); + + // `endcase` can close nothing on a stack of `begin`s, so every one of + // them is the no-match case. + let mut stray = "begin\n".repeat(N); + stray.push_str(&"endcase\n".repeat(N)); + let tokens = tokenize(&stray).expect("lexes"); + let started = std::time::Instant::now(); + let analysis = analyze(&tokens); + let elapsed = started.elapsed(); + assert_eq!(analysis.unmatched_close.len(), N, "premise: none of them matched"); + assert_eq!(analysis.unmatched_open.len(), N, "premise: and none of the begins closed"); + assert!(elapsed < BUDGET, "{N} never-matching closers took {elapsed:?}"); + + // `endcase` closes the `case` at the bottom and drains N `begin`s out + // of the middle on the way — so by the time the N `case`s below the + // `end`s are on the stack, no `begin` is open and every `end` must be + // declined without a scan. It is declined either way; the question is + // whether the counts remember that the drained `begin`s are gone. + let mut given_back = String::from("case (x)\n"); + given_back.push_str(&"begin\n".repeat(N)); + given_back.push_str("endcase\n"); + given_back.push_str(&"case (x)\n".repeat(N)); + given_back.push_str(&"end\n".repeat(N)); + let tokens = tokenize(&given_back).expect("lexes"); + let started = std::time::Instant::now(); + let analysis = analyze(&tokens); + let elapsed = started.elapsed(); + assert_eq!(analysis.pairs.len(), 1, "premise: only the outer case/endcase pairs"); + assert_eq!(analysis.unmatched_open.len(), 2 * N, "premise: N drained begins, N open cases"); + assert_eq!(analysis.unmatched_close.len(), N, "premise: no end can close a case"); + assert!(elapsed < BUDGET, "{N} closers over drained frames took {elapsed:?}"); +} + +// ------------------------------------------------------------------ +// QA (2026-08-25, perf fix) — independent full-fidelity differential +// check against the pre-`Stack` algorithm. Kept as a permanent +// regression test, unlike the dev's own oracle +// (`the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack`), +// which only compares `(open start, depth)`: this one diffs every field +// of `ScopeAnalysis` — both unmatched lists included — and adds +// adversarial fixtures the dev's own tests do not cover (shared-closer +// priority, deep mixed-rainbow drains with more pushes/closes +// afterward, prototype interleavings, closers before any opener) plus a +// fixed-seed fuzz sweep. +// ------------------------------------------------------------------ + +/// HEAD's `Frame`, transcribed from `git show HEAD:.../pairs.rs`, before +/// `Stack` existed. +struct OldFrame { + rule: &'static Rule, + span: TextRange, + depth: u32, +} + +/// HEAD's `close`, transcribed verbatim (modulo the `Vec` type). +fn old_close( + analysis: &mut ScopeAnalysis, + stack: &mut Vec, + closer: &'static str, + span: TextRange, +) { + let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else { + analysis.unmatched_close.push(Unmatched { + span, + keyword: closer, + expected: opener_of(closer), + }); + return; + }; + for frame in stack.drain(index + 1..) { + analysis.unmatched_open.push(Unmatched { + span: frame.span, + keyword: frame.rule.open, + expected: frame.rule.close[0], + }); + } + if let Some(frame) = stack.pop() { + analysis.pairs.push(Pair { + open: frame.span, + close: span, + keyword: frame.rule.open, + depth: frame.depth, + }); + } +} + +/// HEAD's `analyze`, transcribed verbatim (modulo `opener_rule`'s new +/// `(usize, &Rule)` signature, whose index this oracle ignores). +fn old_analyze(tokens: &[Token]) -> ScopeAnalysis { + let mut analysis = ScopeAnalysis::default(); + let mut stack: Vec = Vec::new(); + let mut prototype = false; + for (i, token) in tokens.iter().enumerate() { + if token.is_sym(";") { + prototype = false; + continue; + } + if token.kind != TokenKind::Keyword { + continue; + } + let text = token.text.as_str(); + if PROTOTYPE_STARTERS.contains(&text) { + prototype = true; + continue; + } + if let Some((_, rule)) = opener_rule(text) { + if !prototype && opens_a_scope(tokens, i) { + let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32; + stack.push(OldFrame { rule, span: token.span, depth }); + } + } else if let Some(closer) = closer_keyword(text) { + old_close(&mut analysis, &mut stack, closer, token.span); + } + } + for frame in stack { + analysis.unmatched_open.push(Unmatched { + span: frame.span, + keyword: frame.rule.open, + expected: frame.rule.close[0], + }); + } + analysis.pairs.sort_by_key(|p| p.open.start); + analysis.unmatched_open.sort_by_key(|u| u.span.start); + analysis.unmatched_close.sort_by_key(|u| u.span.start); + analysis +} + +/// Every field of `ScopeAnalysis` that matters, in one comparable value — +/// not just `(open start, depth)` the dev's own oracle checks. +#[allow(clippy::type_complexity)] +fn qa_fingerprint( + a: &ScopeAnalysis, +) -> ( + Vec<(u32, u32, &'static str, u32)>, + Vec<(u32, &'static str, &'static str)>, + Vec<(u32, &'static str, &'static str)>, +) { + ( + a.pairs.iter().map(|p| (p.open.start, p.close.start, p.keyword, p.depth)).collect(), + a.unmatched_open.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(), + a.unmatched_close.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(), + ) +} + +fn qa_assert_identical(text: &str, what: &str) { + let tokens = tokenize(text).unwrap_or_else(|e| panic!("{what}: fixture must lex: {e:?}")); + let old = qa_fingerprint(&old_analyze(&tokens)); + let new = qa_fingerprint(&analyze(&tokens)); + assert_eq!(old, new, "{what}: old and new algorithms disagree on:\n{text:?}"); +} + +#[test] +fn qa_old_and_new_algorithms_agree_field_for_field() { + // Empty input. + qa_assert_identical("", "empty input"); + + // Every closer keyword, alone and before any opener at all — every + // closer in RULES, not just `end`. + for rule in RULES { + for closer in rule.close { + qa_assert_identical(closer, &format!("bare closer {closer}")); + qa_assert_identical( + &format!("{closer} {closer} {closer}"), + &format!("three bare {closer} in a row"), + ); + } + } + + // Shared-closer priority: several rules accept the same closer + // keyword. `endcase` is accepted by case/casex/casez/randcase (4 + // rules); `endmodule` by module/macromodule (2). Nest mismatched + // openers that share a closer and confirm both algorithms pick the + // same *topmost* frame (the `rposition` scan's priority), not merely + // "some frame that fits". + qa_assert_identical( + "case casex casez randcase endcase endcase endcase endcase", + "endcase closes topmost-first across 4 sharing rules", + ); + qa_assert_identical( + "module macromodule endmodule endmodule", + "endmodule closes topmost-first across 2 sharing rules", + ); + qa_assert_identical( + "module begin fork case casex endcase join begin end endmodule", + "a shared-closer rule interleaved with rainbow frames, drained and not", + ); + + // Interleaved rainbow / non-rainbow scopes, closers reaching deep + // below the top and draining a mix of both kinds, with more + // pushing/closing continuing afterward (so a stale count would show + // up on the *next* pair, not just the one being closed). + qa_assert_identical( + "begin fork case begin fork begin join begin end endcase begin end join end begin end end", + "deep mixed drain (join draining case+begin+fork) then more begins after", + ); + qa_assert_identical( + "module function task begin fork case endcase join endtask endfunction begin end endmodule", + "drain across 3 non-rainbow frames and 2 rainbow frames in one closer, then a fresh pair after", + ); + qa_assert_identical( + "begin begin begin endcase begin end end end end", + "a non-matching closer (endcase) between two begins changes nothing, more begins follow", + ); + + // Prototype mode interleaved with opens and closes: the flag must + // drop at the next `;` regardless of what real scopes are doing + // around it. + qa_assert_identical( + "extern function ; begin fork join end pure task ; begin end import function ; class endclass", + "prototype starters interleaved with real opens/closes", + ); + qa_assert_identical( + "begin extern module ; fork join end typedef class ; begin end", + "a prototype flag raised and dropped while a rainbow frame is already open", + ); + + // Unmatched closers of every flavor stacked back to back with no + // openers anywhere, then a real pair afterward. + qa_assert_identical( + "end join join_any join_none endcase endmodule endfunction begin end", + "a run of unmatched closers of every closer family, then one real pair", + ); + + // Closers before any opener, mixed with a later real pair. + qa_assert_identical("end end join begin end", "closers before any opener, then a real pair"); + + // A small xorshift PRNG (no external dependency, per CLAUDE.md) over + // a vocabulary that exercises every `opens_a_scope` guard + // (interface/property/sequence/clocking/fork/function) as well as + // plain opens, closes, prototype starters and `;`. + let vocab: Vec<&str> = RULES + .iter() + .flat_map(|r| std::iter::once(r.open).chain(r.close.iter().copied())) + .chain(PROTOTYPE_STARTERS.iter().copied()) + .chain([ + "with", "disable", "wait", "virtual", "class", "(", ",", "@", "posedge", "x", "cb", ";", + ]) + .collect(); + + let mut state: u64 = 0x2545_F491_4F6C_DD1D; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + + for round in 0..500u32 { + let len = 10 + (next() % 40) as usize; + let mut text = String::new(); + for _ in 0..len { + let word = vocab[(next() as usize) % vocab.len()]; + text.push_str(word); + text.push(' '); + } + // Not every random token soup lexes (e.g. a lone `@` needs + // nothing special, but skip anything the lexer itself rejects — + // this test is about matcher agreement, not lexer coverage). + if let Ok(tokens) = tokenize(&text) { + let old = qa_fingerprint(&old_analyze(&tokens)); + let new = qa_fingerprint(&analyze(&tokens)); + assert_eq!(old, new, "fuzz round {round}: old and new disagree on:\n{text:?}"); + } + } +} + +// ------------------------------------------------------------------ +// documentHighlight +// ------------------------------------------------------------------ + +#[test] +fn the_cursor_on_begin_highlights_its_own_end() { + let text = + "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + let outer = at(text, "begin"); + let found = highlights(&doc, outer).expect("a pair"); + assert_eq!(found.len(), 2); + assert_eq!(found[0].range.start.line, 1, "the outer begin"); + assert_eq!(found[1].range.start.line, 5, "and the outer end, not the inner one"); + assert_eq!(found[0].kind, Some(DocumentHighlightKind::TEXT)); +} + +#[test] +fn the_cursor_on_end_highlights_its_own_begin() { + let text = + "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + let inner_end = at(text, " end"); + let found = highlights(&doc, inner_end + 4).expect("a pair"); + assert_eq!(found[0].range.start.line, 2, "the inner begin"); + assert_eq!(found[1].range.start.line, 4, "the inner end"); +} + +#[test] +fn the_cursor_at_either_edge_of_the_keyword_still_matches() { + let text = "module m;\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let begin = at(text, "begin"); + for (offset, where_) in [(begin, "first byte"), (begin + 5, "just past the last")] { + let found = highlights(&doc, offset).expect(where_); + assert_eq!(found.len(), 2, "cursor at the {where_}"); + } + assert!(highlights(&doc, begin - 1).is_none(), "the space before is not the keyword"); +} + +#[test] +fn a_multibyte_comment_before_the_keyword_does_not_shift_the_range() { + // The `é` is 2 bytes and 1 UTF-16 unit; a byte-based range would put + // the highlight one column late. + let text = "module m;\n // é\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let found = highlights(&doc, at(text, "begin")).expect("a pair"); + assert_eq!(found[0].range.start.line, 2); + assert_eq!(found[0].range.start.character, 10, "in UTF-16 units"); + assert_eq!(found[0].range.end.character, 15); +} + +#[test] +fn the_cursor_on_an_unmatched_keyword_highlights_nothing() { + // Not "everything that looks like an `end`" — `None` lets the editor + // fall back to its own word highlighting. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + assert!(highlights(&doc, at(text, "begin")).is_none(), "the begin never closed"); + let stray = "module m;\n end\nendmodule\n"; + let doc = doc_of(stray); + assert!(highlights(&doc, at(stray, "end\n")).is_none(), "the end opened nothing"); +} + +#[test] +fn the_cursor_somewhere_else_entirely_highlights_nothing() { + let text = "module m;\n wire a;\nendmodule\n"; + let doc = doc_of(text); + assert!(highlights(&doc, at(text, "wire")).is_none()); +} + +// ------------------------------------------------------------------ +// lucisv/scopePairs +// ------------------------------------------------------------------ + +#[test] +fn scope_pairs_carries_only_block_delimiters() { + // The module, the class and the case are all matched by the engine and + // all dropped here: the rainbow is for the `begin` ladder. + let text = "module m;\n initial begin\n case (x)\n 1: y = 1;\n endcase\n end\n function f;\n endfunction\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "only the begin/end survives the filter"); + assert_eq!(sent.pairs[0].open.start.line, 1); + assert_eq!(sent.pairs[0].close.start.line, 5); + // The engine itself still saw all four. + assert_eq!(analyze(&doc.tokens).pairs.len(), 4); +} + +#[test] +fn scope_pairs_depths_nest_and_forks_are_included() { + let text = "module top;\n initial begin\n if (a) begin\n b = 1;\n end\n end\n initial fork\n c = 1;\n join\nendmodule\n"; + let doc = doc_of(text); + let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); + // The module does not count, so the outer begin is 0; the begin inside + // it is 1; the fork is the outer begin's sibling, so 0 again. + assert_eq!(depths, vec![0, 1, 0]); +} + +#[test] +fn a_scope_the_rainbow_hides_does_not_shift_the_colour_of_one_it_shows() { + // The M5 bug, as the user reported it: "for blocks that don't have + // begin/end, like inside of a case statement, I can see an invisible + // begin/end being highlighted." The `case` was counted but never + // drawn, so the `begin` inside it came out one colour deeper than its + // sibling outside — a phantom level with no keyword on screen. + let text = concat!( + "module m;\n", + " initial begin\n", // depth 0 + " x = 1;\n", + " end\n", + " always_comb begin\n", // depth 0 — the sibling to match + " case (y)\n", // hidden: must not count + " 1: begin\n", // depth 1, NOT 2 + " z = 1;\n", + " end\n", + " endcase\n", + " end\n", + "endmodule\n", + ); + let doc = doc_of(text); + let sent = scope_pairs(&doc); + let depths: Vec = sent.pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 0, 1], "the two outer begins are siblings"); + assert_eq!(sent.pairs.len(), 3, "the case itself is still not on the wire"); +} + +#[test] +fn no_hidden_scope_counts_toward_the_depth() { + // Every scope kind the rainbow filters out, one at a time, wrapping a + // `begin` that must still come out at depth 0. A new entry in `RULES` + // that forgets to stay out of `RAINBOW_KEYWORDS` fails here. + let cases = [ + ("module m;\n initial begin\n end\nendmodule\n", "module"), + ( + "package p;\n function f;\n begin\n end\n endfunction\nendpackage\n", + "package+function", + ), + ( + "module m;\n generate\n if (A) begin\n end\n endgenerate\nendmodule\n", + "generate", + ), + ("module m;\n task t;\n begin\n end\n endtask\nendmodule\n", "task"), + ( + "class c;\n function new();\n begin\n end\n endfunction\nendclass\n", + "class+function", + ), + ("interface i;\n initial begin\n end\nendinterface\n", "interface"), + ("program p;\n initial begin\n end\nendprogram\n", "program"), + ("module m;\n specify\n if (a) begin\n end\n endspecify\nendmodule\n", "specify"), + ]; + for (text, what) in cases { + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "{what}: exactly one begin on the wire"); + assert_eq!(sent.pairs[0].depth, 0, "{what} must not count toward depth"); + } +} + +#[test] +fn only_begins_and_forks_stack_up_the_colours() { + // A begin in a fork in a begin is three distinct levels, because all + // three are drawn. + let text = "module m;\n initial begin\n fork\n begin\n x = 1;\n end\n join\n end\nendmodule\n"; + let doc = doc_of(text); + let depths: Vec = scope_pairs(&doc).pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 1, 2], "begin, fork, begin"); +} + +#[test] +fn the_depth_counter_and_the_wire_filter_read_the_same_list() { + // The invariant that keeps the M5 bug from coming back: a scope is + // counted if and only if it is sent. Asserted over the whole rule + // table rather than by re-reading the const. + for rule in RULES { + let counted = is_rainbow(rule.open); + let text = format!("module m;\n {} \nendmodule\n", rule.open); + let _ = doc_of(&text); // never panics on any opener, closed or not + assert_eq!( + counted, + RAINBOW_KEYWORDS.contains(&rule.open), + "`{}` must be counted exactly when it is sent", + rule.open + ); + } + assert_eq!(RAINBOW_KEYWORDS, ["begin", "fork"], "the set the extension was built for"); +} + +#[test] +fn scope_pairs_ranges_are_utf16_and_cover_the_keyword() { + let text = "module m;\n // é ✓\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1); + let open = sent.pairs[0].open; + assert_eq!(open.start.line, 2); + assert_eq!(open.start.character, 10, "the `begin`, in UTF-16 units"); + assert_eq!(open.end.character, 15, "and it covers the whole keyword"); + assert_eq!(sent.pairs[0].close.start.line, 3); +} + +#[test] +fn scope_pairs_omits_a_pair_that_never_closed() { + // Half a pair is nothing to *colour by depth* — it has none — so it + // stays out of `pairs` and goes on the wire as `unmatched` instead. + let text = "module m;\n initial begin\n if (x) begin\n end\nendmodule\n"; + let doc = doc_of(text); + let sent = scope_pairs(&doc); + assert_eq!(sent.pairs.len(), 1, "only the inner begin closed"); + assert_eq!(sent.pairs[0].open.start.line, 2); + assert_eq!(sent.unmatched.len(), 1, "the outer begin is reported, not dropped"); + assert_eq!(sent.unmatched[0].start.line, 1); +} + +#[test] +fn scope_pairs_of_a_file_with_no_blocks_is_empty_not_absent() { + let doc = doc_of("module m;\n wire a;\nendmodule\n"); + let sent = scope_pairs(&doc); + assert!(sent.pairs.is_empty()); + assert!(sent.unmatched.is_empty()); + let json = serde_json::to_value(&sent).expect("serializes"); + assert_eq!(json, serde_json::json!({ "pairs": [], "unmatched": [] }), "the shape is stable"); +} + +// ------------------------------------------------------------------ +// lucisv/scopePairs — unmatched block delimiters +// ------------------------------------------------------------------ + +/// The unmatched ranges of a buffer as `(line, character)` starts. +fn unmatched_starts(text: &str) -> Vec<(u32, u32)> { + scope_pairs(&doc_of(text)).unmatched.iter().map(|r| (r.start.line, r.start.character)).collect() +} + +#[test] +fn an_opener_that_never_closes_is_reported_as_unmatched() { + // The 0.3.1 bug's own shape: three nested `begin`s in a task, the + // outermost one missing its `end`. Before this, the wire said nothing + // about it and the extension painted it with no decoration at all. + let text = concat!( + "module m;\n", + " task t;\n", + " begin\n", // line 2 — never closes + " begin\n", // line 3 — closes on line 6 + " begin\n", + " end\n", + " end\n", + " endtask\n", + "endmodule\n", + ); + assert_eq!(unmatched_starts(text), vec![(2, 4)], "the `begin` that lost its `end`"); + // And the pairs that *did* close still carry the depth they always + // did: an unmatched frame is still an enclosing scope. + let depths: Vec = scope_pairs(&doc_of(text)).pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![1, 2], "the two inner begins, unshifted"); +} + +#[test] +fn a_closer_that_opens_nothing_is_reported_as_unmatched() { + let text = "module m;\n initial begin\n end\n end\nendmodule\n"; + assert_eq!(unmatched_starts(text), vec![(3, 2)], "the second `end` closes nothing"); + assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 1, "the real pair is untouched"); +} + +#[test] +fn a_balanced_file_reports_nothing_unmatched() { + let text = "module m;\n initial begin\n fork\n x = 1;\n join\n end\nendmodule\n"; + assert!(scope_pairs(&doc_of(text)).unmatched.is_empty()); + assert_eq!(scope_pairs(&doc_of(text)).pairs.len(), 2); +} + +#[test] +fn a_keyword_is_never_both_paired_and_unmatched() { + // The two lists are painted with different colours, so an overlap + // would be two decorations fighting over one keyword. + let text = concat!( + "module m;\n", + " initial begin\n", + " begin\n", + " end\n", + " end\n", + " initial begin\n", + " end\n", + " end\n", + " initial fork\n", + "endmodule\n", + ); + let sent = scope_pairs(&doc_of(text)); + let paired: Vec = sent.pairs.iter().flat_map(|p| [p.open, p.close]).collect(); + assert_eq!(paired.len(), 6, "three pairs"); + assert_eq!(sent.unmatched.len(), 2, "the stray `end` and the unclosed `fork`"); + for lonely in &sent.unmatched { + assert!(!paired.contains(lonely), "{lonely:?} is on both lists"); + } +} + +#[test] +fn unmatched_carries_only_block_delimiters() { + // Same filter as `pairs`: the rainbow does not draw `module` or + // `function`, so it does not report their halves either. + let text = "module m;\n function f;\n begin\n"; + let sent = scope_pairs(&doc_of(text)); + assert!(sent.pairs.is_empty()); + assert_eq!(sent.unmatched.len(), 1, "the begin only, not the module or the function"); + assert_eq!(sent.unmatched[0].start.line, 2); + // The engine itself still saw all three unclosed. + assert_eq!(analyze(&doc_of(text).tokens).unmatched_open.len(), 3); +} + +#[test] +fn an_unmatched_join_is_reported_but_an_unmatched_endcase_is_not() { + // `unmatched_close` carries the closer; the filter asks about the + // *opener* it wanted, which is what `expected` holds. + assert_eq!(unmatched_starts("module m;\n join\nendmodule\n"), vec![(1, 2)]); + assert!(unmatched_starts("module m;\n endcase\nendmodule\n").is_empty()); +} + +#[test] +fn the_scope_pairs_wire_shape_is_what_the_extension_reads() { + // Pinned against the Handshakes section of the feature README: the + // extension indexes `pairs[].depth % 6`, paints `unmatched` in its + // error colour, and hands every range straight to the client's Range + // converter. + let doc = doc_of("module m;\n initial begin\n end\n begin\nendmodule\n"); + let json = serde_json::to_value(scope_pairs(&doc)).expect("serializes"); + assert_eq!( + json, + serde_json::json!({ + "pairs": [{ + "open": { + "start": { "line": 1, "character": 10 }, + "end": { "line": 1, "character": 15 } + }, + "close": { + "start": { "line": 2, "character": 2 }, + "end": { "line": 2, "character": 5 } + }, + "depth": 0 + }], + "unmatched": [{ + "start": { "line": 3, "character": 2 }, + "end": { "line": 3, "character": 7 } + }] + }) + ); +} + +// ------------------------------------------------------------------ +// missing-closer diagnostics, and the gate +// ------------------------------------------------------------------ + +#[test] +fn a_missing_end_warns_at_the_begin_that_lost_it() { + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + assert!(!doc.diagnostics.is_empty(), "premise: the parser must have failed"); + let warnings = missing_end_diagnostics(&doc); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].severity, Some(DiagnosticSeverity::WARNING)); + assert_eq!(warnings[0].source.as_deref(), Some("lucisv")); + assert_eq!(warnings[0].range.start.line, 1, "the `initial begin` line"); + assert_eq!(warnings[0].message, "`begin` has no matching `end` — is an `end` missing?"); +} + +#[test] +fn a_missing_join_names_join_and_not_end() { + let text = "module m;\n initial fork\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + let warnings = missing_end_diagnostics(&doc); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].message, "`fork` has no matching `join` — is a `join` missing?"); +} + +#[test] +fn an_orphan_closer_warns_on_itself() { + let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + assert!(!doc.diagnostics.is_empty(), "premise: the stray end breaks the parse"); + let warnings = missing_end_diagnostics(&doc); + assert!( + warnings.iter().any(|w| w.message == "`end` has no matching `begin`"), + "got {warnings:#?}" + ); +} + +#[test] +fn the_gate_alone_suppresses_the_warnings() { + // The precise claim: the *only* reason a clean-parsing buffer stays + // quiet is the gate. Clearing the parse diagnostics on a buffer the + // matcher does find unbalanced must not change the answer. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let mut doc = doc_of(text); + assert_eq!(missing_end_diagnostics(&doc).len(), 1, "premise: it warns"); + doc.diagnostics.clear(); + assert!(!analyze(&doc.tokens).unmatched_open.is_empty(), "still unbalanced"); + assert!(missing_end_diagnostics(&doc).is_empty(), "the gate must shut"); +} + +#[test] +fn a_file_that_parses_is_never_told_it_is_unbalanced() { + // Every hazard above, as a whole buffer the parser accepts. + let clean = [ + "module m;\n initial begin\n x = 1;\n end\nendmodule\n", + "class c;\n extern function void f(int a);\n pure virtual function int g();\nendclass\n", + "typedef class C;\nclass C;\n int x;\nendclass\n", + "class c;\n virtual interface bus_if vif;\nendclass\n", + "module m;\n import \"DPI-C\" function void c_init(input int a);\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n", + "module m;\n a1: assert property (@(posedge clk) a |-> b);\nendmodule\n", + "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n end\nendmodule\n", + "class c;\n covergroup cg;\n coverpoint x;\n endgroup\nendclass\n", + "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n", + ]; + for text in clean { + let doc = doc_of(text); + assert!(doc.diagnostics.is_empty(), "premise: this must parse — {text}"); + assert!(missing_end_diagnostics(&doc).is_empty(), "warned about {text}"); + // Stronger than the gate: the matcher itself must agree. + let analysis = analyze(&doc.tokens); + assert!(analysis.unmatched_open.is_empty(), "phantom unclosed scope in {text}"); + assert!(analysis.unmatched_close.is_empty(), "phantom stray closer in {text}"); + } +} + +#[test] +fn a_lint_warning_does_not_open_the_gate() { + // The gate reads the *parse* diagnostics. A file that only violates a + // lint rule parses fine and must stay quiet. + let doc = doc_of("module m;\n\twire a;\nendmodule\n"); + assert!(doc.diagnostics.is_empty(), "premise: a tab is not a parse error"); + assert!(missing_end_diagnostics(&doc).is_empty()); +} + +#[test] +fn the_warnings_are_capped() { + // Twenty-five stray `end`s. Flat on purpose: nesting them instead + // would charge the *parser's* recursion, and a test thread's 2 MiB + // stack is not the 8 MiB `docs/features/recursion-limit/README.md` + // requires — the cap under test here is this module's, not that one's. + let mut text = String::from("module m;\n initial begin\n x = 1;\n end\n"); + for _ in 0..25 { + text.push_str(" end\n"); + } + text.push_str("endmodule\n"); + let doc = doc_of(&text); + assert!(!doc.diagnostics.is_empty(), "premise: stray `end`s do not parse"); + assert_eq!(analyze(&doc.tokens).unmatched_close.len(), 25, "the matcher sees them all"); + assert_eq!(missing_end_diagnostics(&doc).len(), MAX_WARNINGS, "the publish is capped"); +} + +#[test] +fn the_published_list_carries_the_pair_warning() { + // The wiring, not the engine: `diagnostics::all` must include these. + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module m;\n initial begin\n x = 1;\nendmodule\n".into()); + let published = crate::diagnostics::all(ws.document(&uri).expect("open")); + assert!( + published.iter().any(|d| d.message.contains("has no matching `end`")), + "got {published:#?}" + ); + assert_eq!( + published[0].severity, + Some(DiagnosticSeverity::ERROR), + "the parse error still leads" + ); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index 3f1d75a..572cd83 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -601,1181 +601,6 @@ fn map_edits(positions: &Positions<'_>, edits: &[vlog_refactor::TextEdit]) -> Ve } #[cfg(test)] -mod tests { - use super::*; - use std::fs; - - /// A scratch workspace root. Removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_ports_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; - const TOP: &str = "module top;\n logic cfg;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"; - - /// A two-file workspace with `top.sv` open. - fn opened(tree: &Tree) -> (Workspace, Uri, Uri) { - let sub = tree.write("sub.sv", SUB); - let top = tree.write("top.sv", TOP); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let top_uri = path_to_uri(&top).expect("uri"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(top_uri.clone(), TOP.to_string()); - (ws, top_uri, sub_uri) - } - - fn edits_for<'a>(edit: &'a WorkspaceEdit, uri: &Uri) -> &'a [TextEdit] { - edit.changes.as_ref().expect("changes").get(uri).map_or(&[], Vec::as_slice) - } - - #[test] - fn add_port_edits_the_declaration_and_every_instantiation() { - let tree = Tree::new("add"); - 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()), - ]; - let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(edits_for(&edit, &sub_uri).len(), 1); - assert_eq!(edits_for(&edit, &sub_uri)[0].new_text, ",\n input logic cfg"); - let top = edits_for(&edit, &top_uri); - assert_eq!(top.len(), 1); - assert_eq!(top[0].new_text, ", .cfg(cfg)"); - assert_eq!(top[0].range.start.line, 2, "the instantiation's line"); - } - - #[test] - fn add_port_refuses_a_declaration_that_is_not_one() { - let tree = Tree::new("add_bad"); - let (ws, top_uri, _) = opened(&tree); - let arguments = vec![ - serde_json::to_value(&top_uri).expect("uri"), - Value::String("sub".into()), - Value::String("wire".into()), - ]; - let message = execute(&ws, ADD_PORT, &arguments).expect_err("not a port"); - assert!(message.contains("not a single ANSI port declaration"), "{message}"); - } - - #[test] - fn add_port_accepts_a_position_instead_of_a_module_name() { - let tree = Tree::new("add_at"); - let (ws, _, sub_uri) = opened(&tree); - let arguments = vec![ - serde_json::to_value(&sub_uri).expect("uri"), - serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), - Value::String("input logic cfg".into()), - ]; - let (edit, _) = execute(&ws, ADD_PORT, &arguments).expect("adds"); - assert_eq!(edits_for(&edit, &sub_uri).len(), 1); - } - - #[test] - fn remove_port_takes_a_position() { - let tree = Tree::new("remove"); - let (ws, top_uri, sub_uri) = opened(&tree); - let arguments = vec![ - serde_json::to_value(&sub_uri).expect("uri"), - serde_json::to_value(Position { line: 2, character: 14 }).expect("position"), - ]; - let (edit, warnings) = execute(&ws, REMOVE_PORT, &arguments).expect("removes"); - assert_eq!(warnings.len(), 1, "the dropped expression is reported: {warnings:?}"); - assert!(warnings[0].contains("`.rst(r)`"), "{warnings:?}"); - assert_eq!(edits_for(&edit, &sub_uri).len(), 2, "the comma and the port itself"); - assert_eq!(edits_for(&edit, &top_uri).len(), 2, "the connection and its comma"); - assert!(edits_for(&edit, &top_uri).iter().all(|e| e.new_text.is_empty())); - } - - #[test] - fn propagate_ports_fills_in_what_is_missing() { - let tree = Tree::new("propagate"); - let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", text); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - let arguments = vec![ - serde_json::to_value(&uri).expect("uri"), - serde_json::to_value(Position { line: 2, character: 6 }).expect("position"), - ]; - let (edit, _) = execute(&ws, PROPAGATE_PORTS, &arguments).expect("propagates"); - assert_eq!(edits_for(&edit, &uri).len(), 1); - assert_eq!(edits_for(&edit, &uri)[0].new_text, ", .rst(rst)"); - } - - #[test] - fn a_code_action_on_a_port_carries_the_whole_edit() { - let tree = Tree::new("action"); - let (ws, top_uri, sub_uri) = opened(&tree); - // The server computes offsets against the file's own text. - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - let actions = code_actions(&ws, &sub_uri, offset); - assert_eq!(actions.len(), 0, "sub.sv is not an open document"); - - // With the buffer open, the action is offered and carries its edit. - let mut ws = ws; - ws.set_document(sub_uri.clone(), SUB.to_string()); - let actions = code_actions(&ws, &sub_uri, offset); - assert_eq!(actions.len(), 1, "{actions:#?}"); - let CodeActionOrCommand::CodeAction(action) = &actions[0] else { panic!("an action") }; - assert_eq!(action.title, "lucisv: remove port `rst` (updates 1 instantiation)"); - assert_eq!(action.kind, Some(CodeActionKind::new(REFACTOR_PORTS))); - let edit = action.edit.as_ref().expect("an edit"); - assert_eq!(edits_for(edit, &sub_uri).len(), 2, "the comma and the port itself"); - assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma"); - } - - // ------------------------------------------------------------------ - // the answer is the whole workspace's answer, computed over a subset - // ------------------------------------------------------------------ - - /// One action's title and the edits it carries, per file in path order. - type Shape = (String, Vec<(String, Vec)>); - - /// A code action as a comparable value: its title and every edit it - /// carries, per file in path order — the whole of what a client receives. - /// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather - /// than compared as it is stored. - fn shape(actions: &[CodeActionOrCommand]) -> Vec { - actions - .iter() - .map(|action| { - let CodeActionOrCommand::CodeAction(action) = action else { - return ("a command".to_string(), Vec::new()); - }; - let mut changes: Vec<(String, Vec)> = action - .edit - .as_ref() - .and_then(|edit| edit.changes.as_ref()) - .map(|changes| { - changes - .iter() - .map(|(uri, edits)| { - let edits = edits - .iter() - .map(|edit| format!("{:?}{}", edit.range, edit.new_text)) - .collect(); - (uri.as_str().to_string(), edits) - }) - .collect() - }) - .unwrap_or_default(); - changes.sort(); - (action.title.clone(), changes) - }) - .collect() - } - - /// What `code_actions` used to compute: the same engine call over every - /// in-scope file. The equivalence tests below assert the new answer - /// against this one rather than against a transcription of it. - fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { - let doc = ws.document(uri).expect("an open document"); - let path = doc.path.clone().expect("a saved file"); - let sources = ws.sources(); - vlog_refactor::port_actions(&sources, &path, offset) - .into_iter() - .filter_map(|action| { - let edit = workspace_edit(ws, &action.edit).ok()?; - Some(CodeActionOrCommand::CodeAction(CodeAction { - title: action.title, - kind: Some(CodeActionKind::new(REFACTOR_PORTS)), - edit: Some(edit), - ..Default::default() - })) - }) - .collect() - } - - /// A workspace of `noise` files that have nothing to do with `sub`, plus - /// `sub.sv` and three files that instantiate it. - fn crowded(tree: &Tree, noise: usize) -> Workspace { - tree.write("sub.sv", SUB); - for n in 0..3 { - tree.write( - &format!("top{n}.sv"), - &format!( - "module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n" - ), - ); - } - for n in 0..noise { - tree.write( - &format!("noise{n}.sv"), - &format!("module noise{n};\n logic a;\n wire b;\n assign b = a;\nendmodule\n"), - ); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - ws - } - - #[test] - fn a_code_action_answers_what_the_whole_workspace_would() { - let tree = Tree::new("equivalence"); - let mut ws = crowded(&tree, 40); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let subset = code_actions(&ws, &sub_uri, offset); - assert_eq!(subset.len(), 1, "{subset:#?}"); - let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; - assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)"); - assert_eq!( - shape(&subset), - shape(&whole_workspace_at(&ws, &sub_uri, offset)), - "the subset must answer exactly what every file would have" - ); - } - - #[test] - fn the_files_a_code_action_reads_are_the_modules_own_fan_out() { - let tree = Tree::new("fanout"); - let mut ws = crowded(&tree, 40); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - - assert_eq!(ws.sources().len(), 44, "the whole workspace"); - let read = ws.module_sources(&sub, &["sub".to_string()]); - let mut names: Vec = read - .iter() - .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) - .collect(); - names.sort(); - assert_eq!(names, ["sub.sv", "top0.sv", "top1.sv", "top2.sv"], "and not one noise file"); - } - - #[test] - fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() { - let tree = Tree::new("unsaved"); - let mut ws = crowded(&tree, 20); - // A file the index knows as instantiating nothing, whose buffer now - // instantiates `sub`. No save, so no edge in the index. - let extra = tree.path.join("noise0.sv"); - let extra_uri = path_to_uri(&extra).expect("uri"); - let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; - ws.set_document(extra_uri.clone(), typed.to_string()); - assert!( - ws.index() - .instantiations_of("sub") - .iter() - .all(|edge| ws.index().path(edge.file) != Some(extra.as_path())), - "the index has not seen the unsaved instantiation" - ); - - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let subset = code_actions(&ws, &sub_uri, offset); - let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; - assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)"); - let edit = action.edit.as_ref().expect("an edit"); - assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); - assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset))); - } - - #[test] - fn a_module_declared_twice_is_refused_through_the_subset_as_well() { - let tree = Tree::new("ambiguous"); - let mut ws = crowded(&tree, 10); - // A second declaration of `sub`, in a file nothing else names. - tree.write("clone.sv", SUB); - ws.rebuild_index(); - assert_eq!(ws.index().units("sub").len(), 2, "two declarations"); - - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - // Both definers are in the set, so the engine sees the ambiguity and - // refuses — which is no action, exactly as over the whole workspace. - assert!(ws - .module_sources(&sub, &["sub".to_string()]) - .iter() - .any(|(path, _)| path.ends_with("clone.sv"))); - assert!(code_actions(&ws, &sub_uri, offset).is_empty()); - assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty()); - } - - #[test] - fn a_command_computes_over_the_subset_and_answers_the_same() { - let tree = Tree::new("command"); - let mut ws = crowded(&tree, 40); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - - let arguments = vec![ - serde_json::to_value(&sub_uri).expect("uri"), - Value::String("sub".into()), - Value::String("input logic cfg".into()), - ]; - let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); - let whole = - vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") - .expect("adds"); - assert_eq!(warnings, whole.warnings); - assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); - assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops"); - } - - #[test] - fn qa_file_scope_instantiation_lands_in_the_subset() { - let tree = Tree::new("qa_filescope"); - let mut ws = crowded(&tree, 20); - // A file-scope (owner-less) instantiation of `sub` — illegal SV, but - // a tolerant parse still produces an Instantiation item, and the old - // whole-workspace engine would still edit it (collect_instantiations - // walks tree.items directly). It records no InstantiationEdge (edges_of - // requires an owner), so only the references_to half of rung 3 can - // possibly find it. - let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n"); - ws.rebuild_index(); - assert!( - ws.index() - .instantiations_of("sub") - .iter() - .all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())), - "file-scope site records no edge, as documented" - ); - - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - - let read = ws.module_sources(&sub, &["sub".to_string()]); - let names: Vec = read - .iter() - .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) - .collect(); - assert!( - names.contains(&"filescope.sv".to_string()), - "file-scope instantiation site must be in the subset: {names:?}" - ); - - // And the whole-workspace engine really would have edited it, so - // omitting it from the subset would be a real divergence. - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - let whole = whole_workspace_at(&ws, &sub_uri, offset); - let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") }; - let edit = action.edit.as_ref().expect("an edit"); - let fs_uri = path_to_uri(&filescope_path).expect("uri"); - assert_eq!( - edits_for(edit, &fs_uri).len(), - 2, - "the whole-workspace answer edits the file-scope site" - ); - - let subset = code_actions(&ws, &sub_uri, offset); - assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); - } - - #[test] - fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() { - // The subset builder trusts the index for rungs 2/3, so a file that - // changed on disk with nothing telling the server (no rebuild_index, - // no didChange) is invisible to it — unlike the old `sources()` path, - // which re-reads the directory fresh every call. Attack: write a - // *second* definer of `sub` straight to disk, do NOT reindex, and - // fire a code action. Judged against invariant 1 (never corrupt), not - // against freshness: an answer that goes stale (or a refusal) is - // fine; an edit that is not internally verified would not be. - let tree = Tree::new("qa_stale_dup"); - let mut ws = crowded(&tree, 10); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - // Sanity: before the duplicate exists anywhere, the subset offers the - // action normally. - assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1); - - // Write a duplicate declaration straight to disk, bypassing the - // server entirely (no rebuild_index, no set_document for this path). - tree.write("dupe.sv", SUB); - - // The index still knows only one definer, so the subset the server - // computes is unaware of the ambiguity and still offers the action. - assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told"); - let subset = code_actions(&ws, &sub_uri, offset); - assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv"); - - // The critical assertion: whatever it produced must still be an - // honest, self-consistent, verified edit over the files it actually - // read — not corruption of a file it never looked at. `dupe.sv` - // itself must be untouched (never read, never in the edit) and the - // edit that *was* produced must still verify against what changed. - let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; - let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri"); - let edit = action.edit.as_ref().expect("an edit"); - assert!( - edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)), - "the unindexed duplicate must not be touched: {edit:?}" - ); - - // Once the index is told (rebuild_index, exactly what the watcher - // does on a save it's told about), parity is restored: the subset - // now sees the duplicate and refuses, exactly like the whole - // workspace always would have. - ws.rebuild_index(); - assert_eq!(ws.index().units("sub").len(), 2, "now indexed"); - assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told"); - } - - #[test] - fn qa_generate_block_instantiation_lands_in_the_subset() { - let tree = Tree::new("qa_generate"); - let mut ws = crowded(&tree, 20); - let gen_path = tree.write( - "gen.sv", - "module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n", - ); - ws.rebuild_index(); - assert!( - ws.index() - .instantiations_of("sub") - .iter() - .any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())), - "the generate-for body instantiation is a real edge" - ); - - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let read = ws.module_sources(&sub, &["sub".to_string()]); - let names: Vec = read - .iter() - .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) - .collect(); - assert!(names.contains(&"gen.sv".to_string()), "{names:?}"); - - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - let subset = code_actions(&ws, &sub_uri, offset); - let whole = whole_workspace_at(&ws, &sub_uri, offset); - assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); - } - - #[test] - fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() { - // Not a subset-specific question: does an escaped-identifier - // instantiation (`\sub$weird u1 (...)`) even resolve to the module it - // names, workspace-index-wise, so the subset builder's `units`/ - // `instantiations_of`/`references_to` lookups have anything to find? - // Attacking whether the *subset* diverges from the *whole-workspace* - // answer here, not whether escaped identifiers work at all (a - // pre-existing question this round did not touch). - let tree = Tree::new("qa_escaped"); - tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n"); - let mut ws = crowded(&tree, 10); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let subset = code_actions(&ws, &sub_uri, offset); - let whole = whole_workspace_at(&ws, &sub_uri, offset); - // Whichever way the parser/binder treats the escaped identifier - // `\sub ` (as `sub`, or as a distinct name), the subset and the - // whole-workspace computation must agree either way. - assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); - } - - #[test] - fn qa_add_port_by_position_still_fans_out_to_instantiation_files() { - // `a_command_computes_over_the_subset_and_answers_the_same` (the - // dev's own equivalence test) drives `lucisv.addPort` with a - // *module-name* argument. The *Position* argument takes a completely - // different path to the module (`sources_at` → `port_action_modules` - // + `enclosing_module`, rather than `module_sources` fed the name - // directly) and is exactly the code action's own code path - // (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it - // still reaches every instantiating file, not just the declaring one. - let tree = Tree::new("qa_add_by_position"); - let mut ws = crowded(&tree, 30); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - - let arguments = vec![ - serde_json::to_value(&sub_uri).expect("uri"), - serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), - Value::String("input logic cfg".into()), - ]; - let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); - assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}"); - let changes = edit.changes.as_ref().expect("changes"); - assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}"); - for n in 0..3 { - let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri"); - assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection"); - } - - let whole = - vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") - .expect("adds"); - assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); - } - - #[test] - fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() { - // A module the index has never seen at all — not stale, genuinely - // absent, e.g. a brand-new buffer the user has not saved yet. Rung 2 - // (`index.units`) has nothing; only rung 1 (the request's own file) - // can supply it. The cursor sits in that same new buffer, so rung 1 - // must be enough on its own — and it must not panic or silently - // return no action just because the index is empty for this name. - let tree = Tree::new("qa_unsaved_new_module"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it"); - - let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n"; - let new_path = tree.path.join("brandnew.sv"); // never written to disk - let new_uri = path_to_uri(&new_path).expect("uri"); - ws.set_document(new_uri.clone(), text.to_string()); - - let offset = text.find("input logic b").expect("b") as u32 + 12; - let subset = code_actions(&ws, &new_uri, offset); - assert_eq!(subset.len(), 1, "{subset:#?}"); - let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; - assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)"); - assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2); - } - - // ------------------------------------------------------------------ - // the lazy offer and its resolve (TODO §37.1) - // ------------------------------------------------------------------ - - /// The offer a client that can resolve receives at `offset`. - fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { - let position = ws.document(uri).expect("an open document").positions().position(offset); - offers(ws, uri, position, offset) - } - - /// One action's title and kind — what a lightbulb draws, and all an offer - /// promises. - fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option)> { - actions - .iter() - .map(|action| { - let CodeActionOrCommand::CodeAction(action) = action else { - return ("a command".to_string(), None); - }; - (action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string())) - }) - .collect() - } - - /// The one action an offer holds. - fn only(actions: &[CodeActionOrCommand]) -> &CodeAction { - let [CodeActionOrCommand::CodeAction(action)] = actions else { - panic!("exactly one action, got {actions:#?}") - }; - action - } - - #[test] - fn the_lazy_offer_names_exactly_what_the_eager_one_names() { - let tree = Tree::new("lazy_menu"); - let mut ws = crowded(&tree, 40); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let lazy = offered(&ws, &sub_uri, offset); - assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset))); - assert_eq!( - menu(&lazy)[0].0, - "lucisv: remove port `rst` (updates 3 instantiations)", - "counted from the index, and it agrees with the plan's own count" - ); - let action = only(&lazy); - assert!(action.edit.is_none(), "an offer carries no edit"); - assert!(action.data.is_some(), "it carries what resolve needs instead"); - } - - #[test] - fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() { - // The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out` - // is to the eager path; this is the same question asked of the offer, - // through the set it hands the engine. Neither the 40 noise files nor - // — and this is the point — any of the three instantiating tops. - let tree = Tree::new("lazy_reads"); - let mut ws = crowded(&tree, 40); - let sub = tree.path.join("sub.sv"); - let sub_uri = path_to_uri(&sub).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - assert_eq!(ws.sources().len(), 44, "the whole workspace"); - assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out"); - - // A cursor on a port declaration: the module is the buffer's own. - let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]); - let names: Vec = read - .iter() - .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) - .collect(); - assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself"); - - // A cursor on an instantiation: the buffer, plus the one file the - // index says declares the module. - let top = tree.path.join("top0.sv"); - let top_text = std::fs::read_to_string(&top).expect("read"); - let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]); - let mut names: Vec = read - .iter() - .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) - .collect(); - names.sort(); - assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file"); - } - - #[test] - fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() { - let tree = Tree::new("resolve_port"); - let mut ws = crowded(&tree, 40); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit"); - let eager = only(&code_actions(&ws, &sub_uri, offset)).clone(); - assert_eq!(resolved.title, eager.title); - assert_eq!(resolved.kind, eager.kind); - assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte"); - assert!(resolved.data.is_some(), "the offer's own data survives the round trip"); - } - - #[test] - fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() { - // The other cursor shape: an instantiation missing a connection, where - // the offer has to read the *instantiated* module's declaration to - // know there is anything to offer at all. - let tree = Tree::new("resolve_inst"); - let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", text); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - let offset = text.find("sub u_sub").expect("the instantiation") as u32; - - let lazy = offered(&ws, &uri, offset); - assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); - assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port"); - assert!(only(&lazy).edit.is_none()); - - let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); - assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); - assert_eq!( - edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, - ", .rst(rst)" - ); - } - - #[test] - fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() { - // The pin `an_unsaved_buffer_contributes_the_instantiation_the_index - // _has_not_seen` moved to the lazy path. The offer counts instances - // from the index, which has not seen the unsaved one, so the title - // says three; the *edit* is computed over the fan-out plus every open - // buffer, so it disconnects all four. Exactness lives in the edit, - // which is what the user actually applies. - let tree = Tree::new("lazy_unsaved"); - let mut ws = crowded(&tree, 20); - let extra = tree.path.join("noise0.sv"); - let extra_uri = path_to_uri(&extra).expect("uri"); - let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; - ws.set_document(extra_uri.clone(), typed.to_string()); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - let lazy = offered(&ws, &sub_uri, offset); - assert_eq!( - menu(&lazy)[0].0, - "lucisv: remove port `rst` (updates 3 instantiations)", - "the index has not seen the fourth" - ); - let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); - assert_eq!( - resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)", - "and the resolve says so" - ); - let edit = resolved.edit.as_ref().expect("an edit"); - assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); - assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit); - } - - #[test] - fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() { - let tree = Tree::new("lazy_stale"); - let mut ws = crowded(&tree, 10); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - let offered = only(&offered(&ws, &sub_uri, offset)).clone(); - - // The user kept typing: the port the lightbulb was about is gone. - ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into()); - let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve"); - assert_eq!(message, GONE); - - // And a document that has been closed altogether says the same. - ws.close_document(&sub_uri); - assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE); - } - - #[test] - fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() { - // `codeAction/resolve`'s params are a `CodeAction`, so the fast path's - // own gate — which reads a `textDocument` out of the params — never - // sees this request. A buffer that grew past the threshold since it - // was offered an action must still not be parsed. - let tree = Tree::new("lazy_large"); - let mut ws = crowded(&tree, 5); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - let offered = only(&offered(&ws, &sub_uri, offset)).clone(); - - let _ = ws.set_client_settings(crate::settings::ClientSettings { - large_file_threshold: 8, - ..Default::default() - }); - ws.set_document(sub_uri.clone(), SUB.to_string()); - assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path"); - assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE); - } - - #[test] - fn a_resolve_of_something_this_server_never_offered_says_so() { - let tree = Tree::new("lazy_foreign"); - let (ws, uri, _) = opened(&tree); - let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() }; - assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS); - - // Data that is not ours either — a shape `serde` cannot read as an - // offer. Refused, not guessed at. - let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() }; - assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS); - - // An action that already carries its edit — every quick fix in - // `code_action.rs`, and the port actions a non-resolving client is - // sent — comes straight back, because there is nothing to add to it. - let complete = - CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare }; - assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete); - } - - #[test] - fn a_name_the_workspace_declares_twice_is_not_offered_either() { - // The eager path refuses because both declaring files are in the set - // it reads (`a_module_declared_twice_is_refused_through_the_subset_as - // _well`). The offer reads neither, so it asks the index the same - // question — otherwise it would offer an action resolve then refuses. - let tree = Tree::new("lazy_ambiguous"); - let mut ws = crowded(&tree, 10); - tree.write("clone.sv", SUB); - ws.rebuild_index(); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - ws.set_document(sub_uri.clone(), SUB.to_string()); - let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; - - assert!(offered(&ws, &sub_uri, offset).is_empty()); - assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does"); - } - - #[test] - fn a_title_keys_on_everything_but_its_count() { - assert_eq!( - key("lucisv: remove port `rst` (updates 3 instantiations)"), - key("lucisv: remove port `rst` (no instantiation in scope)") - ); - assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port"); - assert_ne!( - key("lucisv: remove port `rst` (updates 1 instantiation)"), - key("lucisv: remove port `clk` (updates 1 instantiation)") - ); - } - - /// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` - #[test] - #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] - fn the_offer_is_flat_where_the_eager_answer_grows() { - // `performance_take2.md` §6a measured the eager answer growing with - // the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms - // floor, 185 ms at 128 files, to offer *zero* actions. The offer reads - // one file (a cursor on a port declaration) or two (a cursor on an - // instantiation), so its column should be flat. Beside the code it - // measures rather than in `perf.rs`, which is what `perf::mean` is - // `pub(crate)` for. - for instantiators in [3usize, 40, 128] { - let tree = Tree::new(&format!("perf_offer_{instantiators}")); - tree.write("sub.sv", SUB); - for n in 0..instantiators { - tree.write( - &format!("top{n:03}.sv"), - &format!( - "module top{n:03};\n logic c, r;\n \ - sub u_sub (.clk(c), .rst(r));\nendmodule\n" - ), - ); - } - for n in 0..200 { - tree.write( - &format!("noise{n:03}.sv"), - &format!( - "module noise{n:03};\n logic a;\n wire b;\n \ - assign b = a;\nendmodule\n" - ), - ); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - - for (what, file, needle, skip) in [ - ("a port declaration", "sub.sv", "input logic rst", 12u32), - ("an instantiation ", "top000.sv", "sub u_sub", 0), - ] { - let path = tree.path.join(file); - let text = std::fs::read_to_string(&path).expect("read"); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), text.clone()); - let offset = text.find(needle).expect("the cursor") as u32 + skip; - let eager = crate::perf::mean(5, || { - std::hint::black_box(code_actions(&ws, &uri, offset)); - }); - let offer = crate::perf::mean(20, || { - std::hint::black_box(offered(&ws, &uri, offset)); - }); - eprintln!( - " fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \ - offer {offer:?} ({} actions)", - offered(&ws, &uri, offset).len() - ); - } - } - } - - #[test] - fn an_unknown_command_is_declined() { - let tree = Tree::new("unknown"); - let (ws, uri, _) = opened(&tree); - let arguments = vec![serde_json::to_value(&uri).expect("uri")]; - let message = execute(&ws, "lucisv.nope", &arguments).expect_err("unknown"); - assert!(message.contains("not a lucisv command"), "{message}"); - } - - #[test] - fn a_command_without_its_arguments_is_declined() { - let tree = Tree::new("args"); - let (ws, uri, _) = opened(&tree); - let message = execute(&ws, REMOVE_PORT, &[]).expect_err("no uri"); - assert!(message.contains("document URI"), "{message}"); - let only_uri = vec![serde_json::to_value(&uri).expect("uri")]; - let message = execute(&ws, REMOVE_PORT, &only_uri).expect_err("no position"); - assert!(message.contains("position"), "{message}"); - } - - // ------------------------------------------------------------------ - // the `.*` expansion (TODO §50) - // ------------------------------------------------------------------ - - /// A workspace whose `top.sv` instantiates `sub` with a wildcard. - fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) { - const TEXT: &str = - "module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n"; - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", TEXT); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), TEXT.to_string()); - (ws, uri, TEXT) - } - - #[test] - fn expand_wildcard_takes_a_position() { - let tree = Tree::new("expand"); - let (ws, uri, text) = wildcard(&tree); - let arguments = vec![ - serde_json::to_value(&uri).expect("uri"), - serde_json::to_value(Position { line: 2, character: 24 }).expect("position"), - ]; - let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands"); - assert!(warnings.is_empty(), "{warnings:?}"); - let edits = edits_for(&edit, &uri); - assert_eq!(edits.len(), 1, "{edits:#?}"); - assert_eq!(edits[0].new_text, ".rst(rst)"); - // The range is the `.*` itself, in the client's own coordinates. - assert_eq!(edits[0].range.start.character, 24); - assert_eq!(edits[0].range.end.character, 26); - assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*"); - } - - #[test] - fn expand_wildcard_refuses_where_there_is_no_wildcard() { - let tree = Tree::new("expand_none"); - let (ws, top_uri, _) = opened(&tree); - let arguments = vec![ - serde_json::to_value(&top_uri).expect("uri"), - serde_json::to_value(Position { line: 2, character: 6 }).expect("position"), - ]; - let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard"); - assert!(message.contains("writes no `.*` to expand"), "{message}"); - } - - #[test] - fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() { - let tree = Tree::new("expand_action"); - let (ws, uri, text) = wildcard(&tree); - let offset = text.find(".*").expect("the wildcard") as u32; - - let lazy = offered(&ws, &uri, offset); - assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); - // The count is the connections the wildcard becomes, and the index's - // instantiation census must not overwrite it. - assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)"); - assert!(only(&lazy).edit.is_none(), "an offer carries no edit"); - - let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); - assert_eq!(resolved.title, "lucisv: expand .* (1 connection)"); - assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); - assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)"); - } - - // ------------------------------------------------------------------ - // the non-ANSI → ANSI conversion (TODO §51) - // ------------------------------------------------------------------ - - /// A workspace whose `legacy.sv` writes a Verilog-2001 header. - const LEGACY: &str = - "module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n"; - - fn legacy(tree: &Tree) -> (Workspace, Uri) { - let path = tree.write("legacy.sv", LEGACY); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), LEGACY.to_string()); - (ws, uri) - } - - #[test] - fn convert_to_ansi_takes_a_position() { - let tree = Tree::new("ansi"); - let (ws, uri) = legacy(&tree); - let arguments = vec![ - serde_json::to_value(&uri).expect("uri"), - // The module's own name — inside the header, and nowhere near a - // port declaration. - serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), - ]; - // Two insertions — the ANSI prefixes — and three deletions: `input a;`, - // `output [7:0] b;` and the `reg [7:0] b;` that completed it. - let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts"); - assert!(warnings.is_empty(), "{warnings:?}"); - let edits = edits_for(&edit, &uri); - let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect(); - assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}"); - } - - #[test] - fn convert_to_ansi_refuses_an_ansi_header() { - let tree = Tree::new("ansi_none"); - let (ws, top_uri, _) = opened(&tree); - let arguments = vec![ - serde_json::to_value(&top_uri).expect("uri"), - serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), - ]; - let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert"); - assert!(message.contains("declares no ports"), "{message}"); - } - - #[test] - fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() { - let tree = Tree::new("ansi_action"); - let (ws, uri) = legacy(&tree); - // The cursor on the module's name: in the header, on no port. - let offset = LEGACY.find("legacy (").expect("the name") as u32; - - let lazy = offered(&ws, &uri, offset); - assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); - assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)"); - assert!(only(&lazy).edit.is_none(), "an offer carries no edit"); - - let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); - assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)"); - assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); - assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input "); - } - - #[test] - fn the_command_list_is_what_the_server_advertises() { - assert_eq!( - commands(), - 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:?}"); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/ports/tests.rs b/crates/lucisv_server/src/ports/tests.rs new file mode 100644 index 0000000..99c080d --- /dev/null +++ b/crates/lucisv_server/src/ports/tests.rs @@ -0,0 +1,1167 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use std::fs; + +/// A scratch workspace root. Removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = + std::env::temp_dir().join(format!("lucisv_server_ports_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; +const TOP: &str = "module top;\n logic cfg;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"; + +/// A two-file workspace with `top.sv` open. +fn opened(tree: &Tree) -> (Workspace, Uri, Uri) { + let sub = tree.write("sub.sv", SUB); + let top = tree.write("top.sv", TOP); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let top_uri = path_to_uri(&top).expect("uri"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(top_uri.clone(), TOP.to_string()); + (ws, top_uri, sub_uri) +} + +fn edits_for<'a>(edit: &'a WorkspaceEdit, uri: &Uri) -> &'a [TextEdit] { + edit.changes.as_ref().expect("changes").get(uri).map_or(&[], Vec::as_slice) +} + +#[test] +fn add_port_edits_the_declaration_and_every_instantiation() { + let tree = Tree::new("add"); + 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()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 1); + assert_eq!(edits_for(&edit, &sub_uri)[0].new_text, ",\n input logic cfg"); + let top = edits_for(&edit, &top_uri); + assert_eq!(top.len(), 1); + assert_eq!(top[0].new_text, ", .cfg(cfg)"); + assert_eq!(top[0].range.start.line, 2, "the instantiation's line"); +} + +#[test] +fn add_port_refuses_a_declaration_that_is_not_one() { + let tree = Tree::new("add_bad"); + let (ws, top_uri, _) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + Value::String("sub".into()), + Value::String("wire".into()), + ]; + let message = execute(&ws, ADD_PORT, &arguments).expect_err("not a port"); + assert!(message.contains("not a single ANSI port declaration"), "{message}"); +} + +#[test] +fn add_port_accepts_a_position_instead_of_a_module_name() { + let tree = Tree::new("add_at"); + let (ws, _, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + Value::String("input logic cfg".into()), + ]; + let (edit, _) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 1); +} + +#[test] +fn remove_port_takes_a_position() { + let tree = Tree::new("remove"); + let (ws, top_uri, sub_uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 14 }).expect("position"), + ]; + let (edit, warnings) = execute(&ws, REMOVE_PORT, &arguments).expect("removes"); + assert_eq!(warnings.len(), 1, "the dropped expression is reported: {warnings:?}"); + assert!(warnings[0].contains("`.rst(r)`"), "{warnings:?}"); + assert_eq!(edits_for(&edit, &sub_uri).len(), 2, "the comma and the port itself"); + assert_eq!(edits_for(&edit, &top_uri).len(), 2, "the connection and its comma"); + assert!(edits_for(&edit, &top_uri).iter().all(|e| e.new_text.is_empty())); +} + +#[test] +fn propagate_ports_fills_in_what_is_missing() { + let tree = Tree::new("propagate"); + let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", text); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 6 }).expect("position"), + ]; + let (edit, _) = execute(&ws, PROPAGATE_PORTS, &arguments).expect("propagates"); + assert_eq!(edits_for(&edit, &uri).len(), 1); + assert_eq!(edits_for(&edit, &uri)[0].new_text, ", .rst(rst)"); +} + +#[test] +fn a_code_action_on_a_port_carries_the_whole_edit() { + let tree = Tree::new("action"); + let (ws, top_uri, sub_uri) = opened(&tree); + // The server computes offsets against the file's own text. + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let actions = code_actions(&ws, &sub_uri, offset); + assert_eq!(actions.len(), 0, "sub.sv is not an open document"); + + // With the buffer open, the action is offered and carries its edit. + let mut ws = ws; + ws.set_document(sub_uri.clone(), SUB.to_string()); + let actions = code_actions(&ws, &sub_uri, offset); + assert_eq!(actions.len(), 1, "{actions:#?}"); + let CodeActionOrCommand::CodeAction(action) = &actions[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `rst` (updates 1 instantiation)"); + assert_eq!(action.kind, Some(CodeActionKind::new(REFACTOR_PORTS))); + let edit = action.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &sub_uri).len(), 2, "the comma and the port itself"); + assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma"); +} + +// ------------------------------------------------------------------ +// the answer is the whole workspace's answer, computed over a subset +// ------------------------------------------------------------------ + +/// One action's title and the edits it carries, per file in path order. +type Shape = (String, Vec<(String, Vec)>); + +/// A code action as a comparable value: its title and every edit it +/// carries, per file in path order — the whole of what a client receives. +/// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather +/// than compared as it is stored. +fn shape(actions: &[CodeActionOrCommand]) -> Vec { + actions + .iter() + .map(|action| { + let CodeActionOrCommand::CodeAction(action) = action else { + return ("a command".to_string(), Vec::new()); + }; + let mut changes: Vec<(String, Vec)> = action + .edit + .as_ref() + .and_then(|edit| edit.changes.as_ref()) + .map(|changes| { + changes + .iter() + .map(|(uri, edits)| { + let edits = edits + .iter() + .map(|edit| format!("{:?}{}", edit.range, edit.new_text)) + .collect(); + (uri.as_str().to_string(), edits) + }) + .collect() + }) + .unwrap_or_default(); + changes.sort(); + (action.title.clone(), changes) + }) + .collect() +} + +/// What `code_actions` used to compute: the same engine call over every +/// in-scope file. The equivalence tests below assert the new answer +/// against this one rather than against a transcription of it. +fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let doc = ws.document(uri).expect("an open document"); + let path = doc.path.clone().expect("a saved file"); + let sources = ws.sources(); + vlog_refactor::port_actions(&sources, &path, offset) + .into_iter() + .filter_map(|action| { + let edit = workspace_edit(ws, &action.edit).ok()?; + Some(CodeActionOrCommand::CodeAction(CodeAction { + title: action.title, + kind: Some(CodeActionKind::new(REFACTOR_PORTS)), + edit: Some(edit), + ..Default::default() + })) + }) + .collect() +} + +/// A workspace of `noise` files that have nothing to do with `sub`, plus +/// `sub.sv` and three files that instantiate it. +fn crowded(tree: &Tree, noise: usize) -> Workspace { + tree.write("sub.sv", SUB); + for n in 0..3 { + tree.write( + &format!("top{n}.sv"), + &format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"), + ); + } + for n in 0..noise { + tree.write( + &format!("noise{n}.sv"), + &format!("module noise{n};\n logic a;\n wire b;\n assign b = a;\nendmodule\n"), + ); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + ws +} + +#[test] +fn a_code_action_answers_what_the_whole_workspace_would() { + let tree = Tree::new("equivalence"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(subset.len(), 1, "{subset:#?}"); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)"); + assert_eq!( + shape(&subset), + shape(&whole_workspace_at(&ws, &sub_uri, offset)), + "the subset must answer exactly what every file would have" + ); +} + +#[test] +fn the_files_a_code_action_reads_are_the_modules_own_fan_out() { + let tree = Tree::new("fanout"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + assert_eq!(ws.sources().len(), 44, "the whole workspace"); + let read = ws.module_sources(&sub, &["sub".to_string()]); + let mut names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["sub.sv", "top0.sv", "top1.sv", "top2.sv"], "and not one noise file"); +} + +#[test] +fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() { + let tree = Tree::new("unsaved"); + let mut ws = crowded(&tree, 20); + // A file the index knows as instantiating nothing, whose buffer now + // instantiates `sub`. No save, so no edge in the index. + let extra = tree.path.join("noise0.sv"); + let extra_uri = path_to_uri(&extra).expect("uri"); + let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; + ws.set_document(extra_uri.clone(), typed.to_string()); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .all(|edge| ws.index().path(edge.file) != Some(extra.as_path())), + "the index has not seen the unsaved instantiation" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)"); + let edit = action.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); + assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset))); +} + +#[test] +fn a_module_declared_twice_is_refused_through_the_subset_as_well() { + let tree = Tree::new("ambiguous"); + let mut ws = crowded(&tree, 10); + // A second declaration of `sub`, in a file nothing else names. + tree.write("clone.sv", SUB); + ws.rebuild_index(); + assert_eq!(ws.index().units("sub").len(), 2, "two declarations"); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + // Both definers are in the set, so the engine sees the ambiguity and + // refuses — which is no action, exactly as over the whole workspace. + assert!(ws + .module_sources(&sub, &["sub".to_string()]) + .iter() + .any(|(path, _)| path.ends_with("clone.sv"))); + assert!(code_actions(&ws, &sub_uri, offset).is_empty()); + assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty()); +} + +#[test] +fn a_command_computes_over_the_subset_and_answers_the_same() { + let tree = Tree::new("command"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + Value::String("sub".into()), + Value::String("input logic cfg".into()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + let whole = vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") + .expect("adds"); + assert_eq!(warnings, whole.warnings); + assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); + assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops"); +} + +#[test] +fn qa_file_scope_instantiation_lands_in_the_subset() { + let tree = Tree::new("qa_filescope"); + let mut ws = crowded(&tree, 20); + // A file-scope (owner-less) instantiation of `sub` — illegal SV, but + // a tolerant parse still produces an Instantiation item, and the old + // whole-workspace engine would still edit it (collect_instantiations + // walks tree.items directly). It records no InstantiationEdge (edges_of + // requires an owner), so only the references_to half of rung 3 can + // possibly find it. + let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n"); + ws.rebuild_index(); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())), + "file-scope site records no edge, as documented" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let read = ws.module_sources(&sub, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert!( + names.contains(&"filescope.sv".to_string()), + "file-scope instantiation site must be in the subset: {names:?}" + ); + + // And the whole-workspace engine really would have edited it, so + // omitting it from the subset would be a real divergence. + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let whole = whole_workspace_at(&ws, &sub_uri, offset); + let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") }; + let edit = action.edit.as_ref().expect("an edit"); + let fs_uri = path_to_uri(&filescope_path).expect("uri"); + assert_eq!( + edits_for(edit, &fs_uri).len(), + 2, + "the whole-workspace answer edits the file-scope site" + ); + + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); +} + +#[test] +fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() { + // The subset builder trusts the index for rungs 2/3, so a file that + // changed on disk with nothing telling the server (no rebuild_index, + // no didChange) is invisible to it — unlike the old `sources()` path, + // which re-reads the directory fresh every call. Attack: write a + // *second* definer of `sub` straight to disk, do NOT reindex, and + // fire a code action. Judged against invariant 1 (never corrupt), not + // against freshness: an answer that goes stale (or a refusal) is + // fine; an edit that is not internally verified would not be. + let tree = Tree::new("qa_stale_dup"); + let mut ws = crowded(&tree, 10); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + // Sanity: before the duplicate exists anywhere, the subset offers the + // action normally. + assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1); + + // Write a duplicate declaration straight to disk, bypassing the + // server entirely (no rebuild_index, no set_document for this path). + tree.write("dupe.sv", SUB); + + // The index still knows only one definer, so the subset the server + // computes is unaware of the ambiguity and still offers the action. + assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told"); + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv"); + + // The critical assertion: whatever it produced must still be an + // honest, self-consistent, verified edit over the files it actually + // read — not corruption of a file it never looked at. `dupe.sv` + // itself must be untouched (never read, never in the edit) and the + // edit that *was* produced must still verify against what changed. + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri"); + let edit = action.edit.as_ref().expect("an edit"); + assert!( + edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)), + "the unindexed duplicate must not be touched: {edit:?}" + ); + + // Once the index is told (rebuild_index, exactly what the watcher + // does on a save it's told about), parity is restored: the subset + // now sees the duplicate and refuses, exactly like the whole + // workspace always would have. + ws.rebuild_index(); + assert_eq!(ws.index().units("sub").len(), 2, "now indexed"); + assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told"); +} + +#[test] +fn qa_generate_block_instantiation_lands_in_the_subset() { + let tree = Tree::new("qa_generate"); + let mut ws = crowded(&tree, 20); + let gen_path = tree.write( + "gen.sv", + "module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n", + ); + ws.rebuild_index(); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())), + "the generate-for body instantiation is a real edge" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let read = ws.module_sources(&sub, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert!(names.contains(&"gen.sv".to_string()), "{names:?}"); + + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let subset = code_actions(&ws, &sub_uri, offset); + let whole = whole_workspace_at(&ws, &sub_uri, offset); + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); +} + +#[test] +fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() { + // Not a subset-specific question: does an escaped-identifier + // instantiation (`\sub$weird u1 (...)`) even resolve to the module it + // names, workspace-index-wise, so the subset builder's `units`/ + // `instantiations_of`/`references_to` lookups have anything to find? + // Attacking whether the *subset* diverges from the *whole-workspace* + // answer here, not whether escaped identifiers work at all (a + // pre-existing question this round did not touch). + let tree = Tree::new("qa_escaped"); + tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n"); + let mut ws = crowded(&tree, 10); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + let whole = whole_workspace_at(&ws, &sub_uri, offset); + // Whichever way the parser/binder treats the escaped identifier + // `\sub ` (as `sub`, or as a distinct name), the subset and the + // whole-workspace computation must agree either way. + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); +} + +#[test] +fn qa_add_port_by_position_still_fans_out_to_instantiation_files() { + // `a_command_computes_over_the_subset_and_answers_the_same` (the + // dev's own equivalence test) drives `lucisv.addPort` with a + // *module-name* argument. The *Position* argument takes a completely + // different path to the module (`sources_at` → `port_action_modules` + // + `enclosing_module`, rather than `module_sources` fed the name + // directly) and is exactly the code action's own code path + // (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it + // still reaches every instantiating file, not just the declaring one. + let tree = Tree::new("qa_add_by_position"); + let mut ws = crowded(&tree, 30); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + Value::String("input logic cfg".into()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}"); + for n in 0..3 { + let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri"); + assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection"); + } + + let whole = vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") + .expect("adds"); + assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); +} + +#[test] +fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() { + // A module the index has never seen at all — not stale, genuinely + // absent, e.g. a brand-new buffer the user has not saved yet. Rung 2 + // (`index.units`) has nothing; only rung 1 (the request's own file) + // can supply it. The cursor sits in that same new buffer, so rung 1 + // must be enough on its own — and it must not panic or silently + // return no action just because the index is empty for this name. + let tree = Tree::new("qa_unsaved_new_module"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it"); + + let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n"; + let new_path = tree.path.join("brandnew.sv"); // never written to disk + let new_uri = path_to_uri(&new_path).expect("uri"); + ws.set_document(new_uri.clone(), text.to_string()); + + let offset = text.find("input logic b").expect("b") as u32 + 12; + let subset = code_actions(&ws, &new_uri, offset); + assert_eq!(subset.len(), 1, "{subset:#?}"); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)"); + assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2); +} + +// ------------------------------------------------------------------ +// the lazy offer and its resolve (TODO §37.1) +// ------------------------------------------------------------------ + +/// The offer a client that can resolve receives at `offset`. +fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let position = ws.document(uri).expect("an open document").positions().position(offset); + offers(ws, uri, position, offset) +} + +/// One action's title and kind — what a lightbulb draws, and all an offer +/// promises. +fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option)> { + actions + .iter() + .map(|action| { + let CodeActionOrCommand::CodeAction(action) = action else { + return ("a command".to_string(), None); + }; + (action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string())) + }) + .collect() +} + +/// The one action an offer holds. +fn only(actions: &[CodeActionOrCommand]) -> &CodeAction { + let [CodeActionOrCommand::CodeAction(action)] = actions else { + panic!("exactly one action, got {actions:#?}") + }; + action +} + +#[test] +fn the_lazy_offer_names_exactly_what_the_eager_one_names() { + let tree = Tree::new("lazy_menu"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let lazy = offered(&ws, &sub_uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset))); + assert_eq!( + menu(&lazy)[0].0, + "lucisv: remove port `rst` (updates 3 instantiations)", + "counted from the index, and it agrees with the plan's own count" + ); + let action = only(&lazy); + assert!(action.edit.is_none(), "an offer carries no edit"); + assert!(action.data.is_some(), "it carries what resolve needs instead"); +} + +#[test] +fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() { + // The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out` + // is to the eager path; this is the same question asked of the offer, + // through the set it hands the engine. Neither the 40 noise files nor + // — and this is the point — any of the three instantiating tops. + let tree = Tree::new("lazy_reads"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + assert_eq!(ws.sources().len(), 44, "the whole workspace"); + assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out"); + + // A cursor on a port declaration: the module is the buffer's own. + let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself"); + + // A cursor on an instantiation: the buffer, plus the one file the + // index says declares the module. + let top = tree.path.join("top0.sv"); + let top_text = std::fs::read_to_string(&top).expect("read"); + let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]); + let mut names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file"); +} + +#[test] +fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() { + let tree = Tree::new("resolve_port"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit"); + let eager = only(&code_actions(&ws, &sub_uri, offset)).clone(); + assert_eq!(resolved.title, eager.title); + assert_eq!(resolved.kind, eager.kind); + assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte"); + assert!(resolved.data.is_some(), "the offer's own data survives the round trip"); +} + +#[test] +fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() { + // The other cursor shape: an instantiation missing a connection, where + // the offer has to read the *instantiated* module's declaration to + // know there is anything to offer at all. + let tree = Tree::new("resolve_inst"); + let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", text); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + let offset = text.find("sub u_sub").expect("the instantiation") as u32; + + let lazy = offered(&ws, &uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); + assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port"); + assert!(only(&lazy).edit.is_none()); + + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); + assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ", .rst(rst)"); +} + +#[test] +fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() { + // The pin `an_unsaved_buffer_contributes_the_instantiation_the_index + // _has_not_seen` moved to the lazy path. The offer counts instances + // from the index, which has not seen the unsaved one, so the title + // says three; the *edit* is computed over the fan-out plus every open + // buffer, so it disconnects all four. Exactness lives in the edit, + // which is what the user actually applies. + let tree = Tree::new("lazy_unsaved"); + let mut ws = crowded(&tree, 20); + let extra = tree.path.join("noise0.sv"); + let extra_uri = path_to_uri(&extra).expect("uri"); + let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; + ws.set_document(extra_uri.clone(), typed.to_string()); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let lazy = offered(&ws, &sub_uri, offset); + assert_eq!( + menu(&lazy)[0].0, + "lucisv: remove port `rst` (updates 3 instantiations)", + "the index has not seen the fourth" + ); + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!( + resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)", + "and the resolve says so" + ); + let edit = resolved.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit); +} + +#[test] +fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() { + let tree = Tree::new("lazy_stale"); + let mut ws = crowded(&tree, 10); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let offered = only(&offered(&ws, &sub_uri, offset)).clone(); + + // The user kept typing: the port the lightbulb was about is gone. + ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into()); + let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve"); + assert_eq!(message, GONE); + + // And a document that has been closed altogether says the same. + ws.close_document(&sub_uri); + assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE); +} + +#[test] +fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() { + // `codeAction/resolve`'s params are a `CodeAction`, so the fast path's + // own gate — which reads a `textDocument` out of the params — never + // sees this request. A buffer that grew past the threshold since it + // was offered an action must still not be parsed. + let tree = Tree::new("lazy_large"); + let mut ws = crowded(&tree, 5); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let offered = only(&offered(&ws, &sub_uri, offset)).clone(); + + let _ = ws.set_client_settings(crate::settings::ClientSettings { + large_file_threshold: 8, + ..Default::default() + }); + ws.set_document(sub_uri.clone(), SUB.to_string()); + assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path"); + assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE); +} + +#[test] +fn a_resolve_of_something_this_server_never_offered_says_so() { + let tree = Tree::new("lazy_foreign"); + let (ws, uri, _) = opened(&tree); + let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() }; + assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS); + + // Data that is not ours either — a shape `serde` cannot read as an + // offer. Refused, not guessed at. + let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() }; + assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS); + + // An action that already carries its edit — every quick fix in + // `code_action.rs`, and the port actions a non-resolving client is + // sent — comes straight back, because there is nothing to add to it. + let complete = + CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare }; + assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete); +} + +#[test] +fn a_name_the_workspace_declares_twice_is_not_offered_either() { + // The eager path refuses because both declaring files are in the set + // it reads (`a_module_declared_twice_is_refused_through_the_subset_as + // _well`). The offer reads neither, so it asks the index the same + // question — otherwise it would offer an action resolve then refuses. + let tree = Tree::new("lazy_ambiguous"); + let mut ws = crowded(&tree, 10); + tree.write("clone.sv", SUB); + ws.rebuild_index(); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + assert!(offered(&ws, &sub_uri, offset).is_empty()); + assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does"); +} + +#[test] +fn a_title_keys_on_everything_but_its_count() { + assert_eq!( + key("lucisv: remove port `rst` (updates 3 instantiations)"), + key("lucisv: remove port `rst` (no instantiation in scope)") + ); + assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port"); + assert_ne!( + key("lucisv: remove port `rst` (updates 1 instantiation)"), + key("lucisv: remove port `clk` (updates 1 instantiation)") + ); +} + +/// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn the_offer_is_flat_where_the_eager_answer_grows() { + // `performance_take2.md` §6a measured the eager answer growing with + // the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms + // floor, 185 ms at 128 files, to offer *zero* actions. The offer reads + // one file (a cursor on a port declaration) or two (a cursor on an + // instantiation), so its column should be flat. Beside the code it + // measures rather than in `perf.rs`, which is what `perf::mean` is + // `pub(crate)` for. + for instantiators in [3usize, 40, 128] { + let tree = Tree::new(&format!("perf_offer_{instantiators}")); + tree.write("sub.sv", SUB); + for n in 0..instantiators { + tree.write( + &format!("top{n:03}.sv"), + &format!( + "module top{n:03};\n logic c, r;\n \ + sub u_sub (.clk(c), .rst(r));\nendmodule\n" + ), + ); + } + for n in 0..200 { + tree.write( + &format!("noise{n:03}.sv"), + &format!( + "module noise{n:03};\n logic a;\n wire b;\n \ + assign b = a;\nendmodule\n" + ), + ); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + + for (what, file, needle, skip) in [ + ("a port declaration", "sub.sv", "input logic rst", 12u32), + ("an instantiation ", "top000.sv", "sub u_sub", 0), + ] { + let path = tree.path.join(file); + let text = std::fs::read_to_string(&path).expect("read"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let offset = text.find(needle).expect("the cursor") as u32 + skip; + let eager = crate::perf::mean(5, || { + std::hint::black_box(code_actions(&ws, &uri, offset)); + }); + let offer = crate::perf::mean(20, || { + std::hint::black_box(offered(&ws, &uri, offset)); + }); + eprintln!( + " fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \ + offer {offer:?} ({} actions)", + offered(&ws, &uri, offset).len() + ); + } + } +} + +#[test] +fn an_unknown_command_is_declined() { + let tree = Tree::new("unknown"); + let (ws, uri, _) = opened(&tree); + let arguments = vec![serde_json::to_value(&uri).expect("uri")]; + let message = execute(&ws, "lucisv.nope", &arguments).expect_err("unknown"); + assert!(message.contains("not a lucisv command"), "{message}"); +} + +#[test] +fn a_command_without_its_arguments_is_declined() { + let tree = Tree::new("args"); + let (ws, uri, _) = opened(&tree); + let message = execute(&ws, REMOVE_PORT, &[]).expect_err("no uri"); + assert!(message.contains("document URI"), "{message}"); + let only_uri = vec![serde_json::to_value(&uri).expect("uri")]; + let message = execute(&ws, REMOVE_PORT, &only_uri).expect_err("no position"); + assert!(message.contains("position"), "{message}"); +} + +// ------------------------------------------------------------------ +// the `.*` expansion (TODO §50) +// ------------------------------------------------------------------ + +/// A workspace whose `top.sv` instantiates `sub` with a wildcard. +fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) { + const TEXT: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n"; + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", TEXT); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), TEXT.to_string()); + (ws, uri, TEXT) +} + +#[test] +fn expand_wildcard_takes_a_position() { + let tree = Tree::new("expand"); + let (ws, uri, text) = wildcard(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 24 }).expect("position"), + ]; + let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands"); + assert!(warnings.is_empty(), "{warnings:?}"); + let edits = edits_for(&edit, &uri); + assert_eq!(edits.len(), 1, "{edits:#?}"); + assert_eq!(edits[0].new_text, ".rst(rst)"); + // The range is the `.*` itself, in the client's own coordinates. + assert_eq!(edits[0].range.start.character, 24); + assert_eq!(edits[0].range.end.character, 26); + assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*"); +} + +#[test] +fn expand_wildcard_refuses_where_there_is_no_wildcard() { + let tree = Tree::new("expand_none"); + let (ws, top_uri, _) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + serde_json::to_value(Position { line: 2, character: 6 }).expect("position"), + ]; + let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard"); + assert!(message.contains("writes no `.*` to expand"), "{message}"); +} + +#[test] +fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() { + let tree = Tree::new("expand_action"); + let (ws, uri, text) = wildcard(&tree); + let offset = text.find(".*").expect("the wildcard") as u32; + + let lazy = offered(&ws, &uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); + // The count is the connections the wildcard becomes, and the index's + // instantiation census must not overwrite it. + assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)"); + assert!(only(&lazy).edit.is_none(), "an offer carries no edit"); + + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!(resolved.title, "lucisv: expand .* (1 connection)"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); + assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)"); +} + +// ------------------------------------------------------------------ +// the non-ANSI → ANSI conversion (TODO §51) +// ------------------------------------------------------------------ + +/// A workspace whose `legacy.sv` writes a Verilog-2001 header. +const LEGACY: &str = + "module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n"; + +fn legacy(tree: &Tree) -> (Workspace, Uri) { + let path = tree.write("legacy.sv", LEGACY); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), LEGACY.to_string()); + (ws, uri) +} + +#[test] +fn convert_to_ansi_takes_a_position() { + let tree = Tree::new("ansi"); + let (ws, uri) = legacy(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + // The module's own name — inside the header, and nowhere near a + // port declaration. + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + ]; + // Two insertions — the ANSI prefixes — and three deletions: `input a;`, + // `output [7:0] b;` and the `reg [7:0] b;` that completed it. + let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts"); + assert!(warnings.is_empty(), "{warnings:?}"); + let edits = edits_for(&edit, &uri); + let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect(); + assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}"); +} + +#[test] +fn convert_to_ansi_refuses_an_ansi_header() { + let tree = Tree::new("ansi_none"); + let (ws, top_uri, _) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + ]; + let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert"); + assert!(message.contains("declares no ports"), "{message}"); +} + +#[test] +fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() { + let tree = Tree::new("ansi_action"); + let (ws, uri) = legacy(&tree); + // The cursor on the module's name: in the header, on no port. + let offset = LEGACY.find("legacy (").expect("the name") as u32; + + let lazy = offered(&ws, &uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); + assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)"); + assert!(only(&lazy).edit.is_none(), "an offer carries no edit"); + + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); + assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input "); +} + +#[test] +fn the_command_list_is_what_the_server_advertises() { + assert_eq!( + commands(), + 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 344ff45..36ed286 100644 --- a/crates/lucisv_server/src/rename.rs +++ b/crates/lucisv_server/src/rename.rs @@ -181,1138 +181,6 @@ fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String 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; - - /// [`rename_traced`] with the trace thrown away — what a test that is not - /// about the trace asks. - fn rename( - ws: &Workspace, - uri: &Uri, - offset: u32, - new_name: &str, - ) -> Result<(WorkspaceEdit, Vec), String> { - rename_traced(ws, uri, offset, new_name, &mut None) - } - - /// A scratch workspace root. Removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_rename_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - const SUB: &str = "module sub (input logic clk);\nendmodule\n"; - const TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; - - /// A two-file workspace with `top.sv` open. - fn opened(tree: &Tree) -> (Workspace, Uri) { - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", TOP); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), TOP.to_string()); - (ws, uri) - } - - /// A third file that spells nothing this rename is about, kept open so - /// the open-buffer rung selects it: the "container" class in miniature — - /// a file the engine must index and never analyses. - const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n"; - - /// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a - /// persistent index store behind the workspace — so a rename is handed - /// records keyed on the very bytes it reads. - fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) { - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", TOP); - let quiet = tree.write("bystander.sv", BYSTANDER); - let mut ws = Workspace::default(); - ws.set_client_settings(crate::settings::ClientSettings { - index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()), - index_scope: crate::settings::IndexScope::Workspace, - ..Default::default() - }); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), TOP.to_string()); - ws.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string()); - (ws, uri) - } - - /// Every edit and every warning one rename produced, with the workspace's - /// own scratch path taken out — the fingerprint the parity proof compares. - fn print(result: &(WorkspaceEdit, Vec), root: &Path) -> String { - let (edit, warnings) = result; - let mut lines: Vec = Vec::new(); - for (uri, edits) in edit.changes.iter().flatten() { - for one in edits { - lines.push(format!( - "{} {:?}..{:?} -> {}", - uri.as_str(), - one.range.start, - one.range.end, - one.new_text - )); - } - } - lines.sort(); - lines.extend(warnings.iter().map(|w| format!("warn {w}"))); - lines.join("\n").replace(root.to_str().expect("utf-8"), "") - } - - /// **§R3b's server-side proof.** The same rename over the same files, once - /// with a warm index store behind it — where the engine is handed every - /// file's record and stops parsing the ones nothing analyses — and once - /// with no store at all, where it parses them all: byte-identical edits, - /// byte-identical warnings. - /// - /// The reuse is asserted to have happened *and* to have removed a parse, - /// so a store that silently stopped answering would fail this rather than - /// pass it for the wrong reason. - #[test] - fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() { - let tree = Tree::new("reuse_store"); - let store = Tree::new("reuse_store_cache"); - let (warm, uri) = three_with_store(&tree, Some(&store)); - let mut line = None; - let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line) - .expect("the rename succeeds"); - let trace = line.expect("a trace is always written"); - assert!(trace.contains("selected=3"), "all three files are selected: {trace}"); - assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}"); - assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}"); - assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}"); - - let bare = Tree::new("reuse_none"); - let (plain, plain_uri) = three_with_store(&bare, None); - let mut plain_line = None; - let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line) - .expect("the rename succeeds"); - let plain_trace = plain_line.expect("a trace is always written"); - assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse"); - assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed"); - - assert_eq!( - print(&with_store, &tree.path), - print(&no_store, &bare.path), - "the reuse changed an edit or a warning" - ); - } - - /// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees - /// with the file on disk is not the bytes any record was written from, so - /// the store answers nothing for it and it is parsed — and the rename acts - /// on the buffer's text, which is the precedence it always had. - /// - /// Nothing in the reuse arranges this: the key is the content, so unsaved - /// text misses the same way changed text does. - #[test] - fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() { - let tree = Tree::new("reuse_unsaved"); - let store = Tree::new("reuse_unsaved_cache"); - let (mut ws, uri) = three_with_store(&tree, Some(&store)); - // A signal that exists only in the buffer. Its record cannot be in a - // store keyed on what is on disk. - let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n"; - ws.set_document(uri.clone(), edited.to_string()); - - let mut line = None; - let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line) - .expect("the buffer's own declaration renames"); - let trace = line.expect("a trace is always written"); - // Two untouched records: the open `bystander.sv`, and `sub.sv`, which - // the buffer instantiates and the fan-out's instantiation step hands - // over (M3.5) — both reused, and the edited buffer still parsed. - assert!(trace.contains("reused_files=2"), "only the untouched files' records: {trace}"); - assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}"); - let edits = edit.changes.as_ref().expect("changes").values().flatten().count(); - assert_eq!(edits, 2, "the declaration and its one use, both in the buffer"); - } - - #[test] - fn prepare_offers_the_identifier_and_its_placeholder() { - let tree = Tree::new("prepare"); - let (ws, uri) = opened(&tree); - let response = prepare(&ws, &uri, at(TOP, "u_sub")).expect("renameable"); - let PrepareRenameResponse::RangeWithPlaceholder { range, placeholder } = response else { - panic!("a placeholder is what an editor wants"); - }; - assert_eq!(placeholder, "u_sub"); - assert_eq!(range.start.line, 1); - assert_eq!(range.start.character, 6); - assert_eq!(range.end.character, 11); - } - - #[test] - fn prepare_declines_where_there_is_nothing_to_rename() { - let tree = Tree::new("prepare_no"); - let (ws, uri) = opened(&tree); - let message = prepare(&ws, &uri, at(TOP, "module")).expect_err("a keyword"); - assert!(message.contains("no symbol to rename"), "{message}"); - } - - #[test] - fn prepare_declines_in_an_untitled_buffer() { - let mut ws = Workspace::default(); - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - ws.set_document(uri.clone(), "module m;\n wire a;\nendmodule\n".to_string()); - assert_eq!(prepare(&ws, &uri, 16).expect_err("no path"), UNSAVED); - } - - #[test] - fn a_rename_edits_every_file_that_names_the_symbol() { - let tree = Tree::new("cross"); - let (ws, uri) = opened(&tree); - let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames"); - assert!(warnings.is_empty(), "{warnings:?}"); - - let changes = edit.changes.expect("changes"); - assert_eq!(changes.len(), 2, "the declaration's file and this one"); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - let sub_edits = changes.get(&sub_uri).expect("sub.sv is edited"); - assert_eq!(sub_edits.len(), 1); - assert_eq!(sub_edits[0].new_text, "child"); - assert_eq!(sub_edits[0].range.start.line, 0); - assert_eq!(sub_edits[0].range.start.character, 7, "the name `sub`"); - - let top_edits = changes.get(&uri).expect("top.sv is edited"); - assert_eq!(top_edits.len(), 1); - assert_eq!(top_edits[0].range.start.line, 1); - assert_eq!(top_edits[0].range.start.character, 2); - } - - #[test] - fn a_refused_rename_returns_the_engines_sentence() { - let tree = Tree::new("refused"); - let (ws, uri) = opened(&tree); - let message = rename(&ws, &uri, at(TOP, "u_sub"), "module").expect_err("a keyword"); - assert!(message.contains("keyword"), "{message}"); - } - - #[test] - fn ranges_are_utf16_in_a_file_with_multi_byte_text() { - let tree = Tree::new("utf16"); - let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n"; - let file = tree.write("m.sv", text); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&file).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - - let (edit, _) = rename(&ws, &uri, at(text, "wire a") + 5, "sig").expect("renames"); - let mut changes = edit.changes.expect("changes"); - let edits = changes.remove(&uri).expect("this file"); - assert_eq!(edits.len(), 2); - assert_eq!(edits[0].range.start.line, 2); - assert_eq!(edits[0].range.start.character, 7); - } - - // ------------------------------------------------------------------ - // The fan-out equivalence suite - // ------------------------------------------------------------------ - // - // `rename` is handed the symbol's fan-out through the index instead of - // every in-scope file. A rename that edits fewer files than the truth is - // corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot - // reach is a refusal the user never sees — so every case below asks the - // engine the same question twice, over the subset and over the whole - // workspace, and asserts the two answers are the same bytes and the same - // sentences. The sufficiency argument they are the evidence for is in - // `docs/features/refactor-rename/README.md`. - - /// The file set the server would hand `rename` for a cursor at `offset`. - fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec { - let doc = ws.document_for_path(path).expect("the request's file is open"); - match vlog_refactor::rename_name_at(&doc.semantics, offset) { - Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0, - None => ws.sources(), - } - .into_iter() - .map(|(path, _)| path) - .collect() - } - - /// Ask the engine over the fan-out and over the whole workspace, and - /// assert the two answers are indistinguishable. Returns the answer, so a - /// caller can also assert *what* it was. - fn same_answer( - ws: &Workspace, - path: &Path, - offset: u32, - new_name: &str, - ) -> Result { - let everything = ws.sources(); - let doc = ws.document_for_path(path).expect("the request's file is open"); - let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) { - Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0, - None => everything.clone(), - }; - for (path, text) in &subset { - let found = everything.iter().find(|(held, _)| held == path); - assert_eq!( - found.map(|(_, text)| text), - Some(text), - "{} is in the fan-out with text the whole scope does not have", - path.display() - ); - } - let whole = vlog_refactor::rename(&everything, path, offset, new_name); - let narrow = vlog_refactor::rename(&subset, path, offset, new_name); - match (&whole, &narrow) { - (Ok(whole), Ok(narrow)) => { - assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes"); - assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently"); - } - (Err(whole), Err(narrow)) => { - assert_eq!(whole, narrow, "the fan-out refused in different words"); - } - (Ok(whole), Err(narrow)) => panic!( - "the fan-out invented a refusal: {narrow}, where the workspace edited {} files", - whole.file_count() - ), - (Err(whole), Ok(narrow)) => panic!( - "the fan-out lost the refusal `{whole}` and edited {} files instead", - narrow.file_count() - ), - } - narrow - } - - /// A workspace of `files`, every one of them also opened as a buffer when - /// `open` names it, with the first named file's URI returned. - fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec) { - let paths: Vec = files.iter().map(|(name, text)| tree.write(name, text)).collect(); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - for name in open { - let path = tree.path.join(name); - let text = fs::read_to_string(&path).expect("written above"); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri, text); - } - (ws, paths) - } - - const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n"; - const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n"; - const TWO: &str = - "module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n"; - const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n"; - const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n"; - - #[test] - fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() { - let tree = Tree::new("fanout_module"); - let files = [ - ("sub.sv", MOD), - ("one.sv", ONE), - ("two.sv", TWO), - ("three.sv", GEN), - ("quiet.sv", QUIET), - ]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let at = at(ONE, "sub u_a"); - - let edit = same_answer(&ws, &path, at, "child").expect("renames"); - assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it"); - - // And the narrowing is real: the file that never spells the name is - // not read at all. - let fan = fan_out(&ws, &path, at, "child"); - assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}"); - assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}"); - } - - #[test] - fn the_fan_out_keeps_the_end_label_and_the_declaration_together() { - let tree = Tree::new("fanout_endlabel"); - let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]); - let path = tree.path.join("sub.sv"); - let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames"); - let own = edit.edits_for(&path); - assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label"); - } - - #[test] - fn the_fan_out_carries_a_port_rename_to_every_connection() { - let tree = Tree::new("fanout_port"); - let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)]; - let (ws, _) = tree_with(&tree, &files, &["sub.sv"]); - let path = tree.path.join("sub.sv"); - let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames"); - assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`"); - } - - #[test] - fn the_fan_out_carries_a_package_member_rename_to_every_importer() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const IMPORTER: &str = - "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; - const QUALIFIER: &str = - "module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n"; - let tree = Tree::new("fanout_pkg"); - let files = - [("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)]; - let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); - let path = tree.path.join("reader.sv"); - let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames"); - assert_eq!(edit.file_count(), 3, "the package and both files reading it"); - } - - #[test] - fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() { - let tree = Tree::new("fanout_unsaved"); - // On disk `two.sv` says nothing about `sub`; the buffer instantiates - // it. The index has never seen the buffer's text. - let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)]; - let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]); - let two = tree.path.join("two.sv"); - ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string()); - assert!( - ws.index().instantiations_of("sub").len() < 2, - "premise: the index has not seen the buffer's instantiation" - ); - - let path = tree.path.join("one.sv"); - let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); - assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too"); - } - - #[test] - fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() { - let tree = Tree::new("fanout_dup"); - let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let refusal = - same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice"); - assert!(refusal.contains("more than one indexed file"), "{refusal}"); - } - - #[test] - fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() { - // `three.sv` names `sub`; `taken.sv` declares the module the rename - // wants to become. Renaming `sub` to `taken` makes every `sub` site - // ambiguous — a file the postings for `sub` alone would never name. - const TAKEN: &str = "module taken;\nendmodule\n"; - const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n"; - let tree = Tree::new("fanout_capture"); - let files = - [("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let refusal = - same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture"); - assert!(refusal.contains("would change what"), "{refusal}"); - - let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken"); - assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}"); - } - - /// The two `` `define`` warnings come from files the index's own define - /// tables name, so both survive the narrowing: a macro *called* the name, - /// and a macro whose **body** spells it, each in a file that has nothing - /// else to do with the symbol. - #[test] - fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() { - const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n"; - const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n"; - let tree = Tree::new("fanout_macro"); - let files = [ - ("sub.sv", MOD), - ("one.sv", ONE), - ("named.sv", NAMED), - ("body.svh", BODY), - ("quiet.sv", QUIET), - ]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); - assert!( - edit.warnings.iter().any(|w| w.contains("is also a macro defined")), - "{:?}", - edit.warnings - ); - assert!( - edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")), - "{:?}", - edit.warnings - ); - let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child"); - assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}"); - assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}"); - assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}"); - } - - #[test] - fn every_file_the_workspace_rename_edits_is_in_the_fan_out() { - // The invariant-1 assertion, made directly rather than through an - // equality: whatever the whole workspace would rewrite, the narrow set - // must contain — otherwise a rename edits fewer files than the truth. - let tree = Tree::new("fanout_covers"); - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n"; - let files = [ - ("sub.sv", MOD), - ("one.sv", ONE), - ("two.sv", TWO), - ("three.sv", GEN), - ("pkg.sv", PKG), - ("reader.sv", IMPORTER), - ("quiet.sv", QUIET), - ]; - let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); - let path = tree.path.join("reader.sv"); - let everything = ws.sources(); - let text = fs::read_to_string(&path).expect("written"); - for offset in 0..=text.len() as u32 { - let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing") - else { - continue; - }; - let fan = fan_out(&ws, &path, offset, "renamed_thing"); - for (edited, _) in &whole.edits { - assert!( - fan.contains(edited), - "byte {offset} renames {} and the fan-out does not hold it: {fan:?}", - edited.display() - ); - } - let _ = same_answer(&ws, &path, offset, "renamed_thing"); - } - } - - /// QA, 2026-08-28 attack: an instantiation spelled with an escaped - /// identifier (`` \sub ``) is a *different* name from `sub` to - /// `vlog_semantic` today (a pre-existing simplification, noted in this - /// feature's own 2026-08-24 QA round for a declaration, not an - /// instantiation) — it resolves to nothing, so it is renamed by neither - /// path. The question this pins is narrower: does narrowing the file set - /// change that answer? It must not, since both paths call the identical - /// engine; the risk would be the fan-out *dropping* the file outright - /// while the whole-workspace run still watches it (`\sub` contains the - /// word `sub`, so `contains_word` — and hence `watched_files` — still - /// picks it up in the whole run). `same_answer` checks the observable - /// output only (edits, warnings, or refusal), which is what must agree. - #[test] - fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() { - const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n"; - let tree = Tree::new("fanout_escaped"); - let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); - assert!( - edit.edits_for(&tree.path.join("escaped.sv")).is_empty(), - "the escaped spelling is a different name to vlog_semantic and must stay untouched" - ); - } - - /// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a - /// module unit named `sub` vs. a port/member also named `sub` in an - /// unrelated module) must not cross-contaminate the fan-out — renaming - /// the unit must not touch the member's own declaration or its file. - #[test] - fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() { - const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str = - "module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n"; - let tree = Tree::new("fanout_same_spelling_different_symbol"); - let files = - [("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); - assert!( - edit.edits_for(&tree.path.join("other.sv")).is_empty(), - "the unrelated wire named `sub` must not be touched: {:?}", - edit.edits_for(&tree.path.join("other.sv")) - ); - // other.sv may legitimately be *watched* by the whole-word text - // search (it spells "sub"), but it must never be *edited* — checked - // above — nor must its own local wire's meaning change, which - // `same_answer`'s byte-identical edits/warnings assertion already - // confirmed by passing at all. - } - - /// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous - /// posting) must fire even when the ambiguity is on the **new** name, - /// discovered on the second spelling `fan_out_of` walks, not the first. - /// `Workspace::rename_sources` iterates `[name, new_name]` in that order - /// and bails to `sources()` on the first ambiguous hit — this attacks the - /// case where the *old* name's rung is completely unambiguous and only - /// the second iteration finds the problem, to check the early return - /// doesn't leak a partially-built (too-narrow) `wanted` set instead of - /// truly falling back to the whole scope. - #[test] - fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() { - const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; - const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; - const READER: &str = - "module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; - let tree = Tree::new("fanout_ambig_on_new_name"); - let files = - [("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)]; - let (ws, _) = tree_with(&tree, &files, &["one.sv"]); - let path = tree.path.join("one.sv"); - let at = at(ONE, "sub u_a"); - // `sub` (the old name) has an unambiguous, tiny fan-out on its own. - let fan = fan_out(&ws, &path, at, "taken_pkg"); - assert_eq!( - fan.len(), - ws.sources().len(), - "the new name's own ambiguity must still hand back the whole scope: {fan:?}" - ); - same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name"); - } - - #[test] - fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() { - // Two files declare the *same* package, so `cfg_pkg::DEPTH` names - // either declaration equally. The index records that the declarations - // are ambiguously referenced but not which file does it, so the - // fan-out refuses to narrow at all — which is how the refusal - // survives. - const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; - const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; - const READER: &str = - "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; - let tree = Tree::new("fanout_ambig"); - let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)]; - let (ws, _) = tree_with(&tree, &files, &["a.sv"]); - let path = tree.path.join("a.sv"); - let at = at(A, "DEPTH ="); - let fan = fan_out(&ws, &path, at, "SIZE"); - assert_eq!( - fan.len(), - ws.sources().len(), - "an ambiguous posting hands back the whole scope: {fan:?}" - ); - same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous"); - } - - /// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the - /// sixth rung the lead ruled for the same day; kept as the regression - /// test for it, now asserting parity rather than pinning the divergence. - /// - /// A file whose only mention of the **new** name is a bare use that - /// resolves to nothing today — `import taken_pkg::*` of a package nobody - /// declares yet — declares nothing, references nothing under the *old* - /// name, instantiates nothing and defines no macro, so the first five - /// rungs of the fan-out cannot see it. The rename is exactly what gives - /// that import a meaning, which is what capture rule 12 refuses over, so - /// the narrow path used to answer `Ok` where the whole workspace refused - /// — a materially weaker answer, not a lost warning. - /// `WorkspaceIndex::files_spelling` is the rung that finds it: the - /// per-file records keep every external use under the name it spells, - /// including the ones that resolved to nothing. - #[test] - fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n"; - let tree = Tree::new("fanout_dangling_import"); - let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - let at = at(PKG, "cfg_pkg;"); - - let fan = fan_out(&ws, &path, at, "taken_pkg"); - assert!( - fan.contains(&tree.path.join("stray.sv")), - "the dangling import's file is in the fan-out through `files_spelling`: {fan:?}" - ); - - let refusal = - same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import"); - assert!(refusal.contains("would change what"), "{refusal}"); - assert!(refusal.contains("taken_pkg"), "{refusal}"); - } - - /// The other half of the ruling: the **old** name needs no such rung, and - /// this is the case that would expose it if it did. `stray.sv`'s only tie - /// to the rename is an `import cfg_pkg::*`-shaped use of a name that - /// resolves to nothing — spelled with the name being renamed *away*. - /// A rename only ever removes declarations of the old name, so a lookup - /// that failed before still fails after; the answer cannot move, and both - /// paths agree without `stray.sv` being read. - #[test] - fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - // `absent_pkg` is declared nowhere, and is what the rename renames to - // nothing: the file's only spelling of it stays unresolved throughout. - const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n"; - let tree = Tree::new("fanout_dangling_old"); - let files = [("pkg.sv", PKG), ("stray.sv", STRAY)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - - // Rename the *package* to `absent_pkg` — the new-name rung must pull - // `stray.sv` in and both paths must refuse … - let package = at(PKG, "cfg_pkg;"); - same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import"); - - // … while a rename whose *old* name is the dangling one has nothing to - // capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it - // out of the set and both paths agree. - let depth = at(PKG, "DEPTH ="); - let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames"); - assert_eq!(edit.file_count(), 1, "only the package's own file"); - let fan = fan_out(&ws, &path, depth, "SIZE"); - assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}"); - } - - // ------------------------------------------------------------------ - // QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the - // lead-authorized fix for the dangling-import residue. - // ------------------------------------------------------------------ - - /// Attack on rung 6's completeness: the new name spelled **only** as the - /// base of an `extends` clause the workspace does not (yet) declare. This - /// goes through `Target::Unit`, not `Target::Package` — a different - /// resolution path than the import case rung 6 was built for — so it is - /// worth checking on its own rather than trusting the same mechanism - /// covers it by analogy. - #[test] - fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const STRAY_EXTENDS: &str = - "class derived extends taken_base;\n function void go();\n endfunction\nendclass\n"; - let tree = Tree::new("fanout_extends_base"); - let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - let at = at(PKG, "cfg_pkg;"); - - let fan = fan_out(&ws, &path, at, "taken_base"); - assert!( - fan.contains(&tree.path.join("stray.sv")), - "the extends base is a Target::Unit miss, always non-empty paths: {fan:?}" - ); - let refusal = - same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning"); - assert!(refusal.contains("would change what"), "{refusal}"); - } - - /// Attack on rung 6's completeness: a bare, unqualified reference to the - /// new name written inside a class that `extends` an **existing, - /// unrelated** base, with no import in scope — the one shape that - /// produces `Resolution::InheritedCandidate` with genuinely **empty** - /// paths (`miss()`'s branch when `nearest_extends` finds a base but no - /// import supplied anything), which `files_spelling` cannot see (it reads - /// only facts with non-empty paths). The argument this pins: such a - /// reference is resolved *purely* from the file's own unedited text and - /// never depends on the workspace (`resolve_external` never even tries - /// `follow_paths` against an empty list), so it cannot change meaning - /// under any rename — excluding the file costs nothing, on this rung or - /// the whole-workspace path alike. - #[test] - fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const EXISTING_BASE: &str = "class existing_base;\nendclass\n"; - // No import anywhere in `stray.sv`, so the lexical miss on - // `taken_member` inside `derived` (which extends `existing_base`) - // collects an empty `external` list and becomes an `InheritedCandidate` - // with `paths: []` — recorded nowhere, per `facts_from_analysis`. - const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n"; - let tree = Tree::new("fanout_inherited_empty_paths"); - let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - let at = at(PKG, "cfg_pkg;"); - - let fan = fan_out(&ws, &path, at, "taken_member"); - assert!( - !fan.contains(&tree.path.join("stray.sv")), - "an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}" - ); - // Parity must still hold: excluding the file must not change the - // answer, because the reference inside it can never resolve - // differently regardless of what `cfg_pkg` becomes. - same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible"); - } - - /// Attack on rung 6's soundness: a **local-only** symbol in a third file - /// that happens to share the new name's spelling must not trigger a - /// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local` - /// facts (a local declaration/use resolves inside its own file and the - /// workspace was never consulted), so the file should not even be pulled - /// in — and if it were, the rename must still succeed, since no capture is - /// possible against a symbol nothing outside that file can see. - /// - /// The symbol is a **function's** local, not a module's net: since - /// 2026-09-05 a net is a declaration on the module's hierarchical surface - /// and joins the fan-out by that rung (the test below), which would answer - /// this one for the wrong reason. A name inside a subprogram body is on - /// neither surface, which is what this attack needs. - #[test] - fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n"; - let tree = Tree::new("fanout_local_only"); - let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - let at = at(PKG, "cfg_pkg;"); - - let fan = fan_out(&ws, &path, at, "taken_local"); - assert!( - !fan.contains(&tree.path.join("local.sv")), - "a purely local declaration/use is not an external fact: {fan:?}" - ); - let edit = - same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible"); - assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty()); - } - - /// The rung the hierarchical surface added: a module's internal **net** - /// spelled like the new name *is* a declaration the fan-out has to hold, - /// because `assign w = u_unrelated.taken_net;` in a fourth file resolves - /// to it now. So the file is pulled in — and the rename still succeeds - /// and still writes nothing there, because a package name and a net - /// inside a module capture nothing of each other. - #[test] - fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() { - const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; - const NET_ONLY: &str = - "module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n"; - let tree = Tree::new("fanout_hierarchical_net"); - let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)]; - let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); - let path = tree.path.join("pkg.sv"); - let at = at(PKG, "cfg_pkg;"); - - let fan = fan_out(&ws, &path, at, "taken_net"); - assert!( - fan.contains(&tree.path.join("net.sv")), - "a net is a hierarchical declaration of its name: {fan:?}" - ); - let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible"); - assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty()); - } - - /// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two - /// packages, `p_pkg` and `q_pkg`, both export a member spelled the same - /// (`shared_name`); a third file imports both, `p_pkg` first, so - /// "first-written import wins" resolves `shared_name` to `p_pkg`'s - /// declaration. Renaming *away* `p_pkg::shared_name` removes the winning - /// candidate, so the same reference should fall through to `q_pkg`'s - /// pre-existing, completely unrelated declaration — a meaning change the - /// whole-workspace verifier must refuse over (rule 12, in the direction - /// "an existing use is captured by nothing new — it silently rebinds to - /// another *existing* declaration"). The old-name argument says this - /// cannot be missed because rung 1 walks *every* declaration named - /// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's), - /// so the importer is pulled in via `references_to` of `p_pkg`'s - /// declaration regardless. - #[test] - fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() { - const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n"; - const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n"; - const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n"; - let tree = Tree::new("fanout_shadow_unmask"); - let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)]; - let (ws, _) = tree_with(&tree, &files, &["p.sv"]); - let path = tree.path.join("p.sv"); - let at = at(P, "shared_name ="); - - let fan = fan_out(&ws, &path, at, "renamed_thing"); - assert!( - fan.contains(&tree.path.join("user.sv")), - "the importer is posted against p_pkg's declaration today: {fan:?}" - ); - assert!( - fan.contains(&tree.path.join("q.sv")), - "rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}" - ); - // Whichever way the whole-workspace path answers this (refuse, since - // `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit, - // if some other rule intervenes first), the subset must answer - // identically — that is the property under attack, not a specific - // outcome. - // The hunt comes up empty, and reading why is the point: `user.sv`'s - // `shared_name` currently resolves to `p_pkg`'s declaration — the - // rename target itself — so it is not a bystander a removal could - // silently unmask, it is an *edit site*: the rename rewrites it to - // `renamed_thing` along with the declaration, so the text never says - // `shared_name` again for `follow_paths` to re-resolve against - // `q_pkg`. A reference can only be affected by a name's removal by - // spelling that exact name, and by the Lemma any such reference - // either resolves to the target (edited away, as here) or to some - // *other* declaration of the same name (already covered by rung 1/2's - // sweep over every declarer, not only the target's) — there is no - // third case for the old name to fall into. - let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames"); - assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference"); - assert!( - edit.edits_for(&tree.path.join("q.sv")).is_empty(), - "q_pkg's own unrelated declaration is never touched" - ); - } - - #[test] - fn an_open_buffer_beats_disk_when_the_rename_is_computed() { - let tree = Tree::new("buffer"); - tree.write("sub.sv", SUB); - let top_path = tree.write("top.sv", "module top;\nendmodule\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - // The buffer instantiates `sub`; the file on disk does not. - let uri = path_to_uri(&top_path).expect("uri"); - ws.set_document(uri.clone(), TOP.to_string()); - - let (edit, _) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames"); - let changes = edit.changes.expect("changes"); - assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation"); - } - - /// `sub.sv` declares the port, `top.sv` connects it, and `far.svh` names - /// it inside a macro invocation and has no other relationship to anything - /// in the rename — so the fan-out does not hand it to the engine and the - /// engine cannot warn about it. The census does: §2.9-18's server half. - const M_SUB: &str = "module sub (output logic sig);\n assign sig = 1'b0;\nendmodule\n"; - const M_TOP: &str = "module top;\n logic w;\n sub u_sub (.sig(w));\nendmodule\n"; - const M_FAR: &str = "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n"; - - /// The workspace of the two pins below, with `top.sv` open. `far` is what - /// `far.svh` holds, which is the only difference between them. - fn macro_workspace(tree: &Tree, far: &str) -> (Workspace, Uri) { - tree.write("sub.sv", M_SUB); - let top = tree.write("top.sv", M_TOP); - tree.write("far.svh", far); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), M_TOP.to_string()); - (ws, uri) - } - - /// How often a warning naming `far.svh` is in the list. - fn far_warnings(warnings: &[String]) -> usize { - warnings.iter().filter(|w| w.contains("far.svh")).count() - } - - #[test] - fn a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread() { - let tree = Tree::new("macrocensus"); - let (ws, uri) = macro_workspace(&tree, M_FAR); - - // The premise: `far.svh` is in no rung of the fan-out, so the engine - // never sees it. Asked of the same function `rename` asks. - let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0; - assert!( - !handed.iter().any(|(path, _)| path.ends_with("far.svh")), - "premise: the engine is not handed far.svh — {handed:?}" - ); - - let (edit, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames"); - let changes = edit.changes.expect("changes"); - assert_eq!(changes.len(), 2, "the declaration's file and the connection's"); - let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); - assert_eq!(changes.get(&sub_uri).map(Vec::len), Some(2), "the port and its assignment"); - assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the `.sig(` connection"); - assert!( - !changes.contains_key(&path_to_uri(&tree.path.join("far.svh")).expect("uri")), - "a macro argument is never edited" - ); - - assert_eq!(far_warnings(&warnings), 1, "{warnings:?}"); - let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named"); - assert!(warning.contains("`sig`"), "{warning}"); - assert!(warning.contains("this rename did not read"), "{warning}"); - assert!(warning.contains("a macro argument cannot be edited"), "{warning}"); - } - - /// The control: give `far.svh` a reason to be read — it instantiates - /// `sub` — and it *is* a source, so the engine's own macro-argument - /// warning covers it and this one must stay quiet. Exactly one warning - /// names the file either way; two would be the bug. - #[test] - fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() { - let tree = Tree::new("macrocontrol"); - // Spelled after a `.`: since §65.1's scoping of rename warnings, a - // *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port, - // and the engine rightly says nothing about it; a dotted one may be a - // path to the port and is still said — once. - let dotted = M_FAR.replace("sig)", "u_far.sig)"); - let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n"); - let (ws, uri) = macro_workspace(&tree, &far); - - let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0; - assert!( - handed.iter().any(|(path, _)| path.ends_with("far.svh")), - "premise: instantiating `sub` puts far.svh in the source set" - ); - - let (_, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames"); - assert_eq!(far_warnings(&warnings), 1, "no double warning: {warnings:?}"); - let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named"); - assert!( - warning.contains("one opaque token"), - "and it is the engine's sentence, not the census's: {warning}" - ); - } - - // ------------------------------------------------------------------ - // The engine-owned preflight (take 5 review §3 item 6, TODO §61.1) - // ------------------------------------------------------------------ - - /// A cursor on nothing used to select every in-scope file, parse all of - /// them and index them before the engine's 0.1 ms refusal. The preflight - /// is only worth having if that is now literally no parses at all — not - /// fewer, none — so the gate is asserted, not measured. - #[test] - fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() { - let tree = Tree::new("nosymbolparses"); - let (ws, uri) = opened(&tree); - let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule` - - let before = vlog_parser::stats::parses(); - let mut trace = None; - let refusal = - rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there"); - let parses = vlog_parser::stats::parses() - before; - - assert_eq!(parses, 0, "the refusal parsed {parses} whole files"); - assert_eq!(refusal, "there is no symbol to rename at this position."); - - // And the `--verbose` channel says so in its own fields, so the phase - // that measures this row reads the parse count instead of trusting it. - let trace = trace.expect("a refusal traces too"); - assert!(trace.contains("selected=0"), "{trace}"); - assert!(trace.contains("parses=0"), "{trace}"); - assert!(trace.contains("preflight=true"), "{trace}"); - } - - /// …and it is the same sentence the whole workspace produced, taken from - /// the engine over every in-scope file rather than from this module. - #[test] - fn the_preflights_refusal_is_the_whole_workspaces_refusal() { - let tree = Tree::new("preflightparity"); - let (ws, uri) = opened(&tree); - let path = tree.path.join("top.sv"); - for (case, offset) in [ - ("past the last item", TOP.len() as u32 - 1), - ("on the `module` keyword", at(TOP, "module")), - ("on a literal", at(TOP, "1'b0")), - ] { - let fast = rename(&ws, &uri, offset, "probe").expect_err(case); - let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe") - .expect_err("the whole workspace refuses too"); - assert_eq!(fast, slow, "{case}"); - } - } - - /// Precedence, in the two places the preflight could have disturbed it: an - /// unusable buffer is refused by this module before the engine is asked - /// anything, and an invalid new name outranks whatever the cursor is on. - #[test] - fn the_preflight_does_not_disturb_the_refusal_order() { - let tree = Tree::new("preflightorder"); - let (ws, uri) = opened(&tree); - - let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut with_untitled = Workspace::default(); - with_untitled.set_document(untitled.clone(), TOP.to_string()); - assert_eq!( - rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"), - UNSAVED, - "an untitled buffer is refused before the engine sees the cursor" - ); - - // A cursor on nothing *and* a keyword for a new name: the name's - // sentence, which is the one `renaming` reaches first. - let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword"); - assert_eq!(refusal, "`module` is a Verilog keyword."); - } - - /// The one buffer the preflight must never judge: on the large-file fast - /// path every field but the text is the analysis of the *empty* file, so a - /// preflight over it would refuse every cursor as symbolless. The - /// large-buffer gate refuses the whole request first, and this pins that - /// it still does. - #[test] - fn a_large_buffer_is_refused_before_the_preflight_could_see_it() { - let tree = Tree::new("preflightlarge"); - tree.write("sub.sv", SUB); - let top = tree.write("top.sv", TOP); - let mut ws = Workspace::default(); - ws.set_client_settings(crate::settings::ClientSettings { - index_scope: crate::settings::IndexScope::Workspace, - large_file_threshold: 1, - ..Default::default() - }); - ws.open_whole_workspace(vec![tree.path.clone()]); - let uri = path_to_uri(&top).expect("uri"); - ws.set_document(uri.clone(), TOP.to_string()); - - let doc = ws.document(&uri).expect("open"); - assert!(doc.large, "premise: the buffer took the fast path"); - assert!( - vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(), - "premise: the empty analysis would refuse a real cursor, which is why \ - `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); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/rename/tests.rs b/crates/lucisv_server/src/rename/tests.rs new file mode 100644 index 0000000..2860b3e --- /dev/null +++ b/crates/lucisv_server/src/rename/tests.rs @@ -0,0 +1,1119 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use std::fs; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +/// [`rename_traced`] with the trace thrown away — what a test that is not +/// about the trace asks. +fn rename( + ws: &Workspace, + uri: &Uri, + offset: u32, + new_name: &str, +) -> Result<(WorkspaceEdit, Vec), String> { + rename_traced(ws, uri, offset, new_name, &mut None) +} + +/// A scratch workspace root. Removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_rename_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +const SUB: &str = "module sub (input logic clk);\nendmodule\n"; +const TOP: &str = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n"; + +/// A two-file workspace with `top.sv` open. +fn opened(tree: &Tree) -> (Workspace, Uri) { + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", TOP); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + (ws, uri) +} + +/// A third file that spells nothing this rename is about, kept open so +/// the open-buffer rung selects it: the "container" class in miniature — +/// a file the engine must index and never analyses. +const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n"; + +/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a +/// persistent index store behind the workspace — so a rename is handed +/// records keyed on the very bytes it reads. +fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) { + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", TOP); + let quiet = tree.write("bystander.sv", BYSTANDER); + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()), + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + ws.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string()); + (ws, uri) +} + +/// Every edit and every warning one rename produced, with the workspace's +/// own scratch path taken out — the fingerprint the parity proof compares. +fn print(result: &(WorkspaceEdit, Vec), root: &Path) -> String { + let (edit, warnings) = result; + let mut lines: Vec = Vec::new(); + for (uri, edits) in edit.changes.iter().flatten() { + for one in edits { + lines.push(format!( + "{} {:?}..{:?} -> {}", + uri.as_str(), + one.range.start, + one.range.end, + one.new_text + )); + } + } + lines.sort(); + lines.extend(warnings.iter().map(|w| format!("warn {w}"))); + lines.join("\n").replace(root.to_str().expect("utf-8"), "") +} + +/// **§R3b's server-side proof.** The same rename over the same files, once +/// with a warm index store behind it — where the engine is handed every +/// file's record and stops parsing the ones nothing analyses — and once +/// with no store at all, where it parses them all: byte-identical edits, +/// byte-identical warnings. +/// +/// The reuse is asserted to have happened *and* to have removed a parse, +/// so a store that silently stopped answering would fail this rather than +/// pass it for the wrong reason. +#[test] +fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() { + let tree = Tree::new("reuse_store"); + let store = Tree::new("reuse_store_cache"); + let (warm, uri) = three_with_store(&tree, Some(&store)); + let mut line = None; + let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line) + .expect("the rename succeeds"); + let trace = line.expect("a trace is always written"); + assert!(trace.contains("selected=3"), "all three files are selected: {trace}"); + assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}"); + assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}"); + assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}"); + + let bare = Tree::new("reuse_none"); + let (plain, plain_uri) = three_with_store(&bare, None); + let mut plain_line = None; + let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line) + .expect("the rename succeeds"); + let plain_trace = plain_line.expect("a trace is always written"); + assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse"); + assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed"); + + assert_eq!( + print(&with_store, &tree.path), + print(&no_store, &bare.path), + "the reuse changed an edit or a warning" + ); +} + +/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees +/// with the file on disk is not the bytes any record was written from, so +/// the store answers nothing for it and it is parsed — and the rename acts +/// on the buffer's text, which is the precedence it always had. +/// +/// Nothing in the reuse arranges this: the key is the content, so unsaved +/// text misses the same way changed text does. +#[test] +fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() { + let tree = Tree::new("reuse_unsaved"); + let store = Tree::new("reuse_unsaved_cache"); + let (mut ws, uri) = three_with_store(&tree, Some(&store)); + // A signal that exists only in the buffer. Its record cannot be in a + // store keyed on what is on disk. + let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n"; + ws.set_document(uri.clone(), edited.to_string()); + + let mut line = None; + let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line) + .expect("the buffer's own declaration renames"); + let trace = line.expect("a trace is always written"); + // Two untouched records: the open `bystander.sv`, and `sub.sv`, which + // the buffer instantiates and the fan-out's instantiation step hands + // over (M3.5) — both reused, and the edited buffer still parsed. + assert!(trace.contains("reused_files=2"), "only the untouched files' records: {trace}"); + assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}"); + let edits = edit.changes.as_ref().expect("changes").values().flatten().count(); + assert_eq!(edits, 2, "the declaration and its one use, both in the buffer"); +} + +#[test] +fn prepare_offers_the_identifier_and_its_placeholder() { + let tree = Tree::new("prepare"); + let (ws, uri) = opened(&tree); + let response = prepare(&ws, &uri, at(TOP, "u_sub")).expect("renameable"); + let PrepareRenameResponse::RangeWithPlaceholder { range, placeholder } = response else { + panic!("a placeholder is what an editor wants"); + }; + assert_eq!(placeholder, "u_sub"); + assert_eq!(range.start.line, 1); + assert_eq!(range.start.character, 6); + assert_eq!(range.end.character, 11); +} + +#[test] +fn prepare_declines_where_there_is_nothing_to_rename() { + let tree = Tree::new("prepare_no"); + let (ws, uri) = opened(&tree); + let message = prepare(&ws, &uri, at(TOP, "module")).expect_err("a keyword"); + assert!(message.contains("no symbol to rename"), "{message}"); +} + +#[test] +fn prepare_declines_in_an_untitled_buffer() { + let mut ws = Workspace::default(); + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + ws.set_document(uri.clone(), "module m;\n wire a;\nendmodule\n".to_string()); + assert_eq!(prepare(&ws, &uri, 16).expect_err("no path"), UNSAVED); +} + +#[test] +fn a_rename_edits_every_file_that_names_the_symbol() { + let tree = Tree::new("cross"); + let (ws, uri) = opened(&tree); + let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames"); + assert!(warnings.is_empty(), "{warnings:?}"); + + let changes = edit.changes.expect("changes"); + assert_eq!(changes.len(), 2, "the declaration's file and this one"); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + let sub_edits = changes.get(&sub_uri).expect("sub.sv is edited"); + assert_eq!(sub_edits.len(), 1); + assert_eq!(sub_edits[0].new_text, "child"); + assert_eq!(sub_edits[0].range.start.line, 0); + assert_eq!(sub_edits[0].range.start.character, 7, "the name `sub`"); + + let top_edits = changes.get(&uri).expect("top.sv is edited"); + assert_eq!(top_edits.len(), 1); + assert_eq!(top_edits[0].range.start.line, 1); + assert_eq!(top_edits[0].range.start.character, 2); +} + +#[test] +fn a_refused_rename_returns_the_engines_sentence() { + let tree = Tree::new("refused"); + let (ws, uri) = opened(&tree); + let message = rename(&ws, &uri, at(TOP, "u_sub"), "module").expect_err("a keyword"); + assert!(message.contains("keyword"), "{message}"); +} + +#[test] +fn ranges_are_utf16_in_a_file_with_multi_byte_text() { + let tree = Tree::new("utf16"); + let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n"; + let file = tree.write("m.sv", text); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + + let (edit, _) = rename(&ws, &uri, at(text, "wire a") + 5, "sig").expect("renames"); + let mut changes = edit.changes.expect("changes"); + let edits = changes.remove(&uri).expect("this file"); + assert_eq!(edits.len(), 2); + assert_eq!(edits[0].range.start.line, 2); + assert_eq!(edits[0].range.start.character, 7); +} + +// ------------------------------------------------------------------ +// The fan-out equivalence suite +// ------------------------------------------------------------------ +// +// `rename` is handed the symbol's fan-out through the index instead of +// every in-scope file. A rename that edits fewer files than the truth is +// corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot +// reach is a refusal the user never sees — so every case below asks the +// engine the same question twice, over the subset and over the whole +// workspace, and asserts the two answers are the same bytes and the same +// sentences. The sufficiency argument they are the evidence for is in +// `docs/features/refactor-rename/README.md`. + +/// The file set the server would hand `rename` for a cursor at `offset`. +fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec { + let doc = ws.document_for_path(path).expect("the request's file is open"); + match vlog_refactor::rename_name_at(&doc.semantics, offset) { + Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0, + None => ws.sources(), + } + .into_iter() + .map(|(path, _)| path) + .collect() +} + +/// Ask the engine over the fan-out and over the whole workspace, and +/// assert the two answers are indistinguishable. Returns the answer, so a +/// caller can also assert *what* it was. +fn same_answer( + ws: &Workspace, + path: &Path, + offset: u32, + new_name: &str, +) -> Result { + let everything = ws.sources(); + let doc = ws.document_for_path(path).expect("the request's file is open"); + let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) { + Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0, + None => everything.clone(), + }; + for (path, text) in &subset { + let found = everything.iter().find(|(held, _)| held == path); + assert_eq!( + found.map(|(_, text)| text), + Some(text), + "{} is in the fan-out with text the whole scope does not have", + path.display() + ); + } + let whole = vlog_refactor::rename(&everything, path, offset, new_name); + let narrow = vlog_refactor::rename(&subset, path, offset, new_name); + match (&whole, &narrow) { + (Ok(whole), Ok(narrow)) => { + assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes"); + assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently"); + } + (Err(whole), Err(narrow)) => { + assert_eq!(whole, narrow, "the fan-out refused in different words"); + } + (Ok(whole), Err(narrow)) => panic!( + "the fan-out invented a refusal: {narrow}, where the workspace edited {} files", + whole.file_count() + ), + (Err(whole), Ok(narrow)) => panic!( + "the fan-out lost the refusal `{whole}` and edited {} files instead", + narrow.file_count() + ), + } + narrow +} + +/// A workspace of `files`, every one of them also opened as a buffer when +/// `open` names it, with the first named file's URI returned. +fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec) { + let paths: Vec = files.iter().map(|(name, text)| tree.write(name, text)).collect(); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + for name in open { + let path = tree.path.join(name); + let text = fs::read_to_string(&path).expect("written above"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri, text); + } + (ws, paths) +} + +const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n"; +const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n"; +const TWO: &str = "module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n"; +const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n"; +const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n"; + +#[test] +fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() { + let tree = Tree::new("fanout_module"); + let files = + [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("three.sv", GEN), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let at = at(ONE, "sub u_a"); + + let edit = same_answer(&ws, &path, at, "child").expect("renames"); + assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it"); + + // And the narrowing is real: the file that never spells the name is + // not read at all. + let fan = fan_out(&ws, &path, at, "child"); + assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}"); + assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}"); +} + +#[test] +fn the_fan_out_keeps_the_end_label_and_the_declaration_together() { + let tree = Tree::new("fanout_endlabel"); + let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]); + let path = tree.path.join("sub.sv"); + let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames"); + let own = edit.edits_for(&path); + assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label"); +} + +#[test] +fn the_fan_out_carries_a_port_rename_to_every_connection() { + let tree = Tree::new("fanout_port"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["sub.sv"]); + let path = tree.path.join("sub.sv"); + let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames"); + assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`"); +} + +#[test] +fn the_fan_out_carries_a_package_member_rename_to_every_importer() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const IMPORTER: &str = + "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + const QUALIFIER: &str = "module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_pkg"); + let files = + [("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); + let path = tree.path.join("reader.sv"); + let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames"); + assert_eq!(edit.file_count(), 3, "the package and both files reading it"); +} + +#[test] +fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() { + let tree = Tree::new("fanout_unsaved"); + // On disk `two.sv` says nothing about `sub`; the buffer instantiates + // it. The index has never seen the buffer's text. + let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)]; + let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]); + let two = tree.path.join("two.sv"); + ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string()); + assert!( + ws.index().instantiations_of("sub").len() < 2, + "premise: the index has not seen the buffer's instantiation" + ); + + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too"); +} + +#[test] +fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() { + let tree = Tree::new("fanout_dup"); + let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let refusal = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice"); + assert!(refusal.contains("more than one indexed file"), "{refusal}"); +} + +#[test] +fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() { + // `three.sv` names `sub`; `taken.sv` declares the module the rename + // wants to become. Renaming `sub` to `taken` makes every `sub` site + // ambiguous — a file the postings for `sub` alone would never name. + const TAKEN: &str = "module taken;\nendmodule\n"; + const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n"; + let tree = Tree::new("fanout_capture"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let refusal = same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture"); + assert!(refusal.contains("would change what"), "{refusal}"); + + let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken"); + assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}"); +} + +/// The two `` `define`` warnings come from files the index's own define +/// tables name, so both survive the narrowing: a macro *called* the name, +/// and a macro whose **body** spells it, each in a file that has nothing +/// else to do with the symbol. +#[test] +fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() { + const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n"; + const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n"; + let tree = Tree::new("fanout_macro"); + let files = [ + ("sub.sv", MOD), + ("one.sv", ONE), + ("named.sv", NAMED), + ("body.svh", BODY), + ("quiet.sv", QUIET), + ]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.warnings.iter().any(|w| w.contains("is also a macro defined")), + "{:?}", + edit.warnings + ); + assert!( + edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")), + "{:?}", + edit.warnings + ); + let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child"); + assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}"); + assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}"); + assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}"); +} + +#[test] +fn every_file_the_workspace_rename_edits_is_in_the_fan_out() { + // The invariant-1 assertion, made directly rather than through an + // equality: whatever the whole workspace would rewrite, the narrow set + // must contain — otherwise a rename edits fewer files than the truth. + let tree = Tree::new("fanout_covers"); + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n"; + let files = [ + ("sub.sv", MOD), + ("one.sv", ONE), + ("two.sv", TWO), + ("three.sv", GEN), + ("pkg.sv", PKG), + ("reader.sv", IMPORTER), + ("quiet.sv", QUIET), + ]; + let (ws, _) = tree_with(&tree, &files, &["reader.sv"]); + let path = tree.path.join("reader.sv"); + let everything = ws.sources(); + let text = fs::read_to_string(&path).expect("written"); + for offset in 0..=text.len() as u32 { + let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing") else { + continue; + }; + let fan = fan_out(&ws, &path, offset, "renamed_thing"); + for (edited, _) in &whole.edits { + assert!( + fan.contains(edited), + "byte {offset} renames {} and the fan-out does not hold it: {fan:?}", + edited.display() + ); + } + let _ = same_answer(&ws, &path, offset, "renamed_thing"); + } +} + +/// QA, 2026-08-28 attack: an instantiation spelled with an escaped +/// identifier (`` \sub ``) is a *different* name from `sub` to +/// `vlog_semantic` today (a pre-existing simplification, noted in this +/// feature's own 2026-08-24 QA round for a declaration, not an +/// instantiation) — it resolves to nothing, so it is renamed by neither +/// path. The question this pins is narrower: does narrowing the file set +/// change that answer? It must not, since both paths call the identical +/// engine; the risk would be the fan-out *dropping* the file outright +/// while the whole-workspace run still watches it (`\sub` contains the +/// word `sub`, so `contains_word` — and hence `watched_files` — still +/// picks it up in the whole run). `same_answer` checks the observable +/// output only (edits, warnings, or refusal), which is what must agree. +#[test] +fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() { + const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n"; + let tree = Tree::new("fanout_escaped"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.edits_for(&tree.path.join("escaped.sv")).is_empty(), + "the escaped spelling is a different name to vlog_semantic and must stay untouched" + ); +} + +/// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a +/// module unit named `sub` vs. a port/member also named `sub` in an +/// unrelated module) must not cross-contaminate the fan-out — renaming +/// the unit must not touch the member's own declaration or its file. +#[test] +fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() { + const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str = + "module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n"; + let tree = Tree::new("fanout_same_spelling_different_symbol"); + let files = + [("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames"); + assert!( + edit.edits_for(&tree.path.join("other.sv")).is_empty(), + "the unrelated wire named `sub` must not be touched: {:?}", + edit.edits_for(&tree.path.join("other.sv")) + ); + // other.sv may legitimately be *watched* by the whole-word text + // search (it spells "sub"), but it must never be *edited* — checked + // above — nor must its own local wire's meaning change, which + // `same_answer`'s byte-identical edits/warnings assertion already + // confirmed by passing at all. +} + +/// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous +/// posting) must fire even when the ambiguity is on the **new** name, +/// discovered on the second spelling `fan_out_of` walks, not the first. +/// `Workspace::rename_sources` iterates `[name, new_name]` in that order +/// and bails to `sources()` on the first ambiguous hit — this attacks the +/// case where the *old* name's rung is completely unambiguous and only +/// the second iteration finds the problem, to check the early return +/// doesn't leak a partially-built (too-narrow) `wanted` set instead of +/// truly falling back to the whole scope. +#[test] +fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() { + const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; + const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; + const READER: &str = + "module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_ambig_on_new_name"); + let files = [("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)]; + let (ws, _) = tree_with(&tree, &files, &["one.sv"]); + let path = tree.path.join("one.sv"); + let at = at(ONE, "sub u_a"); + // `sub` (the old name) has an unambiguous, tiny fan-out on its own. + let fan = fan_out(&ws, &path, at, "taken_pkg"); + assert_eq!( + fan.len(), + ws.sources().len(), + "the new name's own ambiguity must still hand back the whole scope: {fan:?}" + ); + same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name"); +} + +#[test] +fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() { + // Two files declare the *same* package, so `cfg_pkg::DEPTH` names + // either declaration equally. The index records that the declarations + // are ambiguously referenced but not which file does it, so the + // fan-out refuses to narrow at all — which is how the refusal + // survives. + const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n"; + const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n"; + const READER: &str = + "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n"; + let tree = Tree::new("fanout_ambig"); + let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)]; + let (ws, _) = tree_with(&tree, &files, &["a.sv"]); + let path = tree.path.join("a.sv"); + let at = at(A, "DEPTH ="); + let fan = fan_out(&ws, &path, at, "SIZE"); + assert_eq!( + fan.len(), + ws.sources().len(), + "an ambiguous posting hands back the whole scope: {fan:?}" + ); + same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous"); +} + +/// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the +/// sixth rung the lead ruled for the same day; kept as the regression +/// test for it, now asserting parity rather than pinning the divergence. +/// +/// A file whose only mention of the **new** name is a bare use that +/// resolves to nothing today — `import taken_pkg::*` of a package nobody +/// declares yet — declares nothing, references nothing under the *old* +/// name, instantiates nothing and defines no macro, so the first five +/// rungs of the fan-out cannot see it. The rename is exactly what gives +/// that import a meaning, which is what capture rule 12 refuses over, so +/// the narrow path used to answer `Ok` where the whole workspace refused +/// — a materially weaker answer, not a lost warning. +/// `WorkspaceIndex::files_spelling` is the rung that finds it: the +/// per-file records keep every external use under the name it spells, +/// including the ones that resolved to nothing. +#[test] +fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n"; + let tree = Tree::new("fanout_dangling_import"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_pkg"); + assert!( + fan.contains(&tree.path.join("stray.sv")), + "the dangling import's file is in the fan-out through `files_spelling`: {fan:?}" + ); + + let refusal = same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import"); + assert!(refusal.contains("would change what"), "{refusal}"); + assert!(refusal.contains("taken_pkg"), "{refusal}"); +} + +/// The other half of the ruling: the **old** name needs no such rung, and +/// this is the case that would expose it if it did. `stray.sv`'s only tie +/// to the rename is an `import cfg_pkg::*`-shaped use of a name that +/// resolves to nothing — spelled with the name being renamed *away*. +/// A rename only ever removes declarations of the old name, so a lookup +/// that failed before still fails after; the answer cannot move, and both +/// paths agree without `stray.sv` being read. +#[test] +fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + // `absent_pkg` is declared nowhere, and is what the rename renames to + // nothing: the file's only spelling of it stays unresolved throughout. + const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n"; + let tree = Tree::new("fanout_dangling_old"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + + // Rename the *package* to `absent_pkg` — the new-name rung must pull + // `stray.sv` in and both paths must refuse … + let package = at(PKG, "cfg_pkg;"); + same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import"); + + // … while a rename whose *old* name is the dangling one has nothing to + // capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it + // out of the set and both paths agree. + let depth = at(PKG, "DEPTH ="); + let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames"); + assert_eq!(edit.file_count(), 1, "only the package's own file"); + let fan = fan_out(&ws, &path, depth, "SIZE"); + assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}"); +} + +// ------------------------------------------------------------------ +// QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the +// lead-authorized fix for the dangling-import residue. +// ------------------------------------------------------------------ + +/// Attack on rung 6's completeness: the new name spelled **only** as the +/// base of an `extends` clause the workspace does not (yet) declare. This +/// goes through `Target::Unit`, not `Target::Package` — a different +/// resolution path than the import case rung 6 was built for — so it is +/// worth checking on its own rather than trusting the same mechanism +/// covers it by analogy. +#[test] +fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const STRAY_EXTENDS: &str = + "class derived extends taken_base;\n function void go();\n endfunction\nendclass\n"; + let tree = Tree::new("fanout_extends_base"); + let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_base"); + assert!( + fan.contains(&tree.path.join("stray.sv")), + "the extends base is a Target::Unit miss, always non-empty paths: {fan:?}" + ); + let refusal = + same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning"); + assert!(refusal.contains("would change what"), "{refusal}"); +} + +/// Attack on rung 6's completeness: a bare, unqualified reference to the +/// new name written inside a class that `extends` an **existing, +/// unrelated** base, with no import in scope — the one shape that +/// produces `Resolution::InheritedCandidate` with genuinely **empty** +/// paths (`miss()`'s branch when `nearest_extends` finds a base but no +/// import supplied anything), which `files_spelling` cannot see (it reads +/// only facts with non-empty paths). The argument this pins: such a +/// reference is resolved *purely* from the file's own unedited text and +/// never depends on the workspace (`resolve_external` never even tries +/// `follow_paths` against an empty list), so it cannot change meaning +/// under any rename — excluding the file costs nothing, on this rung or +/// the whole-workspace path alike. +#[test] +fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const EXISTING_BASE: &str = "class existing_base;\nendclass\n"; + // No import anywhere in `stray.sv`, so the lexical miss on + // `taken_member` inside `derived` (which extends `existing_base`) + // collects an empty `external` list and becomes an `InheritedCandidate` + // with `paths: []` — recorded nowhere, per `facts_from_analysis`. + const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n"; + let tree = Tree::new("fanout_inherited_empty_paths"); + let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_member"); + assert!( + !fan.contains(&tree.path.join("stray.sv")), + "an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}" + ); + // Parity must still hold: excluding the file must not change the + // answer, because the reference inside it can never resolve + // differently regardless of what `cfg_pkg` becomes. + same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible"); +} + +/// Attack on rung 6's soundness: a **local-only** symbol in a third file +/// that happens to share the new name's spelling must not trigger a +/// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local` +/// facts (a local declaration/use resolves inside its own file and the +/// workspace was never consulted), so the file should not even be pulled +/// in — and if it were, the rename must still succeed, since no capture is +/// possible against a symbol nothing outside that file can see. +/// +/// The symbol is a **function's** local, not a module's net: since +/// 2026-09-05 a net is a declaration on the module's hierarchical surface +/// and joins the fan-out by that rung (the test below), which would answer +/// this one for the wrong reason. A name inside a subprogram body is on +/// neither surface, which is what this attack needs. +#[test] +fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n"; + let tree = Tree::new("fanout_local_only"); + let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_local"); + assert!( + !fan.contains(&tree.path.join("local.sv")), + "a purely local declaration/use is not an external fact: {fan:?}" + ); + let edit = same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible"); + assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty()); +} + +/// The rung the hierarchical surface added: a module's internal **net** +/// spelled like the new name *is* a declaration the fan-out has to hold, +/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves +/// to it now. So the file is pulled in — and the rename still succeeds +/// and still writes nothing there, because a package name and a net +/// inside a module capture nothing of each other. +#[test] +fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() { + const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n"; + const NET_ONLY: &str = + "module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n"; + let tree = Tree::new("fanout_hierarchical_net"); + let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)]; + let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]); + let path = tree.path.join("pkg.sv"); + let at = at(PKG, "cfg_pkg;"); + + let fan = fan_out(&ws, &path, at, "taken_net"); + assert!( + fan.contains(&tree.path.join("net.sv")), + "a net is a hierarchical declaration of its name: {fan:?}" + ); + let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible"); + assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty()); +} + +/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two +/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same +/// (`shared_name`); a third file imports both, `p_pkg` first, so +/// "first-written import wins" resolves `shared_name` to `p_pkg`'s +/// declaration. Renaming *away* `p_pkg::shared_name` removes the winning +/// candidate, so the same reference should fall through to `q_pkg`'s +/// pre-existing, completely unrelated declaration — a meaning change the +/// whole-workspace verifier must refuse over (rule 12, in the direction +/// "an existing use is captured by nothing new — it silently rebinds to +/// another *existing* declaration"). The old-name argument says this +/// cannot be missed because rung 1 walks *every* declaration named +/// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's), +/// so the importer is pulled in via `references_to` of `p_pkg`'s +/// declaration regardless. +#[test] +fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() { + const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n"; + const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n"; + const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n"; + let tree = Tree::new("fanout_shadow_unmask"); + let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)]; + let (ws, _) = tree_with(&tree, &files, &["p.sv"]); + let path = tree.path.join("p.sv"); + let at = at(P, "shared_name ="); + + let fan = fan_out(&ws, &path, at, "renamed_thing"); + assert!( + fan.contains(&tree.path.join("user.sv")), + "the importer is posted against p_pkg's declaration today: {fan:?}" + ); + assert!( + fan.contains(&tree.path.join("q.sv")), + "rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}" + ); + // Whichever way the whole-workspace path answers this (refuse, since + // `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit, + // if some other rule intervenes first), the subset must answer + // identically — that is the property under attack, not a specific + // outcome. + // The hunt comes up empty, and reading why is the point: `user.sv`'s + // `shared_name` currently resolves to `p_pkg`'s declaration — the + // rename target itself — so it is not a bystander a removal could + // silently unmask, it is an *edit site*: the rename rewrites it to + // `renamed_thing` along with the declaration, so the text never says + // `shared_name` again for `follow_paths` to re-resolve against + // `q_pkg`. A reference can only be affected by a name's removal by + // spelling that exact name, and by the Lemma any such reference + // either resolves to the target (edited away, as here) or to some + // *other* declaration of the same name (already covered by rung 1/2's + // sweep over every declarer, not only the target's) — there is no + // third case for the old name to fall into. + let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames"); + assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference"); + assert!( + edit.edits_for(&tree.path.join("q.sv")).is_empty(), + "q_pkg's own unrelated declaration is never touched" + ); +} + +#[test] +fn an_open_buffer_beats_disk_when_the_rename_is_computed() { + let tree = Tree::new("buffer"); + tree.write("sub.sv", SUB); + let top_path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + // The buffer instantiates `sub`; the file on disk does not. + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + + let (edit, _) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames"); + let changes = edit.changes.expect("changes"); + assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation"); +} + +/// `sub.sv` declares the port, `top.sv` connects it, and `far.svh` names +/// it inside a macro invocation and has no other relationship to anything +/// in the rename — so the fan-out does not hand it to the engine and the +/// engine cannot warn about it. The census does: §2.9-18's server half. +const M_SUB: &str = "module sub (output logic sig);\n assign sig = 1'b0;\nendmodule\n"; +const M_TOP: &str = "module top;\n logic w;\n sub u_sub (.sig(w));\nendmodule\n"; +const M_FAR: &str = "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n"; + +/// The workspace of the two pins below, with `top.sv` open. `far` is what +/// `far.svh` holds, which is the only difference between them. +fn macro_workspace(tree: &Tree, far: &str) -> (Workspace, Uri) { + tree.write("sub.sv", M_SUB); + let top = tree.write("top.sv", M_TOP); + tree.write("far.svh", far); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), M_TOP.to_string()); + (ws, uri) +} + +/// How often a warning naming `far.svh` is in the list. +fn far_warnings(warnings: &[String]) -> usize { + warnings.iter().filter(|w| w.contains("far.svh")).count() +} + +#[test] +fn a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread() { + let tree = Tree::new("macrocensus"); + let (ws, uri) = macro_workspace(&tree, M_FAR); + + // The premise: `far.svh` is in no rung of the fan-out, so the engine + // never sees it. Asked of the same function `rename` asks. + let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0; + assert!( + !handed.iter().any(|(path, _)| path.ends_with("far.svh")), + "premise: the engine is not handed far.svh — {handed:?}" + ); + + let (edit, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames"); + let changes = edit.changes.expect("changes"); + assert_eq!(changes.len(), 2, "the declaration's file and the connection's"); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + assert_eq!(changes.get(&sub_uri).map(Vec::len), Some(2), "the port and its assignment"); + assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the `.sig(` connection"); + assert!( + !changes.contains_key(&path_to_uri(&tree.path.join("far.svh")).expect("uri")), + "a macro argument is never edited" + ); + + assert_eq!(far_warnings(&warnings), 1, "{warnings:?}"); + let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named"); + assert!(warning.contains("`sig`"), "{warning}"); + assert!(warning.contains("this rename did not read"), "{warning}"); + assert!(warning.contains("a macro argument cannot be edited"), "{warning}"); +} + +/// The control: give `far.svh` a reason to be read — it instantiates +/// `sub` — and it *is* a source, so the engine's own macro-argument +/// warning covers it and this one must stay quiet. Exactly one warning +/// names the file either way; two would be the bug. +#[test] +fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() { + let tree = Tree::new("macrocontrol"); + // Spelled after a `.`: since §65.1's scoping of rename warnings, a + // *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port, + // and the engine rightly says nothing about it; a dotted one may be a + // path to the port and is still said — once. + let dotted = M_FAR.replace("sig)", "u_far.sig)"); + let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n"); + let (ws, uri) = macro_workspace(&tree, &far); + + let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0; + assert!( + handed.iter().any(|(path, _)| path.ends_with("far.svh")), + "premise: instantiating `sub` puts far.svh in the source set" + ); + + let (_, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames"); + assert_eq!(far_warnings(&warnings), 1, "no double warning: {warnings:?}"); + let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named"); + assert!( + warning.contains("one opaque token"), + "and it is the engine's sentence, not the census's: {warning}" + ); +} + +// ------------------------------------------------------------------ +// The engine-owned preflight (take 5 review §3 item 6, TODO §61.1) +// ------------------------------------------------------------------ + +/// A cursor on nothing used to select every in-scope file, parse all of +/// them and index them before the engine's 0.1 ms refusal. The preflight +/// is only worth having if that is now literally no parses at all — not +/// fewer, none — so the gate is asserted, not measured. +#[test] +fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() { + let tree = Tree::new("nosymbolparses"); + let (ws, uri) = opened(&tree); + let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule` + + let before = vlog_parser::stats::parses(); + let mut trace = None; + let refusal = + rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there"); + let parses = vlog_parser::stats::parses() - before; + + assert_eq!(parses, 0, "the refusal parsed {parses} whole files"); + assert_eq!(refusal, "there is no symbol to rename at this position."); + + // And the `--verbose` channel says so in its own fields, so the phase + // that measures this row reads the parse count instead of trusting it. + let trace = trace.expect("a refusal traces too"); + assert!(trace.contains("selected=0"), "{trace}"); + assert!(trace.contains("parses=0"), "{trace}"); + assert!(trace.contains("preflight=true"), "{trace}"); +} + +/// …and it is the same sentence the whole workspace produced, taken from +/// the engine over every in-scope file rather than from this module. +#[test] +fn the_preflights_refusal_is_the_whole_workspaces_refusal() { + let tree = Tree::new("preflightparity"); + let (ws, uri) = opened(&tree); + let path = tree.path.join("top.sv"); + for (case, offset) in [ + ("past the last item", TOP.len() as u32 - 1), + ("on the `module` keyword", at(TOP, "module")), + ("on a literal", at(TOP, "1'b0")), + ] { + let fast = rename(&ws, &uri, offset, "probe").expect_err(case); + let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe") + .expect_err("the whole workspace refuses too"); + assert_eq!(fast, slow, "{case}"); + } +} + +/// Precedence, in the two places the preflight could have disturbed it: an +/// unusable buffer is refused by this module before the engine is asked +/// anything, and an invalid new name outranks whatever the cursor is on. +#[test] +fn the_preflight_does_not_disturb_the_refusal_order() { + let tree = Tree::new("preflightorder"); + let (ws, uri) = opened(&tree); + + let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut with_untitled = Workspace::default(); + with_untitled.set_document(untitled.clone(), TOP.to_string()); + assert_eq!( + rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"), + UNSAVED, + "an untitled buffer is refused before the engine sees the cursor" + ); + + // A cursor on nothing *and* a keyword for a new name: the name's + // sentence, which is the one `renaming` reaches first. + let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword"); + assert_eq!(refusal, "`module` is a Verilog keyword."); +} + +/// The one buffer the preflight must never judge: on the large-file fast +/// path every field but the text is the analysis of the *empty* file, so a +/// preflight over it would refuse every cursor as symbolless. The +/// large-buffer gate refuses the whole request first, and this pins that +/// it still does. +#[test] +fn a_large_buffer_is_refused_before_the_preflight_could_see_it() { + let tree = Tree::new("preflightlarge"); + tree.write("sub.sv", SUB); + let top = tree.write("top.sv", TOP); + let mut ws = Workspace::default(); + ws.set_client_settings(crate::settings::ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + large_file_threshold: 1, + ..Default::default() + }); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + + let doc = ws.document(&uri).expect("open"); + assert!(doc.large, "premise: the buffer took the fast path"); + assert!( + vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(), + "premise: the empty analysis would refuse a real cursor, which is why \ + `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/server/tests/large_file.rs b/crates/lucisv_server/src/server/tests/large_file.rs index 3649952..39dd8ae 100644 --- a/crates/lucisv_server/src/server/tests/large_file.rs +++ b/crates/lucisv_server/src/server/tests/large_file.rs @@ -236,6 +236,76 @@ fn definition_and_references_answer_from_one_scan_of_the_buffer() { assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration"); } +/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other* +/// fast-path consumer of `Positions`: `references`' hits still have to +/// become `lsp_types::Location`s (`Server::large_scan`), one +/// `Positions::range` each. `large::references` itself was always linear; +/// the wall was entirely in turning up to `REFERENCE_LIMIT` hits on one +/// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s** +/// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms. +/// +/// `large_scan` now walks the hits with one `Positions::walker`, which +/// they are already in ascending order for. The hits and the line both +/// grow with `width`, so the walker's work (each byte of the line once) is +/// linear in it and the per-hit rescan's (the line once per hit) +/// quadratic; the bound is the same shape check as the colour test's in +/// `large::tests`. +/// +/// What is timed is the **request**, through the real dispatch — the scan, +/// `large_scan`'s conversion and the reply — not a copy of the loop, so a +/// regression in `large_scan` itself is what trips it +/// (`docs/features/linux-test-portability/README.md`, QA finding 4; +/// `docs/features/hygiene-splits-r12/README.md`). Everything else on that +/// path is linear in the line too. +#[test] +fn references_on_one_giant_line_locate_their_hits_in_linear_time() { + use crate::large::tests::{assert_grows_linearly, fastest_of_five}; + use std::cell::RefCell; + + let sizes = [100u32, 200, 400, 800]; + let sessions: Vec<(Tree, RefCell, Value)> = sizes + .iter() + .map(|&width| { + // One line: `wire sig;` filler `sig` filler `sig` ... — + // `width` occurrences of the needle spread over one line, all + // comfortably under REFERENCE_LIMIT so the cap is not what is + // being timed. + let mut text = String::from("wire sig;"); + for _ in 0..width { + text.push_str(&" filler_word ".repeat(250)); + text.push_str("sig"); + } + text.push('\n'); + let tree = Tree::new(&format!("largeoneline{width}")); + let path = tree.path.join("net.v"); + tree.write("net.v", &text); + let mut session = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + fast_path_settings(), + ); + let uri = session.open(&path, &text); + let _ = session.drain(); + let params = serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 0, "character": 5 }, + "context": { "includeDeclaration": true }, + }); + let hits = session.result(References::METHOD, params.clone()); + let hits = hits.as_array().expect("an array").len(); + assert_eq!(hits as u32, width + 1, "the declaration plus every use"); + (tree, RefCell::new(session), params) + }) + .collect(); + assert_grows_linearly(&sizes, "locating hits on one line", || { + fastest_of_five(&sessions, |(_tree, session, params)| { + let clock = std::time::Instant::now(); + std::hint::black_box(session.borrow_mut().result(References::METHOD, params)); + clock.elapsed() + }) + }); +} + /// **The dispatch table.** Every document-scoped request, and what a /// buffer on the fast path answers it. The point is that the list is /// complete and pinned: a handler added later that reads a large buffer's diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index 329d741..f46fa16 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -686,870 +686,6 @@ fn strings(value: Option<&Value>) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - /// The settings a `didChangeConfiguration` payload resolves to. - fn settings(payload: Value) -> ClientSettings { - from_payload(&payload) - } - - /// The payload shape `vscode-languageclient` actually sends for - /// `synchronize.configurationSection: 'lucisv'` — the whole section, with - /// every key present at its default. Verified against the real library in - /// `node_modules`; see the feature README's Handshakes. - fn vscode_payload(line_length: Value, indent: Value, exclude: Value) -> Value { - json!({ - "lucisv": { - "serverPath": "lucisv-server", - "rainbowBeginEnd": true, - "lineLength": line_length, - "indent": indent, - "exclude": exclude, - "filelist": "", - "inlineTemplates": true, - "inlineInstantiation": true, - "inlineKeywords": true, - "autoEnd": true, - "formatOnSave": false, - "index": { - "maxFileSize": 1048576, "logFiles": true, - "scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH - } - } - }) - } - - #[test] - fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() { - assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE); - assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says"); - // The whole sub-section missing is the same as the key missing. - assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576); - let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } })); - assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all"); - let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } })); - assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound"); - } - - #[test] - fn a_wrong_typed_size_cap_leaves_the_default_standing() { - // The safe direction is the shipped cap: reading junk as `0` would - // turn the cap *off*, which is the failure the setting exists to - // prevent. - for bad in - [json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])] - { - let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } })); - assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored"); - } - // An `index` that is not an object at all is the same as no `index`. - for bad in [json!(null), json!(7), json!("index"), json!([])] { - let found = settings(json!({ "lucisv": { "index": bad } })); - assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored"); - assert!(found.log_files, "and so is its logFiles"); - assert_eq!(found.index_scope, IndexScope::Folder, "and its scope"); - assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth"); - } - } - - #[test] - fn the_file_log_is_on_until_a_client_turns_it_off() { - assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on"); - assert!( - settings(json!({ "lucisv": { "index": {} } })).log_files, - "and so is an empty section" - ); - assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files); - assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files); - for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { - let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } })); - assert!(found.log_files, "logFiles {bad} must be ignored"); - } - } - - #[test] - fn the_index_settings_come_through_the_pull_door_too() { - // `from_section` is the same parser, and these were the first nested - // keys to go through it — a section that lost the nesting on the way - // would silently un-cap every pulling client. - let section = json!({ - "index": { - "maxFileSize": 4096, "logFiles": false, - "scope": "workspace", "scopeDepth": 2, - "persist": false, "cachePath": "/tmp/store" - } - }); - let pulled = from_section(§ion); - assert_eq!(pulled.max_file_size, 4096); - assert!(!pulled.log_files); - assert_eq!(pulled.index_scope, IndexScope::Workspace); - assert_eq!(pulled.index_scope_depth, 2); - assert!(!pulled.index_persist); - assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store")); - assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules"); - } - - #[test] - fn the_index_cache_is_on_until_a_client_turns_it_off() { - // Same shape as the file log, and the same direction for junk: the - // setting that costs a user work if it is guessed wrong is "off", so - // anything unreadable leaves it on. - assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on"); - assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one"); - assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist); - assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist); - for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { - let found = settings(json!({ "lucisv": { "index": { "persist": bad } } })); - assert!(found.index_persist, "persist {bad} must be ignored"); - } - } - - #[test] - fn the_cache_path_is_unset_until_a_client_names_one() { - // The empty string is `lucisv.index.cachePath`'s own default and means - // "you decide", exactly as it does for `lucisv.filelist` — not "the - // directory named by the empty path". - assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None); - assert_eq!( - settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path, - None - ); - assert_eq!( - settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } })) - .index_cache_path - .as_deref(), - Some(".cache/lucisv") - ); - for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] { - let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } })); - assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored"); - } - } - - #[test] - fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() { - // The default is the narrow one, and it is what silence, an empty - // sub-section and a missing `index` all resolve to. - assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder); - assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder); - assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees"); - let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } })); - assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting"); - let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } })); - assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing"); - // Anything else is junk, and junk leaves the *narrow* default: a - // misparse must never buy a whole-workspace scan silently. - for bad in - [json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])] - { - let found = settings(json!({ "lucisv": { "index": { "scope": bad } } })); - assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored"); - } - } - - #[test] - fn the_scope_depth_is_two_until_a_client_says_otherwise() { - // Two, not zero, since 2026-08-28: `performance.md` §4 measured the - // file's-own-folder default indexing exactly one file in opentitan's - // `dv/tb` layout, so every cross-file answer was empty until some - // later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`]. - assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH); - assert_eq!( - settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, - DEFAULT_SCOPE_DEPTH - ); - let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } })); - assert_eq!(raised.index_scope_depth, 3); - // Zero is still exactly what it always was — the file's own folder and - // nothing above it — and asking for it still gets it. - let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } })); - assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted"); - // No upper bound here: the clamp is structural — `state.rs` stops at - // the workspace root — so an absurd number is not wrong, just fully - // clamped. - let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } })); - assert_eq!(absurd.index_scope_depth, 9999); - for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] { - let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } })); - assert_eq!( - found.index_scope_depth, DEFAULT_SCOPE_DEPTH, - "scopeDepth {bad} must be ignored" - ); - } - } - - #[test] - fn a_filelist_is_taken_when_it_names_something() { - let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } })); - assert_eq!(found.filelist.as_deref(), Some("rtl/files.f")); - let found = settings(json!({ "lucisv": { "filelist": " /abs/files.f " } })); - assert_eq!( - found.filelist.as_deref(), - Some("/abs/files.f"), - "surrounding space is not path" - ); - } - - #[test] - fn an_empty_or_wrong_typed_filelist_is_no_opinion() { - // `""` is the setting's own default: it must mean "no filelist", not - // "a filelist whose path is empty". - for bad in [json!(""), json!(" "), json!(null), json!(3), json!(["a.f"]), json!(true)] { - let found = settings(json!({ "lucisv": { "filelist": bad } })); - assert_eq!(found.filelist, None, "filelist {bad} must be ignored"); - } - assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence"); - } - - /// The style drop-down offers exactly the names `[format] style` takes, - /// one description each, defaulting to the default style; and each one - /// arrives here as itself, while a name that is not one is dropped. - #[test] - fn the_style_drop_down_is_the_style_names() { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../editors/vscode/package.json"); - let text = std::fs::read_to_string(&path).expect("the extension manifest"); - let manifest: Value = serde_json::from_str(&text).expect("valid json"); - let style = &manifest["contributes"]["configuration"]["properties"]["lucisv.format.style"]; - assert_eq!(style["enum"], json!(lucisv_core::config::STYLE_NAMES)); - let descriptions = style["enumDescriptions"].as_array().expect("descriptions"); - assert_eq!(descriptions.len(), lucisv_core::config::STYLE_NAMES.len()); - assert_eq!(style["default"], json!("lucisv")); - for name in lucisv_core::config::STYLE_NAMES { - let pushed = settings(json!({ "lucisv": { "format": { "style": name } } })); - assert_eq!(pushed.style, Some(name)); - } - for junk in [json!("Google"), json!(""), json!(4), json!(null)] { - let pushed = settings(json!({ "lucisv": { "format": { "style": junk } } })); - assert_eq!(pushed.style, None, "{junk}"); - } - assert!(settings(json!({ "lucisv": {} })).style.is_none()); - } - - #[test] - fn selective_format_override_settings_match_manifest_and_ignore_bad_values() { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../editors/vscode/package.json"); - let text = std::fs::read_to_string(&path).expect("the extension manifest"); - let manifest: Value = serde_json::from_str(&text).expect("valid json"); - let props = &manifest["contributes"]["configuration"]["properties"]; - - assert_eq!( - props["lucisv.format.begin"]["default"], - json!(null), - "override defaults must be null" - ); - assert_eq!(props["lucisv.format.begin"]["enum"], json!(["same-line", "own-line", null])); - assert_eq!(props["lucisv.format.else"]["enum"], json!(["same-line", "own-line", null])); - assert_eq!( - props["lucisv.format.elseAfterLabel"]["enum"], - json!(["same-line", "own-line", null]) - ); - assert_eq!(props["lucisv.format.portLists"]["enum"], json!(["fit", "one-per-line", null])); - assert_eq!(props["lucisv.format.listIndent"]["enum"], json!(["block", "wrap", null])); - assert_eq!(props["lucisv.format.alignment"]["enum"], json!(["infer", "always", null])); - assert_eq!(props["lucisv.format.connectionAlignMin"]["default"], json!(null)); - - let parsed = settings(json!({ - "lucisv": { - "format": { - "begin": "own-line", - "else": "own-line", - "elseAfterLabel": "same-line", - "portLists": "one-per-line", - "listIndent": "wrap", - "alignment": "always", - "connectionAlignMin": 0 - } - } - })); - assert_eq!(parsed.format_begin, Some("own-line")); - assert_eq!(parsed.format_else, Some("own-line")); - assert_eq!(parsed.format_else_after_label, Some("same-line")); - assert_eq!(parsed.format_port_lists, Some("one-per-line")); - assert_eq!(parsed.format_list_indent, Some("wrap")); - assert_eq!(parsed.format_alignment, Some("always")); - assert_eq!(parsed.format_connection_align_min, Some(0)); - - let bad = settings(json!({ - "lucisv": { - "format": { - "begin": "wrong", - "else": 3, - "elseAfterLabel": null, - "portLists": true, - "listIndent": "Block", - "alignment": "Always", - "connectionAlignMin": 9 - } - } - })); - assert_eq!(bad.format_begin, None); - assert_eq!(bad.format_else, None); - assert_eq!(bad.format_else_after_label, None); - assert_eq!(bad.format_port_lists, None); - assert_eq!(bad.format_list_indent, None); - assert_eq!(bad.format_alignment, None); - assert_eq!(bad.format_connection_align_min, None); - } - - /// [`vscode_payload`] above is a hand-written copy of what the extension - /// declares, and a copy that drifts proves nothing. The extension's own - /// `package.json` is the thing a user's settings UI reads, so the two - /// defaults that are not "no opinion" are checked against it directly. - #[test] - fn the_extensions_declared_defaults_are_the_ones_this_module_ships() { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../editors/vscode/package.json"); - let text = std::fs::read_to_string(&path).expect("the extension manifest"); - let manifest: Value = serde_json::from_str(&text).expect("valid json"); - let properties = &manifest["contributes"]["configuration"]["properties"]; - assert_eq!( - properties["lucisv.index.scopeDepth"]["default"], - json!(DEFAULT_SCOPE_DEPTH), - "the settings UI and the server must ship the same scope depth" - ); - assert_eq!( - properties["lucisv.index.maxFileSize"]["default"], - json!(DEFAULT_MAX_FILE_SIZE), - "and the same size cap" - ); - // The two ghost-text settings are the ones whose absence resolves to - // `true` here, so a `false` default in the manifest would make the - // settings UI and the server disagree about a feature being on. - // `autoEnd` is the same kind of switch: absent means on. - for ghost in [ - "lucisv.inlineTemplates", - "lucisv.inlineInstantiation", - "lucisv.inlineKeywords", - "lucisv.autoEnd", - ] { - assert_eq!(properties[ghost]["default"], json!(true), "{ghost}"); - assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}"); - } - } - - /// **The drift guard.** `editors/vscode/package.json` declares one switch - /// per severity class and one per rule, generated by - /// `vlog_linter::vscode_lint_settings`. This compares the two as JSON - /// *values*, so formatting is free but a rule added without its toggle — - /// or a summary, default or severity edited on one side only — fails here. - /// - /// Regenerate with - /// `cargo run -p vlog_linter --example vscode_lint_settings`. - #[test] - fn the_vscode_lint_toggles_match_the_registry() { - let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../editors/vscode/package.json"); - let text = std::fs::read_to_string(&path).expect("the extension manifest"); - let manifest: Value = serde_json::from_str(&text).expect("valid json"); - let properties = manifest["contributes"]["configuration"]["properties"] - .as_object() - .expect("a properties object"); - let declared: serde_json::Map = properties - .iter() - .filter(|(key, _)| { - key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.") - }) - .map(|(key, value)| (key.clone(), value.clone())) - .collect(); - - let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings()) - .expect("the generator emits valid json"); - let generated = generated.as_object().expect("an object"); - - let names = |map: &serde_json::Map| { - let mut keys: Vec = map.keys().cloned().collect(); - keys.sort(); - keys - }; - assert_eq!( - names(&declared), - names(generated), - "package.json and the rule registry disagree about which lint settings exist; \ - regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`" - ); - for (key, value) in generated { - assert_eq!(declared.get(key), Some(value), "{key} drifted"); - } - // And every rule really does have one, which is the promise the whole - // generator exists to keep. - for rule in vlog_linter::all_rules() { - assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name()); - } - } - - /// A default-everything payload — which is what a client sends for a user - /// who has touched nothing — must say nothing about any rule. - #[test] - fn the_shipped_lint_toggles_are_no_opinion() { - let mut rules = serde_json::Map::new(); - for rule in vlog_linter::all_rules() { - rules.insert(rule.name().to_string(), json!("default")); - } - let found = settings(json!({"lucisv": {"lint": { - "severity": {"error": true, "warning": true, "style": true}, - "rules": Value::Object(rules), - }}})); - assert_eq!(found, ClientSettings::default(), "every shipped value is silence"); - } - - #[test] - fn the_severity_switches_and_rule_toggles_are_read() { - let found = settings(json!({"lucisv": {"lint": { - "severity": {"style": false, "warning": "yes"}, - "rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default", - "no-such-rule": "on", "case-missing-default": 3}, - }}})); - assert!(!found.lint_severity[&Severity::Style]); - assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on"); - assert!(found.lint_severity[&Severity::Error], "and so does absence"); - assert_eq!( - found.lint_rules, - [("no-tabs".to_string(), true), ("unused-signal".to_string(), false)] - .into_iter() - .collect::>(), - "`default`, an unknown rule and a wrong-typed choice all say nothing" - ); - // A `lint` that is not an object leaves every class on and nothing said. - let junk = settings(json!({"lucisv": {"lint": 7}})); - assert_eq!(junk.lint_severity, every_class_on()); - assert!(junk.lint_rules.is_empty()); - } - - /// A severity word is a legal `select`/`ignore` entry since §33.0, so the - /// validating filter must keep it. - #[test] - fn a_severity_word_survives_the_select_and_ignore_filter() { - let found = settings(json!({"lucisv": {"lint": { - "select": ["style", "no-tabs", "nope"], - "ignore": ["warning"], - }}})); - assert_eq!(found.lint_select, vec!["style", "no-tabs"]); - assert_eq!(found.lint_ignore, vec!["warning"]); - // And the one name that is neither is described, not just dropped. - assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]); - } - - /// TODO §45.1: a name the registry does not know is still dropped — the - /// rule stays where it was — and now says so, once per name, naming the - /// list the user typed it in. - #[test] - fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() { - let found = settings(json!({"lucisv": {"lint": { - "select": ["no-tabs", "nope", "also-nope"], - "ignore": ["nope"], - }}})); - assert_eq!(found.lint_select, vec!["no-tabs"]); - assert!(found.lint_ignore.is_empty()); - assert_eq!( - found.lint_name_warnings, - vec![ - "lucisv.lint.select: unknown rule: nope", - "lucisv.lint.select: unknown rule: also-nope", - "lucisv.lint.ignore: unknown rule: nope", - ] - ); - } - - #[test] - fn two_lists_of_known_names_describe_nothing() { - let found = settings(json!({"lucisv": {"lint": { - "select": ["no-tabs", "error"], - "ignore": ["unused-signal"], - }}})); - assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings); - assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty()); - } - - /// What the server compares two settings pushes by, to decide whether the - /// squiggles it already drew are still right. - #[test] - fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() { - let base = ClientSettings::default(); - let mut severity = base.clone(); - severity.lint_severity.insert(Severity::Style, false); - let mut toggled = base.clone(); - toggled.lint_rules.insert("no-tabs".to_string(), false); - let mut selected = base.clone(); - selected.lint_select = vec!["error".to_string()]; - let mut ignored = base.clone(); - ignored.lint_ignore = vec!["no-tabs".to_string()]; - let mut configured = base.clone(); - configured.lint_options.set_raw("line-length", "length", "120").expect("accepted"); - for changed in [severity, toggled, selected, ignored, configured] { - assert_ne!(lint_selection(&base), lint_selection(&changed)); - } - // A setting that does not change which rules run does not republish. - let mut unrelated = base.clone(); - unrelated.indent = Some(4); - assert_eq!(lint_selection(&base), lint_selection(&unrelated)); - } - - /// §34.0(c): the object is read, validated against the registry, and a - /// bad entry is dropped **with a warning** rather than failing the push. - #[test] - fn the_lint_options_object_is_read_and_validated() { - let found = settings(json!({"lucisv": {"lint": {"options": { - "line-length": {"length": 120}, - "generate-label-prefix": {"prefix": ["blk_"]}, - "typedef-structs-unions": {"allow_anonymous_nested": true}, - "signal-name-style": {"style_regex": "[a-z_0-9]+"}, - }}}})); - assert_eq!(found.lint_options.int("line-length", "length"), 120); - assert_eq!( - found.lint_options.list("generate-label-prefix", "prefix"), - vec!["blk_".to_string()] - ); - assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested")); - assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+"); - assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings); - } - - #[test] - fn a_refused_option_is_dropped_and_described_rather_than_fatal() { - let found = settings(json!({"lucisv": {"lint": {"options": { - "line-length": {"length": 10, "len": 120}, - "no-such-rule": {"x": 1}, - "no-tabs": {"width": 4}, - "signal-name-style": {"style_regex": "[a-"}, - "interface-name-style": {"style_regex": "\\bword\\b"}, - "macro-name-style": {"style_regex": 4}, - "package-filename": "not-an-object", - "port-name-suffix": {"suffixes": [1, 2]}, - }}}})); - // Nothing was accepted, and every refusal says which entry and why. - assert!(found.lint_options.is_empty(), "{:?}", found.lint_options); - let warnings = found.lint_option_warnings.join("\n"); - for wanted in [ - "line-length.length", - "must be between", - "has no option `len`", - "unknown rule `no-such-rule`", - "takes no options", - "not a valid pattern", - "unsupported escape `\\b`", - "expects a pattern, found an integer", - "package-filename is not an object", - "port-name-suffix.suffixes", - ] { - assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}"); - } - // ... and the rest of the settings survived the bad object. - assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE); - } - - /// `lucisv.lint.waivers` is a list of paths, taken as written: this module - /// has no filesystem to check them against, and whether a file exists or - /// parses is answered where it is read. TODO §39. - #[test] - fn the_waivers_setting_is_a_list_of_paths_taken_as_written() { - let found = settings(json!({"lucisv": {"lint": { - "waivers": ["project.waiver", "/abs/other.waiver", 7, null] - }}})); - assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]); - assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty()); - // Wrong-typed altogether: the whole list is "no opinion", never a - // guess, exactly as `select` and `exclude` are. - for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] { - assert!( - settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(), - "waivers {bad} must be ignored" - ); - } - // A changed list republishes, for the reason a changed option does. - let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}})); - let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}})); - assert_ne!(lint_selection(&one), lint_selection(&two)); - } - - /// A settings payload with no options object is exactly today's - /// behaviour: every rule reads its own default. - #[test] - fn no_options_object_means_every_default() { - for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] { - let found = settings(payload); - assert!(found.lint_options.is_empty()); - assert!(found.lint_option_warnings.is_empty()); - assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default"); - } - } - - #[test] - fn the_default_vscode_payload_is_no_opinion_about_anything() { - // Every setting at its `package.json` default: nulls and an empty - // list, which must leave today's behaviour exactly unchanged. - // The two ghost-text settings are the defaults that are not "no - // opinion" — both default to `true`, and `None` resolves to the same - // thing. - let found = settings(vscode_payload(json!(null), json!(null), json!([]))); - assert_eq!( - found, - ClientSettings { - inline_templates: Some(true), - inline_instantiation: Some(true), - inline_keywords: Some(true), - auto_end: Some(true), - ..Default::default() - }, - "the only difference from silence must be the settings whose \ - default is not null" - ); - } - - #[test] - fn inline_templates_is_a_boolean_and_nothing_else() { - let found = settings(json!({ "lucisv": { "inlineTemplates": false } })); - assert_eq!(found.inline_templates, Some(false)); - let found = settings(json!({ "lucisv": { "inlineTemplates": true } })); - assert_eq!(found.inline_templates, Some(true)); - // Absence is not `false`: the feature is on unless a client says no. - assert_eq!(settings(json!({ "lucisv": {} })).inline_templates, None); - for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { - let found = settings(json!({ "lucisv": { "inlineTemplates": bad } })); - assert_eq!(found.inline_templates, None, "inlineTemplates {bad} must be ignored"); - } - } - - #[test] - fn inline_instantiation_is_a_boolean_and_nothing_else() { - let found = settings(json!({ "lucisv": { "inlineInstantiation": false } })); - assert_eq!(found.inline_instantiation, Some(false)); - let found = settings(json!({ "lucisv": { "inlineInstantiation": true } })); - assert_eq!(found.inline_instantiation, Some(true)); - // Absence is not `false`: the feature is on unless a client says no. - assert_eq!(settings(json!({ "lucisv": {} })).inline_instantiation, None); - for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { - let found = settings(json!({ "lucisv": { "inlineInstantiation": bad } })); - assert_eq!(found.inline_instantiation, None, "inlineInstantiation {bad} ignored"); - } - // The two ghost settings are independent: one off leaves the other on. - let found = settings(json!({ "lucisv": { "inlineInstantiation": false } })); - assert_eq!(found.inline_templates, None, "the templates setting is untouched"); - } - - #[test] - fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() { - let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } })); - assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false))); - let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } })); - assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true))); - // Absence is not `false`: both are on unless a client says no. - let found = settings(json!({ "lucisv": {} })); - assert_eq!((found.inline_keywords, found.auto_end), (None, None)); - for bad in [json!("false"), json!(0), json!(null), json!([false])] { - let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } })); - assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored"); - } - // Independent of the template ghosts: one off leaves the other alone. - let found = settings(json!({ "lucisv": { "inlineKeywords": false } })); - assert_eq!(found.inline_templates, None, "the templates setting is untouched"); - } - - #[test] - fn format_on_save_is_off_until_a_client_asks_for_it() { - assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save); - assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save); - // Absence is off: the hook runs on every save of every buffer, and a - // server that formatted uninvited would fight the editor's own - // format-on-save. - assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence"); - for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] { - let found = settings(json!({ "lucisv": { "formatOnSave": bad } })); - assert!(!found.format_on_save, "formatOnSave {bad} must be ignored"); - } - } - - #[test] - fn a_populated_payload_is_read_whole() { - let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"]))); - assert_eq!(found.line_length, Some(120)); - assert_eq!(found.indent, Some(4)); - assert_eq!(found.exclude, vec!["vendor".to_string(), "*_gen.sv".to_string()]); - } - - #[test] - fn a_payload_without_our_section_says_nothing() { - assert_eq!(settings(json!({ "someOtherServer": { "indent": 4 } })), Default::default()); - assert_eq!(settings(json!(null)), Default::default(), "the `settings: null` form"); - assert_eq!(settings(json!({})), Default::default()); - } - - #[test] - fn a_missing_key_is_not_an_opinion() { - // A hand-written Neovim `settings` table names only what it cares - // about; the keys it leaves out must stay silent, not become 0. - let found = settings(json!({ "lucisv": { "indent": 4 } })); - assert_eq!(found.indent, Some(4)); - assert_eq!(found.line_length, None); - assert!(found.exclude.is_empty()); - } - - #[test] - fn out_of_range_numbers_are_ignored() { - for bad in [json!(0), json!(9), json!(100), json!(-1)] { - let found = settings(json!({ "lucisv": { "indent": bad } })); - assert_eq!(found.indent, None, "indent {bad} must be ignored"); - } - for bad in [json!(0), json!(39), json!(401), json!(-40)] { - let found = settings(json!({ "lucisv": { "lineLength": bad } })); - assert_eq!(found.line_length, None, "lineLength {bad} must be ignored"); - } - } - - #[test] - fn the_range_edges_are_accepted() { - let found = settings(json!({ "lucisv": { "indent": 1, "lineLength": 40 } })); - assert_eq!((found.indent, found.line_length), (Some(1), Some(40))); - let found = settings(json!({ "lucisv": { "indent": 8, "lineLength": 400 } })); - assert_eq!((found.indent, found.line_length), (Some(8), Some(400))); - } - - #[test] - fn wrong_types_are_ignored_rather_than_coerced() { - for bad in [json!("4"), json!(true), json!([4]), json!({ "n": 4 }), json!(4.5)] { - let found = settings(json!({ "lucisv": { "indent": bad, "lineLength": bad } })); - assert_eq!(found.indent, None, "indent {bad} must be ignored"); - assert_eq!(found.line_length, None, "lineLength {bad} must be ignored"); - } - } - - #[test] - fn an_exclude_that_is_not_a_list_of_strings_contributes_nothing() { - assert!(settings(json!({ "lucisv": { "exclude": "vendor" } })).exclude.is_empty()); - assert!(settings(json!({ "lucisv": { "exclude": 3 } })).exclude.is_empty()); - assert!(settings(json!({ "lucisv": { "exclude": null } })).exclude.is_empty()); - // A mixed array keeps the strings and drops the rest. - let found = settings(json!({ "lucisv": { "exclude": ["ok", 3, null, "fine"] } })); - assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]); - } - - #[test] - fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() { - // The whole point of `from_section`: the pull answers the section's - // contents, the push nests them one level deeper, and every rule - // about ranges, types and defaults must be the one set of rules. - let section = json!({ - "lineLength": 120, "indent": 4, "exclude": ["vendor"], - "filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true - }); - assert_eq!(from_section(§ion), settings(json!({ "lucisv": section }))); - // ...including the rejections. - let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" }); - assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk }))); - assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections"); - } - - #[test] - fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() { - // A client that cannot provide the section must answer `null`, per - // spec — and one that answers something absurd instead must cost the - // user no more than one that answered nothing. - for answer in [ - json!(null), - json!({}), - json!("lucisv"), - json!(7), - json!([1, 2]), - json!({ "lucisv": { "indent": 4 } }), - ] { - assert_eq!( - from_section(&answer), - ClientSettings::default(), - "the answer {answer} must resolve to the defaults" - ); - } - } - - #[test] - fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() { - // `{"settings": null}` is what a modern `vscode-languageclient` - // sends: "something changed, ask me". Applying it as a payload would - // silently reset every setting the user had pulled. - assert!(says_nothing(&json!(null))); - assert!(says_nothing(&json!({}))); - assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } }))); - // A legacy push that syncs some *other* server's section is still a - // push: it carries a payload, and this server's answer to it — no - // opinion about anything — is what it has always been. - assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } }))); - // Neither an array nor a scalar is the client saying "ask me"; both - // are junk, and junk goes down the push path where `from_payload` - // drops it. - assert!(!says_nothing(&json!([]))); - assert!(!says_nothing(&json!(""))); - } - - #[test] - fn the_section_constant_is_the_key_the_parser_reads() { - // The pull asks for `SECTION` by name and the push nests under it. A - // constant that drifted from the parser would make every pulled - // setting silently invisible. - let found = from_payload(&json!({ SECTION: { "indent": 4 } })); - assert_eq!(found.indent, Some(4)); - assert_eq!(SECTION, "lucisv"); - } - - #[test] - fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() { - // The bounds above are copied from `lucisv_core::config`, which exports - // no constant for them. Rather than trust the copy, ask the real - // parser: every edge this module accepts must parse, and every value - // it rejects must be rejected there too. If `lucisv.toml` ever widens a - // range, this fails and says so. - let ok = |text: &str| lucisv_core::config::parse(text).is_ok(); - assert!(ok("indent = 1") && ok("indent = 8"), "the indent edges"); - assert!(!ok("indent = 0") && !ok("indent = 9"), "just outside indent"); - assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges"); - assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length"); - } - - /// `lucisv.lint.select` / `lucisv.lint.ignore` nest like every other dotted - /// id, and carry only names the rule registry knows. - #[test] - fn the_lint_selection_is_read_and_validated() { - let read = settings(json!({"lucisv": {"lint": { - "select": ["unused-signal", "no-tabs"], - "ignore": ["no-tabs"], - }}})); - assert_eq!(read.lint_select, vec!["unused-signal", "no-tabs"]); - assert_eq!(read.lint_ignore, vec!["no-tabs"]); - - // A name the registry does not know is dropped, not an error: a push - // is JSON on a socket, and one typo must not cost every diagnostic. - let typo = settings(json!({"lucisv": {"lint": { - "select": ["unused-signal", "unusedsignal", 7, null], - "ignore": "no-tabs", - }}})); - assert_eq!(typo.lint_select, vec!["unused-signal"]); - assert!(typo.lint_ignore.is_empty(), "an array is required"); - - // Absent, or absent-shaped, is "no opinion". - assert!(settings(json!({"lucisv": {}})).lint_select.is_empty()); - assert!(settings(json!({"lucisv": {"lint": 3}})).lint_ignore.is_empty()); - assert!(ClientSettings::default().lint_select.is_empty()); - } - - /// The pull door reads the same keys as the push door — the property the - /// whole module is built on, asserted for the new keys too. - #[test] - fn a_pull_reads_the_lint_selection_the_same_way() { - let pulled = from_section(&json!({"lint": {"ignore": ["unused-signal"]}})); - assert_eq!(pulled.lint_ignore, vec!["unused-signal"]); - assert_eq!(pulled, settings(json!({"lucisv": {"lint": {"ignore": ["unused-signal"]}}}))); - } - - /// The rule names the settings accept are the ones `lucisv check` accepts: - /// one registry, not a list copied into a schema. - #[test] - fn the_accepted_rule_names_are_the_registrys() { - for rule in vlog_linter::all_rules() { - let read = settings(json!({"lucisv": {"lint": {"ignore": [rule.name()]}}})); - assert_eq!(read.lint_ignore, vec![rule.name()], "{}", rule.name()); - } - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/settings/tests.rs b/crates/lucisv_server/src/settings/tests.rs new file mode 100644 index 0000000..bc619ae --- /dev/null +++ b/crates/lucisv_server/src/settings/tests.rs @@ -0,0 +1,859 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use serde_json::json; + +/// The settings a `didChangeConfiguration` payload resolves to. +fn settings(payload: Value) -> ClientSettings { + from_payload(&payload) +} + +/// The payload shape `vscode-languageclient` actually sends for +/// `synchronize.configurationSection: 'lucisv'` — the whole section, with +/// every key present at its default. Verified against the real library in +/// `node_modules`; see the feature README's Handshakes. +fn vscode_payload(line_length: Value, indent: Value, exclude: Value) -> Value { + json!({ + "lucisv": { + "serverPath": "lucisv-server", + "rainbowBeginEnd": true, + "lineLength": line_length, + "indent": indent, + "exclude": exclude, + "filelist": "", + "inlineTemplates": true, + "inlineInstantiation": true, + "inlineKeywords": true, + "autoEnd": true, + "formatOnSave": false, + "index": { + "maxFileSize": 1048576, "logFiles": true, + "scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH + } + } + }) +} + +#[test] +fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() { + assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE); + assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says"); + // The whole sub-section missing is the same as the key missing. + assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576); + let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } })); + assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all"); + let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } })); + assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound"); +} + +#[test] +fn a_wrong_typed_size_cap_leaves_the_default_standing() { + // The safe direction is the shipped cap: reading junk as `0` would + // turn the cap *off*, which is the failure the setting exists to + // prevent. + for bad in [json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])] + { + let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } })); + assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored"); + } + // An `index` that is not an object at all is the same as no `index`. + for bad in [json!(null), json!(7), json!("index"), json!([])] { + let found = settings(json!({ "lucisv": { "index": bad } })); + assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored"); + assert!(found.log_files, "and so is its logFiles"); + assert_eq!(found.index_scope, IndexScope::Folder, "and its scope"); + assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth"); + } +} + +#[test] +fn the_file_log_is_on_until_a_client_turns_it_off() { + assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on"); + assert!(settings(json!({ "lucisv": { "index": {} } })).log_files, "and so is an empty section"); + assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files); + assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } })); + assert!(found.log_files, "logFiles {bad} must be ignored"); + } +} + +#[test] +fn the_index_settings_come_through_the_pull_door_too() { + // `from_section` is the same parser, and these were the first nested + // keys to go through it — a section that lost the nesting on the way + // would silently un-cap every pulling client. + let section = json!({ + "index": { + "maxFileSize": 4096, "logFiles": false, + "scope": "workspace", "scopeDepth": 2, + "persist": false, "cachePath": "/tmp/store" + } + }); + let pulled = from_section(§ion); + assert_eq!(pulled.max_file_size, 4096); + assert!(!pulled.log_files); + assert_eq!(pulled.index_scope, IndexScope::Workspace); + assert_eq!(pulled.index_scope_depth, 2); + assert!(!pulled.index_persist); + assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store")); + assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules"); +} + +#[test] +fn the_index_cache_is_on_until_a_client_turns_it_off() { + // Same shape as the file log, and the same direction for junk: the + // setting that costs a user work if it is guessed wrong is "off", so + // anything unreadable leaves it on. + assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on"); + assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one"); + assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist); + assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "index": { "persist": bad } } })); + assert!(found.index_persist, "persist {bad} must be ignored"); + } +} + +#[test] +fn the_cache_path_is_unset_until_a_client_names_one() { + // The empty string is `lucisv.index.cachePath`'s own default and means + // "you decide", exactly as it does for `lucisv.filelist` — not "the + // directory named by the empty path". + assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None); + assert_eq!( + settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path, + None + ); + assert_eq!( + settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } })) + .index_cache_path + .as_deref(), + Some(".cache/lucisv") + ); + for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] { + let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } })); + assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored"); + } +} + +#[test] +fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() { + // The default is the narrow one, and it is what silence, an empty + // sub-section and a missing `index` all resolve to. + assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder); + assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder); + assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees"); + let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } })); + assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting"); + let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } })); + assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing"); + // Anything else is junk, and junk leaves the *narrow* default: a + // misparse must never buy a whole-workspace scan silently. + for bad in + [json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])] + { + let found = settings(json!({ "lucisv": { "index": { "scope": bad } } })); + assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored"); + } +} + +#[test] +fn the_scope_depth_is_two_until_a_client_says_otherwise() { + // Two, not zero, since 2026-08-28: `performance.md` §4 measured the + // file's-own-folder default indexing exactly one file in opentitan's + // `dv/tb` layout, so every cross-file answer was empty until some + // later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`]. + assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH); + assert_eq!( + settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, + DEFAULT_SCOPE_DEPTH + ); + let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } })); + assert_eq!(raised.index_scope_depth, 3); + // Zero is still exactly what it always was — the file's own folder and + // nothing above it — and asking for it still gets it. + let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } })); + assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted"); + // No upper bound here: the clamp is structural — `state.rs` stops at + // the workspace root — so an absurd number is not wrong, just fully + // clamped. + let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } })); + assert_eq!(absurd.index_scope_depth, 9999); + for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] { + let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } })); + assert_eq!( + found.index_scope_depth, DEFAULT_SCOPE_DEPTH, + "scopeDepth {bad} must be ignored" + ); + } +} + +#[test] +fn a_filelist_is_taken_when_it_names_something() { + let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } })); + assert_eq!(found.filelist.as_deref(), Some("rtl/files.f")); + let found = settings(json!({ "lucisv": { "filelist": " /abs/files.f " } })); + assert_eq!(found.filelist.as_deref(), Some("/abs/files.f"), "surrounding space is not path"); +} + +#[test] +fn an_empty_or_wrong_typed_filelist_is_no_opinion() { + // `""` is the setting's own default: it must mean "no filelist", not + // "a filelist whose path is empty". + for bad in [json!(""), json!(" "), json!(null), json!(3), json!(["a.f"]), json!(true)] { + let found = settings(json!({ "lucisv": { "filelist": bad } })); + assert_eq!(found.filelist, None, "filelist {bad} must be ignored"); + } + assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence"); +} + +/// The style drop-down offers exactly the names `[format] style` takes, +/// one description each, defaulting to the default style; and each one +/// arrives here as itself, while a name that is not one is dropped. +#[test] +fn the_style_drop_down_is_the_style_names() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../editors/vscode/package.json"); + let text = std::fs::read_to_string(&path).expect("the extension manifest"); + let manifest: Value = serde_json::from_str(&text).expect("valid json"); + let style = &manifest["contributes"]["configuration"]["properties"]["lucisv.format.style"]; + assert_eq!(style["enum"], json!(lucisv_core::config::STYLE_NAMES)); + let descriptions = style["enumDescriptions"].as_array().expect("descriptions"); + assert_eq!(descriptions.len(), lucisv_core::config::STYLE_NAMES.len()); + assert_eq!(style["default"], json!("lucisv")); + for name in lucisv_core::config::STYLE_NAMES { + let pushed = settings(json!({ "lucisv": { "format": { "style": name } } })); + assert_eq!(pushed.style, Some(name)); + } + for junk in [json!("Google"), json!(""), json!(4), json!(null)] { + let pushed = settings(json!({ "lucisv": { "format": { "style": junk } } })); + assert_eq!(pushed.style, None, "{junk}"); + } + assert!(settings(json!({ "lucisv": {} })).style.is_none()); +} + +#[test] +fn selective_format_override_settings_match_manifest_and_ignore_bad_values() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../editors/vscode/package.json"); + let text = std::fs::read_to_string(&path).expect("the extension manifest"); + let manifest: Value = serde_json::from_str(&text).expect("valid json"); + let props = &manifest["contributes"]["configuration"]["properties"]; + + assert_eq!( + props["lucisv.format.begin"]["default"], + json!(null), + "override defaults must be null" + ); + assert_eq!(props["lucisv.format.begin"]["enum"], json!(["same-line", "own-line", null])); + assert_eq!(props["lucisv.format.else"]["enum"], json!(["same-line", "own-line", null])); + assert_eq!( + props["lucisv.format.elseAfterLabel"]["enum"], + json!(["same-line", "own-line", null]) + ); + assert_eq!(props["lucisv.format.portLists"]["enum"], json!(["fit", "one-per-line", null])); + assert_eq!(props["lucisv.format.listIndent"]["enum"], json!(["block", "wrap", null])); + assert_eq!(props["lucisv.format.alignment"]["enum"], json!(["infer", "always", null])); + assert_eq!(props["lucisv.format.connectionAlignMin"]["default"], json!(null)); + + let parsed = settings(json!({ + "lucisv": { + "format": { + "begin": "own-line", + "else": "own-line", + "elseAfterLabel": "same-line", + "portLists": "one-per-line", + "listIndent": "wrap", + "alignment": "always", + "connectionAlignMin": 0 + } + } + })); + assert_eq!(parsed.format_begin, Some("own-line")); + assert_eq!(parsed.format_else, Some("own-line")); + assert_eq!(parsed.format_else_after_label, Some("same-line")); + assert_eq!(parsed.format_port_lists, Some("one-per-line")); + assert_eq!(parsed.format_list_indent, Some("wrap")); + assert_eq!(parsed.format_alignment, Some("always")); + assert_eq!(parsed.format_connection_align_min, Some(0)); + + let bad = settings(json!({ + "lucisv": { + "format": { + "begin": "wrong", + "else": 3, + "elseAfterLabel": null, + "portLists": true, + "listIndent": "Block", + "alignment": "Always", + "connectionAlignMin": 9 + } + } + })); + assert_eq!(bad.format_begin, None); + assert_eq!(bad.format_else, None); + assert_eq!(bad.format_else_after_label, None); + assert_eq!(bad.format_port_lists, None); + assert_eq!(bad.format_list_indent, None); + assert_eq!(bad.format_alignment, None); + assert_eq!(bad.format_connection_align_min, None); +} + +/// [`vscode_payload`] above is a hand-written copy of what the extension +/// declares, and a copy that drifts proves nothing. The extension's own +/// `package.json` is the thing a user's settings UI reads, so the two +/// defaults that are not "no opinion" are checked against it directly. +#[test] +fn the_extensions_declared_defaults_are_the_ones_this_module_ships() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../editors/vscode/package.json"); + let text = std::fs::read_to_string(&path).expect("the extension manifest"); + let manifest: Value = serde_json::from_str(&text).expect("valid json"); + let properties = &manifest["contributes"]["configuration"]["properties"]; + assert_eq!( + properties["lucisv.index.scopeDepth"]["default"], + json!(DEFAULT_SCOPE_DEPTH), + "the settings UI and the server must ship the same scope depth" + ); + assert_eq!( + properties["lucisv.index.maxFileSize"]["default"], + json!(DEFAULT_MAX_FILE_SIZE), + "and the same size cap" + ); + // The two ghost-text settings are the ones whose absence resolves to + // `true` here, so a `false` default in the manifest would make the + // settings UI and the server disagree about a feature being on. + // `autoEnd` is the same kind of switch: absent means on. + for ghost in [ + "lucisv.inlineTemplates", + "lucisv.inlineInstantiation", + "lucisv.inlineKeywords", + "lucisv.autoEnd", + ] { + assert_eq!(properties[ghost]["default"], json!(true), "{ghost}"); + assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}"); + } +} + +/// **The drift guard.** `editors/vscode/package.json` declares one switch +/// per severity class and one per rule, generated by +/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON +/// *values*, so formatting is free but a rule added without its toggle — +/// or a summary, default or severity edited on one side only — fails here. +/// +/// Regenerate with +/// `cargo run -p vlog_linter --example vscode_lint_settings`. +#[test] +fn the_vscode_lint_toggles_match_the_registry() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../editors/vscode/package.json"); + let text = std::fs::read_to_string(&path).expect("the extension manifest"); + let manifest: Value = serde_json::from_str(&text).expect("valid json"); + let properties = manifest["contributes"]["configuration"]["properties"] + .as_object() + .expect("a properties object"); + let declared: serde_json::Map = properties + .iter() + .filter(|(key, _)| { + key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.") + }) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + + let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings()) + .expect("the generator emits valid json"); + let generated = generated.as_object().expect("an object"); + + let names = |map: &serde_json::Map| { + let mut keys: Vec = map.keys().cloned().collect(); + keys.sort(); + keys + }; + assert_eq!( + names(&declared), + names(generated), + "package.json and the rule registry disagree about which lint settings exist; \ + regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`" + ); + for (key, value) in generated { + assert_eq!(declared.get(key), Some(value), "{key} drifted"); + } + // And every rule really does have one, which is the promise the whole + // generator exists to keep. + for rule in vlog_linter::all_rules() { + assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name()); + } +} + +/// A default-everything payload — which is what a client sends for a user +/// who has touched nothing — must say nothing about any rule. +#[test] +fn the_shipped_lint_toggles_are_no_opinion() { + let mut rules = serde_json::Map::new(); + for rule in vlog_linter::all_rules() { + rules.insert(rule.name().to_string(), json!("default")); + } + let found = settings(json!({"lucisv": {"lint": { + "severity": {"error": true, "warning": true, "style": true}, + "rules": Value::Object(rules), + }}})); + assert_eq!(found, ClientSettings::default(), "every shipped value is silence"); +} + +#[test] +fn the_severity_switches_and_rule_toggles_are_read() { + let found = settings(json!({"lucisv": {"lint": { + "severity": {"style": false, "warning": "yes"}, + "rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default", + "no-such-rule": "on", "case-missing-default": 3}, + }}})); + assert!(!found.lint_severity[&Severity::Style]); + assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on"); + assert!(found.lint_severity[&Severity::Error], "and so does absence"); + assert_eq!( + found.lint_rules, + [("no-tabs".to_string(), true), ("unused-signal".to_string(), false)] + .into_iter() + .collect::>(), + "`default`, an unknown rule and a wrong-typed choice all say nothing" + ); + // A `lint` that is not an object leaves every class on and nothing said. + let junk = settings(json!({"lucisv": {"lint": 7}})); + assert_eq!(junk.lint_severity, every_class_on()); + assert!(junk.lint_rules.is_empty()); +} + +/// A severity word is a legal `select`/`ignore` entry since §33.0, so the +/// validating filter must keep it. +#[test] +fn a_severity_word_survives_the_select_and_ignore_filter() { + let found = settings(json!({"lucisv": {"lint": { + "select": ["style", "no-tabs", "nope"], + "ignore": ["warning"], + }}})); + assert_eq!(found.lint_select, vec!["style", "no-tabs"]); + assert_eq!(found.lint_ignore, vec!["warning"]); + // And the one name that is neither is described, not just dropped. + assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]); +} + +/// TODO §45.1: a name the registry does not know is still dropped — the +/// rule stays where it was — and now says so, once per name, naming the +/// list the user typed it in. +#[test] +fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() { + let found = settings(json!({"lucisv": {"lint": { + "select": ["no-tabs", "nope", "also-nope"], + "ignore": ["nope"], + }}})); + assert_eq!(found.lint_select, vec!["no-tabs"]); + assert!(found.lint_ignore.is_empty()); + assert_eq!( + found.lint_name_warnings, + vec![ + "lucisv.lint.select: unknown rule: nope", + "lucisv.lint.select: unknown rule: also-nope", + "lucisv.lint.ignore: unknown rule: nope", + ] + ); +} + +#[test] +fn two_lists_of_known_names_describe_nothing() { + let found = settings(json!({"lucisv": {"lint": { + "select": ["no-tabs", "error"], + "ignore": ["unused-signal"], + }}})); + assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings); + assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty()); +} + +/// What the server compares two settings pushes by, to decide whether the +/// squiggles it already drew are still right. +#[test] +fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() { + let base = ClientSettings::default(); + let mut severity = base.clone(); + severity.lint_severity.insert(Severity::Style, false); + let mut toggled = base.clone(); + toggled.lint_rules.insert("no-tabs".to_string(), false); + let mut selected = base.clone(); + selected.lint_select = vec!["error".to_string()]; + let mut ignored = base.clone(); + ignored.lint_ignore = vec!["no-tabs".to_string()]; + let mut configured = base.clone(); + configured.lint_options.set_raw("line-length", "length", "120").expect("accepted"); + for changed in [severity, toggled, selected, ignored, configured] { + assert_ne!(lint_selection(&base), lint_selection(&changed)); + } + // A setting that does not change which rules run does not republish. + let mut unrelated = base.clone(); + unrelated.indent = Some(4); + assert_eq!(lint_selection(&base), lint_selection(&unrelated)); +} + +/// §34.0(c): the object is read, validated against the registry, and a +/// bad entry is dropped **with a warning** rather than failing the push. +#[test] +fn the_lint_options_object_is_read_and_validated() { + let found = settings(json!({"lucisv": {"lint": {"options": { + "line-length": {"length": 120}, + "generate-label-prefix": {"prefix": ["blk_"]}, + "typedef-structs-unions": {"allow_anonymous_nested": true}, + "signal-name-style": {"style_regex": "[a-z_0-9]+"}, + }}}})); + assert_eq!(found.lint_options.int("line-length", "length"), 120); + assert_eq!( + found.lint_options.list("generate-label-prefix", "prefix"), + vec!["blk_".to_string()] + ); + assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested")); + assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+"); + assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings); +} + +#[test] +fn a_refused_option_is_dropped_and_described_rather_than_fatal() { + let found = settings(json!({"lucisv": {"lint": {"options": { + "line-length": {"length": 10, "len": 120}, + "no-such-rule": {"x": 1}, + "no-tabs": {"width": 4}, + "signal-name-style": {"style_regex": "[a-"}, + "interface-name-style": {"style_regex": "\\bword\\b"}, + "macro-name-style": {"style_regex": 4}, + "package-filename": "not-an-object", + "port-name-suffix": {"suffixes": [1, 2]}, + }}}})); + // Nothing was accepted, and every refusal says which entry and why. + assert!(found.lint_options.is_empty(), "{:?}", found.lint_options); + let warnings = found.lint_option_warnings.join("\n"); + for wanted in [ + "line-length.length", + "must be between", + "has no option `len`", + "unknown rule `no-such-rule`", + "takes no options", + "not a valid pattern", + "unsupported escape `\\b`", + "expects a pattern, found an integer", + "package-filename is not an object", + "port-name-suffix.suffixes", + ] { + assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}"); + } + // ... and the rest of the settings survived the bad object. + assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE); +} + +/// `lucisv.lint.waivers` is a list of paths, taken as written: this module +/// has no filesystem to check them against, and whether a file exists or +/// parses is answered where it is read. TODO §39. +#[test] +fn the_waivers_setting_is_a_list_of_paths_taken_as_written() { + let found = settings(json!({"lucisv": {"lint": { + "waivers": ["project.waiver", "/abs/other.waiver", 7, null] + }}})); + assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]); + assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty()); + // Wrong-typed altogether: the whole list is "no opinion", never a + // guess, exactly as `select` and `exclude` are. + for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] { + assert!( + settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(), + "waivers {bad} must be ignored" + ); + } + // A changed list republishes, for the reason a changed option does. + let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}})); + let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}})); + assert_ne!(lint_selection(&one), lint_selection(&two)); +} + +/// A settings payload with no options object is exactly today's +/// behaviour: every rule reads its own default. +#[test] +fn no_options_object_means_every_default() { + for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] { + let found = settings(payload); + assert!(found.lint_options.is_empty()); + assert!(found.lint_option_warnings.is_empty()); + assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default"); + } +} + +#[test] +fn the_default_vscode_payload_is_no_opinion_about_anything() { + // Every setting at its `package.json` default: nulls and an empty + // list, which must leave today's behaviour exactly unchanged. + // The two ghost-text settings are the defaults that are not "no + // opinion" — both default to `true`, and `None` resolves to the same + // thing. + let found = settings(vscode_payload(json!(null), json!(null), json!([]))); + assert_eq!( + found, + ClientSettings { + inline_templates: Some(true), + inline_instantiation: Some(true), + inline_keywords: Some(true), + auto_end: Some(true), + ..Default::default() + }, + "the only difference from silence must be the settings whose \ + default is not null" + ); +} + +#[test] +fn inline_templates_is_a_boolean_and_nothing_else() { + let found = settings(json!({ "lucisv": { "inlineTemplates": false } })); + assert_eq!(found.inline_templates, Some(false)); + let found = settings(json!({ "lucisv": { "inlineTemplates": true } })); + assert_eq!(found.inline_templates, Some(true)); + // Absence is not `false`: the feature is on unless a client says no. + assert_eq!(settings(json!({ "lucisv": {} })).inline_templates, None); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "inlineTemplates": bad } })); + assert_eq!(found.inline_templates, None, "inlineTemplates {bad} must be ignored"); + } +} + +#[test] +fn inline_instantiation_is_a_boolean_and_nothing_else() { + let found = settings(json!({ "lucisv": { "inlineInstantiation": false } })); + assert_eq!(found.inline_instantiation, Some(false)); + let found = settings(json!({ "lucisv": { "inlineInstantiation": true } })); + assert_eq!(found.inline_instantiation, Some(true)); + // Absence is not `false`: the feature is on unless a client says no. + assert_eq!(settings(json!({ "lucisv": {} })).inline_instantiation, None); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "inlineInstantiation": bad } })); + assert_eq!(found.inline_instantiation, None, "inlineInstantiation {bad} ignored"); + } + // The two ghost settings are independent: one off leaves the other on. + let found = settings(json!({ "lucisv": { "inlineInstantiation": false } })); + assert_eq!(found.inline_templates, None, "the templates setting is untouched"); +} + +#[test] +fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() { + let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } })); + assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false))); + let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } })); + assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true))); + // Absence is not `false`: both are on unless a client says no. + let found = settings(json!({ "lucisv": {} })); + assert_eq!((found.inline_keywords, found.auto_end), (None, None)); + for bad in [json!("false"), json!(0), json!(null), json!([false])] { + let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } })); + assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored"); + } + // Independent of the template ghosts: one off leaves the other alone. + let found = settings(json!({ "lucisv": { "inlineKeywords": false } })); + assert_eq!(found.inline_templates, None, "the templates setting is untouched"); +} + +#[test] +fn format_on_save_is_off_until_a_client_asks_for_it() { + assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save); + assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save); + // Absence is off: the hook runs on every save of every buffer, and a + // server that formatted uninvited would fight the editor's own + // format-on-save. + assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence"); + for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] { + let found = settings(json!({ "lucisv": { "formatOnSave": bad } })); + assert!(!found.format_on_save, "formatOnSave {bad} must be ignored"); + } +} + +#[test] +fn a_populated_payload_is_read_whole() { + let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"]))); + assert_eq!(found.line_length, Some(120)); + assert_eq!(found.indent, Some(4)); + assert_eq!(found.exclude, vec!["vendor".to_string(), "*_gen.sv".to_string()]); +} + +#[test] +fn a_payload_without_our_section_says_nothing() { + assert_eq!(settings(json!({ "someOtherServer": { "indent": 4 } })), Default::default()); + assert_eq!(settings(json!(null)), Default::default(), "the `settings: null` form"); + assert_eq!(settings(json!({})), Default::default()); +} + +#[test] +fn a_missing_key_is_not_an_opinion() { + // A hand-written Neovim `settings` table names only what it cares + // about; the keys it leaves out must stay silent, not become 0. + let found = settings(json!({ "lucisv": { "indent": 4 } })); + assert_eq!(found.indent, Some(4)); + assert_eq!(found.line_length, None); + assert!(found.exclude.is_empty()); +} + +#[test] +fn out_of_range_numbers_are_ignored() { + for bad in [json!(0), json!(9), json!(100), json!(-1)] { + let found = settings(json!({ "lucisv": { "indent": bad } })); + assert_eq!(found.indent, None, "indent {bad} must be ignored"); + } + for bad in [json!(0), json!(39), json!(401), json!(-40)] { + let found = settings(json!({ "lucisv": { "lineLength": bad } })); + assert_eq!(found.line_length, None, "lineLength {bad} must be ignored"); + } +} + +#[test] +fn the_range_edges_are_accepted() { + let found = settings(json!({ "lucisv": { "indent": 1, "lineLength": 40 } })); + assert_eq!((found.indent, found.line_length), (Some(1), Some(40))); + let found = settings(json!({ "lucisv": { "indent": 8, "lineLength": 400 } })); + assert_eq!((found.indent, found.line_length), (Some(8), Some(400))); +} + +#[test] +fn wrong_types_are_ignored_rather_than_coerced() { + for bad in [json!("4"), json!(true), json!([4]), json!({ "n": 4 }), json!(4.5)] { + let found = settings(json!({ "lucisv": { "indent": bad, "lineLength": bad } })); + assert_eq!(found.indent, None, "indent {bad} must be ignored"); + assert_eq!(found.line_length, None, "lineLength {bad} must be ignored"); + } +} + +#[test] +fn an_exclude_that_is_not_a_list_of_strings_contributes_nothing() { + assert!(settings(json!({ "lucisv": { "exclude": "vendor" } })).exclude.is_empty()); + assert!(settings(json!({ "lucisv": { "exclude": 3 } })).exclude.is_empty()); + assert!(settings(json!({ "lucisv": { "exclude": null } })).exclude.is_empty()); + // A mixed array keeps the strings and drops the rest. + let found = settings(json!({ "lucisv": { "exclude": ["ok", 3, null, "fine"] } })); + assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]); +} + +#[test] +fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() { + // The whole point of `from_section`: the pull answers the section's + // contents, the push nests them one level deeper, and every rule + // about ranges, types and defaults must be the one set of rules. + let section = json!({ + "lineLength": 120, "indent": 4, "exclude": ["vendor"], + "filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true + }); + assert_eq!(from_section(§ion), settings(json!({ "lucisv": section }))); + // ...including the rejections. + let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" }); + assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk }))); + assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections"); +} + +#[test] +fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() { + // A client that cannot provide the section must answer `null`, per + // spec — and one that answers something absurd instead must cost the + // user no more than one that answered nothing. + for answer in [ + json!(null), + json!({}), + json!("lucisv"), + json!(7), + json!([1, 2]), + json!({ "lucisv": { "indent": 4 } }), + ] { + assert_eq!( + from_section(&answer), + ClientSettings::default(), + "the answer {answer} must resolve to the defaults" + ); + } +} + +#[test] +fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() { + // `{"settings": null}` is what a modern `vscode-languageclient` + // sends: "something changed, ask me". Applying it as a payload would + // silently reset every setting the user had pulled. + assert!(says_nothing(&json!(null))); + assert!(says_nothing(&json!({}))); + assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } }))); + // A legacy push that syncs some *other* server's section is still a + // push: it carries a payload, and this server's answer to it — no + // opinion about anything — is what it has always been. + assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } }))); + // Neither an array nor a scalar is the client saying "ask me"; both + // are junk, and junk goes down the push path where `from_payload` + // drops it. + assert!(!says_nothing(&json!([]))); + assert!(!says_nothing(&json!(""))); +} + +#[test] +fn the_section_constant_is_the_key_the_parser_reads() { + // The pull asks for `SECTION` by name and the push nests under it. A + // constant that drifted from the parser would make every pulled + // setting silently invisible. + let found = from_payload(&json!({ SECTION: { "indent": 4 } })); + assert_eq!(found.indent, Some(4)); + assert_eq!(SECTION, "lucisv"); +} + +#[test] +fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() { + // The bounds above are copied from `lucisv_core::config`, which exports + // no constant for them. Rather than trust the copy, ask the real + // parser: every edge this module accepts must parse, and every value + // it rejects must be rejected there too. If `lucisv.toml` ever widens a + // range, this fails and says so. + let ok = |text: &str| lucisv_core::config::parse(text).is_ok(); + assert!(ok("indent = 1") && ok("indent = 8"), "the indent edges"); + assert!(!ok("indent = 0") && !ok("indent = 9"), "just outside indent"); + assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges"); + assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length"); +} + +/// `lucisv.lint.select` / `lucisv.lint.ignore` nest like every other dotted +/// id, and carry only names the rule registry knows. +#[test] +fn the_lint_selection_is_read_and_validated() { + let read = settings(json!({"lucisv": {"lint": { + "select": ["unused-signal", "no-tabs"], + "ignore": ["no-tabs"], + }}})); + assert_eq!(read.lint_select, vec!["unused-signal", "no-tabs"]); + assert_eq!(read.lint_ignore, vec!["no-tabs"]); + + // A name the registry does not know is dropped, not an error: a push + // is JSON on a socket, and one typo must not cost every diagnostic. + let typo = settings(json!({"lucisv": {"lint": { + "select": ["unused-signal", "unusedsignal", 7, null], + "ignore": "no-tabs", + }}})); + assert_eq!(typo.lint_select, vec!["unused-signal"]); + assert!(typo.lint_ignore.is_empty(), "an array is required"); + + // Absent, or absent-shaped, is "no opinion". + assert!(settings(json!({"lucisv": {}})).lint_select.is_empty()); + assert!(settings(json!({"lucisv": {"lint": 3}})).lint_ignore.is_empty()); + assert!(ClientSettings::default().lint_select.is_empty()); +} + +/// The pull door reads the same keys as the push door — the property the +/// whole module is built on, asserted for the new keys too. +#[test] +fn a_pull_reads_the_lint_selection_the_same_way() { + let pulled = from_section(&json!({"lint": {"ignore": ["unused-signal"]}})); + assert_eq!(pulled.lint_ignore, vec!["unused-signal"]); + assert_eq!(pulled, settings(json!({"lucisv": {"lint": {"ignore": ["unused-signal"]}}}))); +} + +/// The rule names the settings accept are the ones `lucisv check` accepts: +/// one registry, not a list copied into a schema. +#[test] +fn the_accepted_rule_names_are_the_registrys() { + for rule in vlog_linter::all_rules() { + let read = settings(json!({"lucisv": {"lint": {"ignore": [rule.name()]}}})); + assert_eq!(read.lint_ignore, vec![rule.name()], "{}", rule.name()); + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/tests/incremental.rs b/crates/lucisv_server/src/state/tests/incremental.rs index c5c205e..c7a151c 100644 --- a/crates/lucisv_server/src/state/tests/incremental.rs +++ b/crates/lucisv_server/src/state/tests/incremental.rs @@ -163,7 +163,7 @@ fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() { /// numbers rather than asserting one. The numbers themselves are in /// `docs/features/incremental-index/README.md`. #[test] -#[ignore] +#[ignore = "perf measurement over corpus/, printed not asserted; run with --ignored --nocapture"] fn qa_perf_one_file_against_the_whole_rebuild() { let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); if !corpus.is_dir() { diff --git a/crates/lucisv_server/src/tokens.rs b/crates/lucisv_server/src/tokens.rs index 69cacf1..37d4cc2 100644 --- a/crates/lucisv_server/src/tokens.rs +++ b/crates/lucisv_server/src/tokens.rs @@ -490,1047 +490,6 @@ fn split_lines(text: &str, span: TextRange) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use crate::state::Workspace; - use lsp_types::Uri; - use std::str::FromStr; - use vlog_semantic::WorkspaceIndex; - - /// Analyze `text` as an open buffer and hand the document to `f`. - fn with_document(text: &str, f: impl FnOnce(&Document) -> T) -> T { - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - f(ws.document(&uri).expect("open")) - } - - /// The whole buffer's tokens, as they go on the wire. - fn tokens_of(text: &str) -> Vec { - with_document(text, semantic_tokens) - } - - /// The tokens a range answer carries. - fn ranged(text: &str, range: Range) -> Vec { - with_document(text, |doc| semantic_tokens_in_range(doc, range)) - } - - /// Decode the delta encoding back to absolute (line, start, len, type). - fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> { - let (mut line, mut start) = (0u32, 0u32); - data.iter() - .map(|t| { - line += t.delta_line; - start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start }; - (line, start, t.length, t.token_type, t.token_modifiers_bitset) - }) - .collect() - } - - fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> { - decode(&tokens_of(text)) - } - - /// A range, spelled the way a test reads best. - fn range(from: (u32, u32), to: (u32, u32)) -> Range { - Range { - start: Position { line: from.0, character: from.1 }, - end: Position { line: to.0, character: to.1 }, - } - } - - #[test] - fn keywords_numbers_and_strings_are_classified() { - let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n"); - assert!(out - .iter() - .any(|&(l, c, _, t, _)| l == 0 && c == 0 && t == Highlight::Keyword as u32)); - assert!(out.iter().any(|&(.., t, _)| t == Highlight::Number as u32)); - assert!(out.iter().any(|&(.., t, _)| t == Highlight::String as u32)); - // Punctuation is never emitted. - assert!(out.iter().all(|&(_, _, len, ..)| len > 0)); - } - - #[test] - fn a_module_name_is_a_class_and_carries_the_declaration_modifier() { - let out = decoded("module top;\nendmodule\n"); - let name = out.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("the name `top`"); - assert_eq!(name.2, 3); - assert_eq!(name.3, Highlight::Class as u32); - assert_eq!(name.4, DECLARATION, "a declaration is marked as one"); - } - - #[test] - fn a_parameter_use_takes_its_declarations_type() { - let out = decoded("module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n"); - let uses: Vec<_> = - out.iter().filter(|&&(.., t, _)| t == Highlight::Parameter as u32).copied().collect(); - assert_eq!(uses.len(), 2, "the declaration and the use"); - assert_eq!(uses[0].4, DECLARATION); - assert_eq!(uses[1].4, 0, "a use is not a declaration"); - } - - #[test] - fn a_macro_usage_and_a_directive_are_both_macro() { - let out = decoded("`define W 8\nmodule m;\n wire [`W-1:0] a;\nendmodule\n"); - let macros: Vec<_> = - out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect(); - assert_eq!(macros.len(), 2, "the `define line and the `W usage"); - assert_eq!(macros[0].0, 0, "the directive"); - assert_eq!(macros[1].0, 2, "the usage"); - } - - #[test] - fn comments_are_emitted_including_the_last_one_in_the_file() { - let out = decoded("// first\nmodule m;\nendmodule\n// last\n"); - let comments: Vec<_> = - out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect(); - assert_eq!(comments.len(), 2, "a trailing comment rides the EOF token"); - assert_eq!(comments[0].0, 0); - assert_eq!(comments[1].0, 3); - } - - /// QA (fix-round re-verification): `collect_trivia` became `collect`, - /// folding two callers' duplicated classify-and-push into one function - /// that pushes a token's own piece *between* its leading comments and its - /// trailing one. A single token flanked by both is the shape that - /// exercises every branch of that function on one token, and `flatten`'s - /// stable sort means the exact byte offsets have to be right regardless - /// of the order `collect` happened to push them in. - #[test] - fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() { - let text = "/* lead */\nwire /* mid */ a;\n"; - let out = decoded(text); - let comment = |n: usize| { - out.iter() - .filter(|&&(.., t, _)| t == Highlight::Comment as u32) - .nth(n) - .copied() - .unwrap_or_else(|| panic!("comment {n} missing in {out:?}")) - }; - // Line 0: "/* lead */" is 10 bytes, all ASCII. - assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0)); - // Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14 - // (9 bytes), `a` at 15. - let keyword = out - .iter() - .find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32) - .copied() - .expect("the `wire` keyword"); - assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0)); - assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0)); - let ident = out - .iter() - .find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32) - .copied() - .expect("the `a` identifier"); - // `a` is a real declaration in this fragment's full semantics. - assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION)); - } - - #[test] - fn no_token_ever_spans_a_line_break() { - let text = "/* a\n b\n c */\nmodule m;\nendmodule\n"; - let out = decoded(text); - let comments: Vec<_> = - out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect(); - assert_eq!(comments.len(), 3, "one piece per line of the block comment"); - assert_eq!(comments.iter().map(|c| c.0).collect::>(), vec![0, 1, 2]); - } - - #[test] - fn a_continued_define_is_split_per_line_too() { - let out = decoded( - "`define FF(q, d) \\\n always_ff @(posedge clk) q <= d;\nmodule m;\nendmodule\n", - ); - let macros: Vec<_> = - out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect(); - assert_eq!(macros.len(), 2, "two physical lines, two pieces"); - assert_eq!(macros[0].0, 0); - assert_eq!(macros[1].0, 1); - } - - #[test] - fn lengths_are_utf16_units_not_bytes() { - // The comment is `// é 🎉` — 2 + 1 + 1 + 1 + 2 = 7 UTF-16 units, but - // 3 + 2 + 1 + 4 = 10 bytes. A byte-based server reports 10 and the - // highlight bleeds past the end of the line. - let out = decoded("// é 🎉\nmodule m;\nendmodule\n"); - let comment = - out.iter().find(|&&(.., t, _)| t == Highlight::Comment as u32).expect("comment"); - assert_eq!(comment.1, 0); - assert_eq!(comment.2, 7, "UTF-16 units"); - } - - #[test] - fn tokens_come_out_sorted_so_the_deltas_are_never_negative() { - let out = decoded("module m; // trailing\n wire a; /* mid */ wire b;\nendmodule\n"); - for pair in out.windows(2) { - let (a, b) = (pair[0], pair[1]); - assert!((a.0, a.1) <= (b.0, b.1), "out of order: {a:?} then {b:?}"); - } - } - - #[test] - fn a_file_that_does_not_lex_yields_no_tokens() { - let out = decoded("module m; /* unterminated\n"); - assert!(out.is_empty()); - } - - #[test] - fn splitting_a_span_with_no_newline_is_the_span() { - assert_eq!(split_lines("abc", TextRange::new(0, 3)), vec![TextRange::new(0, 3)]); - assert_eq!( - split_lines("a\nb", TextRange::new(0, 3)), - vec![TextRange::new(0, 1), TextRange::new(2, 3)] - ); - } - - // ------------------------------------------------------------------ - // `semanticTokens/range` - // ------------------------------------------------------------------ - - /// Four lines, every one of them carrying tokens. - const FOUR_LINES: &str = - "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n"; - - #[test] - fn a_range_covering_everything_is_the_full_answer() { - let full = tokens_of(FOUR_LINES); - assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full); - } - - #[test] - fn a_range_answer_re_encodes_from_the_start_of_the_document() { - // The whole point of the re-encoding: a range answer is a - // self-contained `SemanticTokens`, so its first token's deltas are - // absolute — a client that pasted the slice out of the full answer - // would draw line 2's tokens on line 0. - let data = ranged(FOUR_LINES, range((2, 0), (3, 0))); - let first = data.first().expect("line 2 has tokens"); - assert_eq!(first.delta_line, 2, "absolute from the document start"); - assert_eq!(first.delta_start, 2, "the `wire` keyword's own column"); - assert_eq!( - decode(&data), - decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::>(), - "the same tokens the full answer puts on that line" - ); - } - - #[test] - fn an_empty_range_covers_no_characters_and_so_no_tokens() { - // Collapsed on a token, which is the tempting case to get wrong: a - // zero-width range draws nothing, so it must answer nothing. - assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty()); - assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty()); - } - - #[test] - fn a_range_that_starts_mid_token_keeps_that_token_whole() { - // The client asked which tokens to draw, not where to cut them — - // and a length trimmed to the range would be a lie about the source. - let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4))); - assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]); - } - - #[test] - fn a_range_touching_no_token_is_empty() { - // Wholly inside the whitespace of a line, and wholly past the file. - assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty()); - assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty()); - } - - #[test] - fn a_range_answer_never_carries_a_token_from_outside_it() { - let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0)))); - assert!(!inside.is_empty(), "premise: line 1 has tokens"); - assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}"); - } - - /// The range/full agreement, on files nobody wrote to exercise it: for a - /// window of whole lines, the range answer must decode to exactly the - /// tokens the full answer puts on those lines. Stated line-wise rather - /// than with the handler's own overlap test, so the two are independent. - /// Skipped when `corpus/` is not checked out, like every other corpus - /// test in this crate. - #[test] - fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() { - let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let files = - [corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")]; - let mut windows_checked = 0; - for path in files { - let Ok(text) = std::fs::read_to_string(&path) else { - eprintln!("{} not checked out — skipping", path.display()); - continue; - }; - let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default()); - let full = decode(&semantic_tokens(&doc)); - assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display()); - let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0); - // Forty-line windows, the size an editor's viewport request is. - let mut from = 0; - while from <= last { - let to = from + 40; - let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0)))); - let expected: Vec<_> = - full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect(); - assert_eq!(window, expected, "{}: lines {from}..{to}", path.display()); - windows_checked += 1; - from = to; - } - } - assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}"); - } - - /// The legend's indices are the wire contract, so the three kinds added - /// on 2026-09-01 take existing highlights rather than new token types - /// (`docs/features/interface-semantics/README.md`). Pinned so a later - /// round that wants an `interface` token type has to *append* it — and - /// notice it is doing so. - #[test] - fn the_new_kinds_reuse_the_legend_rather_than_growing_it() { - assert_eq!(token_types().len(), 14, "the legend is a wire contract"); - assert_eq!(symbol_type(SymbolKind::Interface), Highlight::Class); - assert_eq!(symbol_type(SymbolKind::Modport), Highlight::Class); - assert_eq!(symbol_type(SymbolKind::Clocking), Highlight::Variable); - - let src = "interface bus_if;\nendinterface\n"; - let name = decode(&tokens_of(src)) - .into_iter() - .find(|&(line, col, ..)| line == 0 && col == 10) - .expect("the interface's name"); - assert_eq!(name.3, Highlight::Class as u32); - } - - // ------------------------------------------------------------------ - // the large-file fast path's window - // ------------------------------------------------------------------ - - /// The classes a plain identifier can take once `Semantics` has spoken. - /// A fast-path buffer has no `Semantics`, so every one of them is - /// `variable` there — the one difference between the two paths, and the - /// one this normalization folds away so the rest can be compared. - fn coarse(ty: u32) -> u32 { - let refined = [ - Highlight::Namespace, - Highlight::Class, - Highlight::Type, - Highlight::EnumMember, - Highlight::Parameter, - Highlight::Variable, - Highlight::Property, - Highlight::Function, - ]; - match refined.iter().any(|&r| r as u32 == ty) { - true => Highlight::Variable as u32, - false => ty, - } - } - - /// Decoded tokens with identifier refinement and AST-only punctuation - /// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared - /// against the full pipeline. - fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> { - let positions = full.positions(); - decode(data) - .into_iter() - .filter(|&(line, character, ..)| { - let at = positions.offset(Position { line, character }); - !full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol) - }) - .map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))) - .collect() - } - - /// Whether any construct in `doc` crosses `offset` — a block comment, a - /// continued `` `define``, a multi-line macro call. A window boundary - /// inside one of those is exactly where the fast path is *documented* to - /// disagree, so the agreement property excludes them rather than - /// pretending they do not exist. - fn crosses(doc: &Document, offset: u32) -> bool { - doc.tokens.iter().any(|token| { - let spans = token - .leading - .iter() - .map(|c| c.span) - .chain(token.trailing.iter().map(|c| c.span)) - .chain(std::iter::once(token.span)); - spans.into_iter().any(|span| span.start < offset && offset < span.end) - }) - } - - /// **The agreement anchor.** For a window no multi-line construct reaches - /// into, the fast path's answer is the full pipeline's answer — same - /// spans, same lengths, same classes. Run over real corpus files, in the - /// forty-line windows an editor asks for. - #[test] - fn the_window_lexer_answers_what_the_full_pipeline_answers() { - let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let files = [ - corpus.join("picorv32/picorv32.v"), - corpus.join("common_cells/src/fifo_v3.sv"), - corpus.join("common_cells/src/rr_arb_tree.sv"), - ]; - let (mut compared, mut skipped) = (0, 0); - for path in files { - let Ok(text) = std::fs::read_to_string(&path) else { - eprintln!("{} not checked out — skipping", path.display()); - continue; - }; - let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default()); - let fast = Document::large(Some(path.clone()), text); - assert!(!full.tokens.is_empty(), "{}: the premise", path.display()); - assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open"); - let lines = full.line_index.line_count(); - let mut from = 0; - while from < lines { - let to = (from + 40).min(lines); - let window = range((from, 0), (to, 0)); - // The two boundaries in bytes: the start of the first line and - // the end of the last line the window lexes. - let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start); - let end = - full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end); - if crosses(&full, start) || crosses(&full, end) { - skipped += 1; - from = to; - continue; - } - assert_eq!( - coarsely(&full, &semantic_tokens_in_window(&fast, window)), - coarsely(&full, &semantic_tokens_in_range(&full, window)), - "{}: lines {from}..{to}", - path.display() - ); - compared += 1; - from = to; - } - } - assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})"); - // The excluded windows are a small minority; if they ever became the - // majority the property would be vacuous. - assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}"); - } - - #[test] - fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() { - let text = "module m;\n wire a;\n wire b;\nendmodule\n"; - let doc = Document::large(None, text.to_string()); - let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0))); - let first = data.first().expect("line 2 has tokens"); - assert_eq!(first.delta_line, 2, "encoded from the start of the document"); - assert_eq!(first.delta_start, 2, "the `wire` keyword's own column"); - assert!(decode(&data).iter().all(|&(line, ..)| line == 2)); - } - - #[test] - fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() { - // The one documented difference: nothing analyzed the buffer, so the - // module name is not a `class` and carries no `declaration` bit. - let text = "module top;\nendmodule\n"; - let doc = Document::large(None, text.to_string()); - let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0)))); - let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`"); - assert_eq!(name.3, Highlight::Variable as u32); - assert_eq!(name.4, 0); - } - - #[test] - fn a_fast_path_window_never_carries_a_token_from_outside_the_range() { - let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; - let doc = Document::large(None, text.to_string()); - let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0)))); - assert!(!inside.is_empty(), "premise: line 2 has tokens"); - assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}"); - } - - /// QA (fix-round re-verification): the load-bearing claim behind the - /// walker's restart-on-backwards-offset behaviour is that a window's tail - /// comment genuinely arrives at `flatten` *after* every token in byte - /// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window` - /// pushes `window.comments` ahead of the token loop). This reproduces that - /// exact shape through the real request path — a long declaration line - /// followed by a banner comment that never closes — and checks two - /// things: that the comment really is a byte-order tail relative to every - /// token (the premise the walker's reset exists for), and that every - /// token's and the comment's own position, once decoded off the wire, - /// matches what `Positions::position` would say for the same offset — - /// i.e. the single mid-window restart the out-of-order comment forces - /// does not corrupt anything that comes after it. - #[test] - fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() { - let mut text = String::from("wire "); - for n in 0..500 { - text.push_str(&format!("a{n},")); - } - text.push_str("last;\n"); - let declaration_line_len = text.len() as u32; - text.push_str("/* a banner that never closes\n"); - let doc = Document::large(None, text.clone()); - - // The final `within` filter re-checks the *exact* requested LSP - // range (not the whole-line window `large::window` snapped to), so - // the end has to reach past the comment's own start on line 1 for it - // to survive onto the wire at all. - let window_range = range((0, 0), (1, 50)); - let window = crate::large::window(&doc, window_range); - assert!(!window.tokens.is_empty(), "premise: the declaration line lexed"); - assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment"); - let comment_span = window.comments[0]; - let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token"); - assert!( - comment_span.start >= declaration_line_len, - "premise: the comment opens on the second line, after every token byte-wise" - ); - assert!( - comment_span.start >= last_token_end, - "premise: the out-of-order shape this test targets — the comment \ - collected before the tokens in `pieces` has the higher byte offset" - ); - - let positions = doc.positions(); - let decoded = decode(&semantic_tokens_in_window(&doc, window_range)); - assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32)); - // Punctuation (`,`, `;`) is deliberately not classified at all, so it - // never reaches `pieces` — only the tokens `classify` keeps are - // expected on the wire. - let empty = HashMap::new(); - for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) { - let expected = positions.position(token.span.start); - let found = decoded - .iter() - .find(|&&(line, start, ..)| line == expected.line && start == expected.character); - assert!( - found.is_some(), - "token at byte {} expected at {expected:?}, not found in {decoded:?}", - token.span.start - ); - } - let comment_expected = positions.position(comment_span.start); - assert!( - decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line - && start == comment_expected.character - && ty == Highlight::Comment as u32), - "comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}", - comment_span.start - ); - } - - // ------------------------------------------------------------------ - // `semanticTokens/full/delta` - // ------------------------------------------------------------------ - - /// The flat `u32` array the wire actually carries — what an edit's - /// `start` and `deleteCount` index into. - fn flat(tokens: &[SemanticToken]) -> Vec { - tokens - .iter() - .flat_map(|t| { - [t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset] - }) - .collect() - } - - /// Apply the edits exactly as a client does: in order, by index, on the - /// flat array. Deliberately shares no code with `delta`. - fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec { - let mut data = old.to_vec(); - for edit in edits { - let start = edit.start as usize; - let end = start + edit.delete_count as usize; - let inserted = flat(edit.data.as_deref().unwrap_or_default()); - data.splice(start..end, inserted); - } - data - } - - /// The invariant: applying what the server sent reproduces the new token - /// list exactly. Returns the edits so a test can also say how many. - fn reconstructs(before: &str, after: &str) -> Vec { - let (old, new) = (tokens_of(before), tokens_of(after)); - let edits = delta(&old, &new); - assert_eq!( - apply_edits(&flat(&old), &edits), - flat(&new), - "the edits must reconstruct the new data:\n{before:?}\n{after:?}" - ); - edits - } - - const MODULE: &str = "module m;\n wire a;\nendmodule\n"; - - #[test] - fn an_unchanged_buffer_produces_no_edits_at_all() { - assert!(reconstructs(MODULE, MODULE).is_empty()); - } - - #[test] - fn an_append_at_the_end_is_one_edit_that_deletes_nothing() { - let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n"); - assert_eq!(edits.len(), 1); - assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}"); - } - - #[test] - fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() { - let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE); - assert_eq!(edits.len(), 1); - assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}"); - } - - #[test] - fn a_change_in_the_middle_leaves_the_ends_alone() { - let edits = reconstructs( - "module m;\n wire a;\n wire b;\nendmodule\n", - "module m;\n logic a;\n wire b;\nendmodule\n", - ); - assert_eq!(edits.len(), 1); - assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}"); - } - - #[test] - fn a_complete_replacement_is_one_edit_over_everything() { - let edits = reconstructs(MODULE, "`define W 8\n"); - assert_eq!(edits.len(), 1); - assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}"); - } - - #[test] - fn a_buffer_that_stops_lexing_deletes_every_token_and_back() { - // Mid-keystroke reality: an unterminated block comment has no tokens - // at all, and the next keystroke brings them all back. - let broken = "module m;\n wire a; /* unterminated\n"; - assert!(tokens_of(broken).is_empty(), "the premise"); - reconstructs(MODULE, broken); - reconstructs(broken, MODULE); - } - - #[test] - fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() { - reconstructs(MODULE, ""); - reconstructs("", MODULE); - assert!(reconstructs("", "").is_empty()); - } - - /// A token, for the shapes that are about the algorithm rather than about - /// Verilog. - fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken { - SemanticToken { - delta_line, - delta_start, - length, - token_type: Highlight::Keyword as u32, - token_modifiers_bitset: 0, - } - } - - #[test] - fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() { - // old = [A, B, A], new = [A]. The prefix claims the leading A; a - // suffix counted over the *whole* lists would claim the trailing one - // — the same token twice — and `new[prefix..new.len() - suffix]` - // would then run backwards. Counting the suffix over what the prefix - // left is the cap, and this is the shape that proves it. - let (a, b) = (token(0, 0, 1), token(1, 0, 2)); - let old = vec![a, b, a]; - let new = vec![a]; - let edits = delta(&old, &new); - assert_eq!(apply_edits(&flat(&old), &edits), flat(&new)); - - // And the mirror: growing into a repeating list. - let edits = delta(&new, &old); - assert_eq!(apply_edits(&flat(&new), &edits), flat(&old)); - - // The fully periodic case, where every token equals every other. - let old = vec![a, a, a, a, a]; - let new = vec![a, a, a]; - let edits = delta(&old, &new); - assert_eq!(apply_edits(&flat(&old), &edits), flat(&new)); - } - - #[test] - fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() { - // Identical lines encode to identical tokens — the delta encoding is - // relative, so line 2 and line 3 of this buffer are byte-for-byte the - // same five numbers. Deleting one of them is the overlap shape above, - // reached without constructing anything by hand. - let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n"; - let one = "module m;\n wire a;\nendmodule\n"; - let data = tokens_of(three); - assert_eq!(data[2], data[4], "the premise: the encoding really does repeat"); - reconstructs(three, one); - reconstructs(one, three); - } - - #[test] - fn an_edits_indices_count_numbers_and_not_tokens() { - // The off-by-five that silently corrupts a client's cache: `start` - // and `deleteCount` index the flat array, so both are five times a - // token index. - let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n"); - assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}"); - assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS); - } - - // ------------------------------------------------------------------ - // randomized sweep - // ------------------------------------------------------------------ - - /// A fixed-seed linear congruential generator — deterministic randomness - /// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses. - struct Lcg(u64); - - impl Lcg { - fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - self.0 >> 33 - } - - fn below(&mut self, n: u64) -> u64 { - self.next() % n.max(1) - } - } - - /// Lines a module body can be built from — repeats included, because - /// repeats are what make the prefix and suffix fight over a token. - const BODY: [&str; 8] = [ - " wire a;", - " wire a;", - " localparam W = 8;", - " // a comment", - " assign a = b & c;", - " always_ff @(posedge clk) q <= d;", - " /* block */", - " wire [W-1:0] bus;", - ]; - - fn buffer(rng: &mut Lcg) -> String { - let mut text = String::from("module m;\n"); - for _ in 0..rng.below(9) { - text.push_str(BODY[rng.below(BODY.len() as u64) as usize]); - text.push('\n'); - } - text.push_str("endmodule\n"); - text - } - - #[test] - fn every_pair_of_real_buffers_round_trips_through_its_delta() { - let mut rng = Lcg(0x5eed); - for _ in 0..300 { - let (before, after) = (buffer(&mut rng), buffer(&mut rng)); - reconstructs(&before, &after); - reconstructs(&after, &before); - } - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): independent verification of the delta round-trip - // and the range boundaries, on a code path that shares nothing with - // the dev's own `apply_edits`/`reconstructs` helpers above. - // ------------------------------------------------------------------ - - /// QA's own applier: unlike `apply_edits`, this never touches the flat - /// `u32` array — it walks `SemanticToken`s and slices by hand instead of - /// calling `Vec::splice`. It also asserts the `FIELDS` division is exact, - /// which is a second, independent check of the "five times a token - /// index" claim (`an_edits_indices_count_numbers_and_not_tokens`). - fn independent_apply( - old: &[SemanticToken], - edits: &[SemanticTokensEdit], - ) -> Vec { - let mut data = old.to_vec(); - for edit in edits { - assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}"); - assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}"); - let start = (edit.start / FIELDS) as usize; - let deleted = (edit.delete_count / FIELDS) as usize; - let mut rebuilt = Vec::with_capacity(data.len()); - rebuilt.extend_from_slice(&data[..start]); - if let Some(inserted) = &edit.data { - rebuilt.extend_from_slice(inserted); - } - rebuilt.extend_from_slice(&data[start + deleted..]); - data = rebuilt; - } - data - } - - /// Same invariant as `reconstructs`, checked with QA's applier instead of - /// the dev's. - fn reconstructs_independently(before: &str, after: &str) -> Vec { - let (old, new) = (tokens_of(before), tokens_of(after)); - let edits = delta(&old, &new); - assert_eq!( - independent_apply(&old, &edits), - new, - "QA reconstruction failed:\n{before:?}\n{after:?}" - ); - edits - } - - #[test] - fn qa_the_two_independently_written_appliers_never_disagree() { - // The dev's applier works on the flat `u32` array; QA's works on - // `SemanticToken`s and never calls `Vec::splice`. Run both over the - // same edits and the same inputs and demand they land on the same - // place — and on the truth. - let mut rng = Lcg(0xC0FFEE); - for _ in 0..200 { - let (before, after) = (buffer(&mut rng), buffer(&mut rng)); - let (old, new) = (tokens_of(&before), tokens_of(&after)); - let edits = delta(&old, &new); - let via_flat = apply_edits(&flat(&old), &edits); - let via_tokens = flat(&independent_apply(&old, &edits)); - assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}"); - assert_eq!(via_tokens, flat(&new)); - } - } - - #[test] - fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() { - let module = "module m;\n wire a;\n wire b;\nendmodule\n"; - // Both ends change at once, middle stays: prefix and suffix both - // trim to non-trivial amounts. - reconstructs_independently( - module, - "`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n", - ); - // Middle only. - reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n"); - // Identical. - reconstructs_independently(module, module); - // Complete replacement: nothing in common. - reconstructs_independently(module, "`define totally different 1\n"); - // Old empty, new empty. - reconstructs_independently("", module); - reconstructs_independently(module, ""); - assert!(reconstructs_independently("", "").is_empty()); - // Single-token file, both directions and against itself. - const SINGLE: &str = "// only one token\n"; - assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token"); - reconstructs_independently(SINGLE, module); - reconstructs_independently(module, SINGLE); - reconstructs_independently(SINGLE, SINGLE); - } - - /// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own - /// seed. - struct Xorshift64(u64); - - impl Xorshift64 { - fn next(&mut self) -> u64 { - let mut x = self.0; - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - self.0 = x; - x - } - - fn below(&mut self, n: u64) -> u64 { - self.next() % n.max(1) - } - } - - /// A pool that does not overlap the dev's `BODY`: it adds a block - /// comment that spans lines, a continued `` `define``, and a generate - /// block — pieces whose token *count* changes non-locally, not just - /// whose content does. - const QA_BODY: [&str; 9] = [ - " wire a;", - " wire a;", - " localparam W = 4;", - " // a trailing comment", - " assign a = b ^ c;", - " /* a block\n comment spanning lines */", - " `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;", - " generate\n if (W > 1) wire c;\n endgenerate", - " wire [W-1:0] bus;", - ]; - - fn qa_buffer(rng: &mut Xorshift64) -> String { - let mut text = String::from("module m;\n"); - for _ in 0..rng.below(9) { - text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]); - text.push('\n'); - } - text.push_str("endmodule\n"); - text - } - - #[test] - fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() { - let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678); - for _ in 0..300 { - let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng)); - reconstructs_independently(&before, &after); - reconstructs_independently(&after, &before); - } - } - - #[test] - fn qa_a_range_ending_mid_token_keeps_that_token_whole() { - // Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`: - // the overlap guard must be symmetric at the far boundary too. - let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3))); - assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]); - } - - #[test] - fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() { - // Not an empty *line* (already covered by - // `a_range_touching_no_token_is_empty`) — whitespace, plus an - // unemitted `=`, between two real tokens on the same line. - let text = "module m;\n assign a = b;\nendmodule\n"; - // "a" is the single character at column 9 (ends at 10); "b" starts - // at column 17. Columns 11..16 are wholly inside that gap. - let data = ranged(text, range((1, 11), (1, 16))); - assert!(decode(&data).is_empty(), "{:?}", decode(&data)); - } - - #[test] - fn qa_a_reversed_range_is_total_and_answers_nothing() { - // start > end is not a shape any client should send, but `within`'s - // guard (`range.start >= range.end`) is symmetric to it: this must - // not panic, and must answer empty exactly like a zero-width range. - let data = ranged(FOUR_LINES, range((3, 0), (1, 0))); - assert!(decode(&data).is_empty(), "{:?}", decode(&data)); - } - - // ------------------------------------------------------------------ - // module instantiation and `#(...)` parameter-list highlighting - // ------------------------------------------------------------------ - - fn named_tokens(text: &str) -> Vec<(String, u32, u32)> { - with_document(text, |doc| { - let pos = doc.positions(); - decode(&semantic_tokens(doc)) - .into_iter() - .map(|(line, character, len, ty, mods)| { - let start = pos.offset(Position { line, character }) as usize; - let end = pos.offset(Position { line, character: character + len }) as usize; - (doc.text[start..end].to_string(), ty, mods) - }) - .collect() - }) - } - - #[test] - fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() { - let src = "\ -module top #( - parameter int DATA_W = 32 -) ( - input logic clk, - input logic rst_ni -); - logic [DATA_W-1:0] data_q; - pkg::uart_core #( - .BAUD_DIV (EXT_DIV), - .WIDTH (DATA_W), - .DEPTH (16) - ) u_uart ( - .clk_i (clk), - .rst_ni, - .data_o (data_q), - .* - ); - assign data_q = u_uart.tx_data; -endmodule -"; - let out = named_tokens(src); - let find_nth = |word: &str, n: usize| { - out.iter() - .filter(|(w, ..)| w == word) - .nth(n) - .cloned() - .unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}")) - }; - - // Both `#` tokens (header parameter port list and instantiation overrides) - // share `Parameter`, while `(` and `)` are never emitted. - assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0)); - assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")")); - - // Scoped module name: `pkg` is Namespace, `uart_core` is Class. - assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0)); - assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0)); - - // Parameter overrides: `.` and parameter names share `Parameter` with `#`, - // as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number. - assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0)); - assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0)); - - // Instance declaration and hierarchical use both highlight as `Function`. - let fn_ty = Highlight::Function as u32; - assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION)); - assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0)); - - // Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`, - // while connected signals (`clk`, `data_q`) stay `Variable`. - assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0)); - assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0)); - assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0)); - assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0)); - assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0)); - assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0)); - assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0)); - } - - #[test] - fn delay_hashes_are_never_classified_as_parameters() { - let src = "\ -module m; - wire #5 a; - assign #(1:2:3) a = 1'b0; - and #(2, 3) g0 (y, a, a); - initial #10 $finish; -endmodule -"; - let out = named_tokens(src); - assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}"); - assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION))); - } - - #[test] - fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() { - let src = "\ -module m; - sub #( - .WIDTH( - ) u0 ( - .clk_i( - .rst_ni(rst_n) - ); -endmodule -"; - let out = named_tokens(src); - assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0))); - assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0))); - assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0))); - assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION))); - assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0))); - assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0))); - assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0))); - reconstructs(MODULE, src); - reconstructs(src, MODULE); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/tokens/tests.rs b/crates/lucisv_server/src/tokens/tests.rs new file mode 100644 index 0000000..5e27e13 --- /dev/null +++ b/crates/lucisv_server/src/tokens/tests.rs @@ -0,0 +1,1034 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::state::Workspace; +use lsp_types::Uri; +use std::str::FromStr; +use vlog_semantic::WorkspaceIndex; + +/// Analyze `text` as an open buffer and hand the document to `f`. +fn with_document(text: &str, f: impl FnOnce(&Document) -> T) -> T { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + f(ws.document(&uri).expect("open")) +} + +/// The whole buffer's tokens, as they go on the wire. +fn tokens_of(text: &str) -> Vec { + with_document(text, semantic_tokens) +} + +/// The tokens a range answer carries. +fn ranged(text: &str, range: Range) -> Vec { + with_document(text, |doc| semantic_tokens_in_range(doc, range)) +} + +/// Decode the delta encoding back to absolute (line, start, len, type). +fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> { + let (mut line, mut start) = (0u32, 0u32); + data.iter() + .map(|t| { + line += t.delta_line; + start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start }; + (line, start, t.length, t.token_type, t.token_modifiers_bitset) + }) + .collect() +} + +fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> { + decode(&tokens_of(text)) +} + +/// A range, spelled the way a test reads best. +fn range(from: (u32, u32), to: (u32, u32)) -> Range { + Range { + start: Position { line: from.0, character: from.1 }, + end: Position { line: to.0, character: to.1 }, + } +} + +#[test] +fn keywords_numbers_and_strings_are_classified() { + let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n"); + assert!(out.iter().any(|&(l, c, _, t, _)| l == 0 && c == 0 && t == Highlight::Keyword as u32)); + assert!(out.iter().any(|&(.., t, _)| t == Highlight::Number as u32)); + assert!(out.iter().any(|&(.., t, _)| t == Highlight::String as u32)); + // Punctuation is never emitted. + assert!(out.iter().all(|&(_, _, len, ..)| len > 0)); +} + +#[test] +fn a_module_name_is_a_class_and_carries_the_declaration_modifier() { + let out = decoded("module top;\nendmodule\n"); + let name = out.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("the name `top`"); + assert_eq!(name.2, 3); + assert_eq!(name.3, Highlight::Class as u32); + assert_eq!(name.4, DECLARATION, "a declaration is marked as one"); +} + +#[test] +fn a_parameter_use_takes_its_declarations_type() { + let out = decoded("module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n"); + let uses: Vec<_> = + out.iter().filter(|&&(.., t, _)| t == Highlight::Parameter as u32).copied().collect(); + assert_eq!(uses.len(), 2, "the declaration and the use"); + assert_eq!(uses[0].4, DECLARATION); + assert_eq!(uses[1].4, 0, "a use is not a declaration"); +} + +#[test] +fn a_macro_usage_and_a_directive_are_both_macro() { + let out = decoded("`define W 8\nmodule m;\n wire [`W-1:0] a;\nendmodule\n"); + let macros: Vec<_> = + out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect(); + assert_eq!(macros.len(), 2, "the `define line and the `W usage"); + assert_eq!(macros[0].0, 0, "the directive"); + assert_eq!(macros[1].0, 2, "the usage"); +} + +#[test] +fn comments_are_emitted_including_the_last_one_in_the_file() { + let out = decoded("// first\nmodule m;\nendmodule\n// last\n"); + let comments: Vec<_> = + out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect(); + assert_eq!(comments.len(), 2, "a trailing comment rides the EOF token"); + assert_eq!(comments[0].0, 0); + assert_eq!(comments[1].0, 3); +} + +/// QA (fix-round re-verification): `collect_trivia` became `collect`, +/// folding two callers' duplicated classify-and-push into one function +/// that pushes a token's own piece *between* its leading comments and its +/// trailing one. A single token flanked by both is the shape that +/// exercises every branch of that function on one token, and `flatten`'s +/// stable sort means the exact byte offsets have to be right regardless +/// of the order `collect` happened to push them in. +#[test] +fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() { + let text = "/* lead */\nwire /* mid */ a;\n"; + let out = decoded(text); + let comment = |n: usize| { + out.iter() + .filter(|&&(.., t, _)| t == Highlight::Comment as u32) + .nth(n) + .copied() + .unwrap_or_else(|| panic!("comment {n} missing in {out:?}")) + }; + // Line 0: "/* lead */" is 10 bytes, all ASCII. + assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0)); + // Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14 + // (9 bytes), `a` at 15. + let keyword = out + .iter() + .find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32) + .copied() + .expect("the `wire` keyword"); + assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0)); + assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0)); + let ident = out + .iter() + .find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32) + .copied() + .expect("the `a` identifier"); + // `a` is a real declaration in this fragment's full semantics. + assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION)); +} + +#[test] +fn no_token_ever_spans_a_line_break() { + let text = "/* a\n b\n c */\nmodule m;\nendmodule\n"; + let out = decoded(text); + let comments: Vec<_> = + out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect(); + assert_eq!(comments.len(), 3, "one piece per line of the block comment"); + assert_eq!(comments.iter().map(|c| c.0).collect::>(), vec![0, 1, 2]); +} + +#[test] +fn a_continued_define_is_split_per_line_too() { + let out = + decoded("`define FF(q, d) \\\n always_ff @(posedge clk) q <= d;\nmodule m;\nendmodule\n"); + let macros: Vec<_> = + out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect(); + assert_eq!(macros.len(), 2, "two physical lines, two pieces"); + assert_eq!(macros[0].0, 0); + assert_eq!(macros[1].0, 1); +} + +#[test] +fn lengths_are_utf16_units_not_bytes() { + // The comment is `// é 🎉` — 2 + 1 + 1 + 1 + 2 = 7 UTF-16 units, but + // 3 + 2 + 1 + 4 = 10 bytes. A byte-based server reports 10 and the + // highlight bleeds past the end of the line. + let out = decoded("// é 🎉\nmodule m;\nendmodule\n"); + let comment = out.iter().find(|&&(.., t, _)| t == Highlight::Comment as u32).expect("comment"); + assert_eq!(comment.1, 0); + assert_eq!(comment.2, 7, "UTF-16 units"); +} + +#[test] +fn tokens_come_out_sorted_so_the_deltas_are_never_negative() { + let out = decoded("module m; // trailing\n wire a; /* mid */ wire b;\nendmodule\n"); + for pair in out.windows(2) { + let (a, b) = (pair[0], pair[1]); + assert!((a.0, a.1) <= (b.0, b.1), "out of order: {a:?} then {b:?}"); + } +} + +#[test] +fn a_file_that_does_not_lex_yields_no_tokens() { + let out = decoded("module m; /* unterminated\n"); + assert!(out.is_empty()); +} + +#[test] +fn splitting_a_span_with_no_newline_is_the_span() { + assert_eq!(split_lines("abc", TextRange::new(0, 3)), vec![TextRange::new(0, 3)]); + assert_eq!( + split_lines("a\nb", TextRange::new(0, 3)), + vec![TextRange::new(0, 1), TextRange::new(2, 3)] + ); +} + +// ------------------------------------------------------------------ +// `semanticTokens/range` +// ------------------------------------------------------------------ + +/// Four lines, every one of them carrying tokens. +const FOUR_LINES: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n"; + +#[test] +fn a_range_covering_everything_is_the_full_answer() { + let full = tokens_of(FOUR_LINES); + assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full); +} + +#[test] +fn a_range_answer_re_encodes_from_the_start_of_the_document() { + // The whole point of the re-encoding: a range answer is a + // self-contained `SemanticTokens`, so its first token's deltas are + // absolute — a client that pasted the slice out of the full answer + // would draw line 2's tokens on line 0. + let data = ranged(FOUR_LINES, range((2, 0), (3, 0))); + let first = data.first().expect("line 2 has tokens"); + assert_eq!(first.delta_line, 2, "absolute from the document start"); + assert_eq!(first.delta_start, 2, "the `wire` keyword's own column"); + assert_eq!( + decode(&data), + decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::>(), + "the same tokens the full answer puts on that line" + ); +} + +#[test] +fn an_empty_range_covers_no_characters_and_so_no_tokens() { + // Collapsed on a token, which is the tempting case to get wrong: a + // zero-width range draws nothing, so it must answer nothing. + assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty()); + assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty()); +} + +#[test] +fn a_range_that_starts_mid_token_keeps_that_token_whole() { + // The client asked which tokens to draw, not where to cut them — + // and a length trimmed to the range would be a lie about the source. + let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4))); + assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]); +} + +#[test] +fn a_range_touching_no_token_is_empty() { + // Wholly inside the whitespace of a line, and wholly past the file. + assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty()); + assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty()); +} + +#[test] +fn a_range_answer_never_carries_a_token_from_outside_it() { + let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0)))); + assert!(!inside.is_empty(), "premise: line 1 has tokens"); + assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}"); +} + +/// The range/full agreement, on files nobody wrote to exercise it: for a +/// window of whole lines, the range answer must decode to exactly the +/// tokens the full answer puts on those lines. Stated line-wise rather +/// than with the handler's own overlap test, so the two are independent. +/// Skipped when `corpus/` is not checked out, like every other corpus +/// test in this crate. +#[test] +fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() { + let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let files = [corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")]; + let mut windows_checked = 0; + for path in files { + let Ok(text) = std::fs::read_to_string(&path) else { + eprintln!("{} not checked out — skipping", path.display()); + continue; + }; + let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default()); + let full = decode(&semantic_tokens(&doc)); + assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display()); + let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0); + // Forty-line windows, the size an editor's viewport request is. + let mut from = 0; + while from <= last { + let to = from + 40; + let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0)))); + let expected: Vec<_> = + full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect(); + assert_eq!(window, expected, "{}: lines {from}..{to}", path.display()); + windows_checked += 1; + from = to; + } + } + assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}"); +} + +/// The legend's indices are the wire contract, so the three kinds added +/// on 2026-09-01 take existing highlights rather than new token types +/// (`docs/features/interface-semantics/README.md`). Pinned so a later +/// round that wants an `interface` token type has to *append* it — and +/// notice it is doing so. +#[test] +fn the_new_kinds_reuse_the_legend_rather_than_growing_it() { + assert_eq!(token_types().len(), 14, "the legend is a wire contract"); + assert_eq!(symbol_type(SymbolKind::Interface), Highlight::Class); + assert_eq!(symbol_type(SymbolKind::Modport), Highlight::Class); + assert_eq!(symbol_type(SymbolKind::Clocking), Highlight::Variable); + + let src = "interface bus_if;\nendinterface\n"; + let name = decode(&tokens_of(src)) + .into_iter() + .find(|&(line, col, ..)| line == 0 && col == 10) + .expect("the interface's name"); + assert_eq!(name.3, Highlight::Class as u32); +} + +// ------------------------------------------------------------------ +// the large-file fast path's window +// ------------------------------------------------------------------ + +/// The classes a plain identifier can take once `Semantics` has spoken. +/// A fast-path buffer has no `Semantics`, so every one of them is +/// `variable` there — the one difference between the two paths, and the +/// one this normalization folds away so the rest can be compared. +fn coarse(ty: u32) -> u32 { + let refined = [ + Highlight::Namespace, + Highlight::Class, + Highlight::Type, + Highlight::EnumMember, + Highlight::Parameter, + Highlight::Variable, + Highlight::Property, + Highlight::Function, + ]; + match refined.iter().any(|&r| r as u32 == ty) { + true => Highlight::Variable as u32, + false => ty, + } +} + +/// Decoded tokens with identifier refinement and AST-only punctuation +/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared +/// against the full pipeline. +fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> { + let positions = full.positions(); + decode(data) + .into_iter() + .filter(|&(line, character, ..)| { + let at = positions.offset(Position { line, character }); + !full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol) + }) + .map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))) + .collect() +} + +/// Whether any construct in `doc` crosses `offset` — a block comment, a +/// continued `` `define``, a multi-line macro call. A window boundary +/// inside one of those is exactly where the fast path is *documented* to +/// disagree, so the agreement property excludes them rather than +/// pretending they do not exist. +fn crosses(doc: &Document, offset: u32) -> bool { + doc.tokens.iter().any(|token| { + let spans = token + .leading + .iter() + .map(|c| c.span) + .chain(token.trailing.iter().map(|c| c.span)) + .chain(std::iter::once(token.span)); + spans.into_iter().any(|span| span.start < offset && offset < span.end) + }) +} + +/// **The agreement anchor.** For a window no multi-line construct reaches +/// into, the fast path's answer is the full pipeline's answer — same +/// spans, same lengths, same classes. Run over real corpus files, in the +/// forty-line windows an editor asks for. +#[test] +fn the_window_lexer_answers_what_the_full_pipeline_answers() { + let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let files = [ + corpus.join("picorv32/picorv32.v"), + corpus.join("common_cells/src/fifo_v3.sv"), + corpus.join("common_cells/src/rr_arb_tree.sv"), + ]; + let (mut compared, mut skipped) = (0, 0); + for path in files { + let Ok(text) = std::fs::read_to_string(&path) else { + eprintln!("{} not checked out — skipping", path.display()); + continue; + }; + let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default()); + let fast = Document::large(Some(path.clone()), text); + assert!(!full.tokens.is_empty(), "{}: the premise", path.display()); + assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open"); + let lines = full.line_index.line_count(); + let mut from = 0; + while from < lines { + let to = (from + 40).min(lines); + let window = range((from, 0), (to, 0)); + // The two boundaries in bytes: the start of the first line and + // the end of the last line the window lexes. + let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start); + let end = full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end); + if crosses(&full, start) || crosses(&full, end) { + skipped += 1; + from = to; + continue; + } + assert_eq!( + coarsely(&full, &semantic_tokens_in_window(&fast, window)), + coarsely(&full, &semantic_tokens_in_range(&full, window)), + "{}: lines {from}..{to}", + path.display() + ); + compared += 1; + from = to; + } + } + assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})"); + // The excluded windows are a small minority; if they ever became the + // majority the property would be vacuous. + assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}"); +} + +#[test] +fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() { + let text = "module m;\n wire a;\n wire b;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0))); + let first = data.first().expect("line 2 has tokens"); + assert_eq!(first.delta_line, 2, "encoded from the start of the document"); + assert_eq!(first.delta_start, 2, "the `wire` keyword's own column"); + assert!(decode(&data).iter().all(|&(line, ..)| line == 2)); +} + +#[test] +fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() { + // The one documented difference: nothing analyzed the buffer, so the + // module name is not a `class` and carries no `declaration` bit. + let text = "module top;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0)))); + let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`"); + assert_eq!(name.3, Highlight::Variable as u32); + assert_eq!(name.4, 0); +} + +#[test] +fn a_fast_path_window_never_carries_a_token_from_outside_the_range() { + let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0)))); + assert!(!inside.is_empty(), "premise: line 2 has tokens"); + assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}"); +} + +/// QA (fix-round re-verification): the load-bearing claim behind the +/// walker's restart-on-backwards-offset behaviour is that a window's tail +/// comment genuinely arrives at `flatten` *after* every token in byte +/// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window` +/// pushes `window.comments` ahead of the token loop). This reproduces that +/// exact shape through the real request path — a long declaration line +/// followed by a banner comment that never closes — and checks two +/// things: that the comment really is a byte-order tail relative to every +/// token (the premise the walker's reset exists for), and that every +/// token's and the comment's own position, once decoded off the wire, +/// matches what `Positions::position` would say for the same offset — +/// i.e. the single mid-window restart the out-of-order comment forces +/// does not corrupt anything that comes after it. +#[test] +fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() { + let mut text = String::from("wire "); + for n in 0..500 { + text.push_str(&format!("a{n},")); + } + text.push_str("last;\n"); + let declaration_line_len = text.len() as u32; + text.push_str("/* a banner that never closes\n"); + let doc = Document::large(None, text.clone()); + + // The final `within` filter re-checks the *exact* requested LSP + // range (not the whole-line window `large::window` snapped to), so + // the end has to reach past the comment's own start on line 1 for it + // to survive onto the wire at all. + let window_range = range((0, 0), (1, 50)); + let window = crate::large::window(&doc, window_range); + assert!(!window.tokens.is_empty(), "premise: the declaration line lexed"); + assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment"); + let comment_span = window.comments[0]; + let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token"); + assert!( + comment_span.start >= declaration_line_len, + "premise: the comment opens on the second line, after every token byte-wise" + ); + assert!( + comment_span.start >= last_token_end, + "premise: the out-of-order shape this test targets — the comment \ + collected before the tokens in `pieces` has the higher byte offset" + ); + + let positions = doc.positions(); + let decoded = decode(&semantic_tokens_in_window(&doc, window_range)); + assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32)); + // Punctuation (`,`, `;`) is deliberately not classified at all, so it + // never reaches `pieces` — only the tokens `classify` keeps are + // expected on the wire. + let empty = HashMap::new(); + for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) { + let expected = positions.position(token.span.start); + let found = decoded + .iter() + .find(|&&(line, start, ..)| line == expected.line && start == expected.character); + assert!( + found.is_some(), + "token at byte {} expected at {expected:?}, not found in {decoded:?}", + token.span.start + ); + } + let comment_expected = positions.position(comment_span.start); + assert!( + decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line + && start == comment_expected.character + && ty == Highlight::Comment as u32), + "comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}", + comment_span.start + ); +} + +// ------------------------------------------------------------------ +// `semanticTokens/full/delta` +// ------------------------------------------------------------------ + +/// The flat `u32` array the wire actually carries — what an edit's +/// `start` and `deleteCount` index into. +fn flat(tokens: &[SemanticToken]) -> Vec { + tokens + .iter() + .flat_map(|t| { + [t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset] + }) + .collect() +} + +/// Apply the edits exactly as a client does: in order, by index, on the +/// flat array. Deliberately shares no code with `delta`. +fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec { + let mut data = old.to_vec(); + for edit in edits { + let start = edit.start as usize; + let end = start + edit.delete_count as usize; + let inserted = flat(edit.data.as_deref().unwrap_or_default()); + data.splice(start..end, inserted); + } + data +} + +/// The invariant: applying what the server sent reproduces the new token +/// list exactly. Returns the edits so a test can also say how many. +fn reconstructs(before: &str, after: &str) -> Vec { + let (old, new) = (tokens_of(before), tokens_of(after)); + let edits = delta(&old, &new); + assert_eq!( + apply_edits(&flat(&old), &edits), + flat(&new), + "the edits must reconstruct the new data:\n{before:?}\n{after:?}" + ); + edits +} + +const MODULE: &str = "module m;\n wire a;\nendmodule\n"; + +#[test] +fn an_unchanged_buffer_produces_no_edits_at_all() { + assert!(reconstructs(MODULE, MODULE).is_empty()); +} + +#[test] +fn an_append_at_the_end_is_one_edit_that_deletes_nothing() { + let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n"); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}"); +} + +#[test] +fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() { + let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}"); +} + +#[test] +fn a_change_in_the_middle_leaves_the_ends_alone() { + let edits = reconstructs( + "module m;\n wire a;\n wire b;\nendmodule\n", + "module m;\n logic a;\n wire b;\nendmodule\n", + ); + assert_eq!(edits.len(), 1); + assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}"); +} + +#[test] +fn a_complete_replacement_is_one_edit_over_everything() { + let edits = reconstructs(MODULE, "`define W 8\n"); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}"); +} + +#[test] +fn a_buffer_that_stops_lexing_deletes_every_token_and_back() { + // Mid-keystroke reality: an unterminated block comment has no tokens + // at all, and the next keystroke brings them all back. + let broken = "module m;\n wire a; /* unterminated\n"; + assert!(tokens_of(broken).is_empty(), "the premise"); + reconstructs(MODULE, broken); + reconstructs(broken, MODULE); +} + +#[test] +fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() { + reconstructs(MODULE, ""); + reconstructs("", MODULE); + assert!(reconstructs("", "").is_empty()); +} + +/// A token, for the shapes that are about the algorithm rather than about +/// Verilog. +fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken { + SemanticToken { + delta_line, + delta_start, + length, + token_type: Highlight::Keyword as u32, + token_modifiers_bitset: 0, + } +} + +#[test] +fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() { + // old = [A, B, A], new = [A]. The prefix claims the leading A; a + // suffix counted over the *whole* lists would claim the trailing one + // — the same token twice — and `new[prefix..new.len() - suffix]` + // would then run backwards. Counting the suffix over what the prefix + // left is the cap, and this is the shape that proves it. + let (a, b) = (token(0, 0, 1), token(1, 0, 2)); + let old = vec![a, b, a]; + let new = vec![a]; + let edits = delta(&old, &new); + assert_eq!(apply_edits(&flat(&old), &edits), flat(&new)); + + // And the mirror: growing into a repeating list. + let edits = delta(&new, &old); + assert_eq!(apply_edits(&flat(&new), &edits), flat(&old)); + + // The fully periodic case, where every token equals every other. + let old = vec![a, a, a, a, a]; + let new = vec![a, a, a]; + let edits = delta(&old, &new); + assert_eq!(apply_edits(&flat(&old), &edits), flat(&new)); +} + +#[test] +fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() { + // Identical lines encode to identical tokens — the delta encoding is + // relative, so line 2 and line 3 of this buffer are byte-for-byte the + // same five numbers. Deleting one of them is the overlap shape above, + // reached without constructing anything by hand. + let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n"; + let one = "module m;\n wire a;\nendmodule\n"; + let data = tokens_of(three); + assert_eq!(data[2], data[4], "the premise: the encoding really does repeat"); + reconstructs(three, one); + reconstructs(one, three); +} + +#[test] +fn an_edits_indices_count_numbers_and_not_tokens() { + // The off-by-five that silently corrupts a client's cache: `start` + // and `deleteCount` index the flat array, so both are five times a + // token index. + let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n"); + assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}"); + assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS); +} + +// ------------------------------------------------------------------ +// randomized sweep +// ------------------------------------------------------------------ + +/// A fixed-seed linear congruential generator — deterministic randomness +/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 >> 33 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n.max(1) + } +} + +/// Lines a module body can be built from — repeats included, because +/// repeats are what make the prefix and suffix fight over a token. +const BODY: [&str; 8] = [ + " wire a;", + " wire a;", + " localparam W = 8;", + " // a comment", + " assign a = b & c;", + " always_ff @(posedge clk) q <= d;", + " /* block */", + " wire [W-1:0] bus;", +]; + +fn buffer(rng: &mut Lcg) -> String { + let mut text = String::from("module m;\n"); + for _ in 0..rng.below(9) { + text.push_str(BODY[rng.below(BODY.len() as u64) as usize]); + text.push('\n'); + } + text.push_str("endmodule\n"); + text +} + +#[test] +fn every_pair_of_real_buffers_round_trips_through_its_delta() { + let mut rng = Lcg(0x5eed); + for _ in 0..300 { + let (before, after) = (buffer(&mut rng), buffer(&mut rng)); + reconstructs(&before, &after); + reconstructs(&after, &before); + } +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): independent verification of the delta round-trip +// and the range boundaries, on a code path that shares nothing with +// the dev's own `apply_edits`/`reconstructs` helpers above. +// ------------------------------------------------------------------ + +/// QA's own applier: unlike `apply_edits`, this never touches the flat +/// `u32` array — it walks `SemanticToken`s and slices by hand instead of +/// calling `Vec::splice`. It also asserts the `FIELDS` division is exact, +/// which is a second, independent check of the "five times a token +/// index" claim (`an_edits_indices_count_numbers_and_not_tokens`). +fn independent_apply(old: &[SemanticToken], edits: &[SemanticTokensEdit]) -> Vec { + let mut data = old.to_vec(); + for edit in edits { + assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}"); + assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}"); + let start = (edit.start / FIELDS) as usize; + let deleted = (edit.delete_count / FIELDS) as usize; + let mut rebuilt = Vec::with_capacity(data.len()); + rebuilt.extend_from_slice(&data[..start]); + if let Some(inserted) = &edit.data { + rebuilt.extend_from_slice(inserted); + } + rebuilt.extend_from_slice(&data[start + deleted..]); + data = rebuilt; + } + data +} + +/// Same invariant as `reconstructs`, checked with QA's applier instead of +/// the dev's. +fn reconstructs_independently(before: &str, after: &str) -> Vec { + let (old, new) = (tokens_of(before), tokens_of(after)); + let edits = delta(&old, &new); + assert_eq!( + independent_apply(&old, &edits), + new, + "QA reconstruction failed:\n{before:?}\n{after:?}" + ); + edits +} + +#[test] +fn qa_the_two_independently_written_appliers_never_disagree() { + // The dev's applier works on the flat `u32` array; QA's works on + // `SemanticToken`s and never calls `Vec::splice`. Run both over the + // same edits and the same inputs and demand they land on the same + // place — and on the truth. + let mut rng = Lcg(0xC0FFEE); + for _ in 0..200 { + let (before, after) = (buffer(&mut rng), buffer(&mut rng)); + let (old, new) = (tokens_of(&before), tokens_of(&after)); + let edits = delta(&old, &new); + let via_flat = apply_edits(&flat(&old), &edits); + let via_tokens = flat(&independent_apply(&old, &edits)); + assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}"); + assert_eq!(via_tokens, flat(&new)); + } +} + +#[test] +fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() { + let module = "module m;\n wire a;\n wire b;\nendmodule\n"; + // Both ends change at once, middle stays: prefix and suffix both + // trim to non-trivial amounts. + reconstructs_independently( + module, + "`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n", + ); + // Middle only. + reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n"); + // Identical. + reconstructs_independently(module, module); + // Complete replacement: nothing in common. + reconstructs_independently(module, "`define totally different 1\n"); + // Old empty, new empty. + reconstructs_independently("", module); + reconstructs_independently(module, ""); + assert!(reconstructs_independently("", "").is_empty()); + // Single-token file, both directions and against itself. + const SINGLE: &str = "// only one token\n"; + assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token"); + reconstructs_independently(SINGLE, module); + reconstructs_independently(module, SINGLE); + reconstructs_independently(SINGLE, SINGLE); +} + +/// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own +/// seed. +struct Xorshift64(u64); + +impl Xorshift64 { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n.max(1) + } +} + +/// A pool that does not overlap the dev's `BODY`: it adds a block +/// comment that spans lines, a continued `` `define``, and a generate +/// block — pieces whose token *count* changes non-locally, not just +/// whose content does. +const QA_BODY: [&str; 9] = [ + " wire a;", + " wire a;", + " localparam W = 4;", + " // a trailing comment", + " assign a = b ^ c;", + " /* a block\n comment spanning lines */", + " `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;", + " generate\n if (W > 1) wire c;\n endgenerate", + " wire [W-1:0] bus;", +]; + +fn qa_buffer(rng: &mut Xorshift64) -> String { + let mut text = String::from("module m;\n"); + for _ in 0..rng.below(9) { + text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]); + text.push('\n'); + } + text.push_str("endmodule\n"); + text +} + +#[test] +fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() { + let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678); + for _ in 0..300 { + let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng)); + reconstructs_independently(&before, &after); + reconstructs_independently(&after, &before); + } +} + +#[test] +fn qa_a_range_ending_mid_token_keeps_that_token_whole() { + // Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`: + // the overlap guard must be symmetric at the far boundary too. + let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3))); + assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]); +} + +#[test] +fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() { + // Not an empty *line* (already covered by + // `a_range_touching_no_token_is_empty`) — whitespace, plus an + // unemitted `=`, between two real tokens on the same line. + let text = "module m;\n assign a = b;\nendmodule\n"; + // "a" is the single character at column 9 (ends at 10); "b" starts + // at column 17. Columns 11..16 are wholly inside that gap. + let data = ranged(text, range((1, 11), (1, 16))); + assert!(decode(&data).is_empty(), "{:?}", decode(&data)); +} + +#[test] +fn qa_a_reversed_range_is_total_and_answers_nothing() { + // start > end is not a shape any client should send, but `within`'s + // guard (`range.start >= range.end`) is symmetric to it: this must + // not panic, and must answer empty exactly like a zero-width range. + let data = ranged(FOUR_LINES, range((3, 0), (1, 0))); + assert!(decode(&data).is_empty(), "{:?}", decode(&data)); +} + +// ------------------------------------------------------------------ +// module instantiation and `#(...)` parameter-list highlighting +// ------------------------------------------------------------------ + +fn named_tokens(text: &str) -> Vec<(String, u32, u32)> { + with_document(text, |doc| { + let pos = doc.positions(); + decode(&semantic_tokens(doc)) + .into_iter() + .map(|(line, character, len, ty, mods)| { + let start = pos.offset(Position { line, character }) as usize; + let end = pos.offset(Position { line, character: character + len }) as usize; + (doc.text[start..end].to_string(), ty, mods) + }) + .collect() + }) +} + +#[test] +fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() { + let src = "\ +module top #( + parameter int DATA_W = 32 +) ( + input logic clk, + input logic rst_ni +); + logic [DATA_W-1:0] data_q; + pkg::uart_core #( + .BAUD_DIV (EXT_DIV), + .WIDTH (DATA_W), + .DEPTH (16) + ) u_uart ( + .clk_i (clk), + .rst_ni, + .data_o (data_q), + .* + ); + assign data_q = u_uart.tx_data; +endmodule +"; + let out = named_tokens(src); + let find_nth = |word: &str, n: usize| { + out.iter() + .filter(|(w, ..)| w == word) + .nth(n) + .cloned() + .unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}")) + }; + + // Both `#` tokens (header parameter port list and instantiation overrides) + // share `Parameter`, while `(` and `)` are never emitted. + assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0)); + assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")")); + + // Scoped module name: `pkg` is Namespace, `uart_core` is Class. + assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0)); + assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0)); + + // Parameter overrides: `.` and parameter names share `Parameter` with `#`, + // as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number. + assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0)); + assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0)); + + // Instance declaration and hierarchical use both highlight as `Function`. + let fn_ty = Highlight::Function as u32; + assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION)); + assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0)); + + // Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`, + // while connected signals (`clk`, `data_q`) stay `Variable`. + assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0)); + assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0)); + assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0)); + assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0)); + assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0)); + assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0)); + assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0)); +} + +#[test] +fn delay_hashes_are_never_classified_as_parameters() { + let src = "\ +module m; + wire #5 a; + assign #(1:2:3) a = 1'b0; + and #(2, 3) g0 (y, a, a); + initial #10 $finish; +endmodule +"; + let out = named_tokens(src); + assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}"); + assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION))); +} + +#[test] +fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() { + let src = "\ +module m; + sub #( + .WIDTH( + ) u0 ( + .clk_i( + .rst_ni(rst_n) + ); +endmodule +"; + let out = named_tokens(src); + assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0))); + assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0))); + assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0))); + assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION))); + assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0))); + assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0))); + assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0))); + reconstructs(MODULE, src); + reconstructs(src, MODULE); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs index d094103..330e9c9 100644 --- a/crates/lucisv_server/src/type_def.rs +++ b/crates/lucisv_server/src/type_def.rs @@ -356,1194 +356,6 @@ fn site(name: &str, window: TextRange) -> Option> { } #[cfg(test)] -mod tests { - use super::*; - use crate::uri::path_to_uri; - use std::fs; - use std::path::PathBuf; - use std::str::FromStr; - // The handler itself no longer reads a `Resolution`; the tests still do, - // to pin *why* an answer came out the way it did. - use vlog_semantic::Resolution; - - fn document(text: &str) -> (Workspace, Uri) { - let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - (ws, uri) - } - - /// The byte offset of the first occurrence of `needle` in `text`. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - /// Every answer as `(line, character)` in the document it was asked of. - fn jumps(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<(u32, u32)> { - type_definition(ws, uri, offset) - .iter() - .map(|l| (l.range.start.line, l.range.start.character)) - .collect() - } - - fn temp_dir(tag: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("lucisv_server_type_{tag}_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("temp dir"); - dir - } - - // ------------------------------------------------------------------ - // casts — `docs/features/comment-slots/README.md` (M11) - // - // The doc comment on `type_name` has always claimed case 2 "is what - // reaches a cast (`state_t'(0)`)". It only became true when `bind_expr` - // started binding the casting type; these pin it. - // ------------------------------------------------------------------ - - #[test] - fn a_cast_reaches_the_typedef_it_names() { - let text = "\ -module m; - typedef logic [1:0] state_t; - logic [1:0] s; - initial s = state_t'(0); -endmodule -"; - let (ws, uri) = document(text); - let cursor = text.rfind("state_t'").expect("the cast") as u32 + 2; - assert_eq!(jumps(&ws, &uri, cursor), vec![(1, 22)], "the `typedef` line's name"); - } - - #[test] - fn a_keyword_cast_asks_nothing_of_the_index() { - let text = "module m;\n initial x = int'(y);\nendmodule\n"; - let (ws, uri) = document(text); - assert!(jumps(&ws, &uri, at(text, "int'") + 1).is_empty(), "`int` declares nothing"); - } - - #[test] - fn a_sized_or_computed_cast_answers_for_its_own_operand() { - // `$bits(t)'(x)` and `(N)'(x)` are widths, not type names: the cursor - // inside them is on an ordinary use, and answers as one. - let text = "\ -module m; - typedef logic [3:0] nib_t; - initial a = $bits(nib_t)'(x); -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "nib_t)") + 1), vec![(1, 22)], "the typedef"); - } - - // ------------------------------------------------------------------ - // in-file types - // ------------------------------------------------------------------ - - #[test] - fn a_block_scoped_typedefs_alias_jumps_one_hop_to_its_type() { - // QA (testbench-mopup, 2026-08-29): the item-level alias hop worked, - // the new statement-level typedef silently answered nothing. Both - // forms now answer through the same alias_site. - let text = "\ -module m; - typedef logic [7:0] byte_t; - initial begin - typedef byte_t word_t; - word_t w; - end -endmodule -"; - let (ws, uri) = document(text); - assert!( - !jumps(&ws, &uri, at(text, "word_t;") + 3).is_empty(), - "the block-scoped alias hops to byte_t instead of answering nothing" - ); - } - - #[test] - fn a_variable_jumps_to_the_typedef_of_its_type() { - let text = "\ -module m; - typedef logic [7:0] byte_t; - byte_t b; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "byte_t b") + 7), [(1, 22)], "the typedef's own name"); - } - - #[test] - fn a_use_of_the_variable_answers_the_same_type() { - // The cursor need not be on the declaration: a use resolves to it - // first, exactly as go-to-definition does. - let text = "\ -module m; - typedef logic [7:0] byte_t; - byte_t b; - assign x = b; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "= b") + 2), [(1, 22)]); - } - - #[test] - fn an_enum_typedef_and_a_struct_typedef_are_both_reachable() { - let text = "\ -module m; - typedef enum logic [1:0] { IDLE, RUN } state_t; - typedef struct packed { logic a; logic b; } pair_t; - state_t s; - pair_t p; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "state_t s") + 8), [(1, 41)], "the enum typedef"); - assert_eq!(jumps(&ws, &uri, at(text, "pair_t p") + 7), [(2, 46)], "the struct typedef"); - } - - #[test] - fn a_class_handle_jumps_to_the_class() { - let text = "\ -class my_cls; -endclass - -module m; - my_cls h; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); - } - - #[test] - fn a_handle_declared_inside_a_method_body_is_reached_too() { - // The declaration is a statement, not a module item, which is the - // whole reason the walk descends into statements. - let text = "\ -class my_cls; -endclass - -class holder; - task run(); - my_cls h; - endtask -endclass -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); - } - - #[test] - fn an_instance_name_jumps_to_the_module_it_instantiates() { - let text = "\ -module sub; -endmodule - -module top; - sub u_sub (.clk(1'b0)); -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "u_sub")), [(0, 7)], "the `sub` declaration"); - } - - #[test] - fn an_interface_instance_and_a_virtual_handle_both_reach_the_interface() { - let text = "\ -interface bus_if; -endinterface - -module m; - bus_if bus (); - virtual bus_if vif; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "bus (")), [(0, 10)], "the instance"); - assert_eq!(jumps(&ws, &uri, at(text, "vif")), [(0, 10)], "the virtual handle"); - } - - #[test] - fn an_interface_port_reaches_its_interface() { - // The interface port is written *first*, with no direction, which is - // how an interface port is normally spelled and what - // `docs/features/ansi-first-port/README.md` made parse. Both - // orderings are asserted: the shape that used to be the only one - // that parsed must keep working. - let text = "\ -interface bus_if; -endinterface - -module m (bus_if bus, input logic clk); -endmodule - -module n (input logic clk, bus_if bus); -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "bus,")), [(0, 10)], "the direction-less first port"); - assert_eq!(jumps(&ws, &uri, at(text, "bus)")), [(0, 10)], "and a later one"); - assert!(type_definition(&ws, &uri, at(text, "clk,")).is_empty(), "`logic` is a built-in"); - } - - #[test] - fn a_modport_qualified_port_reaches_its_interface() { - // `bus_if.mp bus` (IEEE 1800 §25.4): the parser glues the modport - // onto the type name, and `bind_data_type` takes the jump to the - // interface from the half before the dot. - let text = "\ -interface bus_if; - modport mp (input a); -endinterface - -module m (bus_if.mp bus); -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "bus)")), [(0, 10)], "the declarator"); - assert_eq!(jumps(&ws, &uri, at(text, "bus_if.mp")), [(0, 10)], "and the type name itself"); - } - - #[test] - fn a_package_scoped_first_port_reaches_its_typedef() { - let text = "\ -package my_pkg; - typedef enum logic {A, B} state_t; -endpackage - -module m (my_pkg::state_t s, output logic q); -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "s,")), [(1, 28)]); - assert!(type_definition(&ws, &uri, at(text, "q)")).is_empty(), "`logic` is a built-in"); - } - - #[test] - fn a_parameter_and_a_task_argument_are_typed_declarations_like_any_other() { - let text = "\ -package p; - typedef logic [3:0] nib_t; -endpackage - -module m #(parameter p::nib_t N = 0) (); - task run(p::nib_t a); - endtask -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "N = 0")), [(1, 22)], "the header parameter"); - assert_eq!(jumps(&ws, &uri, at(text, "a)")), [(1, 22)], "the task argument"); - } - - // ------------------------------------------------------------------ - // the cursor on the type name itself, and the one-hop rule - // ------------------------------------------------------------------ - - #[test] - fn the_cursor_on_a_type_name_answers_for_that_name() { - // `state_t` in `state_t s;` is the type, so its own declaration is - // the answer — the same location `definition` would give. - let text = "\ -module m; - typedef enum logic { A, B } state_t; - state_t s; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "state_t s")), [(1, 30)]); - } - - #[test] - fn an_alias_chain_is_walked_one_hop_at_a_time() { - // `x` reaches `alias_t`, not `state_t`. The user presses the key - // again for the next hop; nothing here follows the chain. - let text = "\ -module m; - typedef enum logic { A, B } state_t; - typedef state_t alias_t; - alias_t x; -endmodule -"; - let (ws, uri) = document(text); - let alias_line = (2, 18); - let state_line = (1, 30); - assert_eq!(jumps(&ws, &uri, at(text, "alias_t x") + 8), [alias_line], "one hop"); - assert_eq!(jumps(&ws, &uri, at(text, "alias_t x")), [alias_line], "and still one hop"); - assert_eq!( - jumps(&ws, &uri, at(text, "alias_t;")), - [state_line], - "from the alias's own declaration, the next hop" - ); - } - - // ------------------------------------------------------------------ - // nothing to answer - // ------------------------------------------------------------------ - - #[test] - fn a_built_in_type_has_no_declaration_to_jump_to() { - let text = "module m;\n logic a;\n wire [7:0] b;\n int c;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, at(text, "logic a") + 6).is_empty(), "logic"); - assert!(type_definition(&ws, &uri, at(text, "logic a")).is_empty(), "the keyword itself"); - assert!(type_definition(&ws, &uri, at(text, "] b") + 2).is_empty(), "wire"); - assert!(type_definition(&ws, &uri, at(text, "int c") + 4).is_empty(), "int"); - } - - #[test] - fn a_position_on_no_name_at_all_answers_nothing() { - let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, at(text, ";\n")).is_empty(), "a semicolon"); - assert!(type_definition(&ws, &uri, at(text, "endmodule")).is_empty(), "a keyword"); - } - - #[test] - fn a_buffer_the_server_does_not_hold_answers_nothing() { - let ws = Workspace::default(); - let uri = Uri::from_str("file:///rtl/never-opened.sv").expect("uri"); - assert!(type_definition(&ws, &uri, 0).is_empty()); - } - - #[test] - fn a_type_nothing_declares_answers_nothing() { - let text = "module m;\n missing_t a;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, at(text, "missing_t a") + 10).is_empty()); - } - - // ------------------------------------------------------------------ - // across files - // ------------------------------------------------------------------ - - /// A workspace of `(name, text)` files with `which` opened as a buffer. - fn workspace(tag: &str, files: &[(&str, &str)], which: &str) -> (PathBuf, Workspace, Uri) { - let dir = temp_dir(tag); - for (name, text) in files { - fs::write(dir.join(name), text).expect("write"); - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![dir.clone()]); - let path = dir.join(which); - let uri = path_to_uri(&path).expect("uri"); - let text = fs::read_to_string(&path).expect("read"); - ws.set_document(uri.clone(), text); - (dir, ws, uri) - } - - const PKG: &str = "\ -package tdp; - typedef enum logic [1:0] { IDLE, RUN } state_t; -endpackage -"; - - #[test] - fn a_package_qualified_type_resolves_through_the_workspace() { - let top = "module top;\n tdp::state_t s;\nendmodule\n"; - let (dir, ws, uri) = workspace("pkgq", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); - - let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); - assert_eq!((found[0].range.start.line, found[0].range.start.character), (1, 41)); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_imported_type_resolves_through_the_workspace_too() { - // The unqualified spelling: the type name is an external candidate, - // finished by the same overlay `definition` uses. - let top = "module top;\n import tdp::*;\n state_t s;\nendmodule\n"; - let (dir, ws, uri) = workspace("import", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); - - let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); - assert_eq!(found[0].range.start.line, 1); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_interface_declared_in_another_file_is_reached_from_a_port() { - let iface = "interface bus_if;\nendinterface\n"; - let top = "module top (input logic clk, bus_if bus);\n bus_if other ();\nendmodule\n"; - let (dir, ws, uri) = workspace("iface", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); - - for offset in [at(top, "bus)"), at(top, "other")] { - let found = type_definition(&ws, &uri, offset); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); - assert_eq!(found[0].range.start.character, 10, "the interface's name"); - } - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_class_declared_in_another_file_is_reached_from_a_handle() { - let cls = "class my_cls;\nendclass\n"; - let top = "module top;\n my_cls h;\nendmodule\n"; - let (dir, ws, uri) = workspace("xcls", &[("my_cls.sv", cls), ("top.sv", top)], "top.sv"); - - let found = type_definition(&ws, &uri, at(top, "my_cls h") + 7); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("my_cls.sv")).expect("uri")); - assert_eq!(found[0].range.start.character, 6); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_package_of_the_same_name_answers_exactly_as_definition_answers_it() { - // Was `a_package_of_the_same_name_is_not_a_type`, a fence in the - // deleted `indexed_type`: that function filtered the index by kind - // because it *was* a fourth resolution layer and had to justify what - // it looked at. The answer now comes from the one overlay - // `textDocument/definition` uses, whose documented policy is no kind - // filtering — every declaration of the name, never a guess between - // them (`docs/features/workspace-index/README.md`). `thing t;` where - // the workspace's only `thing` is a package is broken source either - // way; giving the same location F12 gives on the same token is the - // honest answer, and disagreeing with F12 here would need the fourth - // layer back. - let pkg = "package thing;\nendpackage\n"; - let top = "module top;\n thing t;\nendmodule\n"; - let (dir, ws, uri) = workspace("pkgtype", &[("thing.sv", pkg), ("top.sv", top)], "top.sv"); - - let offset = at(top, "thing t") + 6; - let found = type_definition(&ws, &uri, offset); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); - assert_eq!(found, nav::definition(&ws, &uri, at(top, "thing t")), "one answer, one layer"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_qualified_name_the_overlay_refused_is_not_retried_against_the_index() { - // A `pkg::missing_t` is an *external candidate* the overlay answered - // with nothing, and a module of that name elsewhere is not what it - // meant. Nothing sweeps the bare tail: `resolve.rs`'s `unit_member` - // never promotes, so the qualifier is never discarded. - let pkg = "package tdp2;\nendpackage\n"; - let decoy = "module missing_t;\nendmodule\n"; - let top = "module top;\n tdp2::missing_t s;\nendmodule\n"; - let files = [("pkg.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; - let (dir, ws, uri) = workspace("refused", &files, "top.sv"); - - assert!(type_definition(&ws, &uri, at(top, "missing_t s") + 10).is_empty()); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_module_declared_twice_returns_both_declarations() { - // The ambiguity policy is `definition`'s, because the answer *is* - // `definition`'s: every candidate, never a guess. - let dup = "module dup;\nendmodule\n"; - let top = "module top;\n dup u (.*);\nendmodule\n"; - let files = [("a.sv", dup), ("b.sv", dup), ("top.sv", top)]; - let (dir, ws, uri) = workspace("ambig", &files, "top.sv"); - - assert_eq!(type_definition(&ws, &uri, at(top, "u (")).len(), 2); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_declaration_inside_a_generate_block_is_reached() { - let text = "\ -module m; - typedef logic t; - generate - if (P) begin : g - t a; - end - endgenerate -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "t a") + 2), [(1, 16)]); - } - - #[test] - fn positions_are_utf16_like_every_other_answer() { - let text = "\ -module m; - typedef logic t; // é 🎉 - t a; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "t a")), [(1, 16)]); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): the `indexed_type` fence, attacked directly. - // ------------------------------------------------------------------ - - #[test] - fn a_class_scoped_type_reference_in_an_extending_class_is_found_cross_file() { - // QA finding (2026-08-26), corpus-spot-check-derived, fixed the same - // day by widening the fence: `resolve.rs`'s `miss` - // (vlog_semantic/src/resolve.rs:201-213) resolves *any* lexical miss - // inside a class body that carries an `extends` clause as - // `Resolution::InheritedCandidate`, never `Resolution::NotFound` — - // unconditionally, whether or not the missing name has anything to do - // with inheritance. `indexed_type` used to fire only on `NotFound`, so - // a cross-file interface/class type used as a member of *any* - // extending class fell through both layers and answered nothing. This - // is not a crafted edge case: it is the real shape of - // corpus/ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv:5,7 - // (`class core_ibex_env_cfg extends uvm_object;` / - // `virtual clk_rst_if ibex_clk_vif;`), i.e. ordinary UVM, where almost - // every class extends something. The resolution is *still* - // `InheritedCandidate` — nothing in `vlog_semantic` changed — and the - // fallback now accepts it. - let iface = "interface bus_if;\nendinterface\n"; - let top = "\ -class base; -endclass -class top extends base; - virtual bus_if h; -endclass -"; - let (dir, ws, uri) = - workspace("extends_gap", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); - - let offset = at(top, "bus_if h") + 2; - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("InheritedCandidate".to_string()), - "still not NotFound: the fence widened, the resolution did not" - ); - let found = type_definition(&ws, &uri, offset); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); - assert_eq!(found[0].range.start.character, 10, "the interface's name"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class() { - // The corpus shape exactly, as a portable fixture: the base class - // (`uvm_object`) is nowhere in this workspace, so the inheritance path - // is not merely unchased but unchaseable, and every member type of the - // class is an `InheritedCandidate` no layer below can place. The two - // interfaces are declared in other files at file scope, which is where - // interfaces live, and both are the answer. - let clk = "interface clk_rst_if;\nendinterface\n"; - let probe = "interface dut_probe_if;\nendinterface\n"; - let cfg = "\ -class env_cfg extends uvm_object; - virtual clk_rst_if clk_vif; - virtual dut_probe_if dut_vif; -endclass -"; - let files = [("clk_rst_if.sv", clk), ("dut_probe_if.sv", probe), ("cfg.sv", cfg)]; - let (dir, ws, uri) = workspace("uvm_shape", &files, "cfg.sv"); - - for (needle, file) in - [("clk_rst_if ", "clk_rst_if.sv"), ("dut_probe_if ", "dut_probe_if.sv")] - { - let found = type_definition(&ws, &uri, at(cfg, needle) + 2); - assert_eq!(found.len(), 1, "{needle}: {found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join(file)).expect("uri")); - assert_eq!(found[0].range.start.character, 10, "the interface's name"); - } - - // The declarator half of the same declaration takes the same hop. - let found = type_definition(&ws, &uri, at(cfg, "clk_vif")); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("clk_rst_if.sv")).expect("uri")); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it() { - // The precedence question the widening raises, answered by reading - // `vlog_semantic` and pinned here. `resolve.rs::lexical` - // (vlog_semantic/src/resolve.rs:39-70) walks `scope.parent` — lexical - // nesting — and never a base class's scope; `miss` (:201-213) records - // the base's *name* and stops, and `resolve_external` - // (vlog_semantic/src/workspace.rs:382-391) only finishes - // `ExternalCandidate`s. So a typedef nested in a base class is - // unreachable to every layer, even when that base is in the same file: - // there is no better answer being displaced here, only an empty one. - // - // And precedence needs no code of its own, now or later: the fallback - // is consulted only after `nav::definition` came back empty, so the day - // `vlog_semantic` does chase an in-file base, this reference becomes - // `Resolution::Resolved`, `nav::definition` answers the nested typedef, - // and `indexed_type` is never reached — the same way the local-genvar - // shadowing test below already works. - let iface = "interface bus_if;\nendinterface\n"; - let top = "\ -class base; - typedef int bus_if; -endclass -class top extends base; - bus_if h; -endclass -"; - let (dir, ws, uri) = - workspace("nested_base", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); - - let offset = at(top, "bus_if h"); - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("InheritedCandidate".to_string()), - "the base's nested typedef is not found lexically, in-file or not" - ); - let found = type_definition(&ws, &uri, offset + 7); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!( - found[0].uri, - path_to_uri(&dir.join("bus_if.sv")).expect("uri"), - "the workspace interface: the only location any layer can produce" - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_non_type_inherited_reference_is_still_never_a_type_site() { - // The structural confinement to type windows has to survive the - // widening: inside an extending class *every* miss is an - // `InheritedCandidate`, including ordinary expression identifiers that - // are genuinely inherited members and have nothing to do with types. - // `indexed_type` is only ever reached with a span `type_name` - // produced, and `site_at` only descends declaration containers, so no - // `Site` is built for an expression statement and the fence is never - // consulted at all. - let dup = "module dup;\nendmodule\n"; - let top = "\ -class base; -endclass -class top extends base; - int x; - function void f(); - x = dup; - endfunction -endclass -"; - let (dir, ws, uri) = - workspace("inherited_expr", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); - - let offset = at(top, "= dup") + 2; - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("InheritedCandidate".to_string()), - "an inherited member, as far as `resolve.rs` knows" - ); - assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_inherited_candidate_answers_only_what_the_workspace_unit_table_holds() { - // Was `the_other_two_fence_conditions_still_hold_under_an_inherited_candidate`. - // The fences moved into `vlog_semantic` and the index: a promoted miss - // is a *unit-table* lookup of a bare name, so a package member is not - // reachable and a qualified name is never swept. Each is re-attacked - // from inside an extending class, where every one of these references - // is an `InheritedCandidate`. - let pkg = "\ -package thing; - typedef logic [3:0] inner_t; -endpackage -"; - let decoy = "module missing_t;\nendmodule\n"; - let top = "\ -class base; -endclass -class top extends base; - thing a; - inner_t b; - thing::missing_t c; -endclass -"; - let files = [("thing.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; - let (dir, ws, uri) = workspace("fence_inherited", &files, "top.sv"); - - // A unit of that name, whatever its kind, is what the workspace has to - // say — the same answer `definition` gives, reached through the - // inherited candidate's own promoted path rather than around it. - assert_eq!( - doc_reference_kind(&ws, &uri, at(top, "thing a")), - Some("InheritedCandidate".to_string()), - "the inherited semantics are untouched by the promotion" - ); - let package = type_definition(&ws, &uri, at(top, "thing a") + 9); - assert_eq!(package.len(), 1, "{package:#?}"); - assert_eq!(package[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); - - // File scope only: `inner_t` is a *member* of `thing`, not a unit, so - // the index's unit table does not hold it and no import brought it in. - assert_eq!( - doc_reference_kind(&ws, &uri, at(top, "inner_t b")), - Some("InheritedCandidate".to_string()) - ); - assert!(type_definition(&ws, &uri, at(top, "inner_t b") + 9).is_empty(), "not file-scope"); - - // A qualified name the overlay already refused stays refused: it is an - // `ExternalCandidate` carrying `thing::missing_t` and nothing else — - // `unit_member` never adds the bare name — so the decoy module of that - // name is not offered. - assert_eq!( - doc_reference_kind(&ws, &uri, at(top, "missing_t c")), - Some("ExternalCandidate".to_string()) - ); - assert!(type_definition(&ws, &uri, at(top, "missing_t c") + 10).is_empty(), "refused"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_local_declaration_of_the_same_name_wins_over_the_workspace_type() { - // `bus_if` is both a workspace interface and, here, a local genvar in - // scope where `bus_if` is written as a type. `vlog_semantic`'s - // `lexical` resolution (`resolve.rs::lexical`) does not filter by - // kind, so the reference resolves *locally* to the genvar and is - // never `Resolution::NotFound` — which means `indexed_type`'s first - // fence condition is never reached, and the wrong workspace jump - // cannot happen. The answer here is the genvar's own declaration - // (`nav::definition`'s answer for the same shadowing, unchanged by - // this feature), not the interface. - let iface = "interface bus_if;\nendinterface\n"; - let top = "\ -module top; - genvar bus_if; - bus_if x; -endmodule -"; - let (dir, ws, uri) = - workspace("shadow", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); - - // The type reference itself — `bus_if`, not the declarator `x` — is - // what the fence inspects. - let type_ref_offset = at(top, "bus_if x"); - assert_eq!( - doc_reference_kind(&ws, &uri, type_ref_offset), - Some("Resolved".to_string()), - "the genvar wins the lexical lookup, so this is never NotFound" - ); - let found = type_definition(&ws, &uri, at(top, "bus_if x") + 7); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, uri, "the genvar is declared in this same file"); - assert_eq!(found[0].range.start.line, 1, "the genvar's own declaration, not the interface"); - - let _ = fs::remove_dir_all(&dir); - } - - /// Which `Resolution` the file's own layer gave the reference at `offset` - /// — used to pin down *why* an answer came out the way it did, rather than - /// only observing the final jump. - fn doc_reference_kind(ws: &Workspace, uri: &Uri, offset: u32) -> Option { - let doc = ws.document(uri)?; - let reference = doc.semantics.reference_at(offset)?; - Some(match reference.resolution { - Resolution::Resolved(_) => "Resolved".to_string(), - Resolution::NotFound => "NotFound".to_string(), - Resolution::InheritedCandidate { .. } => "InheritedCandidate".to_string(), - Resolution::ExternalCandidate { .. } => "ExternalCandidate".to_string(), - }) - } - - #[test] - fn a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site() { - // The promotion fires on type positions only, so such an identifier is - // still a plain `NotFound` and no handler answers it — neither this one - // nor `nav::definition`. Two independent fences, both pinned here: the - // model never offers the coincidence, and this handler's confinement is - // structural anyway (`type_name`'s first and third branches both go - // through `site_at`, which only descends declaration containers — - // `item_site`/`stmt_site` — and an ordinary expression statement is not - // one of them). - let dup = "module dup;\nendmodule\n"; - let top = "module top;\n wire x;\n assign x = dup;\nendmodule\n"; - let (dir, ws, uri) = workspace("exprname", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); - - let offset = at(top, "= dup") + 2; - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("NotFound".to_string()), - "a value-position miss names no unit and is never swept through the unit table" - ); - assert!( - nav::definition(&ws, &uri, offset).is_empty(), - "so F12 answers nothing rather than a same-named module in another file" - ); - assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_promoted_miss_returns_every_workspace_declaration_when_the_name_is_ambiguous() { - // Was `indexed_type_returns_...`: the ambiguity convention is still - // pinned through the promoted-miss path specifically (an unqualified - // lexical miss), which the `Target::Module` ambiguity test does not - // exercise — that one is an external candidate from the start. - let iface = "interface bus_if;\nendinterface\n"; - let top = "module top;\n bus_if bus;\nendmodule\n"; - let files = [("a.sv", iface), ("b.sv", iface), ("top.sv", top)]; - let (dir, ws, uri) = workspace("indexed_ambig", &files, "top.sv"); - - let type_ref_offset = at(top, "bus_if bus"); - assert_eq!( - doc_reference_kind(&ws, &uri, type_ref_offset), - Some("ExternalCandidate".to_string()) - ); - let found = type_definition(&ws, &uri, at(top, "bus_if bus") + 7); - assert_eq!(found.len(), 2, "both interfaces, not a guess: {found:#?}"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_qualified_member_miss_never_falls_back_to_a_bare_name_sweep() { - // Lead fix, 2026-08-26 (QA follow-up finding): `unit_member` can miss - // with the same two spellings the fence accepts — a local package - // that lacks the member — and a bare-name workspace sweep would then - // discard the `pkg::` qualifier and jump to an unrelated declaration - // that merely shares the member's name. The source pointed into - // `pkg`; an answer from anywhere else is a wrong jump, and no answer - // is the honest one. - let other = "typedef logic missing_t;\n"; - let top = "package p;\nendpackage\nmodule top;\n p::missing_t s;\nendmodule\n"; - let files = [("other.sv", other), ("top.sv", top)]; - let (dir, ws, uri) = workspace("qualified_no_sweep", &files, "top.sv"); - - let found = type_definition(&ws, &uri, at(top, "p::missing_t") + 5); - assert!(found.is_empty(), "the qualifier must not be discarded: {found:#?}"); - // The same name unqualified still reaches the workspace type, so the - // guard is about the qualifier, not the name. - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_self_referential_typedef_is_total_and_does_not_loop() { - // `typedef t t;` — the alias and its own type share a name. Nothing - // in this module chases a chain (that is the one-hop rule's whole - // point), so there is no loop to guard against structurally; this - // pins that down operationally: every position on the line answers - // exactly once, promptly, whatever the answer is. - let text = "module m;\n typedef t t;\nendmodule\n"; - let (ws, uri) = document(text); - // No panic, no hang, on the alias name, on the type-of name, or on - // any position in between. - for offset in [at(text, "typedef"), at(text, "t t"), at(text, "t t") + 2, at(text, ";\n")] { - let _ = type_definition(&ws, &uri, offset); - } - } - - #[test] - fn type_definition_on_a_type_name_agrees_exactly_with_definition() { - // The design claim in the feature README ("cursor on a type name - // answers for that name") is that this is *literally* the same - // request `textDocument/definition` would answer at that offset, not - // a coincidentally-equal location built a different way. - let text = "\ -module m; - typedef enum logic { A, B } state_t; - state_t s; -endmodule -"; - let (ws, uri) = document(text); - let offset = at(text, "state_t s"); - assert_eq!(type_definition(&ws, &uri, offset), nav::definition(&ws, &uri, offset)); - } - - #[test] - fn an_inline_anonymous_struct_has_no_type_name_to_jump_to() { - // `struct packed { ... } s;` — the type is written inline, with no - // name of its own, so `DataType::name` is empty and `site()` refuses - // it. Null, not a bogus jump at whatever text happens to sit in the - // window. - let text = "module m;\n struct packed { logic a; } s;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, at(text, "} s") + 2).is_empty(), "the declarator name"); - assert!( - type_definition(&ws, &uri, at(text, "logic a")).is_empty(), - "inside the inline body" - ); - } - - #[test] - fn a_later_declarator_in_a_multi_declarator_line_still_finds_the_type() { - // `state_t a, b, c;` — the window is computed from the *first* - // declarator regardless of which one the cursor is on, because the - // type is written once for the whole list. - let text = "\ -module m; - typedef logic t; - t a, b, c; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!( - jumps(&ws, &uri, at(text, "c;")), - [(1, 16)], - "the cursor on the third declarator" - ); - } - - #[test] - fn var_const_and_signed_qualifiers_do_not_shift_the_type_window() { - // Qualifiers (`DataDecl::qualifiers`) sit textually before the type - // inside the same window this feature scans; they must not be - // mistaken for the type name, and must not shift where it is found. - let text = "\ -module m; - class my_cls; - endclass - const var my_cls h; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(1, 8)]); - } - - #[test] - fn packed_and_unpacked_array_dimensions_do_not_confuse_the_type_match() { - let text = "\ -module m; - typedef logic state_t; - state_t [3:0] x [0:7]; -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "x [0:7]")), [(1, 16)]); - } - - #[test] - fn a_function_arguments_type_is_reached_like_a_task_arguments() { - let text = "\ -package p; - typedef logic [3:0] nib_t; -endpackage - -module m; - function automatic p::nib_t f(p::nib_t a); - return a; - endfunction -endmodule -"; - let (ws, uri) = document(text); - assert_eq!(jumps(&ws, &uri, at(text, "a);")), [(1, 22)], "the function's own argument"); - } - - #[test] - fn a_position_past_the_end_of_the_file_answers_nothing_not_a_panic() { - let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, text.len() as u32 + 5_000).is_empty()); - } - - #[test] - fn a_position_inside_a_comment_answers_nothing() { - let text = "module m;\n // t is not a type here, just a comment\n int a;\nendmodule\n"; - let (ws, uri) = document(text); - assert!(type_definition(&ws, &uri, at(text, "not a type")).is_empty()); - } - - // ------------------------------------------------------------------ - // QA corpus spot-check (2026-08-26). - // - // One `Workspace` is opened once and reused for every probe and every - // file in the full-corpus panic sweep below — `open_roots` indexes the - // whole tree (a one-time cost), and `set_document` only overlays a - // buffer against the index already built, so this is cheap to repeat. - // The first version of this test opened a fresh `Workspace` (and so - // re-indexed all of corpus/ibex) per file in the sweep, which made a - // ~300-file loop re-scan several hundred files each time; that was a - // test-harness bug, not a product one, and is fixed by sharing `ws`. - // ------------------------------------------------------------------ - - #[test] - fn corpus_spot_check_real_uvm_files_no_panic_and_known_jumps() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex"); - if !root.exists() { - eprintln!("corpus not present, skipping"); - return; - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![root.clone()]); - - let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) { - let file = root.join(rel); - let text = fs::read_to_string(&file).unwrap_or_else(|e| panic!("read {rel}: {e}")); - let uri = path_to_uri(&file).expect("uri"); - ws.set_document(uri.clone(), text.clone()); - (uri, text) - }; - - // A genuine, real-world positive control: `core_ibex_tb_top` - // instantiates `clk_rst_if` (declared in a vendored file elsewhere - // in the tree) at module scope, not inside any class — the plain - // cross-file-interface-instance case the feature's design claims to - // solve, exercised on real corpus text rather than a fixture. - let (tb_uri, tb_text) = open(&mut ws, "dv/uvm/core_ibex/tb/core_ibex_tb_top.sv"); - for offset in 0..=tb_text.len() as u32 { - let _ = type_definition(&ws, &tb_uri, offset); // no panic, whole file - } - let found = type_definition(&ws, &tb_uri, at(&tb_text, "clk_rst_if ibex_clk_if") + 2); - assert_eq!(found.len(), 1, "{found:#?}"); - assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); - - // The QA finding of 2026-08-26, now the positive control for its own - // fix, on the real file it was found in rather than only the portable - // fixture above: `core_ibex_env_cfg extends uvm_object`, so every - // otherwise-cross-file type reference inside it — `clk_rst_if`, - // `core_ibex_dut_probe_if`, both real interfaces this same workspace - // indexes — resolves to `InheritedCandidate`, which the widened fence - // now accepts. `scrambling_key_agent_cfg` is different: that class is - // not vendored into this corpus checkout at all, so empty stays the - // correct answer, and it is what keeps the widening from being - // mistaken for "answer something, anything". - let (env_uri, env_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_env_cfg.sv"); - for offset in 0..=env_text.len() as u32 { - let _ = type_definition(&ws, &env_uri, offset); - } - let found = type_definition(&ws, &env_uri, at(&env_text, "clk_rst_if") + 2); - assert_eq!(found.len(), 1, "{found:#?}"); - assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); - let found = type_definition(&ws, &env_uri, at(&env_text, "core_ibex_dut_probe_if ") + 2); - assert_eq!(found.len(), 1, "{found:#?}"); - assert!(found[0].uri.as_str().ends_with("core_ibex_dut_probe_if.sv"), "{found:#?}"); - assert!( - type_definition(&ws, &env_uri, at(&env_text, "scrambling_key_agent_cfg ") + 2) - .is_empty(), - "genuinely not in this corpus checkout, unrelated to the gap" - ); - - let (sb_uri, sb_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_scoreboard.sv"); - for offset in 0..=sb_text.len() as u32 { - let _ = type_definition(&ws, &sb_uri, offset); - } - - // Every small file under corpus/ibex, sharing the one indexed - // workspace: no panic anywhere a real cursor could land. - let mut count = 0; - visit(&root, &mut |path| { - let ext_ok = - matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("svh")); - let Ok(t) = (if ext_ok { fs::read_to_string(path) } else { return }) else { return }; - if t.len() > 4000 { - return; - } - let Some(u) = path_to_uri(path) else { return }; - ws.set_document(u.clone(), t.clone()); - for offset in (0..=t.len() as u32).step_by(3) { - let _ = type_definition(&ws, &u, offset); - } - count += 1; - }); - eprintln!("checked {count} small corpus files, no panic"); - assert!(count > 20, "{count}"); - } - - fn visit(dir: &std::path::Path, f: &mut impl FnMut(&std::path::Path)) { - let Ok(entries) = fs::read_dir(dir) else { return }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - visit(&path, f); - } else { - f(&path); - } - } - } - - // ------------------------------------------------------------------ - // QA fix-round re-attack (2026-08-26) - // ------------------------------------------------------------------ - - #[test] - fn a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type() { - // The dev's precedence test puts the shadowing typedef in the *base* - // class, which `lexical` can never see anyway (it walks `scope.parent`, - // never a base's scope). This puts it directly in the *extending* - // class's own body — the one place `lexical` unambiguously looks first, - // before it ever reaches `miss`/`InheritedCandidate` at all. If lexical - // scoping is doing what it's supposed to, this reference is `Resolved` - // against the local typedef and `indexed_type` is never consulted, so - // the widened fence cannot leak a wrong cross-file jump here. - let iface = "interface bus_if;\nendinterface\n"; - let top = "\ -class base; -endclass -class top extends base; - typedef int bus_if; - bus_if h; -endclass -"; - let (dir, ws, uri) = workspace( - "local_typedef_in_extender", - &[("bus_if.sv", iface), ("top.sv", top)], - "top.sv", - ); - - let offset = at(top, "bus_if h"); - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("Resolved".to_string()), - "lexical finds the class's own typedef before miss ever runs" - ); - let found = type_definition(&ws, &uri, offset + 7); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, uri, "the in-file typedef, not the workspace interface"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did() { - // The fence's kind filter (`Module | Class | Typedef`) was never - // conditioned on which of the two resolutions triggered it, so a - // member-type reference inside an extending class that happens to - // share a name with a workspace *module* should jump there exactly as - // it already would have for a plain top-level `NotFound` reference - // (`a_class_declared_in_another_file_is_reached_from_a_handle`, mutatis - // mutandis for `Module`). Nothing about "module, not class/interface" - // is special-cased in `indexed_type`, so this is a parity check, not a - // new behavior. - let module_file = "module thing;\nendmodule\n"; - let top = "\ -class base; -endclass -class top extends base; - thing h; -endclass -"; - let (dir, ws, uri) = workspace( - "inherited_to_module", - &[("thing.sv", module_file), ("top.sv", top)], - "top.sv", - ); - - let offset = at(top, "thing h"); - assert_eq!( - doc_reference_kind(&ws, &uri, offset), - Some("InheritedCandidate".to_string()), - "member type inside an extending class" - ); - let found = type_definition(&ws, &uri, offset + 3); - assert_eq!(found.len(), 1, "{found:#?}"); - assert_eq!(found[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); - - let _ = fs::remove_dir_all(&dir); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/type_def/tests.rs b/crates/lucisv_server/src/type_def/tests.rs new file mode 100644 index 0000000..0e41d88 --- /dev/null +++ b/crates/lucisv_server/src/type_def/tests.rs @@ -0,0 +1,1173 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use crate::uri::path_to_uri; +use std::fs; +use std::path::PathBuf; +use std::str::FromStr; +// The handler itself no longer reads a `Resolution`; the tests still do, +// to pin *why* an answer came out the way it did. +use vlog_semantic::Resolution; + +fn document(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) +} + +/// The byte offset of the first occurrence of `needle` in `text`. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// Every answer as `(line, character)` in the document it was asked of. +fn jumps(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<(u32, u32)> { + type_definition(ws, uri, offset) + .iter() + .map(|l| (l.range.start.line, l.range.start.character)) + .collect() +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lucisv_server_type_{tag}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir +} + +// ------------------------------------------------------------------ +// casts — `docs/features/comment-slots/README.md` (M11) +// +// The doc comment on `type_name` has always claimed case 2 "is what +// reaches a cast (`state_t'(0)`)". It only became true when `bind_expr` +// started binding the casting type; these pin it. +// ------------------------------------------------------------------ + +#[test] +fn a_cast_reaches_the_typedef_it_names() { + let text = "\ +module m; + typedef logic [1:0] state_t; + logic [1:0] s; + initial s = state_t'(0); +endmodule +"; + let (ws, uri) = document(text); + let cursor = text.rfind("state_t'").expect("the cast") as u32 + 2; + assert_eq!(jumps(&ws, &uri, cursor), vec![(1, 22)], "the `typedef` line's name"); +} + +#[test] +fn a_keyword_cast_asks_nothing_of_the_index() { + let text = "module m;\n initial x = int'(y);\nendmodule\n"; + let (ws, uri) = document(text); + assert!(jumps(&ws, &uri, at(text, "int'") + 1).is_empty(), "`int` declares nothing"); +} + +#[test] +fn a_sized_or_computed_cast_answers_for_its_own_operand() { + // `$bits(t)'(x)` and `(N)'(x)` are widths, not type names: the cursor + // inside them is on an ordinary use, and answers as one. + let text = "\ +module m; + typedef logic [3:0] nib_t; + initial a = $bits(nib_t)'(x); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "nib_t)") + 1), vec![(1, 22)], "the typedef"); +} + +// ------------------------------------------------------------------ +// in-file types +// ------------------------------------------------------------------ + +#[test] +fn a_block_scoped_typedefs_alias_jumps_one_hop_to_its_type() { + // QA (testbench-mopup, 2026-08-29): the item-level alias hop worked, + // the new statement-level typedef silently answered nothing. Both + // forms now answer through the same alias_site. + let text = "\ +module m; + typedef logic [7:0] byte_t; + initial begin + typedef byte_t word_t; + word_t w; + end +endmodule +"; + let (ws, uri) = document(text); + assert!( + !jumps(&ws, &uri, at(text, "word_t;") + 3).is_empty(), + "the block-scoped alias hops to byte_t instead of answering nothing" + ); +} + +#[test] +fn a_variable_jumps_to_the_typedef_of_its_type() { + let text = "\ +module m; + typedef logic [7:0] byte_t; + byte_t b; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "byte_t b") + 7), [(1, 22)], "the typedef's own name"); +} + +#[test] +fn a_use_of_the_variable_answers_the_same_type() { + // The cursor need not be on the declaration: a use resolves to it + // first, exactly as go-to-definition does. + let text = "\ +module m; + typedef logic [7:0] byte_t; + byte_t b; + assign x = b; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "= b") + 2), [(1, 22)]); +} + +#[test] +fn an_enum_typedef_and_a_struct_typedef_are_both_reachable() { + let text = "\ +module m; + typedef enum logic [1:0] { IDLE, RUN } state_t; + typedef struct packed { logic a; logic b; } pair_t; + state_t s; + pair_t p; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "state_t s") + 8), [(1, 41)], "the enum typedef"); + assert_eq!(jumps(&ws, &uri, at(text, "pair_t p") + 7), [(2, 46)], "the struct typedef"); +} + +#[test] +fn a_class_handle_jumps_to_the_class() { + let text = "\ +class my_cls; +endclass + +module m; + my_cls h; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); +} + +#[test] +fn a_handle_declared_inside_a_method_body_is_reached_too() { + // The declaration is a statement, not a module item, which is the + // whole reason the walk descends into statements. + let text = "\ +class my_cls; +endclass + +class holder; + task run(); + my_cls h; + endtask +endclass +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(0, 6)]); +} + +#[test] +fn an_instance_name_jumps_to_the_module_it_instantiates() { + let text = "\ +module sub; +endmodule + +module top; + sub u_sub (.clk(1'b0)); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "u_sub")), [(0, 7)], "the `sub` declaration"); +} + +#[test] +fn an_interface_instance_and_a_virtual_handle_both_reach_the_interface() { + let text = "\ +interface bus_if; +endinterface + +module m; + bus_if bus (); + virtual bus_if vif; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "bus (")), [(0, 10)], "the instance"); + assert_eq!(jumps(&ws, &uri, at(text, "vif")), [(0, 10)], "the virtual handle"); +} + +#[test] +fn an_interface_port_reaches_its_interface() { + // The interface port is written *first*, with no direction, which is + // how an interface port is normally spelled and what + // `docs/features/ansi-first-port/README.md` made parse. Both + // orderings are asserted: the shape that used to be the only one + // that parsed must keep working. + let text = "\ +interface bus_if; +endinterface + +module m (bus_if bus, input logic clk); +endmodule + +module n (input logic clk, bus_if bus); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "bus,")), [(0, 10)], "the direction-less first port"); + assert_eq!(jumps(&ws, &uri, at(text, "bus)")), [(0, 10)], "and a later one"); + assert!(type_definition(&ws, &uri, at(text, "clk,")).is_empty(), "`logic` is a built-in"); +} + +#[test] +fn a_modport_qualified_port_reaches_its_interface() { + // `bus_if.mp bus` (IEEE 1800 §25.4): the parser glues the modport + // onto the type name, and `bind_data_type` takes the jump to the + // interface from the half before the dot. + let text = "\ +interface bus_if; + modport mp (input a); +endinterface + +module m (bus_if.mp bus); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "bus)")), [(0, 10)], "the declarator"); + assert_eq!(jumps(&ws, &uri, at(text, "bus_if.mp")), [(0, 10)], "and the type name itself"); +} + +#[test] +fn a_package_scoped_first_port_reaches_its_typedef() { + let text = "\ +package my_pkg; + typedef enum logic {A, B} state_t; +endpackage + +module m (my_pkg::state_t s, output logic q); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "s,")), [(1, 28)]); + assert!(type_definition(&ws, &uri, at(text, "q)")).is_empty(), "`logic` is a built-in"); +} + +#[test] +fn a_parameter_and_a_task_argument_are_typed_declarations_like_any_other() { + let text = "\ +package p; + typedef logic [3:0] nib_t; +endpackage + +module m #(parameter p::nib_t N = 0) (); + task run(p::nib_t a); + endtask +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "N = 0")), [(1, 22)], "the header parameter"); + assert_eq!(jumps(&ws, &uri, at(text, "a)")), [(1, 22)], "the task argument"); +} + +// ------------------------------------------------------------------ +// the cursor on the type name itself, and the one-hop rule +// ------------------------------------------------------------------ + +#[test] +fn the_cursor_on_a_type_name_answers_for_that_name() { + // `state_t` in `state_t s;` is the type, so its own declaration is + // the answer — the same location `definition` would give. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + state_t s; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "state_t s")), [(1, 30)]); +} + +#[test] +fn an_alias_chain_is_walked_one_hop_at_a_time() { + // `x` reaches `alias_t`, not `state_t`. The user presses the key + // again for the next hop; nothing here follows the chain. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + typedef state_t alias_t; + alias_t x; +endmodule +"; + let (ws, uri) = document(text); + let alias_line = (2, 18); + let state_line = (1, 30); + assert_eq!(jumps(&ws, &uri, at(text, "alias_t x") + 8), [alias_line], "one hop"); + assert_eq!(jumps(&ws, &uri, at(text, "alias_t x")), [alias_line], "and still one hop"); + assert_eq!( + jumps(&ws, &uri, at(text, "alias_t;")), + [state_line], + "from the alias's own declaration, the next hop" + ); +} + +// ------------------------------------------------------------------ +// nothing to answer +// ------------------------------------------------------------------ + +#[test] +fn a_built_in_type_has_no_declaration_to_jump_to() { + let text = "module m;\n logic a;\n wire [7:0] b;\n int c;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "logic a") + 6).is_empty(), "logic"); + assert!(type_definition(&ws, &uri, at(text, "logic a")).is_empty(), "the keyword itself"); + assert!(type_definition(&ws, &uri, at(text, "] b") + 2).is_empty(), "wire"); + assert!(type_definition(&ws, &uri, at(text, "int c") + 4).is_empty(), "int"); +} + +#[test] +fn a_position_on_no_name_at_all_answers_nothing() { + let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, ";\n")).is_empty(), "a semicolon"); + assert!(type_definition(&ws, &uri, at(text, "endmodule")).is_empty(), "a keyword"); +} + +#[test] +fn a_buffer_the_server_does_not_hold_answers_nothing() { + let ws = Workspace::default(); + let uri = Uri::from_str("file:///rtl/never-opened.sv").expect("uri"); + assert!(type_definition(&ws, &uri, 0).is_empty()); +} + +#[test] +fn a_type_nothing_declares_answers_nothing() { + let text = "module m;\n missing_t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "missing_t a") + 10).is_empty()); +} + +// ------------------------------------------------------------------ +// across files +// ------------------------------------------------------------------ + +/// A workspace of `(name, text)` files with `which` opened as a buffer. +fn workspace(tag: &str, files: &[(&str, &str)], which: &str) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let path = dir.join(which); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri.clone(), text); + (dir, ws, uri) +} + +const PKG: &str = "\ +package tdp; + typedef enum logic [1:0] { IDLE, RUN } state_t; +endpackage +"; + +#[test] +fn a_package_qualified_type_resolves_through_the_workspace() { + let top = "module top;\n tdp::state_t s;\nendmodule\n"; + let (dir, ws, uri) = workspace("pkgq", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); + assert_eq!((found[0].range.start.line, found[0].range.start.character), (1, 41)); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_imported_type_resolves_through_the_workspace_too() { + // The unqualified spelling: the type name is an external candidate, + // finished by the same overlay `definition` uses. + let top = "module top;\n import tdp::*;\n state_t s;\nendmodule\n"; + let (dir, ws, uri) = workspace("import", &[("pkg.sv", PKG), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "state_t s") + 8); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("pkg.sv")).expect("uri")); + assert_eq!(found[0].range.start.line, 1); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_interface_declared_in_another_file_is_reached_from_a_port() { + let iface = "interface bus_if;\nendinterface\n"; + let top = "module top (input logic clk, bus_if bus);\n bus_if other ();\nendmodule\n"; + let (dir, ws, uri) = workspace("iface", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + for offset in [at(top, "bus)"), at(top, "other")] { + let found = type_definition(&ws, &uri, offset); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + } + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_class_declared_in_another_file_is_reached_from_a_handle() { + let cls = "class my_cls;\nendclass\n"; + let top = "module top;\n my_cls h;\nendmodule\n"; + let (dir, ws, uri) = workspace("xcls", &[("my_cls.sv", cls), ("top.sv", top)], "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "my_cls h") + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("my_cls.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 6); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_package_of_the_same_name_answers_exactly_as_definition_answers_it() { + // Was `a_package_of_the_same_name_is_not_a_type`, a fence in the + // deleted `indexed_type`: that function filtered the index by kind + // because it *was* a fourth resolution layer and had to justify what + // it looked at. The answer now comes from the one overlay + // `textDocument/definition` uses, whose documented policy is no kind + // filtering — every declaration of the name, never a guess between + // them (`docs/features/workspace-index/README.md`). `thing t;` where + // the workspace's only `thing` is a package is broken source either + // way; giving the same location F12 gives on the same token is the + // honest answer, and disagreeing with F12 here would need the fourth + // layer back. + let pkg = "package thing;\nendpackage\n"; + let top = "module top;\n thing t;\nendmodule\n"; + let (dir, ws, uri) = workspace("pkgtype", &[("thing.sv", pkg), ("top.sv", top)], "top.sv"); + + let offset = at(top, "thing t") + 6; + let found = type_definition(&ws, &uri, offset); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); + assert_eq!(found, nav::definition(&ws, &uri, at(top, "thing t")), "one answer, one layer"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_qualified_name_the_overlay_refused_is_not_retried_against_the_index() { + // A `pkg::missing_t` is an *external candidate* the overlay answered + // with nothing, and a module of that name elsewhere is not what it + // meant. Nothing sweeps the bare tail: `resolve.rs`'s `unit_member` + // never promotes, so the qualifier is never discarded. + let pkg = "package tdp2;\nendpackage\n"; + let decoy = "module missing_t;\nendmodule\n"; + let top = "module top;\n tdp2::missing_t s;\nendmodule\n"; + let files = [("pkg.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; + let (dir, ws, uri) = workspace("refused", &files, "top.sv"); + + assert!(type_definition(&ws, &uri, at(top, "missing_t s") + 10).is_empty()); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_module_declared_twice_returns_both_declarations() { + // The ambiguity policy is `definition`'s, because the answer *is* + // `definition`'s: every candidate, never a guess. + let dup = "module dup;\nendmodule\n"; + let top = "module top;\n dup u (.*);\nendmodule\n"; + let files = [("a.sv", dup), ("b.sv", dup), ("top.sv", top)]; + let (dir, ws, uri) = workspace("ambig", &files, "top.sv"); + + assert_eq!(type_definition(&ws, &uri, at(top, "u (")).len(), 2); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_declaration_inside_a_generate_block_is_reached() { + let text = "\ +module m; + typedef logic t; + generate + if (P) begin : g + t a; + end + endgenerate +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "t a") + 2), [(1, 16)]); +} + +#[test] +fn positions_are_utf16_like_every_other_answer() { + let text = "\ +module m; + typedef logic t; // é 🎉 + t a; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "t a")), [(1, 16)]); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): the `indexed_type` fence, attacked directly. +// ------------------------------------------------------------------ + +#[test] +fn a_class_scoped_type_reference_in_an_extending_class_is_found_cross_file() { + // QA finding (2026-08-26), corpus-spot-check-derived, fixed the same + // day by widening the fence: `resolve.rs`'s `miss` + // (vlog_semantic/src/resolve.rs:201-213) resolves *any* lexical miss + // inside a class body that carries an `extends` clause as + // `Resolution::InheritedCandidate`, never `Resolution::NotFound` — + // unconditionally, whether or not the missing name has anything to do + // with inheritance. `indexed_type` used to fire only on `NotFound`, so + // a cross-file interface/class type used as a member of *any* + // extending class fell through both layers and answered nothing. This + // is not a crafted edge case: it is the real shape of + // corpus/ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv:5,7 + // (`class core_ibex_env_cfg extends uvm_object;` / + // `virtual clk_rst_if ibex_clk_vif;`), i.e. ordinary UVM, where almost + // every class extends something. The resolution is *still* + // `InheritedCandidate` — nothing in `vlog_semantic` changed — and the + // fallback now accepts it. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; +endclass +class top extends base; + virtual bus_if h; +endclass +"; + let (dir, ws, uri) = + workspace("extends_gap", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + let offset = at(top, "bus_if h") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "still not NotFound: the fence widened, the resolution did not" + ); + let found = type_definition(&ws, &uri, offset); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("bus_if.sv")).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_uvm_shaped_member_type_resolves_cross_file_from_an_extending_class() { + // The corpus shape exactly, as a portable fixture: the base class + // (`uvm_object`) is nowhere in this workspace, so the inheritance path + // is not merely unchased but unchaseable, and every member type of the + // class is an `InheritedCandidate` no layer below can place. The two + // interfaces are declared in other files at file scope, which is where + // interfaces live, and both are the answer. + let clk = "interface clk_rst_if;\nendinterface\n"; + let probe = "interface dut_probe_if;\nendinterface\n"; + let cfg = "\ +class env_cfg extends uvm_object; + virtual clk_rst_if clk_vif; + virtual dut_probe_if dut_vif; +endclass +"; + let files = [("clk_rst_if.sv", clk), ("dut_probe_if.sv", probe), ("cfg.sv", cfg)]; + let (dir, ws, uri) = workspace("uvm_shape", &files, "cfg.sv"); + + for (needle, file) in + [("clk_rst_if ", "clk_rst_if.sv"), ("dut_probe_if ", "dut_probe_if.sv")] + { + let found = type_definition(&ws, &uri, at(cfg, needle) + 2); + assert_eq!(found.len(), 1, "{needle}: {found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join(file)).expect("uri")); + assert_eq!(found[0].range.start.character, 10, "the interface's name"); + } + + // The declarator half of the same declaration takes the same hop. + let found = type_definition(&ws, &uri, at(cfg, "clk_vif")); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("clk_rst_if.sv")).expect("uri")); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_in_file_bases_nested_typedef_does_not_beat_the_workspace_type_because_nothing_finds_it() { + // The precedence question the widening raises, answered by reading + // `vlog_semantic` and pinned here. `resolve.rs::lexical` + // (vlog_semantic/src/resolve.rs:39-70) walks `scope.parent` — lexical + // nesting — and never a base class's scope; `miss` (:201-213) records + // the base's *name* and stops, and `resolve_external` + // (vlog_semantic/src/workspace.rs:382-391) only finishes + // `ExternalCandidate`s. So a typedef nested in a base class is + // unreachable to every layer, even when that base is in the same file: + // there is no better answer being displaced here, only an empty one. + // + // And precedence needs no code of its own, now or later: the fallback + // is consulted only after `nav::definition` came back empty, so the day + // `vlog_semantic` does chase an in-file base, this reference becomes + // `Resolution::Resolved`, `nav::definition` answers the nested typedef, + // and `indexed_type` is never reached — the same way the local-genvar + // shadowing test below already works. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; + typedef int bus_if; +endclass +class top extends base; + bus_if h; +endclass +"; + let (dir, ws, uri) = + workspace("nested_base", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + let offset = at(top, "bus_if h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "the base's nested typedef is not found lexically, in-file or not" + ); + let found = type_definition(&ws, &uri, offset + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!( + found[0].uri, + path_to_uri(&dir.join("bus_if.sv")).expect("uri"), + "the workspace interface: the only location any layer can produce" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_non_type_inherited_reference_is_still_never_a_type_site() { + // The structural confinement to type windows has to survive the + // widening: inside an extending class *every* miss is an + // `InheritedCandidate`, including ordinary expression identifiers that + // are genuinely inherited members and have nothing to do with types. + // `indexed_type` is only ever reached with a span `type_name` + // produced, and `site_at` only descends declaration containers, so no + // `Site` is built for an expression statement and the fence is never + // consulted at all. + let dup = "module dup;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + int x; + function void f(); + x = dup; + endfunction +endclass +"; + let (dir, ws, uri) = workspace("inherited_expr", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); + + let offset = at(top, "= dup") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "an inherited member, as far as `resolve.rs` knows" + ); + assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_inherited_candidate_answers_only_what_the_workspace_unit_table_holds() { + // Was `the_other_two_fence_conditions_still_hold_under_an_inherited_candidate`. + // The fences moved into `vlog_semantic` and the index: a promoted miss + // is a *unit-table* lookup of a bare name, so a package member is not + // reachable and a qualified name is never swept. Each is re-attacked + // from inside an extending class, where every one of these references + // is an `InheritedCandidate`. + let pkg = "\ +package thing; + typedef logic [3:0] inner_t; +endpackage +"; + let decoy = "module missing_t;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + thing a; + inner_t b; + thing::missing_t c; +endclass +"; + let files = [("thing.sv", pkg), ("decoy.sv", decoy), ("top.sv", top)]; + let (dir, ws, uri) = workspace("fence_inherited", &files, "top.sv"); + + // A unit of that name, whatever its kind, is what the workspace has to + // say — the same answer `definition` gives, reached through the + // inherited candidate's own promoted path rather than around it. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "thing a")), + Some("InheritedCandidate".to_string()), + "the inherited semantics are untouched by the promotion" + ); + let package = type_definition(&ws, &uri, at(top, "thing a") + 9); + assert_eq!(package.len(), 1, "{package:#?}"); + assert_eq!(package[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); + + // File scope only: `inner_t` is a *member* of `thing`, not a unit, so + // the index's unit table does not hold it and no import brought it in. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "inner_t b")), + Some("InheritedCandidate".to_string()) + ); + assert!(type_definition(&ws, &uri, at(top, "inner_t b") + 9).is_empty(), "not file-scope"); + + // A qualified name the overlay already refused stays refused: it is an + // `ExternalCandidate` carrying `thing::missing_t` and nothing else — + // `unit_member` never adds the bare name — so the decoy module of that + // name is not offered. + assert_eq!( + doc_reference_kind(&ws, &uri, at(top, "missing_t c")), + Some("ExternalCandidate".to_string()) + ); + assert!(type_definition(&ws, &uri, at(top, "missing_t c") + 10).is_empty(), "refused"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_local_declaration_of_the_same_name_wins_over_the_workspace_type() { + // `bus_if` is both a workspace interface and, here, a local genvar in + // scope where `bus_if` is written as a type. `vlog_semantic`'s + // `lexical` resolution (`resolve.rs::lexical`) does not filter by + // kind, so the reference resolves *locally* to the genvar and is + // never `Resolution::NotFound` — which means `indexed_type`'s first + // fence condition is never reached, and the wrong workspace jump + // cannot happen. The answer here is the genvar's own declaration + // (`nav::definition`'s answer for the same shadowing, unchanged by + // this feature), not the interface. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +module top; + genvar bus_if; + bus_if x; +endmodule +"; + let (dir, ws, uri) = workspace("shadow", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + // The type reference itself — `bus_if`, not the declarator `x` — is + // what the fence inspects. + let type_ref_offset = at(top, "bus_if x"); + assert_eq!( + doc_reference_kind(&ws, &uri, type_ref_offset), + Some("Resolved".to_string()), + "the genvar wins the lexical lookup, so this is never NotFound" + ); + let found = type_definition(&ws, &uri, at(top, "bus_if x") + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, uri, "the genvar is declared in this same file"); + assert_eq!(found[0].range.start.line, 1, "the genvar's own declaration, not the interface"); + + let _ = fs::remove_dir_all(&dir); +} + +/// Which `Resolution` the file's own layer gave the reference at `offset` +/// — used to pin down *why* an answer came out the way it did, rather than +/// only observing the final jump. +fn doc_reference_kind(ws: &Workspace, uri: &Uri, offset: u32) -> Option { + let doc = ws.document(uri)?; + let reference = doc.semantics.reference_at(offset)?; + Some(match reference.resolution { + Resolution::Resolved(_) => "Resolved".to_string(), + Resolution::NotFound => "NotFound".to_string(), + Resolution::InheritedCandidate { .. } => "InheritedCandidate".to_string(), + Resolution::ExternalCandidate { .. } => "ExternalCandidate".to_string(), + }) +} + +#[test] +fn a_plain_expression_use_of_a_workspace_module_name_is_never_a_type_site() { + // The promotion fires on type positions only, so such an identifier is + // still a plain `NotFound` and no handler answers it — neither this one + // nor `nav::definition`. Two independent fences, both pinned here: the + // model never offers the coincidence, and this handler's confinement is + // structural anyway (`type_name`'s first and third branches both go + // through `site_at`, which only descends declaration containers — + // `item_site`/`stmt_site` — and an ordinary expression statement is not + // one of them). + let dup = "module dup;\nendmodule\n"; + let top = "module top;\n wire x;\n assign x = dup;\nendmodule\n"; + let (dir, ws, uri) = workspace("exprname", &[("dup.sv", dup), ("top.sv", top)], "top.sv"); + + let offset = at(top, "= dup") + 2; + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("NotFound".to_string()), + "a value-position miss names no unit and is never swept through the unit table" + ); + assert!( + nav::definition(&ws, &uri, offset).is_empty(), + "so F12 answers nothing rather than a same-named module in another file" + ); + assert!(type_definition(&ws, &uri, offset).is_empty(), "not a declaration's type window"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_promoted_miss_returns_every_workspace_declaration_when_the_name_is_ambiguous() { + // Was `indexed_type_returns_...`: the ambiguity convention is still + // pinned through the promoted-miss path specifically (an unqualified + // lexical miss), which the `Target::Module` ambiguity test does not + // exercise — that one is an external candidate from the start. + let iface = "interface bus_if;\nendinterface\n"; + let top = "module top;\n bus_if bus;\nendmodule\n"; + let files = [("a.sv", iface), ("b.sv", iface), ("top.sv", top)]; + let (dir, ws, uri) = workspace("indexed_ambig", &files, "top.sv"); + + let type_ref_offset = at(top, "bus_if bus"); + assert_eq!( + doc_reference_kind(&ws, &uri, type_ref_offset), + Some("ExternalCandidate".to_string()) + ); + let found = type_definition(&ws, &uri, at(top, "bus_if bus") + 7); + assert_eq!(found.len(), 2, "both interfaces, not a guess: {found:#?}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_qualified_member_miss_never_falls_back_to_a_bare_name_sweep() { + // Lead fix, 2026-08-26 (QA follow-up finding): `unit_member` can miss + // with the same two spellings the fence accepts — a local package + // that lacks the member — and a bare-name workspace sweep would then + // discard the `pkg::` qualifier and jump to an unrelated declaration + // that merely shares the member's name. The source pointed into + // `pkg`; an answer from anywhere else is a wrong jump, and no answer + // is the honest one. + let other = "typedef logic missing_t;\n"; + let top = "package p;\nendpackage\nmodule top;\n p::missing_t s;\nendmodule\n"; + let files = [("other.sv", other), ("top.sv", top)]; + let (dir, ws, uri) = workspace("qualified_no_sweep", &files, "top.sv"); + + let found = type_definition(&ws, &uri, at(top, "p::missing_t") + 5); + assert!(found.is_empty(), "the qualifier must not be discarded: {found:#?}"); + // The same name unqualified still reaches the workspace type, so the + // guard is about the qualifier, not the name. + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn a_self_referential_typedef_is_total_and_does_not_loop() { + // `typedef t t;` — the alias and its own type share a name. Nothing + // in this module chases a chain (that is the one-hop rule's whole + // point), so there is no loop to guard against structurally; this + // pins that down operationally: every position on the line answers + // exactly once, promptly, whatever the answer is. + let text = "module m;\n typedef t t;\nendmodule\n"; + let (ws, uri) = document(text); + // No panic, no hang, on the alias name, on the type-of name, or on + // any position in between. + for offset in [at(text, "typedef"), at(text, "t t"), at(text, "t t") + 2, at(text, ";\n")] { + let _ = type_definition(&ws, &uri, offset); + } +} + +#[test] +fn type_definition_on_a_type_name_agrees_exactly_with_definition() { + // The design claim in the feature README ("cursor on a type name + // answers for that name") is that this is *literally* the same + // request `textDocument/definition` would answer at that offset, not + // a coincidentally-equal location built a different way. + let text = "\ +module m; + typedef enum logic { A, B } state_t; + state_t s; +endmodule +"; + let (ws, uri) = document(text); + let offset = at(text, "state_t s"); + assert_eq!(type_definition(&ws, &uri, offset), nav::definition(&ws, &uri, offset)); +} + +#[test] +fn an_inline_anonymous_struct_has_no_type_name_to_jump_to() { + // `struct packed { ... } s;` — the type is written inline, with no + // name of its own, so `DataType::name` is empty and `site()` refuses + // it. Null, not a bogus jump at whatever text happens to sit in the + // window. + let text = "module m;\n struct packed { logic a; } s;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "} s") + 2).is_empty(), "the declarator name"); + assert!(type_definition(&ws, &uri, at(text, "logic a")).is_empty(), "inside the inline body"); +} + +#[test] +fn a_later_declarator_in_a_multi_declarator_line_still_finds_the_type() { + // `state_t a, b, c;` — the window is computed from the *first* + // declarator regardless of which one the cursor is on, because the + // type is written once for the whole list. + let text = "\ +module m; + typedef logic t; + t a, b, c; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "c;")), [(1, 16)], "the cursor on the third declarator"); +} + +#[test] +fn var_const_and_signed_qualifiers_do_not_shift_the_type_window() { + // Qualifiers (`DataDecl::qualifiers`) sit textually before the type + // inside the same window this feature scans; they must not be + // mistaken for the type name, and must not shift where it is found. + let text = "\ +module m; + class my_cls; + endclass + const var my_cls h; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "my_cls h") + 7), [(1, 8)]); +} + +#[test] +fn packed_and_unpacked_array_dimensions_do_not_confuse_the_type_match() { + let text = "\ +module m; + typedef logic state_t; + state_t [3:0] x [0:7]; +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "x [0:7]")), [(1, 16)]); +} + +#[test] +fn a_function_arguments_type_is_reached_like_a_task_arguments() { + let text = "\ +package p; + typedef logic [3:0] nib_t; +endpackage + +module m; + function automatic p::nib_t f(p::nib_t a); + return a; + endfunction +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "a);")), [(1, 22)], "the function's own argument"); +} + +#[test] +fn a_position_past_the_end_of_the_file_answers_nothing_not_a_panic() { + let text = "module m;\n typedef logic t;\n t a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, text.len() as u32 + 5_000).is_empty()); +} + +#[test] +fn a_position_inside_a_comment_answers_nothing() { + let text = "module m;\n // t is not a type here, just a comment\n int a;\nendmodule\n"; + let (ws, uri) = document(text); + assert!(type_definition(&ws, &uri, at(text, "not a type")).is_empty()); +} + +// ------------------------------------------------------------------ +// QA corpus spot-check (2026-08-26). +// +// One `Workspace` is opened once and reused for every probe and every +// file in the full-corpus panic sweep below — `open_roots` indexes the +// whole tree (a one-time cost), and `set_document` only overlays a +// buffer against the index already built, so this is cheap to repeat. +// The first version of this test opened a fresh `Workspace` (and so +// re-indexed all of corpus/ibex) per file in the sweep, which made a +// ~300-file loop re-scan several hundred files each time; that was a +// test-harness bug, not a product one, and is fixed by sharing `ws`. +// ------------------------------------------------------------------ + +#[test] +fn corpus_spot_check_real_uvm_files_no_panic_and_known_jumps() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex"); + if !root.exists() { + eprintln!("corpus not present, skipping"); + return; + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![root.clone()]); + + let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) { + let file = root.join(rel); + let text = fs::read_to_string(&file).unwrap_or_else(|e| panic!("read {rel}: {e}")); + let uri = path_to_uri(&file).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + (uri, text) + }; + + // A genuine, real-world positive control: `core_ibex_tb_top` + // instantiates `clk_rst_if` (declared in a vendored file elsewhere + // in the tree) at module scope, not inside any class — the plain + // cross-file-interface-instance case the feature's design claims to + // solve, exercised on real corpus text rather than a fixture. + let (tb_uri, tb_text) = open(&mut ws, "dv/uvm/core_ibex/tb/core_ibex_tb_top.sv"); + for offset in 0..=tb_text.len() as u32 { + let _ = type_definition(&ws, &tb_uri, offset); // no panic, whole file + } + let found = type_definition(&ws, &tb_uri, at(&tb_text, "clk_rst_if ibex_clk_if") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); + + // The QA finding of 2026-08-26, now the positive control for its own + // fix, on the real file it was found in rather than only the portable + // fixture above: `core_ibex_env_cfg extends uvm_object`, so every + // otherwise-cross-file type reference inside it — `clk_rst_if`, + // `core_ibex_dut_probe_if`, both real interfaces this same workspace + // indexes — resolves to `InheritedCandidate`, which the widened fence + // now accepts. `scrambling_key_agent_cfg` is different: that class is + // not vendored into this corpus checkout at all, so empty stays the + // correct answer, and it is what keeps the widening from being + // mistaken for "answer something, anything". + let (env_uri, env_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_env_cfg.sv"); + for offset in 0..=env_text.len() as u32 { + let _ = type_definition(&ws, &env_uri, offset); + } + let found = type_definition(&ws, &env_uri, at(&env_text, "clk_rst_if") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("clk_rst_if.sv"), "{found:#?}"); + let found = type_definition(&ws, &env_uri, at(&env_text, "core_ibex_dut_probe_if ") + 2); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].uri.as_str().ends_with("core_ibex_dut_probe_if.sv"), "{found:#?}"); + assert!( + type_definition(&ws, &env_uri, at(&env_text, "scrambling_key_agent_cfg ") + 2).is_empty(), + "genuinely not in this corpus checkout, unrelated to the gap" + ); + + let (sb_uri, sb_text) = open(&mut ws, "dv/uvm/core_ibex/env/core_ibex_scoreboard.sv"); + for offset in 0..=sb_text.len() as u32 { + let _ = type_definition(&ws, &sb_uri, offset); + } + + // Every small file under corpus/ibex, sharing the one indexed + // workspace: no panic anywhere a real cursor could land. + let mut count = 0; + visit(&root, &mut |path| { + let ext_ok = matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("svh")); + let Ok(t) = (if ext_ok { fs::read_to_string(path) } else { return }) else { return }; + if t.len() > 4000 { + return; + } + let Some(u) = path_to_uri(path) else { return }; + ws.set_document(u.clone(), t.clone()); + for offset in (0..=t.len() as u32).step_by(3) { + let _ = type_definition(&ws, &u, offset); + } + count += 1; + }); + eprintln!("checked {count} small corpus files, no panic"); + assert!(count > 20, "{count}"); +} + +fn visit(dir: &std::path::Path, f: &mut impl FnMut(&std::path::Path)) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + visit(&path, f); + } else { + f(&path); + } + } +} + +// ------------------------------------------------------------------ +// QA fix-round re-attack (2026-08-26) +// ------------------------------------------------------------------ + +#[test] +fn a_local_typedef_in_the_extending_class_itself_wins_over_the_workspace_type() { + // The dev's precedence test puts the shadowing typedef in the *base* + // class, which `lexical` can never see anyway (it walks `scope.parent`, + // never a base's scope). This puts it directly in the *extending* + // class's own body — the one place `lexical` unambiguously looks first, + // before it ever reaches `miss`/`InheritedCandidate` at all. If lexical + // scoping is doing what it's supposed to, this reference is `Resolved` + // against the local typedef and `indexed_type` is never consulted, so + // the widened fence cannot leak a wrong cross-file jump here. + let iface = "interface bus_if;\nendinterface\n"; + let top = "\ +class base; +endclass +class top extends base; + typedef int bus_if; + bus_if h; +endclass +"; + let (dir, ws, uri) = + workspace("local_typedef_in_extender", &[("bus_if.sv", iface), ("top.sv", top)], "top.sv"); + + let offset = at(top, "bus_if h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("Resolved".to_string()), + "lexical finds the class's own typedef before miss ever runs" + ); + let found = type_definition(&ws, &uri, offset + 7); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, uri, "the in-file typedef, not the workspace interface"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn an_inherited_candidate_reaches_a_same_named_module_exactly_like_not_found_did() { + // The fence's kind filter (`Module | Class | Typedef`) was never + // conditioned on which of the two resolutions triggered it, so a + // member-type reference inside an extending class that happens to + // share a name with a workspace *module* should jump there exactly as + // it already would have for a plain top-level `NotFound` reference + // (`a_class_declared_in_another_file_is_reached_from_a_handle`, mutatis + // mutandis for `Module`). Nothing about "module, not class/interface" + // is special-cased in `indexed_type`, so this is a parity check, not a + // new behavior. + let module_file = "module thing;\nendmodule\n"; + let top = "\ +class base; +endclass +class top extends base; + thing h; +endclass +"; + let (dir, ws, uri) = + workspace("inherited_to_module", &[("thing.sv", module_file), ("top.sv", top)], "top.sv"); + + let offset = at(top, "thing h"); + assert_eq!( + doc_reference_kind(&ws, &uri, offset), + Some("InheritedCandidate".to_string()), + "member type inside an extending class" + ); + let found = type_definition(&ws, &uri, offset + 3); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].uri, path_to_uri(&dir.join("thing.sv")).expect("uri")); + + let _ = fs::remove_dir_all(&dir); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/type_hierarchy.rs b/crates/lucisv_server/src/type_hierarchy.rs index 7cd009e..1f6cb92 100644 --- a/crates/lucisv_server/src/type_hierarchy.rs +++ b/crates/lucisv_server/src/type_hierarchy.rs @@ -335,965 +335,6 @@ fn key(range: Range) -> (u32, u32) { } #[cfg(test)] -mod tests { - use super::*; - use std::fs; - use std::path::PathBuf; - - /// A scratch workspace root, removed on drop. - struct Tree { - path: PathBuf, - } - - impl Tree { - fn new(name: &str) -> Tree { - let path = std::env::temp_dir() - .join(format!("lucisv_server_type_hierarchy_{}_{name}", std::process::id())); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("temp dir"); - Tree { path } - } - - fn write(&self, rel: &str, text: &str) -> PathBuf { - let path = self.path.join(rel); - fs::write(&path, text).expect("write"); - path - } - } - - impl Drop for Tree { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } - } - - /// A workspace over `files`, with the first of them opened as a buffer. - fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { - let tree = Tree::new(name); - let mut first = None; - for (rel, text) in files { - let path = tree.write(rel, text); - if first.is_none() { - first = Some((path, *text)); - } - } - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let (path, text) = first.expect("at least one file"); - let uri = path_to_uri(&path).expect("uri"); - ws.set_document(uri.clone(), text.to_string()); - (tree, ws, uri) - } - - /// The byte offset of the first occurrence of `needle`. - fn at(text: &str, needle: &str) -> u32 { - text.find(needle).expect("needle present") as u32 - } - - /// An item as `(name, file name, selection line)`. - fn shape(item: &TypeHierarchyItem) -> (String, String, u32) { - ( - item.name.clone(), - item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), - item.selection_range.start.line, - ) - } - - const BASE: &str = "class base;\n int x;\nendclass\n"; - const CHILD: &str = "class child extends base;\n int y;\nendclass\n"; - - /// The two-file workspace of the cross-file tests, `child.sv` open. - fn two(name: &str) -> (Tree, Workspace, Uri) { - workspace(name, &[("child.sv", CHILD), ("base.sv", BASE)]) - } - - // ------------------------------------------------------------------ - // prepare - // ------------------------------------------------------------------ - - #[test] - fn the_cursor_on_a_class_declaration_prepares_that_class() { - let (_tree, ws, uri) = workspace("decl", &[("base.sv", BASE)]); - let items = prepare(&ws, &uri, at(BASE, "base")).expect("a class"); - assert_eq!(items.len(), 1); - assert_eq!(shape(&items[0]), ("base".to_string(), "base.sv".to_string(), 0)); - assert_eq!(items[0].kind, SymbolKind::CLASS); - assert_eq!(items[0].selection_range.start.character, 6, "the name, not the keyword"); - assert_eq!(items[0].range.start.character, 0, "the whole declaration"); - assert_eq!(items[0].range.end.line, 2, "through `endclass`"); - assert!(items[0].data.is_none(), "items are re-derived, never carried"); - } - - #[test] - fn the_cursor_on_a_use_prepares_the_class_it_names() { - // Three kinds of use, all answered by the same two layers - // `textDocument/definition` uses. - let text = "\ -class base; -endclass - -class child extends base; - base handle; - function void f(); - base local_one; - endfunction -endclass -"; - let (_tree, ws, uri) = workspace("uses", &[("u.sv", text)]); - let uses = [ - ("the `extends` base", at(text, "extends base") + 8), - ("a property's type", at(text, "base handle")), - ("a method local's type", at(text, "base local_one")), - ]; - for (what, offset) in uses { - let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{what}")); - assert_eq!(items.len(), 1, "{what}: {items:#?}"); - assert_eq!(shape(&items[0]), ("base".to_string(), "u.sv".to_string(), 0), "{what}"); - } - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): the `class` - /// keyword and a property are inside `base` and prepare it. A module - /// and its wire still prepare nothing — modules stay off this view. - #[test] - fn a_position_on_no_class_prepares_the_enclosing_one_or_nothing() { - let text = "\ -class base; - int x; -endclass - -module m; - wire w; -endmodule -"; - let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]); - let name = |offset| shape(&prepare(&ws, &uri, offset).expect("a class")[0]).0; - assert_eq!(name(0), "base", "the `class` keyword is inside `base`"); - assert_eq!(name(at(text, "int x") + 4), "base", "a property name is inside `base`"); - assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class"); - assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire"); - } - - #[test] - fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { - // Where a double-click and an end-of-word motion leave it. - let (_tree, ws, uri) = workspace("edge", &[("base.sv", BASE)]); - assert!(prepare(&ws, &uri, at(BASE, "base") + 4).is_some()); - } - - #[test] - fn a_class_two_files_declare_prepares_both_rather_than_guessing() { - let dup = "class dup;\nendclass\n"; - let user = "class user extends dup;\nendclass\n"; - let (_tree, ws, uri) = workspace("dup", &[("user.sv", user), ("a.sv", dup), ("b.sv", dup)]); - let items = prepare(&ws, &uri, at(user, "extends dup") + 8).expect("both"); - let files: Vec = items.iter().map(|i| shape(i).1).collect(); - assert_eq!(files, ["a.sv", "b.sv"], "every declaration, as definition does"); - } - - #[test] - fn an_unopened_document_prepares_nothing() { - let ws = Workspace::default(); - let uri = path_to_uri(std::path::Path::new("/nowhere/c.sv")).expect("uri"); - assert!(prepare(&ws, &uri, 0).is_none()); - } - - #[test] - fn an_untitled_buffer_prepares_from_itself() { - // No path, so no index entry — but the declaration is right there in - // the buffer, and its own hierarchy root is a fair answer. - use std::str::FromStr; - let text = "class scratch;\nendclass\n"; - let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); - let mut ws = Workspace::default(); - ws.set_document(uri.clone(), text.to_string()); - let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own class"); - assert_eq!(items[0].name, "scratch"); - assert_eq!(items[0].uri, uri); - assert!(supertypes(&ws, &items[0]).is_empty(), "and it extends nothing"); - } - - #[test] - fn an_interface_class_is_a_node() { - // Was `..._is_not_a_node_because_the_parser_does_not_model_one` until - // `vendor-formal-grammar` (2026-09-02) made `interface class` an - // ordinary `ClassDecl` carrying the word in its prefix. It declares a - // class symbol, so it prepares like any other class — which is what - // gives the `implements` edge below something to point at. - let text = "interface class ic;\n pure virtual function void f();\nendclass\n"; - let (_tree, ws, uri) = workspace("ifaceclass", &[("ic.sv", text)]); - let items = prepare(&ws, &uri, at(text, "ic")).expect("the interface class"); - assert_eq!(items.len(), 1); - assert_eq!(items[0].name, "ic"); - assert!(supertypes(&ws, &items[0]).is_empty(), "and it implements nothing"); - } - - #[test] - fn a_class_declared_in_a_package_in_a_module_and_in_a_class_is_all_found() { - let text = "\ -package p; - class in_package; - endclass -endpackage - -module m; - class in_module; - endclass -endmodule - -class outer; - class inner; - endclass -endclass -"; - let (_tree, ws, uri) = workspace("nesting", &[("n.sv", text)]); - for name in ["in_package", "in_module", "outer", "inner"] { - let items = prepare(&ws, &uri, at(text, &format!("class {name}")) + 6) - .unwrap_or_else(|| panic!("{name} is a class")); - assert_eq!(items[0].name, name); - } - } - - // ------------------------------------------------------------------ - // supertypes - // ------------------------------------------------------------------ - - #[test] - fn supertypes_name_the_base_declared_in_the_same_file() { - let text = "class base;\nendclass\n\nclass child extends base;\nendclass\n"; - let (_tree, ws, uri) = workspace("infile", &[("both.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class child") + 6).expect("child")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(shape(&bases[0]), ("base".to_string(), "both.sv".to_string(), 0)); - assert_eq!(bases[0].kind, SymbolKind::CLASS); - } - - #[test] - fn supertypes_reach_a_base_declared_in_another_file() { - // The workspace overlay answers the bare `base`, which is what the - // overlay-promotion round made reachable — no lookup of this feature's - // own. - let (_tree, ws, uri) = two("crossfile"); - let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); - } - - #[test] - fn a_qualified_base_resolves_through_its_package() { - let pkg = "package p;\n class base;\n endclass\nendpackage\n"; - let child = "class child extends p::base;\nendclass\n"; - let (_tree, ws, uri) = workspace("qualified", &[("child.sv", child), ("p.sv", pkg)]); - let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(shape(&bases[0]), ("base".to_string(), "p.sv".to_string(), 1)); - } - - #[test] - fn a_parameterized_base_resolves_by_its_bare_name() { - // `#( ... )` lives on its own field, so the base name the parser stores - // is already bare and nothing here unwraps anything. - let child = "class child extends base #(8);\nendclass\n"; - let (_tree, ws, uri) = workspace("param", &[("child.sv", child), ("base.sv", BASE)]); - let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); - } - - #[test] - fn a_base_the_workspace_does_not_declare_yields_no_supertype() { - // The UVM shape: `uvm_component` is in a library nobody indexed. No - // item is better than an item pointing at a file that is not there. - let child = "class child extends uvm_component;\nendclass\n"; - let (_tree, ws, uri) = workspace("unknown", &[("child.sv", child)]); - let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); - assert!(supertypes(&ws, &root).is_empty()); - } - - #[test] - fn a_class_that_extends_nothing_has_no_supertypes() { - let (_tree, ws, uri) = workspace("root", &[("base.sv", BASE)]); - let root = prepare(&ws, &uri, at(BASE, "base")).expect("base")[0].clone(); - assert!(supertypes(&ws, &root).is_empty()); - } - - #[test] - fn an_implements_clause_names_a_supertype() { - // Was `..._names_no_supertype` until `vendor-formal-grammar` - // (2026-09-02): `implements` names an interface class, and now that one - // is a `ClassDecl` there is a declaration to point at. The hop is the - // same one `extends` takes, so a supertype in another file works with - // no lookup of this feature's own. - let base = "interface class api;\n pure virtual function void f();\nendclass\n"; - let child = "class child implements api;\nendclass\n"; - let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("api.sv", base)]); - let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(shape(&bases[0]), ("api".to_string(), "api.sv".to_string(), 0)); - } - - #[test] - fn extends_and_implements_are_both_edges_of_the_same_answer() { - let api = "interface class api;\nendclass\n"; - let base = "class base;\nendclass\n"; - let child = "class child extends base implements api;\nendclass\n"; - let (_tree, ws, uri) = - workspace("both", &[("child.sv", child), ("base.sv", base), ("api.sv", api)]); - let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); - let names: Vec = supertypes(&ws, &root).iter().map(|i| i.name.clone()).collect(); - assert_eq!(names, ["base", "api"], "the base first, then the interfaces, in source order"); - } - - #[test] - fn supertypes_answer_for_a_file_no_editor_has_open() { - // What a client does after `subtypes`: it sends back an item naming a - // file it never opened, and the hop has to work anyway. - let (_tree, ws, uri) = two("closedfile"); - let base_root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); - assert!(ws.document(&base_root.uri).is_none(), "premise: base.sv is not open"); - let children = subtypes(&ws, &base_root); - assert_eq!(children.len(), 1); - // And `child.sv` *is* open, so go one further: an item from a closed - // file, asked for its own base. - let bases = supertypes(&ws, &children[0]); - assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); - } - - #[test] - fn an_item_naming_a_file_that_is_gone_answers_with_nothing() { - let (tree, ws, uri) = two("missing"); - let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); - assert_eq!(supertypes(&ws, &root).len(), 1, "premise"); - let mut stale = root.clone(); - stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); - assert!(supertypes(&ws, &stale).is_empty(), "no file, no supertype, no panic"); - let mut renamed = root; - renamed.name = "no_such_class".to_string(); - assert!(supertypes(&ws, &renamed).is_empty(), "a name the file does not declare"); - } - - // ------------------------------------------------------------------ - // subtypes - // ------------------------------------------------------------------ - - #[test] - fn subtypes_name_every_class_that_extends_this_one() { - let text = "\ -class base; -endclass - -class first extends base; -endclass - -class second extends base; -endclass - -class unrelated; -endclass -"; - let (_tree, ws, uri) = workspace("subs", &[("all.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); - let children = subtypes(&ws, &root); - assert_eq!( - children.iter().map(shape).collect::>(), - [ - ("first".to_string(), "all.sv".to_string(), 3), - ("second".to_string(), "all.sv".to_string(), 6), - ], - "sorted by file then position: {children:#?}" - ); - } - - #[test] - fn subtypes_reach_other_files_in_a_deterministic_order() { - let base = "class base;\nendclass\n"; - let one = "class one extends base;\nendclass\n"; - let two_text = "class two extends base;\nendclass\n"; - let three = "class three extends base;\nendclass\n"; - let (_tree, ws, uri) = workspace( - "crosssubs", - &[("base.sv", base), ("c.sv", three), ("a.sv", one), ("b.sv", two_text)], - ); - let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); - let first = subtypes(&ws, &root); - assert_eq!( - first.iter().map(|i| shape(i).1).collect::>(), - ["a.sv", "b.sv", "c.sv"], - "sorted by URI, not by whatever order the files were read in" - ); - assert_eq!( - first.iter().map(|i| i.name.clone()).collect::>(), - ["one", "two", "three"] - ); - let again = subtypes(&ws, &root); - assert_eq!(first, again, "the same question twice gives the same answer"); - } - - #[test] - fn a_class_nobody_extends_has_no_subtypes() { - let (_tree, ws, uri) = two("leaf"); - let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); - assert!(subtypes(&ws, &root).is_empty()); - } - - #[test] - fn a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with() { - // The `hierarchy` precedent: matching on the trailing segment would let - // `other_pkg::base` claim to extend *this* `base`. Zero of the 309 - // `extends` clauses in the checked-in corpus are qualified, so this - // costs nothing measurable and never lies. The asymmetry with - // `supertypes` (which *does* follow `p::base`, through the package) is - // deliberate and documented. - let pkg = "package other_pkg;\n class base;\n endclass\nendpackage\n"; - let base = "class base;\nendclass\n"; - let child = "class child extends other_pkg::base;\nendclass\n"; - let (_tree, ws, uri) = - workspace("qualsub", &[("base.sv", base), ("p.sv", pkg), ("child.sv", child)]); - let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); - assert!(subtypes(&ws, &root).is_empty(), "the file-scope `base` is not the one extended"); - } - - #[test] - fn a_class_extended_only_outside_the_index_scope_has_no_subtypes() { - // The scope ladder decides which files exist; a file the configured - // filelist omits extends nothing, exactly as it references nothing. - let tree = Tree::new("scope"); - tree.write("base.sv", BASE); - tree.write("child.sv", CHILD); - tree.write("files.f", "base.sv\n"); - tree.write("lucisv.toml", "filelist = \"files.f\"\n"); - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![tree.path.clone()]); - let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri"); - ws.set_document(base_uri.clone(), BASE.to_string()); - - let root = prepare(&ws, &base_uri, at(BASE, "base")).expect("base")[0].clone(); - assert!(subtypes(&ws, &root).is_empty(), "child.sv is out of scope"); - } - - #[test] - fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() { - // Superseded this round (incremental-index, 2026-08-27): - // `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk - // over `Workspace::sources()`, so a keystroke in another buffer moved - // the answer before anything rebuilt. Subtypes are the index's - // inheritance-edge table now — as of its last build or update, both of - // which fold every open buffer in. Same rule as the call hierarchy's - // census, pinned from both sides. - let (tree, mut ws, uri) = two("unsaved"); - let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); - assert_eq!(subtypes(&ws, &root).len(), 1, "premise"); - - let fresh = tree.path.join("child.sv"); - let child_uri = path_to_uri(&fresh).expect("uri"); - ws.set_document(child_uri, "class child;\nendclass\n".to_string()); - assert_eq!( - subtypes(&ws, &root).len(), - 1, - "the buffer alone does not move the answer — the index has not seen it" - ); - assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough"); - assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away"); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): malformed `extends` clauses at the last-byte offset - // ------------------------------------------------------------------ - // - // `extends.name_span.end - 1` only underflows or lands off the class if - // `name_span` is empty or missing — checked here at the boundary rather - // than only trusted from reading `parse_class_extends`. In every case - // below the tolerant parser either fails the whole `class` item (so there - // is no `ClassDecl` to ask about at all) or produces a non-empty span; - // the assertion each time is survival, not a particular answer. - - #[test] - fn an_extends_clause_with_no_base_name_never_panics() { - // `class a extends ;` — nothing for `parse_scoped_name` to read after - // `extends`, so `parse_class_extends` errors and the whole `class a` - // item fails to parse; there is no `ClassExtends` with an empty span - // to feed the offset math, but the walk must survive regardless of - // what the tolerant parser recovers into. - let text = "class a extends ;\nendclass\n"; - let (_tree, ws, uri) = workspace("emptyextends", &[("a.sv", text)]); - if let Some(items) = prepare(&ws, &uri, at(text, "class a") + 6) { - let _ = supertypes(&ws, &items[0]); - let _ = subtypes(&ws, &items[0]); - } - } - - #[test] - fn an_extends_clause_at_eof_never_panics() { - // The file ends mid-header, no `;`, no `endclass`. - let text = "class child extends base"; - let (_tree, ws, uri) = workspace("eofextends", &[("child.sv", text), ("base.sv", BASE)]); - if let Some(items) = prepare(&ws, &uri, at(text, "child")) { - let _ = supertypes(&ws, &items[0]); - let _ = subtypes(&ws, &items[0]); - } - } - - #[test] - fn a_qualified_base_with_nothing_after_the_double_colon_never_panics() { - // `pkg::` with no tail identifier: `parse_scoped_name` errors after - // the `::`, so this is another whole-class parse failure, not an - // empty tail span. - let text = "class child extends pkg::;\nendclass\n"; - let (_tree, ws, uri) = workspace("danglingcolon", &[("child.sv", text)]); - if let Some(items) = prepare(&ws, &uri, at(text, "child")) { - let _ = supertypes(&ws, &items[0]); - let _ = subtypes(&ws, &items[0]); - } - } - - #[test] - fn a_single_character_base_name_resolves() { - let text = "class b;\nendclass\nclass a extends b;\nendclass\n"; - let (_tree, ws, uri) = workspace("shortname", &[("f.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(bases[0].name, "b"); - } - - #[test] - fn multibyte_text_immediately_after_the_extends_name_does_not_shift_the_offset() { - // The last-byte trick reads `name_span` alone, which the parser - // measures in bytes independent of what follows — but attack the - // boundary anyway: a multibyte comment starts at the very next byte - // after `base`. - let text = "class base;\nendclass\nclass mid extends base/*🎉 日本語*/;\nendclass\n"; - let (_tree, ws, uri) = workspace("multibyteafter", &[("f.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class mid") + 6).expect("mid")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "{bases:#?}"); - assert_eq!(bases[0].name, "base"); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): prepare on the keyword, and name shadowing - // ------------------------------------------------------------------ - - /// Reversed by call-hierarchy-everywhere (2026-10-14): the keyword is - /// inside `child`'s header and prepares `child` — still not `base`. - #[test] - fn prepare_on_the_extends_keyword_itself_prepares_the_class_it_is_written_in() { - let text = "class base;\nendclass\nclass child extends base;\nendclass\n"; - let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]); - let items = prepare(&ws, &uri, at(text, "extends") + 2).expect("the enclosing class"); - assert_eq!(shape(&items[0]).0, "child", "the keyword, not a name"); - } - - /// Reversed by call-hierarchy-everywhere (2026-10-14): the variable use - /// is inside `child` and prepares `child`. The point of the pin stands — - /// it never prepares the class `base` its text spells. - #[test] - fn a_class_name_shadowed_by_a_local_variable_prepares_the_enclosing_class() { - // `base` is both a class and, inside `child`'s method, a local - // variable name. The use on the right-hand side of the assignment - // names the variable, not the class, and must not be treated as a - // type-hierarchy node just because the text matches. - let text = "\ -class base; -endclass - -class child extends base; - function void f(); - int base; - base = base + 1; - endfunction -endclass -"; - let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]); - let use_offset = at(text, "base + 1"); - let items = prepare(&ws, &uri, use_offset).expect("the enclosing class"); - assert_eq!(items.len(), 1); - assert_eq!(shape(&items[0]).0, "child", "a local variable named `base`, not the class"); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): deep chains, cheap per hop - // ------------------------------------------------------------------ - - #[test] - fn a_ten_deep_chain_answers_each_hop_without_recursing() { - let names: Vec = (0..10).map(|i| format!("c{i}")).collect(); - let mut files: Vec<(String, String)> = Vec::new(); - for (i, name) in names.iter().enumerate() { - let text = match names.get(i + 1) { - Some(next) => format!("class {name} extends {next};\nendclass\n"), - None => format!("class {name};\nendclass\n"), - }; - files.push((format!("{name}.sv"), text)); - } - let refs: Vec<(&str, &str)> = files.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect(); - let (_tree, ws, uri) = workspace("chain", &refs); - let root_text = &files[0].1; - let mut node = prepare(&ws, &uri, at(root_text, "c0")).expect("c0")[0].clone(); - for expected_next in &names[1..] { - let up = supertypes(&ws, &node); - assert_eq!(up.len(), 1, "{up:#?}"); - assert_eq!(&up[0].name, expected_next); - node = up[0].clone(); - } - assert!(supertypes(&ws, &node).is_empty(), "the chain really ends at the last class"); - } - - #[test] - fn a_nameless_item_reads_no_files_at_all() { - // A malformed item from a client: the prefilter matches every file for - // an empty name, so without the guard this would read and parse the - // whole workspace to find nothing. - let (_tree, ws, uri) = two("nameless"); - let mut nameless = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); - nameless.name = String::new(); - assert!(subtypes(&ws, &nameless).is_empty()); - assert!(supertypes(&ws, &nameless).is_empty()); - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): census correctness — the substring prefilter is not - // the match step, and same-named classes across files are a known, - // documented (not previously pinned) source of imprecision. - // ------------------------------------------------------------------ - - #[test] - fn a_file_containing_the_name_as_a_substring_but_no_matching_extends_is_not_a_false_positive() { - // `database` passes the substring prefilter for the name `base` (it - // contains it), and `class d extends database;` passes it too — but - // neither should ever be counted as extending `base`. The match step - // (`extends_name(decl.class) != Some(item.name.as_str())`) is a full - // string comparison, not a substring one, so both must be rejected. - let text = "\ -class base; -endclass - -class database; -endclass - -class d extends database; -endclass -"; - let (_tree, ws, uri) = workspace("substring", &[("f.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); - assert!( - subtypes(&ws, &root).is_empty(), - "`database` and `extends database` must not count as extending `base`" - ); - } - - #[test] - fn subtypes_of_two_same_named_classes_in_different_files_share_one_list() { - // Documented in the feature README as a deliberate consequence of - // matching by name and not by uri (the same policy - // `callHierarchy/incomingCalls` uses for a module name), but not - // previously pinned by a test: `subtypes` cannot tell which of two - // same-named `base` declarations `sub` really extends, so *both* - // items answer with `sub` in their subtype list. This is the bound on - // the false positive the name-as-written match allows — not - // eliminated, but confined to genuinely same-named declarations. - let base_a = "class base;\nendclass\n"; - let base_b = "class base;\nendclass\n"; - let sub = "class sub extends base;\nendclass\n"; - let (_tree, ws, uri) = - workspace("samenamesub", &[("sub.sv", sub), ("a.sv", base_a), ("b.sv", base_b)]); - let roots = prepare(&ws, &uri, at(sub, "extends base") + 8).expect("both bases"); - assert_eq!(roots.len(), 2, "two same-named declarations: {roots:#?}"); - for root in &roots { - let children = subtypes(&ws, root); - assert_eq!(children.len(), 1, "{:?}: {children:#?}", root.uri); - assert_eq!(children[0].name, "sub"); - } - } - - // ------------------------------------------------------------------ - // QA (2026-08-26): a class nested inside a generate block - // ------------------------------------------------------------------ - - #[test] - fn a_class_declared_inside_a_generate_block_is_not_found_by_this_walk() { - // The README's Assumptions section states "a generate block is not - // descended into — no class lives there." That justification is not - // quite right: `vlog_parser` *does* parse a `class` written inside - // `generate`/`if`-generate the same way it parses one at module - // scope (`parse_gen_block` shares `item_or_recover` with ordinary - // module-item parsing), so the class is a real `ItemKind::Class` - // node — it is just nested inside `ItemKind::GenIf`/`GenerateRegion`, - // which `collect()` does not descend into. This pins today's answer - // (not found) as a documented gap rather than a silent one; see the - // QA log for the finding filed against the README's wording. - let text = "\ -module m; - generate - if (1) begin : g - class Foo; - int x; - endclass - end - endgenerate -endmodule -"; - let (_tree, ws, uri) = workspace("generateclass", &[("f.sv", text)]); - assert!( - prepare(&ws, &uri, at(text, "class Foo") + 6).is_none(), - "known gap: a class inside a generate block is invisible to this walk" - ); - } - - // ------------------------------------------------------------------ - // cycles - // ------------------------------------------------------------------ - - #[test] - fn a_self_extending_class_answers_one_hop_in_both_directions_without_duplicating() { - // Broken code, reachable through the tolerant parser. Each request is - // one hop, so neither can loop; the assertion is that the answer is one - // item and not the same class twice. - let text = "class a extends a;\nendclass\n"; - let (_tree, ws, uri) = workspace("selfextends", &[("a.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); - let bases = supertypes(&ws, &root); - assert_eq!(bases.len(), 1, "one item, not two: {bases:#?}"); - assert_eq!(bases[0].name, "a"); - assert_eq!(bases[0].selection_range, root.selection_range, "and it is the same node"); - let children = subtypes(&ws, &root); - assert_eq!(children.len(), 1, "one item, not two: {children:#?}"); - assert_eq!(children[0].selection_range, root.selection_range); - } - - #[test] - fn a_two_class_cycle_terminates_in_both_directions() { - let a = "class a extends b;\nendclass\n"; - let b = "class b extends a;\nendclass\n"; - let (_tree, ws, uri) = workspace("cycle", &[("a.sv", a), ("b.sv", b)]); - let root_a = prepare(&ws, &uri, at(a, "class a") + 6).expect("a")[0].clone(); - let up = supertypes(&ws, &root_a); - assert_eq!(up.len(), 1, "a -> b: {up:#?}"); - assert_eq!(up[0].name, "b"); - let hop2 = up[0].clone(); - let up2 = supertypes(&ws, &hop2); - assert_eq!(up2.len(), 1, "b -> a: {up2:#?}"); - assert_eq!(up2[0].name, "a"); - // And the other direction mirrors it, one hop at a time. - let down = subtypes(&ws, &hop2); - assert_eq!(down.len(), 1, "b's only subtype is a: {down:#?}"); - assert_eq!(down[0].name, "a"); - } - - // ------------------------------------------------------------------ - // odds and ends - // ------------------------------------------------------------------ - - #[test] - fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { - let text = "// é 🎉\nclass base;\nendclass\nclass child extends base;\nendclass\n"; - let (_tree, ws, uri) = workspace("utf16", &[("u.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); - assert_eq!( - (root.selection_range.start.line, root.selection_range.start.character), - (1, 6), - "the name of the declaration, in UTF-16 units" - ); - let children = subtypes(&ws, &root); - assert_eq!(children.len(), 1); - assert_eq!( - ( - children[0].selection_range.start.character, - children[0].selection_range.end.character - ), - (6, 11), - "`child`, in UTF-16 units" - ); - } - - #[test] - fn a_buffer_that_does_not_parse_invents_no_types() { - // Whatever the tolerant parse recovered from an unclosed class body, - // nothing may panic and no edge may be invented — the assertion is - // deliberately on survival, so a change in recovery is not a failure. - let broken = "class child extends base;\n int y\n"; - let (_tree, ws, uri) = workspace("broken", &[("child.sv", broken), ("base.sv", BASE)]); - if let Some(items) = prepare(&ws, &uri, at(broken, "child")) { - for base in supertypes(&ws, &items[0]) { - assert_eq!(base.name, "base", "only a class really written there"); - assert!(base.selection_range.start >= base.range.start, "selection inside range"); - } - let _ = subtypes(&ws, &items[0]); - } - } - - #[test] - fn every_item_keeps_its_selection_range_inside_its_range() { - // The protocol requires it, and a client that trusts it will scroll to - // a nonsense position otherwise. - let text = "\ -class base; -endclass - -class child extends base; -endclass -"; - let (_tree, ws, uri) = workspace("contained", &[("c.sv", text)]); - let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); - let mut all = vec![root.clone()]; - all.extend(subtypes(&ws, &root)); - all.extend(supertypes(&ws, &all[1].clone())); - assert_eq!(all.len(), 3, "root, one subtype, one supertype"); - for item in &all { - assert!(item.range.start <= item.selection_range.start, "{item:#?}"); - assert!(item.selection_range.end <= item.range.end, "{item:#?}"); - } - } - - // ------------------------------------------------------------------ - // the corpus, smoke-tested - // ------------------------------------------------------------------ - - /// What `subtypes` costs after the inheritance-edge table, against the - /// workspace walk it replaced. `#[ignore]`d: it prints a number rather - /// than asserting one — the budget is asserted in - /// `the_corpus_uvm_classes_answer_all_three_requests`. - #[test] - #[ignore] - fn qa_perf_subtypes_lookup_against_the_walk_it_replaced() { - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv"); - let Ok(text) = fs::read_to_string(&lib) else { - eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&lib).expect("uri"); - ws.set_document(uri.clone(), text.clone()); - let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6; - let child = prepare(&ws, &uri, offset).expect("the class")[0].clone(); - let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test"); - - let mut lookup = std::time::Duration::ZERO; - let mut walk = std::time::Duration::ZERO; - for _ in 0..3 { - let started = std::time::Instant::now(); - let found = subtypes(&ws, &base); - lookup = lookup.max(started.elapsed()); - assert!(!found.is_empty()); - let started = std::time::Instant::now(); - let _ = ws.sources(); - walk = walk.max(started.elapsed()); - } - eprintln!( - "typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \ - used to begin with) is {walk:?}", - ws.index().files().len() - ); - } - - /// Every class of a real UVM-shaped corpus file, through all three - /// requests, plus one known `extends` chain. Skipped when `corpus/` is not - /// checked out (`tools/corpus_fetch.sh`), like the other corpus tests. - #[test] - fn the_corpus_uvm_classes_answer_all_three_requests() { - let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); - if !corpus.is_dir() { - eprintln!("corpus/ not checked out — skipping"); - return; - } - let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv"); - let Ok(text) = fs::read_to_string(&lib) else { - eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping"); - return; - }; - let mut ws = Workspace::default(); - ws.open_whole_workspace(vec![corpus]); - let uri = path_to_uri(&lib).expect("uri"); - ws.set_document(uri.clone(), text.clone()); - let files = ws.index().files().len(); - - // Every class declared in the file, both directions. No panic, and - // every item the protocol's containment rule. - let doc = ws.document(&uri).expect("the open buffer"); - let names: Vec = - classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect(); - assert!(names.len() > 20, "the file really is class-heavy: {}", names.len()); - let mut with_a_base = 0; - for name in &names { - let offset = at(&text, &format!("class {name}")) + 6; - let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{name} is a class")); - assert_eq!(items[0].name, *name); - let up = supertypes(&ws, &items[0]); - let down = subtypes(&ws, &items[0]); - if !up.is_empty() { - with_a_base += 1; - } - for item in up.iter().chain(down.iter()) { - assert_eq!(item.kind, SymbolKind::CLASS); - assert!(item.range.start <= item.selection_range.start, "{item:#?}"); - assert!(item.selection_range.end <= item.range.end, "{item:#?}"); - } - } - assert!(with_a_base > 10, "most of these extend something indexed: {with_a_base}"); - - // The chain the corpus really has: - // `core_ibex_debug_intr_basic_test extends core_ibex_base_test extends - // uvm_test`, and `uvm_test` is in a library this corpus does not carry. - let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6; - let child = prepare(&ws, &uri, offset).expect("the class")[0].clone(); - let up = supertypes(&ws, &child); - assert_eq!(up.len(), 1, "{up:#?}"); - assert_eq!(up[0].name, "core_ibex_base_test"); - assert!( - up[0].uri.as_str().ends_with("core_ibex_base_test.sv"), - "declared in its own file: {}", - up[0].uri.as_str() - ); - assert!( - supertypes(&ws, &up[0]).is_empty(), - "`uvm_test` is not in this corpus, so the chain stops rather than guessing" - ); - let down = subtypes(&ws, &up[0]); - assert!(down.len() > 5, "many tests extend the base test: {}", down.len()); - assert!( - down.iter().any(|i| i.name == "core_ibex_debug_intr_basic_test"), - "and the class we came from is one of them" - ); - // What each direction costs over the whole corpus. The budget is - // deliberately loose — a debug build on a loaded machine is the worst - // case this ever runs in — and exists to catch an order-of-magnitude - // regression, not to pin a number; the numbers themselves are in - // `docs/features/type-hierarchy/README.md`. - let base = up[0].clone(); - let mut sub_cost = std::time::Duration::ZERO; - let mut super_cost = std::time::Duration::ZERO; - for _ in 0..3 { - let started = std::time::Instant::now(); - let _ = subtypes(&ws, &base); - sub_cost = sub_cost.max(started.elapsed()); - let started = std::time::Instant::now(); - let _ = supertypes(&ws, &child); - super_cost = super_cost.max(started.elapsed()); - } - eprintln!( - "corpus: {} files, {} classes in core_ibex_test_lib.sv, {with_a_base} with an indexed \ - base; core_ibex_base_test has {} subtypes (worst of three: subtypes {sub_cost:?}, \ - supertypes {super_cost:?})", - files, - names.len(), - down.len() - ); - assert!(sub_cost < std::time::Duration::from_millis(1500), "subtypes cost {sub_cost:?}"); - assert!( - super_cost < std::time::Duration::from_millis(500), - "supertypes cost {super_cost:?}" - ); - } -} +mod tests; // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/type_hierarchy/tests.rs b/crates/lucisv_server/src/type_hierarchy/tests.rs new file mode 100644 index 0000000..b0bad0d --- /dev/null +++ b/crates/lucisv_server/src/type_hierarchy/tests.rs @@ -0,0 +1,953 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +use super::*; +use std::fs; +use std::path::PathBuf; + +/// A scratch workspace root, removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_type_hierarchy_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +/// A workspace over `files`, with the first of them opened as a buffer. +fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + let mut first = None; + for (rel, text) in files { + let path = tree.write(rel, text); + if first.is_none() { + first = Some((path, *text)); + } + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let (path, text) = first.expect("at least one file"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + (tree, ws, uri) +} + +/// The byte offset of the first occurrence of `needle`. +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// An item as `(name, file name, selection line)`. +fn shape(item: &TypeHierarchyItem) -> (String, String, u32) { + ( + item.name.clone(), + item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(), + item.selection_range.start.line, + ) +} + +const BASE: &str = "class base;\n int x;\nendclass\n"; +const CHILD: &str = "class child extends base;\n int y;\nendclass\n"; + +/// The two-file workspace of the cross-file tests, `child.sv` open. +fn two(name: &str) -> (Tree, Workspace, Uri) { + workspace(name, &[("child.sv", CHILD), ("base.sv", BASE)]) +} + +// ------------------------------------------------------------------ +// prepare +// ------------------------------------------------------------------ + +#[test] +fn the_cursor_on_a_class_declaration_prepares_that_class() { + let (_tree, ws, uri) = workspace("decl", &[("base.sv", BASE)]); + let items = prepare(&ws, &uri, at(BASE, "base")).expect("a class"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]), ("base".to_string(), "base.sv".to_string(), 0)); + assert_eq!(items[0].kind, SymbolKind::CLASS); + assert_eq!(items[0].selection_range.start.character, 6, "the name, not the keyword"); + assert_eq!(items[0].range.start.character, 0, "the whole declaration"); + assert_eq!(items[0].range.end.line, 2, "through `endclass`"); + assert!(items[0].data.is_none(), "items are re-derived, never carried"); +} + +#[test] +fn the_cursor_on_a_use_prepares_the_class_it_names() { + // Three kinds of use, all answered by the same two layers + // `textDocument/definition` uses. + let text = "\ +class base; +endclass + +class child extends base; + base handle; + function void f(); + base local_one; + endfunction +endclass +"; + let (_tree, ws, uri) = workspace("uses", &[("u.sv", text)]); + let uses = [ + ("the `extends` base", at(text, "extends base") + 8), + ("a property's type", at(text, "base handle")), + ("a method local's type", at(text, "base local_one")), + ]; + for (what, offset) in uses { + let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{what}")); + assert_eq!(items.len(), 1, "{what}: {items:#?}"); + assert_eq!(shape(&items[0]), ("base".to_string(), "u.sv".to_string(), 0), "{what}"); + } +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): the `class` +/// keyword and a property are inside `base` and prepare it. A module +/// and its wire still prepare nothing — modules stay off this view. +#[test] +fn a_position_on_no_class_prepares_the_enclosing_one_or_nothing() { + let text = "\ +class base; + int x; +endclass + +module m; + wire w; +endmodule +"; + let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]); + let name = |offset| shape(&prepare(&ws, &uri, offset).expect("a class")[0]).0; + assert_eq!(name(0), "base", "the `class` keyword is inside `base`"); + assert_eq!(name(at(text, "int x") + 4), "base", "a property name is inside `base`"); + assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class"); + assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire"); +} + +#[test] +fn a_cursor_just_past_the_last_character_of_a_name_still_prepares() { + // Where a double-click and an end-of-word motion leave it. + let (_tree, ws, uri) = workspace("edge", &[("base.sv", BASE)]); + assert!(prepare(&ws, &uri, at(BASE, "base") + 4).is_some()); +} + +#[test] +fn a_class_two_files_declare_prepares_both_rather_than_guessing() { + let dup = "class dup;\nendclass\n"; + let user = "class user extends dup;\nendclass\n"; + let (_tree, ws, uri) = workspace("dup", &[("user.sv", user), ("a.sv", dup), ("b.sv", dup)]); + let items = prepare(&ws, &uri, at(user, "extends dup") + 8).expect("both"); + let files: Vec = items.iter().map(|i| shape(i).1).collect(); + assert_eq!(files, ["a.sv", "b.sv"], "every declaration, as definition does"); +} + +#[test] +fn an_unopened_document_prepares_nothing() { + let ws = Workspace::default(); + let uri = path_to_uri(std::path::Path::new("/nowhere/c.sv")).expect("uri"); + assert!(prepare(&ws, &uri, 0).is_none()); +} + +#[test] +fn an_untitled_buffer_prepares_from_itself() { + // No path, so no index entry — but the declaration is right there in + // the buffer, and its own hierarchy root is a fair answer. + use std::str::FromStr; + let text = "class scratch;\nendclass\n"; + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + let items = prepare(&ws, &uri, at(text, "scratch")).expect("the buffer's own class"); + assert_eq!(items[0].name, "scratch"); + assert_eq!(items[0].uri, uri); + assert!(supertypes(&ws, &items[0]).is_empty(), "and it extends nothing"); +} + +#[test] +fn an_interface_class_is_a_node() { + // Was `..._is_not_a_node_because_the_parser_does_not_model_one` until + // `vendor-formal-grammar` (2026-09-02) made `interface class` an + // ordinary `ClassDecl` carrying the word in its prefix. It declares a + // class symbol, so it prepares like any other class — which is what + // gives the `implements` edge below something to point at. + let text = "interface class ic;\n pure virtual function void f();\nendclass\n"; + let (_tree, ws, uri) = workspace("ifaceclass", &[("ic.sv", text)]); + let items = prepare(&ws, &uri, at(text, "ic")).expect("the interface class"); + assert_eq!(items.len(), 1); + assert_eq!(items[0].name, "ic"); + assert!(supertypes(&ws, &items[0]).is_empty(), "and it implements nothing"); +} + +#[test] +fn a_class_declared_in_a_package_in_a_module_and_in_a_class_is_all_found() { + let text = "\ +package p; + class in_package; + endclass +endpackage + +module m; + class in_module; + endclass +endmodule + +class outer; + class inner; + endclass +endclass +"; + let (_tree, ws, uri) = workspace("nesting", &[("n.sv", text)]); + for name in ["in_package", "in_module", "outer", "inner"] { + let items = prepare(&ws, &uri, at(text, &format!("class {name}")) + 6) + .unwrap_or_else(|| panic!("{name} is a class")); + assert_eq!(items[0].name, name); + } +} + +// ------------------------------------------------------------------ +// supertypes +// ------------------------------------------------------------------ + +#[test] +fn supertypes_name_the_base_declared_in_the_same_file() { + let text = "class base;\nendclass\n\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("infile", &[("both.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class child") + 6).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "both.sv".to_string(), 0)); + assert_eq!(bases[0].kind, SymbolKind::CLASS); +} + +#[test] +fn supertypes_reach_a_base_declared_in_another_file() { + // The workspace overlay answers the bare `base`, which is what the + // overlay-promotion round made reachable — no lookup of this feature's + // own. + let (_tree, ws, uri) = two("crossfile"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); +} + +#[test] +fn a_qualified_base_resolves_through_its_package() { + let pkg = "package p;\n class base;\n endclass\nendpackage\n"; + let child = "class child extends p::base;\nendclass\n"; + let (_tree, ws, uri) = workspace("qualified", &[("child.sv", child), ("p.sv", pkg)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "p.sv".to_string(), 1)); +} + +#[test] +fn a_parameterized_base_resolves_by_its_bare_name() { + // `#( ... )` lives on its own field, so the base name the parser stores + // is already bare and nothing here unwraps anything. + let child = "class child extends base #(8);\nendclass\n"; + let (_tree, ws, uri) = workspace("param", &[("child.sv", child), ("base.sv", BASE)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); +} + +#[test] +fn a_base_the_workspace_does_not_declare_yields_no_supertype() { + // The UVM shape: `uvm_component` is in a library nobody indexed. No + // item is better than an item pointing at a file that is not there. + let child = "class child extends uvm_component;\nendclass\n"; + let (_tree, ws, uri) = workspace("unknown", &[("child.sv", child)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + assert!(supertypes(&ws, &root).is_empty()); +} + +#[test] +fn a_class_that_extends_nothing_has_no_supertypes() { + let (_tree, ws, uri) = workspace("root", &[("base.sv", BASE)]); + let root = prepare(&ws, &uri, at(BASE, "base")).expect("base")[0].clone(); + assert!(supertypes(&ws, &root).is_empty()); +} + +#[test] +fn an_implements_clause_names_a_supertype() { + // Was `..._names_no_supertype` until `vendor-formal-grammar` + // (2026-09-02): `implements` names an interface class, and now that one + // is a `ClassDecl` there is a declaration to point at. The hop is the + // same one `extends` takes, so a supertype in another file works with + // no lookup of this feature's own. + let base = "interface class api;\n pure virtual function void f();\nendclass\n"; + let child = "class child implements api;\nendclass\n"; + let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("api.sv", base)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(shape(&bases[0]), ("api".to_string(), "api.sv".to_string(), 0)); +} + +#[test] +fn extends_and_implements_are_both_edges_of_the_same_answer() { + let api = "interface class api;\nendclass\n"; + let base = "class base;\nendclass\n"; + let child = "class child extends base implements api;\nendclass\n"; + let (_tree, ws, uri) = + workspace("both", &[("child.sv", child), ("base.sv", base), ("api.sv", api)]); + let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone(); + let names: Vec = supertypes(&ws, &root).iter().map(|i| i.name.clone()).collect(); + assert_eq!(names, ["base", "api"], "the base first, then the interfaces, in source order"); +} + +#[test] +fn supertypes_answer_for_a_file_no_editor_has_open() { + // What a client does after `subtypes`: it sends back an item naming a + // file it never opened, and the hop has to work anyway. + let (_tree, ws, uri) = two("closedfile"); + let base_root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); + assert!(ws.document(&base_root.uri).is_none(), "premise: base.sv is not open"); + let children = subtypes(&ws, &base_root); + assert_eq!(children.len(), 1); + // And `child.sv` *is* open, so go one further: an item from a closed + // file, asked for its own base. + let bases = supertypes(&ws, &children[0]); + assert_eq!(shape(&bases[0]), ("base".to_string(), "base.sv".to_string(), 0)); +} + +#[test] +fn an_item_naming_a_file_that_is_gone_answers_with_nothing() { + let (tree, ws, uri) = two("missing"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + assert_eq!(supertypes(&ws, &root).len(), 1, "premise"); + let mut stale = root.clone(); + stale.uri = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); + assert!(supertypes(&ws, &stale).is_empty(), "no file, no supertype, no panic"); + let mut renamed = root; + renamed.name = "no_such_class".to_string(); + assert!(supertypes(&ws, &renamed).is_empty(), "a name the file does not declare"); +} + +// ------------------------------------------------------------------ +// subtypes +// ------------------------------------------------------------------ + +#[test] +fn subtypes_name_every_class_that_extends_this_one() { + let text = "\ +class base; +endclass + +class first extends base; +endclass + +class second extends base; +endclass + +class unrelated; +endclass +"; + let (_tree, ws, uri) = workspace("subs", &[("all.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + let children = subtypes(&ws, &root); + assert_eq!( + children.iter().map(shape).collect::>(), + [ + ("first".to_string(), "all.sv".to_string(), 3), + ("second".to_string(), "all.sv".to_string(), 6), + ], + "sorted by file then position: {children:#?}" + ); +} + +#[test] +fn subtypes_reach_other_files_in_a_deterministic_order() { + let base = "class base;\nendclass\n"; + let one = "class one extends base;\nendclass\n"; + let two_text = "class two extends base;\nendclass\n"; + let three = "class three extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace( + "crosssubs", + &[("base.sv", base), ("c.sv", three), ("a.sv", one), ("b.sv", two_text)], + ); + let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); + let first = subtypes(&ws, &root); + assert_eq!( + first.iter().map(|i| shape(i).1).collect::>(), + ["a.sv", "b.sv", "c.sv"], + "sorted by URI, not by whatever order the files were read in" + ); + assert_eq!(first.iter().map(|i| i.name.clone()).collect::>(), ["one", "two", "three"]); + let again = subtypes(&ws, &root); + assert_eq!(first, again, "the same question twice gives the same answer"); +} + +#[test] +fn a_class_nobody_extends_has_no_subtypes() { + let (_tree, ws, uri) = two("leaf"); + let root = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + assert!(subtypes(&ws, &root).is_empty()); +} + +#[test] +fn a_qualified_base_is_not_claimed_by_the_bare_name_it_ends_with() { + // The `hierarchy` precedent: matching on the trailing segment would let + // `other_pkg::base` claim to extend *this* `base`. Zero of the 309 + // `extends` clauses in the checked-in corpus are qualified, so this + // costs nothing measurable and never lies. The asymmetry with + // `supertypes` (which *does* follow `p::base`, through the package) is + // deliberate and documented. + let pkg = "package other_pkg;\n class base;\n endclass\nendpackage\n"; + let base = "class base;\nendclass\n"; + let child = "class child extends other_pkg::base;\nendclass\n"; + let (_tree, ws, uri) = + workspace("qualsub", &[("base.sv", base), ("p.sv", pkg), ("child.sv", child)]); + let root = prepare(&ws, &uri, at(base, "base")).expect("base")[0].clone(); + assert!(subtypes(&ws, &root).is_empty(), "the file-scope `base` is not the one extended"); +} + +#[test] +fn a_class_extended_only_outside_the_index_scope_has_no_subtypes() { + // The scope ladder decides which files exist; a file the configured + // filelist omits extends nothing, exactly as it references nothing. + let tree = Tree::new("scope"); + tree.write("base.sv", BASE); + tree.write("child.sv", CHILD); + tree.write("files.f", "base.sv\n"); + tree.write("lucisv.toml", "filelist = \"files.f\"\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri"); + ws.set_document(base_uri.clone(), BASE.to_string()); + + let root = prepare(&ws, &base_uri, at(BASE, "base")).expect("base")[0].clone(); + assert!(subtypes(&ws, &root).is_empty(), "child.sv is out of scope"); +} + +#[test] +fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() { + // Superseded this round (incremental-index, 2026-08-27): + // `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk + // over `Workspace::sources()`, so a keystroke in another buffer moved + // the answer before anything rebuilt. Subtypes are the index's + // inheritance-edge table now — as of its last build or update, both of + // which fold every open buffer in. Same rule as the call hierarchy's + // census, pinned from both sides. + let (tree, mut ws, uri) = two("unsaved"); + let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone(); + assert_eq!(subtypes(&ws, &root).len(), 1, "premise"); + + let fresh = tree.path.join("child.sv"); + let child_uri = path_to_uri(&fresh).expect("uri"); + ws.set_document(child_uri, "class child;\nendclass\n".to_string()); + assert_eq!( + subtypes(&ws, &root).len(), + 1, + "the buffer alone does not move the answer — the index has not seen it" + ); + assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough"); + assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away"); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): malformed `extends` clauses at the last-byte offset +// ------------------------------------------------------------------ +// +// `extends.name_span.end - 1` only underflows or lands off the class if +// `name_span` is empty or missing — checked here at the boundary rather +// than only trusted from reading `parse_class_extends`. In every case +// below the tolerant parser either fails the whole `class` item (so there +// is no `ClassDecl` to ask about at all) or produces a non-empty span; +// the assertion each time is survival, not a particular answer. + +#[test] +fn an_extends_clause_with_no_base_name_never_panics() { + // `class a extends ;` — nothing for `parse_scoped_name` to read after + // `extends`, so `parse_class_extends` errors and the whole `class a` + // item fails to parse; there is no `ClassExtends` with an empty span + // to feed the offset math, but the walk must survive regardless of + // what the tolerant parser recovers into. + let text = "class a extends ;\nendclass\n"; + let (_tree, ws, uri) = workspace("emptyextends", &[("a.sv", text)]); + if let Some(items) = prepare(&ws, &uri, at(text, "class a") + 6) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } +} + +#[test] +fn an_extends_clause_at_eof_never_panics() { + // The file ends mid-header, no `;`, no `endclass`. + let text = "class child extends base"; + let (_tree, ws, uri) = workspace("eofextends", &[("child.sv", text), ("base.sv", BASE)]); + if let Some(items) = prepare(&ws, &uri, at(text, "child")) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } +} + +#[test] +fn a_qualified_base_with_nothing_after_the_double_colon_never_panics() { + // `pkg::` with no tail identifier: `parse_scoped_name` errors after + // the `::`, so this is another whole-class parse failure, not an + // empty tail span. + let text = "class child extends pkg::;\nendclass\n"; + let (_tree, ws, uri) = workspace("danglingcolon", &[("child.sv", text)]); + if let Some(items) = prepare(&ws, &uri, at(text, "child")) { + let _ = supertypes(&ws, &items[0]); + let _ = subtypes(&ws, &items[0]); + } +} + +#[test] +fn a_single_character_base_name_resolves() { + let text = "class b;\nendclass\nclass a extends b;\nendclass\n"; + let (_tree, ws, uri) = workspace("shortname", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(bases[0].name, "b"); +} + +#[test] +fn multibyte_text_immediately_after_the_extends_name_does_not_shift_the_offset() { + // The last-byte trick reads `name_span` alone, which the parser + // measures in bytes independent of what follows — but attack the + // boundary anyway: a multibyte comment starts at the very next byte + // after `base`. + let text = "class base;\nendclass\nclass mid extends base/*🎉 日本語*/;\nendclass\n"; + let (_tree, ws, uri) = workspace("multibyteafter", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class mid") + 6).expect("mid")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "{bases:#?}"); + assert_eq!(bases[0].name, "base"); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): prepare on the keyword, and name shadowing +// ------------------------------------------------------------------ + +/// Reversed by call-hierarchy-everywhere (2026-10-14): the keyword is +/// inside `child`'s header and prepares `child` — still not `base`. +#[test] +fn prepare_on_the_extends_keyword_itself_prepares_the_class_it_is_written_in() { + let text = "class base;\nendclass\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]); + let items = prepare(&ws, &uri, at(text, "extends") + 2).expect("the enclosing class"); + assert_eq!(shape(&items[0]).0, "child", "the keyword, not a name"); +} + +/// Reversed by call-hierarchy-everywhere (2026-10-14): the variable use +/// is inside `child` and prepares `child`. The point of the pin stands — +/// it never prepares the class `base` its text spells. +#[test] +fn a_class_name_shadowed_by_a_local_variable_prepares_the_enclosing_class() { + // `base` is both a class and, inside `child`'s method, a local + // variable name. The use on the right-hand side of the assignment + // names the variable, not the class, and must not be treated as a + // type-hierarchy node just because the text matches. + let text = "\ +class base; +endclass + +class child extends base; + function void f(); + int base; + base = base + 1; + endfunction +endclass +"; + let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]); + let use_offset = at(text, "base + 1"); + let items = prepare(&ws, &uri, use_offset).expect("the enclosing class"); + assert_eq!(items.len(), 1); + assert_eq!(shape(&items[0]).0, "child", "a local variable named `base`, not the class"); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): deep chains, cheap per hop +// ------------------------------------------------------------------ + +#[test] +fn a_ten_deep_chain_answers_each_hop_without_recursing() { + let names: Vec = (0..10).map(|i| format!("c{i}")).collect(); + let mut files: Vec<(String, String)> = Vec::new(); + for (i, name) in names.iter().enumerate() { + let text = match names.get(i + 1) { + Some(next) => format!("class {name} extends {next};\nendclass\n"), + None => format!("class {name};\nendclass\n"), + }; + files.push((format!("{name}.sv"), text)); + } + let refs: Vec<(&str, &str)> = files.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect(); + let (_tree, ws, uri) = workspace("chain", &refs); + let root_text = &files[0].1; + let mut node = prepare(&ws, &uri, at(root_text, "c0")).expect("c0")[0].clone(); + for expected_next in &names[1..] { + let up = supertypes(&ws, &node); + assert_eq!(up.len(), 1, "{up:#?}"); + assert_eq!(&up[0].name, expected_next); + node = up[0].clone(); + } + assert!(supertypes(&ws, &node).is_empty(), "the chain really ends at the last class"); +} + +#[test] +fn a_nameless_item_reads_no_files_at_all() { + // A malformed item from a client: the prefilter matches every file for + // an empty name, so without the guard this would read and parse the + // whole workspace to find nothing. + let (_tree, ws, uri) = two("nameless"); + let mut nameless = prepare(&ws, &uri, at(CHILD, "child")).expect("child")[0].clone(); + nameless.name = String::new(); + assert!(subtypes(&ws, &nameless).is_empty()); + assert!(supertypes(&ws, &nameless).is_empty()); +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): census correctness — the substring prefilter is not +// the match step, and same-named classes across files are a known, +// documented (not previously pinned) source of imprecision. +// ------------------------------------------------------------------ + +#[test] +fn a_file_containing_the_name_as_a_substring_but_no_matching_extends_is_not_a_false_positive() { + // `database` passes the substring prefilter for the name `base` (it + // contains it), and `class d extends database;` passes it too — but + // neither should ever be counted as extending `base`. The match step + // (`extends_name(decl.class) != Some(item.name.as_str())`) is a full + // string comparison, not a substring one, so both must be rejected. + let text = "\ +class base; +endclass + +class database; +endclass + +class d extends database; +endclass +"; + let (_tree, ws, uri) = workspace("substring", &[("f.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + assert!( + subtypes(&ws, &root).is_empty(), + "`database` and `extends database` must not count as extending `base`" + ); +} + +#[test] +fn subtypes_of_two_same_named_classes_in_different_files_share_one_list() { + // Documented in the feature README as a deliberate consequence of + // matching by name and not by uri (the same policy + // `callHierarchy/incomingCalls` uses for a module name), but not + // previously pinned by a test: `subtypes` cannot tell which of two + // same-named `base` declarations `sub` really extends, so *both* + // items answer with `sub` in their subtype list. This is the bound on + // the false positive the name-as-written match allows — not + // eliminated, but confined to genuinely same-named declarations. + let base_a = "class base;\nendclass\n"; + let base_b = "class base;\nendclass\n"; + let sub = "class sub extends base;\nendclass\n"; + let (_tree, ws, uri) = + workspace("samenamesub", &[("sub.sv", sub), ("a.sv", base_a), ("b.sv", base_b)]); + let roots = prepare(&ws, &uri, at(sub, "extends base") + 8).expect("both bases"); + assert_eq!(roots.len(), 2, "two same-named declarations: {roots:#?}"); + for root in &roots { + let children = subtypes(&ws, root); + assert_eq!(children.len(), 1, "{:?}: {children:#?}", root.uri); + assert_eq!(children[0].name, "sub"); + } +} + +// ------------------------------------------------------------------ +// QA (2026-08-26): a class nested inside a generate block +// ------------------------------------------------------------------ + +#[test] +fn a_class_declared_inside_a_generate_block_is_not_found_by_this_walk() { + // The README's Assumptions section states "a generate block is not + // descended into — no class lives there." That justification is not + // quite right: `vlog_parser` *does* parse a `class` written inside + // `generate`/`if`-generate the same way it parses one at module + // scope (`parse_gen_block` shares `item_or_recover` with ordinary + // module-item parsing), so the class is a real `ItemKind::Class` + // node — it is just nested inside `ItemKind::GenIf`/`GenerateRegion`, + // which `collect()` does not descend into. This pins today's answer + // (not found) as a documented gap rather than a silent one; see the + // QA log for the finding filed against the README's wording. + let text = "\ +module m; + generate + if (1) begin : g + class Foo; + int x; + endclass + end + endgenerate +endmodule +"; + let (_tree, ws, uri) = workspace("generateclass", &[("f.sv", text)]); + assert!( + prepare(&ws, &uri, at(text, "class Foo") + 6).is_none(), + "known gap: a class inside a generate block is invisible to this walk" + ); +} + +// ------------------------------------------------------------------ +// cycles +// ------------------------------------------------------------------ + +#[test] +fn a_self_extending_class_answers_one_hop_in_both_directions_without_duplicating() { + // Broken code, reachable through the tolerant parser. Each request is + // one hop, so neither can loop; the assertion is that the answer is one + // item and not the same class twice. + let text = "class a extends a;\nendclass\n"; + let (_tree, ws, uri) = workspace("selfextends", &[("a.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class a") + 6).expect("a")[0].clone(); + let bases = supertypes(&ws, &root); + assert_eq!(bases.len(), 1, "one item, not two: {bases:#?}"); + assert_eq!(bases[0].name, "a"); + assert_eq!(bases[0].selection_range, root.selection_range, "and it is the same node"); + let children = subtypes(&ws, &root); + assert_eq!(children.len(), 1, "one item, not two: {children:#?}"); + assert_eq!(children[0].selection_range, root.selection_range); +} + +#[test] +fn a_two_class_cycle_terminates_in_both_directions() { + let a = "class a extends b;\nendclass\n"; + let b = "class b extends a;\nendclass\n"; + let (_tree, ws, uri) = workspace("cycle", &[("a.sv", a), ("b.sv", b)]); + let root_a = prepare(&ws, &uri, at(a, "class a") + 6).expect("a")[0].clone(); + let up = supertypes(&ws, &root_a); + assert_eq!(up.len(), 1, "a -> b: {up:#?}"); + assert_eq!(up[0].name, "b"); + let hop2 = up[0].clone(); + let up2 = supertypes(&ws, &hop2); + assert_eq!(up2.len(), 1, "b -> a: {up2:#?}"); + assert_eq!(up2[0].name, "a"); + // And the other direction mirrors it, one hop at a time. + let down = subtypes(&ws, &hop2); + assert_eq!(down.len(), 1, "b's only subtype is a: {down:#?}"); + assert_eq!(down[0].name, "a"); +} + +// ------------------------------------------------------------------ +// odds and ends +// ------------------------------------------------------------------ + +#[test] +fn positions_are_utf16_units_on_a_line_carrying_multibyte_text() { + let text = "// é 🎉\nclass base;\nendclass\nclass child extends base;\nendclass\n"; + let (_tree, ws, uri) = workspace("utf16", &[("u.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + assert_eq!( + (root.selection_range.start.line, root.selection_range.start.character), + (1, 6), + "the name of the declaration, in UTF-16 units" + ); + let children = subtypes(&ws, &root); + assert_eq!(children.len(), 1); + assert_eq!( + (children[0].selection_range.start.character, children[0].selection_range.end.character), + (6, 11), + "`child`, in UTF-16 units" + ); +} + +#[test] +fn a_buffer_that_does_not_parse_invents_no_types() { + // Whatever the tolerant parse recovered from an unclosed class body, + // nothing may panic and no edge may be invented — the assertion is + // deliberately on survival, so a change in recovery is not a failure. + let broken = "class child extends base;\n int y\n"; + let (_tree, ws, uri) = workspace("broken", &[("child.sv", broken), ("base.sv", BASE)]); + if let Some(items) = prepare(&ws, &uri, at(broken, "child")) { + for base in supertypes(&ws, &items[0]) { + assert_eq!(base.name, "base", "only a class really written there"); + assert!(base.selection_range.start >= base.range.start, "selection inside range"); + } + let _ = subtypes(&ws, &items[0]); + } +} + +#[test] +fn every_item_keeps_its_selection_range_inside_its_range() { + // The protocol requires it, and a client that trusts it will scroll to + // a nonsense position otherwise. + let text = "\ +class base; +endclass + +class child extends base; +endclass +"; + let (_tree, ws, uri) = workspace("contained", &[("c.sv", text)]); + let root = prepare(&ws, &uri, at(text, "class base") + 6).expect("base")[0].clone(); + let mut all = vec![root.clone()]; + all.extend(subtypes(&ws, &root)); + all.extend(supertypes(&ws, &all[1].clone())); + assert_eq!(all.len(), 3, "root, one subtype, one supertype"); + for item in &all { + assert!(item.range.start <= item.selection_range.start, "{item:#?}"); + assert!(item.selection_range.end <= item.range.end, "{item:#?}"); + } +} + +// ------------------------------------------------------------------ +// the corpus, smoke-tested +// ------------------------------------------------------------------ + +/// What `subtypes` costs after the inheritance-edge table, against the +/// workspace walk it replaced. `#[ignore]`d: it prints a number rather +/// than asserting one — the budget is asserted in +/// `the_corpus_uvm_classes_answer_all_three_requests`. +#[test] +#[ignore = "perf measurement over corpus/, printed not asserted; run with --ignored --nocapture"] +fn qa_perf_subtypes_lookup_against_the_walk_it_replaced() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv"); + let Ok(text) = fs::read_to_string(&lib) else { + eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&lib).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6; + let child = prepare(&ws, &uri, offset).expect("the class")[0].clone(); + let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test"); + + let mut lookup = std::time::Duration::ZERO; + let mut walk = std::time::Duration::ZERO; + for _ in 0..3 { + let started = std::time::Instant::now(); + let found = subtypes(&ws, &base); + lookup = lookup.max(started.elapsed()); + assert!(!found.is_empty()); + let started = std::time::Instant::now(); + let _ = ws.sources(); + walk = walk.max(started.elapsed()); + } + eprintln!( + "typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \ + used to begin with) is {walk:?}", + ws.index().files().len() + ); +} + +/// Every class of a real UVM-shaped corpus file, through all three +/// requests, plus one known `extends` chain. Skipped when `corpus/` is not +/// checked out (`tools/corpus_fetch.sh`), like the other corpus tests. +#[test] +fn the_corpus_uvm_classes_answer_all_three_requests() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv"); + let Ok(text) = fs::read_to_string(&lib) else { + eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping"); + return; + }; + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![corpus]); + let uri = path_to_uri(&lib).expect("uri"); + ws.set_document(uri.clone(), text.clone()); + let files = ws.index().files().len(); + + // Every class declared in the file, both directions. No panic, and + // every item the protocol's containment rule. + let doc = ws.document(&uri).expect("the open buffer"); + let names: Vec = + classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect(); + assert!(names.len() > 20, "the file really is class-heavy: {}", names.len()); + let mut with_a_base = 0; + for name in &names { + let offset = at(&text, &format!("class {name}")) + 6; + let items = prepare(&ws, &uri, offset).unwrap_or_else(|| panic!("{name} is a class")); + assert_eq!(items[0].name, *name); + let up = supertypes(&ws, &items[0]); + let down = subtypes(&ws, &items[0]); + if !up.is_empty() { + with_a_base += 1; + } + for item in up.iter().chain(down.iter()) { + assert_eq!(item.kind, SymbolKind::CLASS); + assert!(item.range.start <= item.selection_range.start, "{item:#?}"); + assert!(item.selection_range.end <= item.range.end, "{item:#?}"); + } + } + assert!(with_a_base > 10, "most of these extend something indexed: {with_a_base}"); + + // The chain the corpus really has: + // `core_ibex_debug_intr_basic_test extends core_ibex_base_test extends + // uvm_test`, and `uvm_test` is in a library this corpus does not carry. + let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6; + let child = prepare(&ws, &uri, offset).expect("the class")[0].clone(); + let up = supertypes(&ws, &child); + assert_eq!(up.len(), 1, "{up:#?}"); + assert_eq!(up[0].name, "core_ibex_base_test"); + assert!( + up[0].uri.as_str().ends_with("core_ibex_base_test.sv"), + "declared in its own file: {}", + up[0].uri.as_str() + ); + assert!( + supertypes(&ws, &up[0]).is_empty(), + "`uvm_test` is not in this corpus, so the chain stops rather than guessing" + ); + let down = subtypes(&ws, &up[0]); + assert!(down.len() > 5, "many tests extend the base test: {}", down.len()); + assert!( + down.iter().any(|i| i.name == "core_ibex_debug_intr_basic_test"), + "and the class we came from is one of them" + ); + // What each direction costs over the whole corpus. The budget is + // deliberately loose — a debug build on a loaded machine is the worst + // case this ever runs in — and exists to catch an order-of-magnitude + // regression, not to pin a number; the numbers themselves are in + // `docs/features/type-hierarchy/README.md`. + let base = up[0].clone(); + let mut sub_cost = std::time::Duration::ZERO; + let mut super_cost = std::time::Duration::ZERO; + for _ in 0..3 { + let started = std::time::Instant::now(); + let _ = subtypes(&ws, &base); + sub_cost = sub_cost.max(started.elapsed()); + let started = std::time::Instant::now(); + let _ = supertypes(&ws, &child); + super_cost = super_cost.max(started.elapsed()); + } + eprintln!( + "corpus: {} files, {} classes in core_ibex_test_lib.sv, {with_a_base} with an indexed \ + base; core_ibex_base_test has {} subtypes (worst of three: subtypes {sub_cost:?}, \ + supertypes {super_cost:?})", + files, + names.len(), + down.len() + ); + assert!(sub_cost < std::time::Duration::from_millis(1500), "subtypes cost {sub_cost:?}"); + assert!(super_cost < std::time::Duration::from_millis(500), "supertypes cost {super_cost:?}"); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_formatter/src/format/case.rs b/crates/vlog_formatter/src/format/case.rs new file mode 100644 index 0000000..bac26cd --- /dev/null +++ b/crates/vlog_formatter/src/format/case.rs @@ -0,0 +1,123 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! `case` items: the `A, B:` label head (shared with the generate `case` +//! and `randsequence` arms that spell one the same way), an item with its +//! body, the `case … endcase` body, and the optional `:` after `default`. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; + +use super::comment::is_line_comment; +use super::{skip_trivia, Fmt}; +use crate::style::Placement; + +impl<'a> Fmt<'a> { + /// The `A, B:` head of a case item — `default:` when the list is empty. + /// Labels normally share one line; as soon as any of them carries a + /// comment they go one per line, so a comment written between two labels + /// is printed between the same two labels instead of drifting past them. + pub(super) fn case_labels( + &self, + labels: &[ExprItem], + before_colon: &[Comment], + item: TextRange, + ) -> Doc { + if labels.is_empty() { + if !self.default_has_colon(item) { + return text("default"); + } + let mut docs = vec![text("default")]; + self.slot_comments(before_colon, &mut docs); + docs.push(text(":")); + return concat(docs); + } + let plain = labels.iter().all(|l| { + l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none() + }); + if plain { + let docs: Vec = labels.iter().map(|l| self.expr(&l.expr)).collect(); + return concat(vec![concat(join(docs, text(", "))), text(":")]); + } + let last = labels.len() - 1; + let mut docs = Vec::new(); + for (i, l) in labels.iter().enumerate() { + if i > 0 { + docs.push(Doc::HardLine); + } + for c in &l.meta.leading { + docs.push(self.comment(c)); + docs.push(Doc::HardLine); + } + docs.push(self.expr(&l.expr)); + let ends_line = self.inline_comments(&l.meta.before_sep, &mut docs); + if i < last { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(",")); + } else if ends_line { + docs.push(Doc::HardLine); + } + if let Some(tr) = &l.meta.trailing { + docs.push(text(" ")); + docs.push(self.comment(tr)); + if i == last && is_line_comment(&tr.text) { + docs.push(Doc::HardLine); + } + } + } + docs.push(text(":")); + concat(docs) + } + + fn case_item(&self, item: &CaseItem) -> Doc { + // `default;` — the colon IEEE 1800 §12.5 makes optional, with a null + // body. The `;` closes the keyword rather than standing as a body of + // its own, so it hugs instead of going through `stmt_as_body`. + if item.labels.is_empty() + && matches!(item.stmt.kind, StmtKind::Null) + && is_bare(&item.stmt.meta) + && !self.default_has_colon(item.span) + { + return text("default;"); + } + let labels = self.case_labels(&item.labels, &item.before_colon, item.span); + self.body_after(labels, &item.stmt, 0, Placement::SameLine) + } + + /// The items of a `case`/`randcase` body. `skip` is the number of leading + /// comments of the *first* item the `case (...)` header already printed + /// inside its parentheses (see [`Fmt::header_parens`]). + pub(super) fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc { + let mut body = Vec::new(); + for (i, item) in items.iter().enumerate() { + body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 })); + body.push(self.case_item(item)); + body.extend(self.trailing(&item.meta)); + } + body.extend(self.dangling(dangling)); + concat(vec![indent(body), Doc::HardLine, text("endcase")]) + } + + /// True when the source wrote the optional `:` after a `default` case + /// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and + /// the token stream has to come back with exactly what was written. + fn default_has_colon(&self, span: TextRange) -> bool { + let after = span.start as usize + "default".len(); + matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':') + } +} + +/// True when a node carries no trivia at all, so printing it cannot move a +/// comment anywhere. +fn is_bare(meta: &Meta) -> bool { + meta.leading.is_empty() + && meta.trailing.is_none() + && meta.before_sep.is_empty() + && meta.attrs.is_empty() +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_formatter/src/format/mod.rs b/crates/vlog_formatter/src/format/mod.rs index 3de8792..fae59c6 100644 --- a/crates/vlog_formatter/src/format/mod.rs +++ b/crates/vlog_formatter/src/format/mod.rs @@ -9,13 +9,15 @@ //! //! The rules are one `Fmt` whose methods are spread over the sibling //! modules by grammar domain — `item`, `module`, `instance`, `decl`, -//! `routine`, `class`, `cover`, `sva`, `stmt`, `branch`, `expr` — on top of the -//! shared machinery they all print through — `comment`, `verbatim`, -//! `phrase`, `list`. This file holds what the crate exports (`Config`, -//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and -//! the name helpers every module writes an identifier through. +//! `routine`, `class`, `cover`, `sva`, `stmt`, `case`, `timing`, `branch`, +//! `expr` — on top of the shared machinery they all print through — +//! `comment`, `verbatim`, `phrase`, `list`. This file holds what the crate +//! exports (`Config`, `FormatError`, `format_source`, `format_range`), the +//! `Fmt` state, and the name helpers every module writes an identifier +//! through. mod branch; +mod case; mod class; mod comment; mod cover; @@ -30,6 +32,7 @@ mod randsequence; mod routine; mod stmt; mod sva; +mod timing; mod verbatim; use crate::doc::{concat, text, Doc}; diff --git a/crates/vlog_formatter/src/format/stmt.rs b/crates/vlog_formatter/src/format/stmt.rs index 0da52f4..740744a 100644 --- a/crates/vlog_formatter/src/format/stmt.rs +++ b/crates/vlog_formatter/src/format/stmt.rs @@ -1,23 +1,20 @@ // Author: Guoliang Chen, a Senior Digital Design Engineer //! Statements: the `begin … end` block, a statement as the body of a -//! header (a cuddled block or an indented line), the dispatch from -//! `StmtKind` to its layout, `case` items, and the -//! timing controls and sensitivity lists that head an `always` block or -//! a clocking event. +//! header (a cuddled block or an indented line), and the dispatch from +//! `StmtKind` to its layout. //! //! `stmt_kind` is a dispatch table over `StmtKind` — one arm per -//! statement form — and stays whole; `case` has a layout of its own in the -//! functions after it, `if` in `branch.rs`. +//! statement form — and stays whole; the forms with a layout of their own +//! live next door: `case` in `case.rs`, `if` in `branch.rs`, and the timing +//! controls and sensitivity lists that head a statement in `timing.rs`. use crate::doc::*; use vlog_parser::ast::*; -use vlog_parser::span::TextRange; use vlog_parser::token::Comment; use super::branch::before_keyword; -use super::comment::is_line_comment; -use super::{join_paths, named, skip_trivia, Fmt}; +use super::{join_paths, named, Fmt}; use crate::style::Placement; /// The pieces of a `begin … end` block a printer needs, gathered so the @@ -97,7 +94,7 @@ impl<'a> Fmt<'a> { /// The layout behind both: a block's `begin` goes where `begin` says — /// the style's choice for a statement header, always the label's line /// for a `case` item. - fn body_after(&self, prefix: Doc, s: &Stmt, skip: usize, begin: Placement) -> Doc { + pub(super) fn body_after(&self, prefix: Doc, s: &Stmt, skip: usize, begin: Placement) -> Doc { match &s.kind { StmtKind::Block { label_comments, @@ -155,102 +152,6 @@ impl<'a> Fmt<'a> { concat(docs) } - fn timing_control(&self, tc: &TimingControl) -> Doc { - match tc { - TimingControl::Delay { after_hash, expr } => { - let mut docs = vec![text("#")]; - self.slot_comments(after_hash, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - TimingControl::Event(sens) => self.sens_list(sens), - } - } - - pub(super) fn sens_list(&self, sens: &SensList) -> Doc { - match sens { - // Written without parens, printed without parens: `@ev`, - // `@a.b` — inventing a `( ... )` changes the token stream. - SensList::Bare { expr, after_at } => { - let mut docs = vec![text("@")]; - self.slot_comments(after_at, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - SensList::Star { before, after } => { - if before.is_empty() && after.is_empty() { - return text("@(*)"); - } - // Comments written inside the parens stay inside them, on the - // side of the `*` they were written on. - let mut inner = Vec::new(); - if before.is_empty() { - // `(*` directly followed by anything but `)` lexes as an - // attribute instance, so keep the `*` off the paren. - inner.push(text(" ")); - } - for c in before { - inner.push(self.comment(c)); - inner.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); - } - inner.push(text("*")); - for c in after { - inner.push(text(" ")); - inner.push(self.comment(c)); - if is_line_comment(&c.text) { - inner.push(Doc::HardLine); - } - } - concat(vec![text("@("), indent(inner), text(")")]) - } - SensList::List { items, after_at } => { - // Each separator is printed as it was written: `,` and `or` - // mean the same thing but are different tokens, and rewriting - // one as the other is a token change the safety net rejects. - let mut parts: Vec = Vec::new(); - for i in items { - match i.sep { - Some(SensSep::Comma) => parts.push(text(", ")), - Some(SensSep::Or) => parts.push(text(" or ")), - None => {} - } - for c in &i.meta.leading { - parts.push(self.comment(c)); - parts.push(if is_line_comment(&c.text) { - Doc::HardLine - } else { - text(" ") - }); - } - if let Some(e) = &i.edge { - parts.push(text(e.clone())); - if i.after_edge.is_empty() { - parts.push(text(" ")); - } else { - self.inline_comments_spaced(&i.after_edge, &mut parts); - } - } - parts.push(self.expr(&i.expr)); - // `posedge clk iff enable` — the gate belongs to this - // term, so it prints before the separator, not after it. - if let Some(iff) = &i.iff { - parts.push(text(" iff ")); - parts.push(self.expr(iff)); - } - if self.inline_comments(&i.meta.before_sep, &mut parts) { - parts.push(Doc::HardLine); - } - } - let mut docs = vec![text("@")]; - self.slot_comments(after_at, &mut docs); - docs.push(text("(")); - docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); - docs.push(text(")")); - concat(docs) - } - } - } - /// One arm per `StmtKind`. A dispatch table over the enum, so it stays /// whole past the 150-line mark: the forms that grew a layout of their /// own (`if`, `case`) are the functions after it, and every remaining @@ -563,111 +464,6 @@ impl<'a> Fmt<'a> { StmtKind::Null => text(";"), } } - - /// The `A, B:` head of a case item — `default:` when the list is empty. - /// Labels normally share one line; as soon as any of them carries a - /// comment they go one per line, so a comment written between two labels - /// is printed between the same two labels instead of drifting past them. - pub(super) fn case_labels( - &self, - labels: &[ExprItem], - before_colon: &[Comment], - item: TextRange, - ) -> Doc { - if labels.is_empty() { - if !self.default_has_colon(item) { - return text("default"); - } - let mut docs = vec![text("default")]; - self.slot_comments(before_colon, &mut docs); - docs.push(text(":")); - return concat(docs); - } - let plain = labels.iter().all(|l| { - l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none() - }); - if plain { - let docs: Vec = labels.iter().map(|l| self.expr(&l.expr)).collect(); - return concat(vec![concat(join(docs, text(", "))), text(":")]); - } - let last = labels.len() - 1; - let mut docs = Vec::new(); - for (i, l) in labels.iter().enumerate() { - if i > 0 { - docs.push(Doc::HardLine); - } - for c in &l.meta.leading { - docs.push(self.comment(c)); - docs.push(Doc::HardLine); - } - docs.push(self.expr(&l.expr)); - let ends_line = self.inline_comments(&l.meta.before_sep, &mut docs); - if i < last { - if ends_line { - docs.push(Doc::HardLine); - } - docs.push(text(",")); - } else if ends_line { - docs.push(Doc::HardLine); - } - if let Some(tr) = &l.meta.trailing { - docs.push(text(" ")); - docs.push(self.comment(tr)); - if i == last && is_line_comment(&tr.text) { - docs.push(Doc::HardLine); - } - } - } - docs.push(text(":")); - concat(docs) - } - - fn case_item(&self, item: &CaseItem) -> Doc { - // `default;` — the colon IEEE 1800 §12.5 makes optional, with a null - // body. The `;` closes the keyword rather than standing as a body of - // its own, so it hugs instead of going through `stmt_as_body`. - if item.labels.is_empty() - && matches!(item.stmt.kind, StmtKind::Null) - && is_bare(&item.stmt.meta) - && !self.default_has_colon(item.span) - { - return text("default;"); - } - let labels = self.case_labels(&item.labels, &item.before_colon, item.span); - self.body_after(labels, &item.stmt, 0, Placement::SameLine) - } - - /// The items of a `case`/`randcase` body. `skip` is the number of leading - /// comments of the *first* item the `case (...)` header already printed - /// inside its parentheses (see [`Fmt::header_parens`]). - fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc { - let mut body = Vec::new(); - for (i, item) in items.iter().enumerate() { - body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 })); - body.push(self.case_item(item)); - body.extend(self.trailing(&item.meta)); - } - body.extend(self.dangling(dangling)); - concat(vec![indent(body), Doc::HardLine, text("endcase")]) - } - - /// True when the source wrote the optional `:` after a `default` case - /// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and - /// the token stream has to come back with exactly what was written. - fn default_has_colon(&self, span: TextRange) -> bool { - let after = span.start as usize + "default".len(); - matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':') - } -} - -/// True when a node carries no trivia at all, so printing it cannot move a -/// comment anywhere. -fn is_bare(meta: &Meta) -> bool { - meta.leading.is_empty() - && meta.trailing.is_none() - && meta.before_sep.is_empty() - && meta.attrs.is_empty() } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_formatter/src/format/timing.rs b/crates/vlog_formatter/src/format/timing.rs new file mode 100644 index 0000000..58bc123 --- /dev/null +++ b/crates/vlog_formatter/src/format/timing.rs @@ -0,0 +1,110 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Timing controls and sensitivity lists: the `#delay` or `@(…)` that +//! heads a statement, an `always` block, or a clocking event. + +use crate::doc::*; +use vlog_parser::ast::*; + +use super::comment::is_line_comment; +use super::Fmt; + +impl<'a> Fmt<'a> { + pub(super) fn timing_control(&self, tc: &TimingControl) -> Doc { + match tc { + TimingControl::Delay { after_hash, expr } => { + let mut docs = vec![text("#")]; + self.slot_comments(after_hash, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + TimingControl::Event(sens) => self.sens_list(sens), + } + } + + pub(super) fn sens_list(&self, sens: &SensList) -> Doc { + match sens { + // Written without parens, printed without parens: `@ev`, + // `@a.b` — inventing a `( ... )` changes the token stream. + SensList::Bare { expr, after_at } => { + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + SensList::Star { before, after } => { + if before.is_empty() && after.is_empty() { + return text("@(*)"); + } + // Comments written inside the parens stay inside them, on the + // side of the `*` they were written on. + let mut inner = Vec::new(); + if before.is_empty() { + // `(*` directly followed by anything but `)` lexes as an + // attribute instance, so keep the `*` off the paren. + inner.push(text(" ")); + } + for c in before { + inner.push(self.comment(c)); + inner.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); + } + inner.push(text("*")); + for c in after { + inner.push(text(" ")); + inner.push(self.comment(c)); + if is_line_comment(&c.text) { + inner.push(Doc::HardLine); + } + } + concat(vec![text("@("), indent(inner), text(")")]) + } + SensList::List { items, after_at } => { + // Each separator is printed as it was written: `,` and `or` + // mean the same thing but are different tokens, and rewriting + // one as the other is a token change the safety net rejects. + let mut parts: Vec = Vec::new(); + for i in items { + match i.sep { + Some(SensSep::Comma) => parts.push(text(", ")), + Some(SensSep::Or) => parts.push(text(" or ")), + None => {} + } + for c in &i.meta.leading { + parts.push(self.comment(c)); + parts.push(if is_line_comment(&c.text) { + Doc::HardLine + } else { + text(" ") + }); + } + if let Some(e) = &i.edge { + parts.push(text(e.clone())); + if i.after_edge.is_empty() { + parts.push(text(" ")); + } else { + self.inline_comments_spaced(&i.after_edge, &mut parts); + } + } + parts.push(self.expr(&i.expr)); + // `posedge clk iff enable` — the gate belongs to this + // term, so it prints before the separator, not after it. + if let Some(iff) = &i.iff { + parts.push(text(" iff ")); + parts.push(self.expr(iff)); + } + if self.inline_comments(&i.meta.before_sep, &mut parts) { + parts.push(Doc::HardLine); + } + } + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(text("(")); + docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); + docs.push(text(")")); + concat(docs) + } + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 15118d3..fe8eed6 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -7,9 +7,23 @@ //! attachment phase that folds comments into the neighboring "real" tokens as //! leading/trailing trivia and records blank-line information. The parser and //! formatter then never have to think about interleaved comment tokens. +//! +//! This file is the raw phase's scanner (`RawLexer`) and the entry point +//! that fuses the two ([`tokenize`]). Three pieces of it live next door: +//! numeric literals in `number`, the scan of a function-like `` `define``'s +//! formal-argument list in `define_params`, and the attachment phase in +//! `attach`. use crate::span::TextRange; -use crate::token::{is_keyword, Comment, Token, TokenKind}; +use crate::token::{is_keyword, Token, TokenKind}; + +mod attach; +mod define_params; +mod number; + +use attach::{attach, Attaching}; +use define_params::DefineParams; +use number::is_base_intro; #[derive(Debug, Clone)] pub struct LexError { @@ -575,319 +589,12 @@ impl<'a> RawLexer<'a> { }; trimmed.last() == Some(&b'\\') } - - /// Lex a number starting at an ASCII digit. Handles plain decimal, real - /// numbers with exponents, sized based literals (`8'hFF`, `4'b10_10`, - /// with optional whitespace around the tick), and time-unit suffixes - /// (`10ns`). The returned text is normalized to contain no whitespace. - fn lex_number(&mut self) -> Result { - let start = self.pos; - while self.peek().is_ascii_digit() || self.peek() == b'_' { - self.bump(); - } - // Real number. - if self.peek() == b'.' && self.peek_at(1).is_ascii_digit() { - self.bump(); - while self.peek().is_ascii_digit() || self.peek() == b'_' { - self.bump(); - } - } - if matches!(self.peek(), b'e' | b'E') - && (self.peek_at(1).is_ascii_digit() - || (matches!(self.peek_at(1), b'+' | b'-') && self.peek_at(2).is_ascii_digit())) - { - self.bump(); - if matches!(self.peek(), b'+' | b'-') { - self.bump(); - } - while self.peek().is_ascii_digit() { - self.bump(); - } - } - let mut text = self.text_from(start); - - // Time unit suffix directly attached (1ns, 2.5us). - if self.peek().is_ascii_alphabetic() { - let unit_start = self.pos; - while self.peek().is_ascii_alphabetic() { - self.bump(); - } - text.push_str(&self.text_from(unit_start)); - return Ok(text); - } - - // Sized based literal: whitespace is allowed around the tick - // (`8 'hFF`); normalize it away. - let save = (self.pos, self.line, self.col); - let mut probe = self.pos; - while matches!(self.src.get(probe), Some(b' ') | Some(b'\t')) { - probe += 1; - } - if self.src.get(probe) == Some(&b'\'') - && probe + 1 < self.src.len() - && is_base_intro(self.src[probe + 1]) - && self.src.get(probe + 1) != Some(&b'{') - { - while self.pos < probe { - self.bump(); - } - match self.lex_based_part() { - Ok(based) => { - text.push_str(&based); - return Ok(text); - } - Err(_) => { - self.pos = save.0; - self.line = save.1; - self.col = save.2; - } - } - } - Ok(text) - } - - /// Lex the `'h FF` / `'b1010` / `'0` part, starting at the tick. - fn lex_based_part(&mut self) -> Result { - let start = self.pos; - self.bump(); // ' - let c = self.peek(); - if matches!(c, b'0' | b'1' | b'x' | b'X' | b'z' | b'Z') && !is_ident_char(self.peek_at(1)) { - // Unbased unsized literal: '0 '1 'x 'z - self.bump(); - return Ok(self.text_from(start)); - } - let mut text = String::from("'"); - if matches!(self.peek(), b's' | b'S') { - text.push(self.bump() as char); - } - if !matches!(self.peek(), b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H') { - return Err(self.error("expected number base after '".to_string())); - } - text.push(self.bump() as char); - // A based number whose digits come from a macro: `` 32'h`DM_ADDR `` - // (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The - // digits are preprocessor output lucisv does not expand, so the number - // token ends here, with no digits, and the invocation lexes as the - // macro token it is; the parser rejoins the pair into one primary - // expression and the formatter prints them adjacent, as written. - // - // The backtick must *touch* the base: `` 32'h `DM_ADDR `` keeps the - // "expected digits" error below, because a space there is far more - // likely a typo than this idiom, and accepting it would silently - // change what the source says. - if self.peek() == b'`' { - return Ok(text); - } - // Whitespace is allowed between base and value. - while matches!(self.peek(), b' ' | b'\t') { - self.bump(); - } - let value_start = self.pos; - while self.peek().is_ascii_alphanumeric() || matches!(self.peek(), b'_' | b'?') { - self.bump(); - } - if self.pos == value_start { - return Err(self.error("expected digits after number base".to_string())); - } - text.push_str(&self.text_from(value_start)); - Ok(text) - } -} - -/// Incremental tracker for a function-like `` `define``'s formal-argument -/// list: how deep its parens are, and whether it is still open. -/// -/// One of these lives for the length of one directive, and -/// [`DefineParams::open`] walks **only the bytes added since the last call**. -/// That is the whole point of the type: the question is asked once per line -/// the list stays open on, so re-deriving the depth from the directive's first -/// byte every time would be quadratic in the number of lines — and an -/// unclosed list never stops asking, so a vendor file with one dropped `)` -/// would stall the lexer for minutes (QA, 2026-09-02: 20 000 unclosed lines -/// took 2.5 s that way, and it grew with the square). -struct DefineParams { - /// Absolute byte offset in the source that the scan has consumed. - scanned: usize, - /// Open parens at `scanned`, counting the `(` that opens the list. - depth: u32, - /// What the scan is in the middle of, carried across lines: a default - /// value may hold a paren inside a string or a comment. - mode: ScanMode, - /// `None` until the header has been read. `Some(false)` is **terminal** — - /// either this is not a function-like `` `define``, or its list has - /// closed — and no byte is ever looked at again. - open: Option, - /// Bytes [`DefineParams::advance`] has actually looked at. Counted only in - /// test builds, where it is the structural pin that this scan is one pass - /// and not a rescan — the property a wall-clock bound can only imply. - #[cfg(test)] - walked: usize, -} - -/// What [`DefineParams::advance`] is in the middle of. -#[derive(Clone, Copy, PartialEq)] -enum ScanMode { - Code, - String, - LineComment, - BlockComment, -} - -impl DefineParams { - fn new() -> DefineParams { - DefineParams { - scanned: 0, - depth: 0, - mode: ScanMode::Code, - open: None, - #[cfg(test)] - walked: 0, - } - } - - /// True when the directive running from `start` to `end` is a - /// function-like `` `define`` whose formal-argument list is still open. - /// - /// `end` must never move backwards between calls, which is what makes the - /// whole scan one pass over the directive. - fn open(&mut self, src: &[u8], start: usize, end: usize) -> bool { - if self.open.is_none() { - // The header is decided once. It is a prefix of the directive, so - // the answer cannot change later: the only case where the text so - // far is too short to see a `(` is one where the directive ends - // right there anyway (a `\n` or a comment straight after the name). - self.open = Some(match define_params_start(&src[start..end]) { - Some(at) => { - self.scanned = start + at; - true - } - None => false, - }); - } - if self.open != Some(true) { - return false; - } - self.advance(src, end); - self.open == Some(true) - } - - /// Walk the bytes added since the last call, and nothing else. - fn advance(&mut self, src: &[u8], end: usize) { - #[cfg(test)] - let from = self.scanned; - let mut i = self.scanned; - while i < end { - match self.mode { - ScanMode::String => match src[i] { - b'\\' => i += 1, - b'"' => self.mode = ScanMode::Code, - _ => {} - }, - ScanMode::LineComment => { - if src[i] == b'\n' { - self.mode = ScanMode::Code; - } - } - ScanMode::BlockComment => { - if src[i] == b'*' && src.get(i + 1) == Some(&b'/') { - self.mode = ScanMode::Code; - i += 1; - } - } - ScanMode::Code => match src[i] { - b'"' => self.mode = ScanMode::String, - b'/' if src.get(i + 1) == Some(&b'/') => { - self.mode = ScanMode::LineComment; - i += 1; - } - b'/' if src.get(i + 1) == Some(&b'*') => { - self.mode = ScanMode::BlockComment; - i += 1; - } - b'(' => self.depth += 1, - b')' => { - self.depth = self.depth.saturating_sub(1); - if self.depth == 0 { - // The list closed: the parens of the macro *body* - // can never reopen it, so this is the last byte - // this tracker ever looks at. - self.open = Some(false); - self.scanned = i + 1; - #[cfg(test)] - { - self.walked += self.scanned - from; - } - return; - } - } - _ => {} - }, - } - i += 1; - } - // `i`, not `end`: a two-byte step (`\` in a string, `//`, `*/`) may - // have carried the scan one past `end`, and that byte is consumed. - self.scanned = i; - #[cfg(test)] - { - self.walked += self.scanned - from; - } - } -} - -/// The offset of the `(` that opens a function-like `` `define``'s formal -/// argument list, or `None` when `text` does not start one. -/// -/// Only a `(` that *touches* the macro name opens a list (IEEE 1800 §22.5.1, -/// the same rule `defines.rs` reads the parameters by): `` `define A (x) `` is -/// object-like and its body merely starts with a paren. Everything else that -/// begins with a backtick — a macro invocation above all — answers `None` and -/// keeps the one-line capture it always had. -fn define_params_start(text: &[u8]) -> Option { - const KEYWORD: &[u8] = b"`define"; - let rest = text.strip_prefix(KEYWORD)?; - if !matches!(rest.first(), Some(b' ' | b'\t')) { - return None; - } - let mut i = 0; - while matches!(rest.get(i), Some(b' ' | b'\t')) { - i += 1; - } - let name_start = i; - while rest.get(i).is_some_and(|&c| is_ident_char(c)) { - i += 1; - } - if i == name_start || rest.get(i) != Some(&b'(') { - return None; - } - Some(KEYWORD.len() + i) } fn is_ident_char(c: u8) -> bool { c == b'_' || c == b'$' || c.is_ascii_alphanumeric() } -fn is_base_intro(c: u8) -> bool { - matches!( - c, - b's' | b'S' - | b'd' - | b'D' - | b'b' - | b'B' - | b'o' - | b'O' - | b'h' - | b'H' - | b'0' - | b'1' - | b'x' - | b'X' - | b'z' - | b'Z' - ) -} - /// Directives that consume the rest of the source line. Anything else that /// starts with a backtick is treated as a macro usage token. /// @@ -926,15 +633,6 @@ fn is_line_directive(word: &str) -> bool { ) } -/// What the attachment phase carries from one raw token to the next. -#[derive(Default)] -struct Attaching { - /// Comments waiting for the real token they lead. - pending: Vec, - /// Whether a blank line was seen since the last pending comment. - pending_blank: bool, -} - /// Tokenize source text, attaching comments and blank-line info to tokens. /// /// The two phases are **fused**: each raw token is attached as it is lexed, @@ -970,71 +668,9 @@ fn estimated_tokens(bytes: usize) -> usize { (bytes / 6).min(1 << 20) } -/// Fold one raw token into the token stream: a comment onto its neighbour, -/// a real token onto the end with whatever comments were waiting for it. -fn attach(raw: RawTok, tokens: &mut Vec, state: &mut Attaching) { - match raw.kind { - RawKind::LineComment | RawKind::BlockComment => { - let same_line_as_prev = - raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty(); - let comment = Comment { - text: raw.text, - blank_before: raw.newlines_before > 1 || state.pending_blank, - line: raw.line, - col: raw.col, - span: raw.span, - }; - // A comment that finds no token to trail — unreachable while - // `same_line_as_prev` requires one, kept as a rule rather than a - // hope — leads the next token instead of vanishing (invariant 3). - let orphan = - if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) }; - if let Some(comment) = orphan { - state.pending.push(comment); - state.pending_blank = false; - } - } - RawKind::Real(kind) => { - // Comments already carry their own blank flags; the token is - // blank-separated only if there was a blank line between the last - // comment and the token itself — which is the same test either - // way, so `pending` does not enter into it. - let blank_before = raw.newlines_before > 1; - tokens.push(Token { - kind, - text: raw.text, - line: raw.line, - col: raw.col, - span: raw.span, - leading: std::mem::take(&mut state.pending), - trailing: None, - blank_before, - }); - } - } -} - -/// Hang a comment off the token before it, merging with one already there. -/// Handed back untouched when there is no token before it. -fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option { - let Some(prev) = tokens.last_mut() else { return Some(comment) }; - match &mut prev.trailing { - Some(existing) => { - // Two comments on one line become one node, so its span has to - // cover both — the merge normalizes the gap between them to a - // single space, which is why a merged comment is the one comment - // whose text can differ from `source[span]`. - existing.text.push(' '); - existing.text.push_str(&comment.text); - existing.span = TextRange::new(existing.span.start, comment.span.end); - } - None => prev.trailing = Some(comment), - } - None -} - #[cfg(test)] mod tests { + use super::define_params::{define_params_start, ScanMode}; use super::*; fn kinds(src: &str) -> Vec<(TokenKind, String)> { diff --git a/crates/vlog_parser/src/lexer/attach.rs b/crates/vlog_parser/src/lexer/attach.rs new file mode 100644 index 0000000..6d62653 --- /dev/null +++ b/crates/vlog_parser/src/lexer/attach.rs @@ -0,0 +1,83 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The attachment phase: each raw token folded into the token stream — a +//! comment onto the real token it leads or trails, blank lines recorded. + +use crate::span::TextRange; +use crate::token::{Comment, Token}; + +use super::{RawKind, RawTok}; + +/// What the attachment phase carries from one raw token to the next. +#[derive(Default)] +pub(super) struct Attaching { + /// Comments waiting for the real token they lead. + pending: Vec, + /// Whether a blank line was seen since the last pending comment. + pending_blank: bool, +} + +/// Fold one raw token into the token stream: a comment onto its neighbour, +/// a real token onto the end with whatever comments were waiting for it. +pub(super) fn attach(raw: RawTok, tokens: &mut Vec, state: &mut Attaching) { + match raw.kind { + RawKind::LineComment | RawKind::BlockComment => { + let same_line_as_prev = + raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty(); + let comment = Comment { + text: raw.text, + blank_before: raw.newlines_before > 1 || state.pending_blank, + line: raw.line, + col: raw.col, + span: raw.span, + }; + // A comment that finds no token to trail — unreachable while + // `same_line_as_prev` requires one, kept as a rule rather than a + // hope — leads the next token instead of vanishing (invariant 3). + let orphan = + if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) }; + if let Some(comment) = orphan { + state.pending.push(comment); + state.pending_blank = false; + } + } + RawKind::Real(kind) => { + // Comments already carry their own blank flags; the token is + // blank-separated only if there was a blank line between the last + // comment and the token itself — which is the same test either + // way, so `pending` does not enter into it. + let blank_before = raw.newlines_before > 1; + tokens.push(Token { + kind, + text: raw.text, + line: raw.line, + col: raw.col, + span: raw.span, + leading: std::mem::take(&mut state.pending), + trailing: None, + blank_before, + }); + } + } +} + +/// Hang a comment off the token before it, merging with one already there. +/// Handed back untouched when there is no token before it. +fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option { + let Some(prev) = tokens.last_mut() else { return Some(comment) }; + match &mut prev.trailing { + Some(existing) => { + // Two comments on one line become one node, so its span has to + // cover both — the merge normalizes the gap between them to a + // single space, which is why a merged comment is the one comment + // whose text can differ from `source[span]`. + existing.text.push(' '); + existing.text.push_str(&comment.text); + existing.span = TextRange::new(existing.span.start, comment.span.end); + } + None => prev.trailing = Some(comment), + } + None +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/lexer/define_params.rs b/crates/vlog_parser/src/lexer/define_params.rs new file mode 100644 index 0000000..cbe52fe --- /dev/null +++ b/crates/vlog_parser/src/lexer/define_params.rs @@ -0,0 +1,178 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The formal-argument list of a function-like `` `define``, tracked +//! incrementally so the raw lexer knows whether a directive that spans +//! lines is still inside it. + +use super::is_ident_char; + +/// Incremental tracker for a function-like `` `define``'s formal-argument +/// list: how deep its parens are, and whether it is still open. +/// +/// One of these lives for the length of one directive, and +/// [`DefineParams::open`] walks **only the bytes added since the last call**. +/// That is the whole point of the type: the question is asked once per line +/// the list stays open on, so re-deriving the depth from the directive's first +/// byte every time would be quadratic in the number of lines — and an +/// unclosed list never stops asking, so a vendor file with one dropped `)` +/// would stall the lexer for minutes (QA, 2026-09-02: 20 000 unclosed lines +/// took 2.5 s that way, and it grew with the square). +pub(super) struct DefineParams { + /// Absolute byte offset in the source that the scan has consumed. + pub(super) scanned: usize, + /// Open parens at `scanned`, counting the `(` that opens the list. + depth: u32, + /// What the scan is in the middle of, carried across lines: a default + /// value may hold a paren inside a string or a comment. + mode: ScanMode, + /// `None` until the header has been read. `Some(false)` is **terminal** — + /// either this is not a function-like `` `define``, or its list has + /// closed — and no byte is ever looked at again. + open: Option, + /// Bytes [`DefineParams::advance`] has actually looked at. Counted only in + /// test builds, where it is the structural pin that this scan is one pass + /// and not a rescan — the property a wall-clock bound can only imply. + #[cfg(test)] + pub(super) walked: usize, +} + +/// What [`DefineParams::advance`] is in the middle of. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum ScanMode { + Code, + String, + LineComment, + BlockComment, +} + +impl DefineParams { + pub(super) fn new() -> DefineParams { + DefineParams { + scanned: 0, + depth: 0, + mode: ScanMode::Code, + open: None, + #[cfg(test)] + walked: 0, + } + } + + /// True when the directive running from `start` to `end` is a + /// function-like `` `define`` whose formal-argument list is still open. + /// + /// `end` must never move backwards between calls, which is what makes the + /// whole scan one pass over the directive. + pub(super) fn open(&mut self, src: &[u8], start: usize, end: usize) -> bool { + if self.open.is_none() { + // The header is decided once. It is a prefix of the directive, so + // the answer cannot change later: the only case where the text so + // far is too short to see a `(` is one where the directive ends + // right there anyway (a `\n` or a comment straight after the name). + self.open = Some(match define_params_start(&src[start..end]) { + Some(at) => { + self.scanned = start + at; + true + } + None => false, + }); + } + if self.open != Some(true) { + return false; + } + self.advance(src, end); + self.open == Some(true) + } + + /// Walk the bytes added since the last call, and nothing else. + fn advance(&mut self, src: &[u8], end: usize) { + #[cfg(test)] + let from = self.scanned; + let mut i = self.scanned; + while i < end { + match self.mode { + ScanMode::String => match src[i] { + b'\\' => i += 1, + b'"' => self.mode = ScanMode::Code, + _ => {} + }, + ScanMode::LineComment => { + if src[i] == b'\n' { + self.mode = ScanMode::Code; + } + } + ScanMode::BlockComment => { + if src[i] == b'*' && src.get(i + 1) == Some(&b'/') { + self.mode = ScanMode::Code; + i += 1; + } + } + ScanMode::Code => match src[i] { + b'"' => self.mode = ScanMode::String, + b'/' if src.get(i + 1) == Some(&b'/') => { + self.mode = ScanMode::LineComment; + i += 1; + } + b'/' if src.get(i + 1) == Some(&b'*') => { + self.mode = ScanMode::BlockComment; + i += 1; + } + b'(' => self.depth += 1, + b')' => { + self.depth = self.depth.saturating_sub(1); + if self.depth == 0 { + // The list closed: the parens of the macro *body* + // can never reopen it, so this is the last byte + // this tracker ever looks at. + self.open = Some(false); + self.scanned = i + 1; + #[cfg(test)] + { + self.walked += self.scanned - from; + } + return; + } + } + _ => {} + }, + } + i += 1; + } + // `i`, not `end`: a two-byte step (`\` in a string, `//`, `*/`) may + // have carried the scan one past `end`, and that byte is consumed. + self.scanned = i; + #[cfg(test)] + { + self.walked += self.scanned - from; + } + } +} + +/// The offset of the `(` that opens a function-like `` `define``'s formal +/// argument list, or `None` when `text` does not start one. +/// +/// Only a `(` that *touches* the macro name opens a list (IEEE 1800 §22.5.1, +/// the same rule `defines.rs` reads the parameters by): `` `define A (x) `` is +/// object-like and its body merely starts with a paren. Everything else that +/// begins with a backtick — a macro invocation above all — answers `None` and +/// keeps the one-line capture it always had. +pub(super) fn define_params_start(text: &[u8]) -> Option { + const KEYWORD: &[u8] = b"`define"; + let rest = text.strip_prefix(KEYWORD)?; + if !matches!(rest.first(), Some(b' ' | b'\t')) { + return None; + } + let mut i = 0; + while matches!(rest.get(i), Some(b' ' | b'\t')) { + i += 1; + } + let name_start = i; + while rest.get(i).is_some_and(|&c| is_ident_char(c)) { + i += 1; + } + if i == name_start || rest.get(i) != Some(&b'(') { + return None; + } + Some(KEYWORD.len() + i) +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/lexer/number.rs b/crates/vlog_parser/src/lexer/number.rs new file mode 100644 index 0000000..fb58067 --- /dev/null +++ b/crates/vlog_parser/src/lexer/number.rs @@ -0,0 +1,148 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Numeric literals: plain and real numbers, sized and based literals +//! (`8'hFF`, `'0`), and time-unit suffixes. + +use super::{is_ident_char, LexError, RawLexer}; + +impl<'a> RawLexer<'a> { + /// Lex a number starting at an ASCII digit. Handles plain decimal, real + /// numbers with exponents, sized based literals (`8'hFF`, `4'b10_10`, + /// with optional whitespace around the tick), and time-unit suffixes + /// (`10ns`). The returned text is normalized to contain no whitespace. + pub(super) fn lex_number(&mut self) -> Result { + let start = self.pos; + while self.peek().is_ascii_digit() || self.peek() == b'_' { + self.bump(); + } + // Real number. + if self.peek() == b'.' && self.peek_at(1).is_ascii_digit() { + self.bump(); + while self.peek().is_ascii_digit() || self.peek() == b'_' { + self.bump(); + } + } + if matches!(self.peek(), b'e' | b'E') + && (self.peek_at(1).is_ascii_digit() + || (matches!(self.peek_at(1), b'+' | b'-') && self.peek_at(2).is_ascii_digit())) + { + self.bump(); + if matches!(self.peek(), b'+' | b'-') { + self.bump(); + } + while self.peek().is_ascii_digit() { + self.bump(); + } + } + let mut text = self.text_from(start); + + // Time unit suffix directly attached (1ns, 2.5us). + if self.peek().is_ascii_alphabetic() { + let unit_start = self.pos; + while self.peek().is_ascii_alphabetic() { + self.bump(); + } + text.push_str(&self.text_from(unit_start)); + return Ok(text); + } + + // Sized based literal: whitespace is allowed around the tick + // (`8 'hFF`); normalize it away. + let save = (self.pos, self.line, self.col); + let mut probe = self.pos; + while matches!(self.src.get(probe), Some(b' ') | Some(b'\t')) { + probe += 1; + } + if self.src.get(probe) == Some(&b'\'') + && probe + 1 < self.src.len() + && is_base_intro(self.src[probe + 1]) + && self.src.get(probe + 1) != Some(&b'{') + { + while self.pos < probe { + self.bump(); + } + match self.lex_based_part() { + Ok(based) => { + text.push_str(&based); + return Ok(text); + } + Err(_) => { + self.pos = save.0; + self.line = save.1; + self.col = save.2; + } + } + } + Ok(text) + } + + /// Lex the `'h FF` / `'b1010` / `'0` part, starting at the tick. + pub(super) fn lex_based_part(&mut self) -> Result { + let start = self.pos; + self.bump(); // ' + let c = self.peek(); + if matches!(c, b'0' | b'1' | b'x' | b'X' | b'z' | b'Z') && !is_ident_char(self.peek_at(1)) { + // Unbased unsized literal: '0 '1 'x 'z + self.bump(); + return Ok(self.text_from(start)); + } + let mut text = String::from("'"); + if matches!(self.peek(), b's' | b'S') { + text.push(self.bump() as char); + } + if !matches!(self.peek(), b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H') { + return Err(self.error("expected number base after '".to_string())); + } + text.push(self.bump() as char); + // A based number whose digits come from a macro: `` 32'h`DM_ADDR `` + // (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The + // digits are preprocessor output lucisv does not expand, so the number + // token ends here, with no digits, and the invocation lexes as the + // macro token it is; the parser rejoins the pair into one primary + // expression and the formatter prints them adjacent, as written. + // + // The backtick must *touch* the base: `` 32'h `DM_ADDR `` keeps the + // "expected digits" error below, because a space there is far more + // likely a typo than this idiom, and accepting it would silently + // change what the source says. + if self.peek() == b'`' { + return Ok(text); + } + // Whitespace is allowed between base and value. + while matches!(self.peek(), b' ' | b'\t') { + self.bump(); + } + let value_start = self.pos; + while self.peek().is_ascii_alphanumeric() || matches!(self.peek(), b'_' | b'?') { + self.bump(); + } + if self.pos == value_start { + return Err(self.error("expected digits after number base".to_string())); + } + text.push_str(&self.text_from(value_start)); + Ok(text) + } +} + +pub(super) fn is_base_intro(c: u8) -> bool { + matches!( + c, + b's' | b'S' + | b'd' + | b'D' + | b'b' + | b'B' + | b'o' + | b'O' + | b'h' + | b'H' + | b'0' + | b'1' + | b'x' + | b'X' + | b'z' + | b'Z' + ) +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/parser/connection.rs b/crates/vlog_parser/src/parser/connection.rs new file mode 100644 index 0000000..a85575b --- /dev/null +++ b/crates/vlog_parser/src/parser/connection.rs @@ -0,0 +1,306 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The connection list of an instantiation: named (`.name(expr)`, `.name`, +//! `.*`) and ordered connections, the comments written before the list's +//! closing bracket, and — in tolerant mode — the value whose bracket was +//! never closed and runs into the next instance. + +use super::recover::is_sync_stop; +use super::*; + +impl<'a> Parser<'a> { + /// Move the comments written before a list's closing bracket onto the last + /// entry *in source order*, which is a trailing directive when the list has + /// one and the last element otherwise. + /// + /// Without the directive case they would print before it, having moved + /// backwards across a token; with an element-less list (`` #(`include + /// "config.vh") ``) the directive is the only place they can go at all. + pub(super) fn take_last_entry_before_close( + &mut self, + last_element: Option<&mut Meta>, + directives: &mut [ListDirective], + elements: usize, + ) { + if let Some(d) = directives.last_mut().filter(|d| d.before == elements) { + self.take_before_sep(&mut d.meta, ")"); + } else if let Some(meta) = last_element { + self.take_before_sep(meta, ")"); + } + } + + /// The connections of one instance. `directives` collects the + /// `` `ifdef``-style lines written between them; the harvest must run + /// before the `.`-peek below, or a directive standing before the first + /// connection would be read as a positional expression. + pub(super) fn parse_connections( + &mut self, + directives: &mut Vec, + ) -> PResult { + self.take_list_directives(directives, 0); + if self.cur().is_sym(")") { + return Ok(Connections::Ordered(Vec::new())); + } + if self.at_named_connection() { + let mut conns = Vec::new(); + loop { + let at = self.pos; + conns.push(self.connection_or_recover()?); + let recovered = conns.last().is_some_and(ListElem::is_error); + if let Some(ListElem::Ok(last)) = conns.last_mut() { + self.take_before_sep(&mut last.meta, ","); + } + let comma = self.eat_sym(","); + self.note_trailing_comma(comma); + if let Some(ListElem::Ok(last)) = conns.last_mut() { + last.comma = comma; + if comma && last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + let dirs = self.take_list_directives(directives, conns.len()); + if self.connection_list_ends(at, comma, dirs.any, recovered) { + break; + } + } + // Comments before the closing `)` belong to the last entry: after + // it they would sit outside the connection list entirely. + let n = conns.len(); + let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); + self.take_last_entry_before_close(last, directives, n); + Ok(Connections::Named(conns)) + } else { + let mut conns = Vec::new(); + loop { + let at = self.pos; + conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?); + let recovered = conns.last().is_some_and(ListElem::is_error); + let comma = match conns.last() { + Some(ListElem::Ok(last)) => last.comma, + // A positional connection reads its own separator; an + // error element leaves the `,` for the list, as in a + // non-ANSI port list. + _ => self.eat_sym(","), + }; + let dirs = self.take_list_directives(directives, conns.len()); + if self.list_ends(at, comma, dirs.any, recovered) { + break; + } + } + let n = conns.len(); + let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); + self.take_last_entry_before_close(last, directives, n); + Ok(Connections::Ordered(conns)) + } + } + + /// One positional connection (`u (a, , c)`), its separator included: an + /// omitted one writes no token at all, so the `,` is the only thing that + /// says it was there. + fn parse_ordered_connection(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") { + None + } else { + Some(self.parse_expr()?) + }; + // An omitted connection consumed no token, so this is the empty span + // where it would have started. + let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); + let comma = self.eat_sym(","); + if comma { + meta.trailing = self.take_trailing(); + } + Ok(OrderedConn { meta, expr, comma, span }) + } + + /// True when the connection list starts with a named connection. The + /// leading `(* ... *)` attributes of the first entry are looked past: + /// they belong to the connection, not to the list. + fn at_named_connection(&self) -> bool { + let mut i = self.pos; + while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute { + i += 1; + } + self.tokens.get(i).is_some_and(|t| t.is_sym(".")) + } + + /// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and + /// ordered parameter overrides) a bare expression. + pub(super) fn parse_connection(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + // `(* async *) .async_data_o (x)` — an attribute instance may precede + // a port connection (IEEE 1800 §A.4.1.1), corpus + // `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way + // an item's or a statement's attributes are. + self.take_attrs(&mut meta); + if self.eat_sym(".") { + let after_dot = self.take_gap(); + let star = self.cur().span; + if self.eat_sym("*") { + let span = self.span_from(start); + return Ok(Connection { + meta, + after_dot, + name: "*".to_string(), + name_span: star, + before_open: Vec::new(), + after_open: Vec::new(), + expr: None, + close_comments: Vec::new(), + comma: false, + span, + }); + } + let Name { text: name, span: name_span } = self.expect_name()?; + let before_open = self.take_before_open("("); + let mark = self.pending_trailing.len(); + let paren_start = self.here(); + // A half-typed `.NAME(` whose value would read as the next + // instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing + // inside the list fails — `u0 (.a(x))` is a legal call with named + // arguments — so the greedy parse swallows the instance and the + // whole instantiation collapses into one error item. Failing the + // element here costs the one connection and keeps everything + // else. See `docs/features/small-items-3/README.md`. The same + // failure covers a `.NAME(` left open at the end of its line while + // the next line goes on with the list (`.po(` ⏎ `.b(y));`): the + // entry ends with its line, and the diagnostic is on its `(` + // (`docs/features/port-entry-grace/README.md`). + if self.tolerant + && self.cur().is_sym("(") + && (self.value_runs_into_next_instance() || self.value_left_open()) + { + return self.error("unclosed `(` in a port or parameter connection"); + } + let mut close_comments = Vec::new(); + let mut after_open = Vec::new(); + let expr = if self.eat_sym("(") { + if self.cur().is_sym(")") { + // `.name(/* unused */)`: the comments were written inside + // these parens and are printed back inside them. + let inside = self.take_around(mark); + self.skip(); + Some(self.expr_at(paren_start, ExprKind::Empty(inside))) + } else { + after_open = self.take_gap(); + let value_mark = self.pending_trailing.len(); + let e = match self.conditional_region_end(")") { + Some(end_pos) => self.parse_verbatim_expr(end_pos), + None => self.parse_expr_or_type()?, + }; + // `.name(x /* c */)`: written inside the parens, so it is + // printed inside them too. + close_comments = self.take_around(value_mark); + self.expect_sym(")")?; + Some(e) + } + } else { + None + }; + let span = self.span_from(start); + meta.trailing = self.take_trailing(); + Ok(Connection { + meta, + after_dot, + name, + name_span, + before_open, + after_open, + expr, + close_comments, + comma: false, + span, + }) + } else { + let e = self.parse_expr_or_type()?; + let span = self.span_from(start); + meta.trailing = self.take_trailing(); + Ok(Connection { + meta, + after_dot: Vec::new(), + name: String::new(), + name_span: TextRange::empty(span.start), + before_open: Vec::new(), + after_open: Vec::new(), + expr: Some(e), + close_comments: Vec::new(), + comma: false, + span, + }) + } + } + + /// True when the `(` at the cursor — the one that opens a connection's + /// value — is never closed **and** something that reads as the next + /// instance sits inside it. + /// + /// Tolerant mode only, asked once per named connection before its value + /// is parsed. The walk starts just past the `(` at depth zero and ends at + /// the first of: a closer that would take the depth below zero (the + /// value's own `)` — it closes, so nothing is wrong and the value is + /// parsed as written), a `;` or a construct keyword at depth zero, or end + /// of file. On a file that parses it therefore stops at the value's `)` + /// after a handful of tokens; only a value whose bracket was never closed + /// walks as far as the next `;`. + /// + /// The candidate is an identifier that opens its own line and is followed + /// by `(` — how an instance is written, and how nothing written *inside* + /// a value normally is. Only depth zero is read: a candidate inside a + /// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and + /// that shape falls back to the coarser item-level recovery, which keeps + /// the `endmodule` but loses the instantiation. Deliberate — reading + /// deeper would start guessing which of several unclosed brackets the + /// user meant to close. + fn value_runs_into_next_instance(&self) -> bool { + let mut depth = 0u32; + let mut candidate = false; + let mut i = self.pos + 1; + while let Some(t) = self.tokens.get(i) { + if t.kind == TokenKind::Eof { + break; + } + if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") { + depth += 1; + } else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") { + if depth == 0 { + return false; + } + depth -= 1; + } else if depth == 0 { + if t.is_sym(";") || is_sync_stop(t) { + break; + } + if t.kind == TokenKind::Ident + && self.tokens[i - 1].line != t.line + && self.tokens.get(i + 1).is_some_and(|n| n.is_sym("(")) + { + candidate = true; + } + } + i += 1; + } + candidate + } + + /// Consume the tokens up to `end_pos` as one verbatim expression. + /// + /// [`Parser::open_conds`] is deliberately left alone: it counts *item* + /// scope only, and a construct that walks its body through + /// [`Parser::bump`] inherits "does not count" by doing nothing — see + /// [`Parser::note_item_conditional`]. + fn parse_verbatim_expr(&mut self, end_pos: usize) -> Expr { + let start = self.here(); + let col = self.cur().col; + while self.pos < end_pos && !self.at_eof() { + self.skip(); + } + let raw = self.verbatim_since(start, col); + self.expr_at(start, ExprKind::Verbatim(raw)) + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/parser/generate.rs b/crates/vlog_parser/src/parser/generate.rs new file mode 100644 index 0000000..23c858d --- /dev/null +++ b/crates/vlog_parser/src/parser/generate.rs @@ -0,0 +1,178 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Generate constructs: the `if`, `for` and `case` generate forms and the +//! block — a `begin … end` or one bare item — each of them governs. +//! +//! The `generate … endgenerate` region is not here: it is a plain item list, +//! read by its arm of the dispatch in `item`. + +use super::*; + +impl<'a> Parser<'a> { + /// An `else if` chain recurses here directly, bypassing `parse_item`. Gated. + pub(super) fn parse_gen_if(&mut self) -> PResult { + self.enter()?; + let out = self.parse_gen_if_inner(); + self.leave(); + out + } + + fn parse_gen_if_inner(&mut self) -> PResult { + let start = self.here(); + self.expect_kw("if")?; + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let then = self.parse_gen_block()?; + let (mut then_trailing, mut else_directives, mut else_comments) = + (None, Vec::new(), Vec::new()); + let els = if let Some(gap) = self.take_else_preamble(then.is_block)? { + then_trailing = gap.then_trailing; + else_directives = gap.directives; + else_comments = gap.comments; + self.skip(); + if self.cur().is_kw("if") { + Some(Box::new(GenElse::If(Meta::default(), Box::new(self.parse_gen_if()?)))) + } else { + Some(Box::new(GenElse::Block(self.parse_gen_block()?))) + } + } else { + None + }; + Ok(GenIf { + cond, + then, + then_trailing, + else_directives, + else_comments, + els, + span: self.span_from(start), + }) + } + + pub(super) fn parse_gen_for(&mut self) -> PResult { + self.expect_kw("for")?; + let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() }; + self.expect_sym("(")?; + comments.after_open = self.take_gap(); + let init_genvar = self.eat_kw("genvar"); + let after_genvar = if init_genvar { self.take_gap() } else { Vec::new() }; + let lhs = self.parse_unary()?; + let mut op_comments = BinaryComments { before: self.gap_before("="), after: Vec::new() }; + self.expect_sym("=")?; + op_comments.after = self.take_gap(); + let rhs = self.parse_expr()?; + let init = + SimpleAssign { lhs, op: "=".to_string(), op_comments: Box::new(op_comments), rhs }; + comments.before_first_semi = self.gap_before(";"); + self.expect_sym(";")?; + comments.after_first_semi = self.take_gap(); + let cond = self.parse_expr()?; + comments.before_second_semi = self.gap_before(";"); + self.expect_sym(";")?; + comments.after_second_semi = self.take_gap(); + let step = self.parse_for_step()?; + comments.before_close = self.gap_before(")"); + self.expect_sym(")")?; + let body = self.parse_gen_block()?; + Ok(GenFor { + init, + init_genvar, + after_genvar, + cond, + step, + comments: Box::new(comments), + body, + }) + } + + pub(super) fn parse_gen_case(&mut self) -> PResult { + self.expect_kw("case")?; + self.expect_sym("(")?; + let expr = self.parse_expr()?; + self.expect_sym(")")?; + let mut items = Vec::new(); + while !self.at_body_end("endcase") { + let start = self.here(); + let mut meta = self.take_meta(); + let mut before_colon = Vec::new(); + let labels = if self.eat_kw("default") { + before_colon = self.gap_before(":"); + let _ = self.eat_sym(":"); + Vec::new() + } else { + let first = self.parse_expr_item()?; + let labels = self.parse_expr_list(first, ":")?; + self.expect_sym(":")?; + labels + }; + let body = self.parse_gen_block()?; + let span = self.span_from(start); + meta.trailing = self.take_trailing(); + items.push(GenCaseItem { meta, labels, before_colon, body, span }); + } + let dangling = self.take_dangling(); + self.expect_closer("endcase")?; + Ok(GenCase { expr, items, dangling }) + } + + pub(super) fn parse_gen_block(&mut self) -> PResult { + let start = self.here(); + if self.cur().is_kw("begin") { + // The gap between whatever came before and the `begin` belongs to + // the block — nothing else was written where it could attach. + let before_kw = self.take_gap(); + self.skip(); + let before_colon = self.gap_before(":"); + let mut after_colon = Vec::new(); + let label_name = if self.eat_sym(":") { + after_colon = self.take_gap(); + Some(self.expect_name()?) + } else { + None + }; + let (label, label_span) = split_label(label_name); + let mut items = Vec::new(); + while !self.at_body_end("end") { + items.push(self.item_or_recover()?); + } + let dangling = self.take_dangling(); + self.expect_closer("end")?; + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); + Ok(GenBlock { + before_kw, + before_colon, + after_colon, + label, + label_span, + is_block: true, + items, + dangling, + end_label_comments, + end_label, + end_label_span, + span: self.span_from(start), + }) + } else { + let item = self.item_or_recover()?; + let span = item.span; + Ok(GenBlock { + before_kw: Vec::new(), + before_colon: Vec::new(), + after_colon: Vec::new(), + label: None, + label_span: None, + end_label_comments: Box::default(), + is_block: false, + items: vec![item], + dangling: Vec::new(), + end_label: None, + end_label_span: None, + span, + }) + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/parser/instance.rs b/crates/vlog_parser/src/parser/instance.rs index 7fe8ed9..4225f5c 100644 --- a/crates/vlog_parser/src/parser/instance.rs +++ b/crates/vlog_parser/src/parser/instance.rs @@ -1,11 +1,11 @@ // Author: Guoliang Chen, a Senior Digital Design Engineer //! The items that instantiate or drive: continuous assignments, module and -//! gate instantiations with their parameter overrides and connections, and -//! `bind` directives. Drive strengths and delay values live here because -//! these are the only items that write them. +//! gate instantiations with their parameter overrides, and `bind` +//! directives. Drive strengths and delay values live here because these are +//! the only items that write them. The connection list an instance carries +//! is `connection`. -use super::recover::is_sync_stop; use super::*; /// The strength keywords a drive strength is written from (IEEE 1800 §28.11). @@ -407,296 +407,6 @@ impl<'a> Parser<'a> { }) } - /// Move the comments written before a list's closing bracket onto the last - /// entry *in source order*, which is a trailing directive when the list has - /// one and the last element otherwise. - /// - /// Without the directive case they would print before it, having moved - /// backwards across a token; with an element-less list (`` #(`include - /// "config.vh") ``) the directive is the only place they can go at all. - pub(super) fn take_last_entry_before_close( - &mut self, - last_element: Option<&mut Meta>, - directives: &mut [ListDirective], - elements: usize, - ) { - if let Some(d) = directives.last_mut().filter(|d| d.before == elements) { - self.take_before_sep(&mut d.meta, ")"); - } else if let Some(meta) = last_element { - self.take_before_sep(meta, ")"); - } - } - - /// The connections of one instance. `directives` collects the - /// `` `ifdef``-style lines written between them; the harvest must run - /// before the `.`-peek below, or a directive standing before the first - /// connection would be read as a positional expression. - fn parse_connections(&mut self, directives: &mut Vec) -> PResult { - self.take_list_directives(directives, 0); - if self.cur().is_sym(")") { - return Ok(Connections::Ordered(Vec::new())); - } - if self.at_named_connection() { - let mut conns = Vec::new(); - loop { - let at = self.pos; - conns.push(self.connection_or_recover()?); - let recovered = conns.last().is_some_and(ListElem::is_error); - if let Some(ListElem::Ok(last)) = conns.last_mut() { - self.take_before_sep(&mut last.meta, ","); - } - let comma = self.eat_sym(","); - self.note_trailing_comma(comma); - if let Some(ListElem::Ok(last)) = conns.last_mut() { - last.comma = comma; - if comma && last.meta.trailing.is_none() { - last.meta.trailing = self.take_trailing(); - } - } - let dirs = self.take_list_directives(directives, conns.len()); - if self.connection_list_ends(at, comma, dirs.any, recovered) { - break; - } - } - // Comments before the closing `)` belong to the last entry: after - // it they would sit outside the connection list entirely. - let n = conns.len(); - let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); - self.take_last_entry_before_close(last, directives, n); - Ok(Connections::Named(conns)) - } else { - let mut conns = Vec::new(); - loop { - let at = self.pos; - conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?); - let recovered = conns.last().is_some_and(ListElem::is_error); - let comma = match conns.last() { - Some(ListElem::Ok(last)) => last.comma, - // A positional connection reads its own separator; an - // error element leaves the `,` for the list, as in a - // non-ANSI port list. - _ => self.eat_sym(","), - }; - let dirs = self.take_list_directives(directives, conns.len()); - if self.list_ends(at, comma, dirs.any, recovered) { - break; - } - } - let n = conns.len(); - let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta); - self.take_last_entry_before_close(last, directives, n); - Ok(Connections::Ordered(conns)) - } - } - - /// One positional connection (`u (a, , c)`), its separator included: an - /// omitted one writes no token at all, so the `,` is the only thing that - /// says it was there. - fn parse_ordered_connection(&mut self) -> PResult { - let start = self.here(); - let mut meta = self.take_meta(); - let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") { - None - } else { - Some(self.parse_expr()?) - }; - // An omitted connection consumed no token, so this is the empty span - // where it would have started. - let span = self.span_from(start); - self.take_before_sep(&mut meta, ","); - let comma = self.eat_sym(","); - if comma { - meta.trailing = self.take_trailing(); - } - Ok(OrderedConn { meta, expr, comma, span }) - } - - /// True when the connection list starts with a named connection. The - /// leading `(* ... *)` attributes of the first entry are looked past: - /// they belong to the connection, not to the list. - fn at_named_connection(&self) -> bool { - let mut i = self.pos; - while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute { - i += 1; - } - self.tokens.get(i).is_some_and(|t| t.is_sym(".")) - } - - /// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and - /// ordered parameter overrides) a bare expression. - pub(super) fn parse_connection(&mut self) -> PResult { - let start = self.here(); - let mut meta = self.take_meta(); - // `(* async *) .async_data_o (x)` — an attribute instance may precede - // a port connection (IEEE 1800 §A.4.1.1), corpus - // `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way - // an item's or a statement's attributes are. - self.take_attrs(&mut meta); - if self.eat_sym(".") { - let after_dot = self.take_gap(); - let star = self.cur().span; - if self.eat_sym("*") { - let span = self.span_from(start); - return Ok(Connection { - meta, - after_dot, - name: "*".to_string(), - name_span: star, - before_open: Vec::new(), - after_open: Vec::new(), - expr: None, - close_comments: Vec::new(), - comma: false, - span, - }); - } - let Name { text: name, span: name_span } = self.expect_name()?; - let before_open = self.take_before_open("("); - let mark = self.pending_trailing.len(); - let paren_start = self.here(); - // A half-typed `.NAME(` whose value would read as the next - // instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing - // inside the list fails — `u0 (.a(x))` is a legal call with named - // arguments — so the greedy parse swallows the instance and the - // whole instantiation collapses into one error item. Failing the - // element here costs the one connection and keeps everything - // else. See `docs/features/small-items-3/README.md`. The same - // failure covers a `.NAME(` left open at the end of its line while - // the next line goes on with the list (`.po(` ⏎ `.b(y));`): the - // entry ends with its line, and the diagnostic is on its `(` - // (`docs/features/port-entry-grace/README.md`). - if self.tolerant - && self.cur().is_sym("(") - && (self.value_runs_into_next_instance() || self.value_left_open()) - { - return self.error("unclosed `(` in a port or parameter connection"); - } - let mut close_comments = Vec::new(); - let mut after_open = Vec::new(); - let expr = if self.eat_sym("(") { - if self.cur().is_sym(")") { - // `.name(/* unused */)`: the comments were written inside - // these parens and are printed back inside them. - let inside = self.take_around(mark); - self.skip(); - Some(self.expr_at(paren_start, ExprKind::Empty(inside))) - } else { - after_open = self.take_gap(); - let value_mark = self.pending_trailing.len(); - let e = match self.conditional_region_end(")") { - Some(end_pos) => self.parse_verbatim_expr(end_pos), - None => self.parse_expr_or_type()?, - }; - // `.name(x /* c */)`: written inside the parens, so it is - // printed inside them too. - close_comments = self.take_around(value_mark); - self.expect_sym(")")?; - Some(e) - } - } else { - None - }; - let span = self.span_from(start); - meta.trailing = self.take_trailing(); - Ok(Connection { - meta, - after_dot, - name, - name_span, - before_open, - after_open, - expr, - close_comments, - comma: false, - span, - }) - } else { - let e = self.parse_expr_or_type()?; - let span = self.span_from(start); - meta.trailing = self.take_trailing(); - Ok(Connection { - meta, - after_dot: Vec::new(), - name: String::new(), - name_span: TextRange::empty(span.start), - before_open: Vec::new(), - after_open: Vec::new(), - expr: Some(e), - close_comments: Vec::new(), - comma: false, - span, - }) - } - } - - /// True when the `(` at the cursor — the one that opens a connection's - /// value — is never closed **and** something that reads as the next - /// instance sits inside it. - /// - /// Tolerant mode only, asked once per named connection before its value - /// is parsed. The walk starts just past the `(` at depth zero and ends at - /// the first of: a closer that would take the depth below zero (the - /// value's own `)` — it closes, so nothing is wrong and the value is - /// parsed as written), a `;` or a construct keyword at depth zero, or end - /// of file. On a file that parses it therefore stops at the value's `)` - /// after a handful of tokens; only a value whose bracket was never closed - /// walks as far as the next `;`. - /// - /// The candidate is an identifier that opens its own line and is followed - /// by `(` — how an instance is written, and how nothing written *inside* - /// a value normally is. Only depth zero is read: a candidate inside a - /// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and - /// that shape falls back to the coarser item-level recovery, which keeps - /// the `endmodule` but loses the instantiation. Deliberate — reading - /// deeper would start guessing which of several unclosed brackets the - /// user meant to close. - fn value_runs_into_next_instance(&self) -> bool { - let mut depth = 0u32; - let mut candidate = false; - let mut i = self.pos + 1; - while let Some(t) = self.tokens.get(i) { - if t.kind == TokenKind::Eof { - break; - } - if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") { - depth += 1; - } else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") { - if depth == 0 { - return false; - } - depth -= 1; - } else if depth == 0 { - if t.is_sym(";") || is_sync_stop(t) { - break; - } - if t.kind == TokenKind::Ident - && self.tokens[i - 1].line != t.line - && self.tokens.get(i + 1).is_some_and(|n| n.is_sym("(")) - { - candidate = true; - } - } - i += 1; - } - candidate - } - - /// Consume the tokens up to `end_pos` as one verbatim expression. - /// - /// [`Parser::open_conds`] is deliberately left alone: it counts *item* - /// scope only, and a construct that walks its body through - /// [`Parser::bump`] inherits "does not count" by doing nothing — see - /// [`Parser::note_item_conditional`]. - fn parse_verbatim_expr(&mut self, end_pos: usize) -> Expr { - let start = self.here(); - let col = self.cur().col; - while self.pos < end_pos && !self.at_eof() { - self.skip(); - } - let raw = self.verbatim_since(start, col); - self.expr_at(start, ExprKind::Verbatim(raw)) - } - pub(super) fn parse_gate_instantiation(&mut self) -> PResult { let gate = self.bump().text; // `pullup (weak1) p (x);` — the strength stands where an unnamed diff --git a/crates/vlog_parser/src/parser/item.rs b/crates/vlog_parser/src/parser/item.rs index 06809f0..b8b1e22 100644 --- a/crates/vlog_parser/src/parser/item.rs +++ b/crates/vlog_parser/src/parser/item.rs @@ -5,9 +5,10 @@ //! The top-level loop ([`Parser::parse_source_file`]), the item loop every //! body shares ([`Parser::parse_item`]) and the dispatch from a keyword to //! the grammar that parses it ([`Parser::parse_keyword_item`]); plus the -//! items that are small enough to live beside the dispatch — packages, -//! imports and exports, DPI, generate regions — and the member-qualifier -//! prefix (`virtual`, `local`, `rand`, …) an item may start with. +//! member-qualifier prefix (`virtual`, `local`, `rand`, …) an item may start +//! with. The small grammars the dispatch calls straight into are next door: +//! packages, imports and exports and DPI in `package`, the generate +//! constructs in `generate`. use super::directive::{fragment_file, is_prelude}; use super::*; @@ -445,309 +446,6 @@ impl<'a> Parser<'a> { } out } - - fn parse_package(&mut self) -> PResult { - let kw = self.bump().text; - let before_name = self.take_gap(); - let Name { text: name, span: name_span } = self.expect_name()?; - let before_semi = self.gap_before(";"); - self.expect_sym(";")?; - let mut items = Vec::new(); - while !self.at_body_end("endpackage") { - items.push(self.item_or_recover()?); - } - let dangling = self.take_dangling(); - self.expect_closer("endpackage")?; - let (end_label_comments, end_name) = self.parse_label_with()?; - let (end_label, end_label_span) = split_label(end_name); - Ok(ItemKind::Package { - kw, - before_name, - name, - name_span, - before_semi, - items, - dangling, - end_label_comments, - end_label, - end_label_span, - }) - } - - pub(super) fn parse_import_list(&mut self) -> PResult> { - self.expect_kw("import")?; - let paths = self.parse_package_paths(false)?; - self.expect_sym(";")?; - Ok(paths) - } - - /// The comma-separated `pkg::item` / `pkg::*` list of an `import` or an - /// `export`, without the leading keyword or the closing `;`. - /// `allow_star_pkg` admits `export *::*;`, whose left half is a wildcard - /// too — no `import` spells that. - fn parse_package_paths(&mut self, allow_star_pkg: bool) -> PResult> { - let mut paths = Vec::new(); - loop { - let star = self.cur().span; - let pkg = if allow_star_pkg && self.cur().is_sym("*") { - self.skip(); - Name { text: "*".to_string(), span: star } - } else { - self.expect_name()? - }; - self.expect_sym("::")?; - let star = self.cur().span; - let item = if self.eat_sym("*") { - Name { text: "*".to_string(), span: star } - } else { - self.expect_name()? - }; - paths.push(ImportPath { pkg, item }); - if !self.eat_sym(",") { - break; - } - } - Ok(paths) - } - - // ------------------------------------------------------------------ - // DPI (IEEE 1800 §35.5) and package export (§26.6) - // ------------------------------------------------------------------ - - /// `import "DPI-C" [context|pure] [c_name =] function|task ;`. - /// The declaration is a function/task prototype with a linkage prefix, so - /// it becomes an ordinary [`FunctionDecl`] / [`TaskDecl`] carrying that - /// prefix — every consumer that already knows about functions sees one. - fn parse_dpi_import(&mut self) -> PResult { - self.expect_kw("import")?; - let spec = self.expect_dpi_spec()?; - // `context` is not a reserved word, so it is only the property when an - // `=` does not turn it into the linkage name instead. - let property = if self.cur().is_kw("pure") - || (self.cur().kind == TokenKind::Ident - && self.cur().text == "context" - && !self.nth(1).is_sym("=")) - { - Some(self.bump().text) - } else { - None - }; - let c_identifier = self.parse_dpi_c_identifier(); - let dpi = DpiImport { spec, property, c_identifier }; - if self.cur().is_kw("task") { - self.parse_task_decl(Some(dpi)).map(ItemKind::Task) - } else { - self.parse_function_decl(Some(dpi)).map(ItemKind::Function) - } - } - - /// `export "DPI-C" [c_name =] function|task name;` or a package re-export - /// `export pkg::item, pkg::*;`. - fn parse_export(&mut self) -> PResult { - self.expect_kw("export")?; - if self.cur().kind == TokenKind::String { - let spec = self.expect_dpi_spec()?; - let c_identifier = self.parse_dpi_c_identifier(); - if !self.cur().is_kw("function") && !self.cur().is_kw("task") { - return self.error("expected `function` or `task` in a DPI export"); - } - let kw = self.bump().text; - let name = self.expect_name()?; - self.expect_sym(";")?; - return Ok(ExportDecl::Dpi(DpiExport { spec, c_identifier, kw, name })); - } - let paths = self.parse_package_paths(true)?; - self.expect_sym(";")?; - Ok(ExportDecl::Package(paths)) - } - - fn expect_dpi_spec(&mut self) -> PResult { - if self.cur().kind == TokenKind::String { - Ok(self.bump().text) - } else { - self.error("expected a DPI linkage spec string") - } - } - - /// The optional `c_name =` that gives the linkage symbol a name of its own. - fn parse_dpi_c_identifier(&mut self) -> Option { - if self.cur().kind != TokenKind::Ident || !self.nth(1).is_sym("=") { - return None; - } - let span = self.cur().span; - let name = Name { text: self.bump().text, span }; - self.skip(); - Some(name) - } - - // ------------------------------------------------------------------ - // Generate constructs - // ------------------------------------------------------------------ - - /// An `else if` chain recurses here directly, bypassing `parse_item`. Gated. - fn parse_gen_if(&mut self) -> PResult { - self.enter()?; - let out = self.parse_gen_if_inner(); - self.leave(); - out - } - - fn parse_gen_if_inner(&mut self) -> PResult { - let start = self.here(); - self.expect_kw("if")?; - self.expect_sym("(")?; - let cond = self.parse_expr()?; - self.expect_sym(")")?; - let then = self.parse_gen_block()?; - let (mut then_trailing, mut else_directives, mut else_comments) = - (None, Vec::new(), Vec::new()); - let els = if let Some(gap) = self.take_else_preamble(then.is_block)? { - then_trailing = gap.then_trailing; - else_directives = gap.directives; - else_comments = gap.comments; - self.skip(); - if self.cur().is_kw("if") { - Some(Box::new(GenElse::If(Meta::default(), Box::new(self.parse_gen_if()?)))) - } else { - Some(Box::new(GenElse::Block(self.parse_gen_block()?))) - } - } else { - None - }; - Ok(GenIf { - cond, - then, - then_trailing, - else_directives, - else_comments, - els, - span: self.span_from(start), - }) - } - - fn parse_gen_for(&mut self) -> PResult { - self.expect_kw("for")?; - let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() }; - self.expect_sym("(")?; - comments.after_open = self.take_gap(); - let init_genvar = self.eat_kw("genvar"); - let after_genvar = if init_genvar { self.take_gap() } else { Vec::new() }; - let lhs = self.parse_unary()?; - let mut op_comments = BinaryComments { before: self.gap_before("="), after: Vec::new() }; - self.expect_sym("=")?; - op_comments.after = self.take_gap(); - let rhs = self.parse_expr()?; - let init = - SimpleAssign { lhs, op: "=".to_string(), op_comments: Box::new(op_comments), rhs }; - comments.before_first_semi = self.gap_before(";"); - self.expect_sym(";")?; - comments.after_first_semi = self.take_gap(); - let cond = self.parse_expr()?; - comments.before_second_semi = self.gap_before(";"); - self.expect_sym(";")?; - comments.after_second_semi = self.take_gap(); - let step = self.parse_for_step()?; - comments.before_close = self.gap_before(")"); - self.expect_sym(")")?; - let body = self.parse_gen_block()?; - Ok(GenFor { - init, - init_genvar, - after_genvar, - cond, - step, - comments: Box::new(comments), - body, - }) - } - - fn parse_gen_case(&mut self) -> PResult { - self.expect_kw("case")?; - self.expect_sym("(")?; - let expr = self.parse_expr()?; - self.expect_sym(")")?; - let mut items = Vec::new(); - while !self.at_body_end("endcase") { - let start = self.here(); - let mut meta = self.take_meta(); - let mut before_colon = Vec::new(); - let labels = if self.eat_kw("default") { - before_colon = self.gap_before(":"); - let _ = self.eat_sym(":"); - Vec::new() - } else { - let first = self.parse_expr_item()?; - let labels = self.parse_expr_list(first, ":")?; - self.expect_sym(":")?; - labels - }; - let body = self.parse_gen_block()?; - let span = self.span_from(start); - meta.trailing = self.take_trailing(); - items.push(GenCaseItem { meta, labels, before_colon, body, span }); - } - let dangling = self.take_dangling(); - self.expect_closer("endcase")?; - Ok(GenCase { expr, items, dangling }) - } - - fn parse_gen_block(&mut self) -> PResult { - let start = self.here(); - if self.cur().is_kw("begin") { - // The gap between whatever came before and the `begin` belongs to - // the block — nothing else was written where it could attach. - let before_kw = self.take_gap(); - self.skip(); - let before_colon = self.gap_before(":"); - let mut after_colon = Vec::new(); - let label_name = if self.eat_sym(":") { - after_colon = self.take_gap(); - Some(self.expect_name()?) - } else { - None - }; - let (label, label_span) = split_label(label_name); - let mut items = Vec::new(); - while !self.at_body_end("end") { - items.push(self.item_or_recover()?); - } - let dangling = self.take_dangling(); - self.expect_closer("end")?; - let (end_label_comments, end_name) = self.parse_label_with()?; - let (end_label, end_label_span) = split_label(end_name); - Ok(GenBlock { - before_kw, - before_colon, - after_colon, - label, - label_span, - is_block: true, - items, - dangling, - end_label_comments, - end_label, - end_label_span, - span: self.span_from(start), - }) - } else { - let item = self.item_or_recover()?; - let span = item.span; - Ok(GenBlock { - before_kw: Vec::new(), - before_colon: Vec::new(), - after_colon: Vec::new(), - label: None, - label_span: None, - end_label_comments: Box::default(), - is_block: false, - items: vec![item], - dangling: Vec::new(), - end_label: None, - end_label_span: None, - span, - }) - } - } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/src/parser/mod.rs b/crates/vlog_parser/src/parser/mod.rs index 3513315..2a2e7f8 100644 --- a/crates/vlog_parser/src/parser/mod.rs +++ b/crates/vlog_parser/src/parser/mod.rs @@ -30,11 +30,14 @@ //! | `cursor` | the token cursor, spans, `expect`/`eat`, the comment plumbing | //! | `recover` | tolerant-mode error recovery in item and statement lists | //! | `recover_list` | tolerant-mode error recovery inside a header's lists and brackets | -//! | `item` | the file and item loops, the keyword → item dispatch, packages, imports, DPI, generate | +//! | `item` | the file and item loops, the keyword → item dispatch, member qualifiers | +//! | `package` | packages, `import`/`export` path lists, DPI imports and exports | +//! | `generate` | `if`/`for`/`case` generate and the block each governs | //! | `module` | module/interface/program headers, ports, modports, clocking blocks | //! | `decl` | data types, declarators, parameters, `typedef`/`enum`/`struct` | //! | `tf` | `function`, `task` and `let` declarations | -//! | `instance` | continuous assigns, instantiations and connections, gates, `bind` | +//! | `instance` | continuous assigns, instantiations, gates, `bind`, strengths and delays | +//! | `connection` | an instance's connection list, named and ordered | //! | `stmt`, `keyword_stmt` | statements; the keyword → statement dispatch table | //! | `expr`, `primary` | the operator grammar; its leaves and argument lists | //! | `class`, `covergroup` | classes with their constraints; covergroups | @@ -52,15 +55,18 @@ use crate::token::{Comment, Token, TokenKind}; mod assertion; mod class; +mod connection; mod covergroup; mod cursor; mod decl; mod directive; mod expr; +mod generate; mod instance; mod item; mod keyword_stmt; mod module; +mod package; mod primary; mod randsequence; mod recover; diff --git a/crates/vlog_parser/src/parser/package.rs b/crates/vlog_parser/src/parser/package.rs new file mode 100644 index 0000000..b14e421 --- /dev/null +++ b/crates/vlog_parser/src/parser/package.rs @@ -0,0 +1,145 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Packages and what crosses their boundary: `package … endpackage`, the +//! `pkg::item` path lists of `import` and `export`, and the DPI import and +//! export declarations that share those two keywords. + +use super::*; + +impl<'a> Parser<'a> { + pub(super) fn parse_package(&mut self) -> PResult { + let kw = self.bump().text; + let before_name = self.take_gap(); + let Name { text: name, span: name_span } = self.expect_name()?; + let before_semi = self.gap_before(";"); + self.expect_sym(";")?; + let mut items = Vec::new(); + while !self.at_body_end("endpackage") { + items.push(self.item_or_recover()?); + } + let dangling = self.take_dangling(); + self.expect_closer("endpackage")?; + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); + Ok(ItemKind::Package { + kw, + before_name, + name, + name_span, + before_semi, + items, + dangling, + end_label_comments, + end_label, + end_label_span, + }) + } + + pub(super) fn parse_import_list(&mut self) -> PResult> { + self.expect_kw("import")?; + let paths = self.parse_package_paths(false)?; + self.expect_sym(";")?; + Ok(paths) + } + + /// The comma-separated `pkg::item` / `pkg::*` list of an `import` or an + /// `export`, without the leading keyword or the closing `;`. + /// `allow_star_pkg` admits `export *::*;`, whose left half is a wildcard + /// too — no `import` spells that. + fn parse_package_paths(&mut self, allow_star_pkg: bool) -> PResult> { + let mut paths = Vec::new(); + loop { + let star = self.cur().span; + let pkg = if allow_star_pkg && self.cur().is_sym("*") { + self.skip(); + Name { text: "*".to_string(), span: star } + } else { + self.expect_name()? + }; + self.expect_sym("::")?; + let star = self.cur().span; + let item = if self.eat_sym("*") { + Name { text: "*".to_string(), span: star } + } else { + self.expect_name()? + }; + paths.push(ImportPath { pkg, item }); + if !self.eat_sym(",") { + break; + } + } + Ok(paths) + } + + // ------------------------------------------------------------------ + // DPI (IEEE 1800 §35.5) and package export (§26.6) + // ------------------------------------------------------------------ + + /// `import "DPI-C" [context|pure] [c_name =] function|task ;`. + /// The declaration is a function/task prototype with a linkage prefix, so + /// it becomes an ordinary [`FunctionDecl`] / [`TaskDecl`] carrying that + /// prefix — every consumer that already knows about functions sees one. + pub(super) fn parse_dpi_import(&mut self) -> PResult { + self.expect_kw("import")?; + let spec = self.expect_dpi_spec()?; + // `context` is not a reserved word, so it is only the property when an + // `=` does not turn it into the linkage name instead. + let property = if self.cur().is_kw("pure") + || (self.cur().kind == TokenKind::Ident + && self.cur().text == "context" + && !self.nth(1).is_sym("=")) + { + Some(self.bump().text) + } else { + None + }; + let c_identifier = self.parse_dpi_c_identifier(); + let dpi = DpiImport { spec, property, c_identifier }; + if self.cur().is_kw("task") { + self.parse_task_decl(Some(dpi)).map(ItemKind::Task) + } else { + self.parse_function_decl(Some(dpi)).map(ItemKind::Function) + } + } + + /// `export "DPI-C" [c_name =] function|task name;` or a package re-export + /// `export pkg::item, pkg::*;`. + pub(super) fn parse_export(&mut self) -> PResult { + self.expect_kw("export")?; + if self.cur().kind == TokenKind::String { + let spec = self.expect_dpi_spec()?; + let c_identifier = self.parse_dpi_c_identifier(); + if !self.cur().is_kw("function") && !self.cur().is_kw("task") { + return self.error("expected `function` or `task` in a DPI export"); + } + let kw = self.bump().text; + let name = self.expect_name()?; + self.expect_sym(";")?; + return Ok(ExportDecl::Dpi(DpiExport { spec, c_identifier, kw, name })); + } + let paths = self.parse_package_paths(true)?; + self.expect_sym(";")?; + Ok(ExportDecl::Package(paths)) + } + + fn expect_dpi_spec(&mut self) -> PResult { + if self.cur().kind == TokenKind::String { + Ok(self.bump().text) + } else { + self.error("expected a DPI linkage spec string") + } + } + + /// The optional `c_name =` that gives the linkage symbol a name of its own. + fn parse_dpi_c_identifier(&mut self) -> Option { + if self.cur().kind != TokenKind::Ident || !self.nth(1).is_sym("=") { + return None; + } + let span = self.cur().span; + let name = Name { text: self.bump().text, span }; + self.skip(); + Some(name) + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_parser/tests/census.rs b/crates/vlog_parser/tests/census.rs index 871cecd..deaf9ef 100644 --- a/crates/vlog_parser/tests/census.rs +++ b/crates/vlog_parser/tests/census.rs @@ -26,7 +26,7 @@ fn collect(dir: &Path, out: &mut Vec) { /// is a construct this round had no business touching. Set `SVA_LINES` to a /// file list (one path per line) rather than `CENSUS` to a directory. #[test] -#[ignore] +#[ignore = "read-only probe: needs SVA_LINES=; run with --ignored --nocapture"] fn sva_lines() { std::thread::Builder::new() .stack_size(vlog_parser::PARSE_STACK_SIZE) @@ -146,7 +146,7 @@ fn vlog_linter_visit(stmt: &vlog_parser::ast::Stmt, out: &mut Vec<(u32, u32)>) { } #[test] -#[ignore] +#[ignore = "read-only sweep probe: needs CENSUS=; run with --ignored --nocapture"] fn census() { std::thread::Builder::new() .stack_size(vlog_parser::PARSE_STACK_SIZE) diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index 3e16767..d0bd091 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -1234,7 +1234,7 @@ impl KnownFacts for CorpusFacts { /// it with `cargo test -p vlog_refactor --test corpus -- --ignored --nocapture` /// (through `tools/guard.sh`), which also prints the parse counts. #[test] -#[ignore] +#[ignore = "renames a module across corpus/ three times; run with --ignored --nocapture"] fn a_corpus_rename_says_the_same_thing_however_many_records_are_reused() { let Some(files) = corpus() else { return }; let sources = read(&files); diff --git a/crates/vlog_refactor/tests/rename_bind.rs b/crates/vlog_refactor/tests/rename_bind.rs index c72af74..90bb49c 100644 --- a/crates/vlog_refactor/tests/rename_bind.rs +++ b/crates/vlog_refactor/tests/rename_bind.rs @@ -598,7 +598,7 @@ endmodule /// `LUCISV_BIND_ROOT=$HOME/repo/opentitan tools/guard.sh -m 8 -t 1800 -- \ /// cargo test -p vlog_refactor --test rename_bind -- --ignored --nocapture`. #[test] -#[ignore] +#[ignore = "reads the opentitan tree LUCISV_BIND_ROOT names; run with --ignored --nocapture"] fn the_three_qa_renames_agree_across_reuse_modes_and_edit_the_bind_file() { let Ok(root) = std::env::var("LUCISV_BIND_ROOT") else { eprintln!("LUCISV_BIND_ROOT unset — skipping"); diff --git a/crates/vlog_semantic/src/resolve.rs b/crates/vlog_semantic/src/resolve.rs index 632810d..a53af18 100644 --- a/crates/vlog_semantic/src/resolve.rs +++ b/crates/vlog_semantic/src/resolve.rs @@ -5,11 +5,25 @@ //! Everything is bound before anything is resolved, so a name used before it //! is declared resolves exactly like one used after — which is what Verilog //! requires at module scope and what an editor needs mid-edit. +//! +//! This file is the dispatch ([`resolve`]) and the walks that answer a name +//! written by itself: on the lexical chain, as a unit (`p::x`), or at file +//! scope. The spine of a dotted path (`a.b.c`) is `member`, what this file +//! says about a written type name is `types`, and a path rooted at a +//! top-level module is `root`. use crate::bind::{Pending, Target}; use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind}; +mod member; mod root; +mod types; + +pub(crate) use member::member_site; +pub(crate) use types::extends_chain; + +use member::{bind_member, in_bind_target, member_of, type_member}; +use types::{container_scope, member_in_chain}; /// Resolve one pending use against the finished scope tree. /// @@ -88,73 +102,6 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti }) } -/// A name written in the expression half of a `bind`'s connection, looked up -/// in the **target** scope (IEEE 1800 §23.11). -/// -/// The target's own declaration when this file holds it — and a miss there is -/// `None`, never `NotFound`: a module opens a scope per generate block, so a -/// connection may legitimately name something the module's *own* scope does -/// not hold, and "absent from this scope" is not "absent". The target -/// declared somewhere else is the same question a hierarchical tail asks of -/// the workspace — "is `name` a member of this module?" — in the -/// `unit::name` path spelling `follow_one` reads. -/// -/// The surface is the **hierarchical** one (IEEE 1800 §23.6): a bind's -/// connection may name any of the target's declarations, its internal nets -/// and variables included, which is exactly what `bind aes chk u -/// (.req(entropy_masking_req))` does and what the connection surface — ports -/// and parameters only — cannot answer. Asking the narrow surface is what -/// made such a connection resolve to nothing, and a `name`-less path is what -/// kept the miss silent: the warning scan names the unit a candidate was -/// searched in by splitting the path at its `::`. -fn in_bind_target( - scopes: &[Scope], - symbols: &[Symbol], - target: &str, - name: &str, -) -> Option { - match owning_scope(scopes, symbols, target, is_instantiable) { - Some(scope) => scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved), - None => Some(Resolution::ExternalCandidate { - paths: vec![format!("{target}::{name}")], - surface: Surface::Hierarchical, - }), - } -} - -/// A hierarchical path written in a `bind`'s connection, rooted where the -/// directive elaborates rather than where it is written. -/// -/// `bind aes chk u (.s(u_aes_core.u_aes_prng_clearing.seed_en))` is -/// [`member_of`]'s walk with one substitution: the head starts in `aes`'s -/// scope instead of the writing scope's lexical chain. So `head` is simply -/// one more link of the spine, and the target is where the spine begins — its -/// own scope when this file declares the target, and otherwise the unit the -/// workspace answers hierarchical members of. -/// -/// `None` — no reference at all — wherever [`member_of`] would record none: -/// a link this file declares as something with no members to search, or a -/// name genuinely absent from a scope this file holds whole. -fn bind_member( - scopes: &[Scope], - symbols: &[Symbol], - target: &str, - head: &str, - mids: &[String], - name: &str, -) -> Option { - let mut here = match owning_scope(scopes, symbols, target, is_instantiable) { - Some(scope) => MemberSite::Scope(scope), - None => MemberSite::Unit { path: target.to_string(), surface: Surface::Hierarchical }, - }; - for link in std::iter::once(head).chain(mids.iter().map(String::as_str)) { - here = descend(scopes, symbols, here, link)?; - } - // Never the `InheritedCandidate` shape: that is a class's business, and - // the head of this spine is a place in the design hierarchy. - member_at(scopes, symbols, here, name, false) -} - /// A name looked up **only** in the scope it is written in, never outward: a /// modport's port list and a clocking block's signal list, both of which name /// members of the interface (or module) they are written in and nothing else. @@ -168,562 +115,6 @@ fn in_scope(scopes: &[Scope], scope: ScopeId, name: &str) -> Option scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved) } -/// The `mp` of a glued `bus_if.mp` type name: a member of the *type*, looked -/// up on exactly the terms [`member_of`]'s last link is. -/// -/// The interface's scope when this file declares it — a hit is the modport's -/// declaration, a miss is nothing at all, because this file has answered what -/// `bus_if` is and it holds no such modport. A name this file declares as -/// something without members ([`TypeHere::NotAUnit`]) is nothing either. Only a -/// name **nothing here declares** reaches the workspace, as the one composed -/// path `follow_one` reads back as `member(bus_if, mp)`. -fn type_member( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - unit: &str, - name: &str, -) -> Option { - match type_here(scopes, symbols, from, unit) { - TypeHere::Scope(scope) => { - scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved) - } - TypeHere::NotAUnit => None, - TypeHere::Absent => Some(Resolution::ExternalCandidate { - paths: vec![format!("{}::{name}", last_segment(unit))], - surface: Surface::Connection, - }), - } -} - -/// The `member` of `head.mids….member`: the head is resolved on the ordinary -/// lexical chain, its **declared type** is resolved on the same chain, each -/// name in `mids` is looked up in that type's scope (and up its `extends` -/// chain) to give the next type, and the tail is looked up in the last one. -/// -/// `None` — no reference recorded at all — whenever this crate has nothing to -/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head -/// nothing in this file declares, a head that is neither typed nor a unit a -/// hierarchical name may start at (a `logic [3:0]`, a genvar, a -/// built-in), a type **this file declares** as something with no members to -/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a -/// member genuinely absent from a class this file declares whole. Recording a -/// `NotFound` for those would move `reference_at` under every `a.b` in the -/// corpus to answer "a name that resolves to nothing", which is a different -/// claim than "not modelled". **A link that cannot be resolved honestly stops -/// the chain**: nothing is recorded for it or for anything after it. -/// -/// Only a type name **nothing in this file declares** reaches the workspace. -/// The distinction is the whole of QA finding 1 (2026-09-01): a `bus_t` this -/// file declares as a struct typedef must not be asked about in a workspace -/// where some unrelated file declares a *class* `bus_t`, or `s.field` lands on -/// a stranger's property — a wrong answer, where recording nothing is merely a -/// missing one. -fn member_of( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - head: &str, - mids: &[String], - name: &str, -) -> Option { - if head == root::ROOT && mids.is_empty() { - // `$root.tb`: the tail is the top module itself. - return Some(root::top_module(scopes, symbols, name)); - } - let site = spine_site(scopes, symbols, from, head, mids, HeadMiss::TopModule)?; - member_at(scopes, symbols, site, name, mids.is_empty()) -} - -/// The **tail** of a spine: `name` looked up in the site the links before it -/// landed on. -/// -/// `direct` says whether this is a plain `head.member` — the one shape that -/// may report an inherited candidate, because for a longer chain the base is -/// the owner of an earlier link, not of this name, and claiming it here would -/// send the overlay's inheritance chase after the wrong class. -/// -/// Shared with [`bind_member`], which walks the same links from a different -/// start: two spellings of this lookup would eventually answer one name two -/// ways. -fn member_at( - scopes: &[Scope], - symbols: &[Symbol], - site: MemberSite, - name: &str, - direct: bool, -) -> Option { - match site { - MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, name) { - Ok(id) => Some(Resolution::Resolved(id)), - // The chain leaves this file: the base, plus the path the - // workspace's member table answers it by. - Err(Some(base)) if direct => Some(Resolution::InheritedCandidate { - paths: vec![format!("{}::{name}", last_segment(&base))], - base, - }), - Err(Some(base)) => Some(Resolution::ExternalCandidate { - paths: vec![format!("{}::{name}", last_segment(&base))], - surface: Surface::Connection, - }), - // A class this file declares whole, with no such member: nothing - // to say that `NotFound` would not overstate. - Err(None) => None, - }, - // A type this file does not declare: the workspace's member table is - // the only layer that can say. The last `::` segment names the unit, - // the spelling `follow_one` turns back into `member(unit, name)`. - MemberSite::Unit { path, surface } => { - Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")], surface }) - } - } -} - -/// **The prefix of [`member_of`]**, and the whole of what a completion list -/// after a `.` needs: where `head.mids….` puts the cursor, with no tail -/// looked up yet. -/// -/// One walk, called by both — `member_of` is this function plus one lookup in -/// what it returns. Every stopping condition is therefore shared: a head -/// nothing here declares, a head with no type this crate can look members up -/// in, a mid that leaves the chain unfinishable. `None` means *nothing to -/// say*, which for a completion list means no popup and for a resolution -/// means no reference recorded. -/// -/// `this` and `super` are heads here even though [`Target::MemberOf`] never -/// carries them (the binder sends those to [`this_member`]/[`super_member`], -/// which resolve one member and stop): a `this.` popup is asking the same -/// question about the same class, and answering it from the same walk is what -/// keeps the two from drifting. `super` names the first hop of the `extends` -/// chain — the base's scope when this file declares it, the base's *name* -/// when it does not, which is the unit the overlay's own chase starts at. -/// -/// **One difference from the resolution walk**, and only one: a head this -/// file does not declare is *not* rooted at a top-level module here -/// ([`HeadMiss::Nothing`]), where [`member_of`] roots it at one -/// ([`HeadMiss::TopModule`], TODO §65.4). A popup after `no_such_handle.` has -/// always answered nothing so the ordinary completion tiers run, and a -/// workspace unit list after every unknown head would replace them with an -/// empty one; offering a top module's members after `tb.` is a completion -/// change the language server's member list must make knowingly -/// (`docs/features/top-rooted-paths/README.md`, Handshakes). `$root.tb.` is -/// rooted in both: it says what it is. -pub(crate) fn member_site( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - head: &str, - mids: &[String], -) -> Option { - spine_site(scopes, symbols, from, head, mids, HeadMiss::Nothing) -} - -/// What a spine's head that this file does not declare roots the spine at. -#[derive(Clone, Copy)] -enum HeadMiss { - /// Nothing: the spine stops (the completion walk). - Nothing, - /// The top-level module of that name (the resolution walk). - TopModule, -} - -/// [`member_site`]'s walk, with what a head miss means said by the caller. -fn spine_site( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - head: &str, - mids: &[String], - miss: HeadMiss, -) -> Option { - let (mut here, mids) = match (head, mids.split_first()) { - (root::ROOT, Some((top, rest))) => (root::top_site(scopes, symbols, top), rest), - _ => (head_site(scopes, symbols, from, head, miss)?, mids), - }; - for mid in mids { - here = descend(scopes, symbols, here, mid)?; - } - Some(here) -} - -/// One more link of a spine: where `here`'s member `link` puts the cursor. -/// -/// Shared with [`bind_member`] for the same reason [`member_at`] is — a -/// second spelling of the hop would eventually walk somewhere the first does -/// not. -fn descend( - scopes: &[Scope], - symbols: &[Symbol], - here: MemberSite, - link: &str, -) -> Option { - match here { - MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, link) { - Ok(id) => link_type(scopes, symbols, id), - // The chain leaves this file at a base class: everything from - // here on is one composed path for the workspace to walk. - Err(Some(base)) => Some(MemberSite::Unit { - path: format!("{}::{link}", last_segment(&base)), - surface: Surface::Connection, - }), - Err(None) => None, - }, - // Already outside this file — each further name is one more segment - // of the path `follow_one` walks member by member. - MemberSite::Unit { path, surface } => { - Some(MemberSite::Unit { path: format!("{path}::{link}"), surface }) - } - } -} - -/// Where the *first* segment of a spine puts the cursor. -fn head_site( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - head: &str, - miss: HeadMiss, -) -> Option { - match head { - // Neither is a name this crate binds, so neither goes through - // `lexical`; both are the enclosing class, one hop apart. - "this" => nearest_class(scopes, from).map(MemberSite::Scope), - "super" => { - let class = nearest_class(scopes, from)?; - let (chain, base) = extends_chain(scopes, symbols, class); - match chain.get(1) { - Some(&base_scope) => Some(MemberSite::Scope(base_scope)), - None => Some(MemberSite::Unit { - path: last_segment(&base?).to_string(), - surface: Surface::Connection, - }), - } - } - // `$root` alone, a system name, a macro: no unit to root a path at. - _ if head.starts_with(['$', '`']) => None, - _ => match lexical(scopes, from, head, false) { - Resolution::Resolved(id) => link_type(scopes, symbols, id), - // A plain miss where nothing unseen could declare the name is a - // top-level module's name — the very rule `Target::PathHead` - // applies to the head's own reference (`root::roots_at_top`), so - // the head and the segments after it agree. Anything else is - // doubt, and doubt roots nothing. - Resolution::NotFound - if matches!(miss, HeadMiss::TopModule) && root::roots_at_top(scopes, from) => - { - Some(root::unit_root(head)) - } - _ => None, - }, - } -} - -/// **The prefix of [`unit_member`]**: which unit `unit::` names, without -/// looking a member up in it. -/// -/// The same outward walk, with the same kind filter — a package or class -/// declared here answers with its own scope, a `typedef class c;` forward -/// declaration and a name nothing here declares answer with the workspace -/// unit, and a non-unit shadower is stepped over. A `pkg::cls` path descends -/// segment by segment afterwards, on [`type_here`]'s terms: a segment missing -/// from a container this file holds is `None`, because this file has answered -/// what the container holds. -pub(crate) fn unit_site( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - path: &str, -) -> Option { - let mut segments = path.split("::"); - let mut here = unit_scope(scopes, symbols, from, segments.next()?); - for segment in segments { - here = match here { - MemberSite::Scope(scope) => { - let id = scopes.get(scope.0 as usize)?.lookup_local(segment)?; - MemberSite::Scope(container_scope(symbols, id)?) - } - MemberSite::Unit { path, surface } => { - MemberSite::Unit { path: format!("{path}::{segment}"), surface } - } - }; - } - Some(here) -} - -/// One `::` segment: the scope this file opens for it, else the workspace -/// unit of that name. Never `None` — a name nothing here declares is exactly -/// what the index is for. -fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -> MemberSite { - let mut current = Some(from); - while let Some(id) = current { - let scope = &scopes[id.0 as usize]; - if let Some(sym) = scope.lookup_local(unit) { - match symbols[sym.0 as usize].kind { - SymbolKind::Package | SymbolKind::Class => { - if let Some(child) = symbols[sym.0 as usize].child_scope { - return MemberSite::Scope(child); - } - } - // `typedef class c;` promises the class lives elsewhere. - SymbolKind::Typedef => break, - // A non-unit shadower; keep walking outward. - _ => {} - } - } - current = scope.parent; - } - MemberSite::Unit { path: unit.to_string(), surface: Surface::Connection } -} - -/// Where the members of one declaration live: its **declared type**'s scope -/// when this file declares that type, else the workspace path for it. -/// -/// A declaration with no declared type at all can still be a chain's head when -/// it opens a scope a `.` may name members of — a module or an interface, -/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a -/// top-level module name is the root of a hierarchical path), or a class, -/// where the answer can only ever be that very class's own member. Everything -/// else — a `logic` net, a genvar, a package — answers `None`, which stops -/// the chain. A block label has no type either, and opens its own scope the -/// way a module does. -fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { - let symbol = symbols.get(id.0 as usize)?; - let Some(type_name) = symbol.type_name.as_deref() else { - return member_scope(scopes, symbols, id).map(MemberSite::Scope); - }; - // The type name is looked up where the declaration is written, by the same - // walk the type *reference* itself took. - match type_here(scopes, symbols, symbol.scope, type_name) { - TypeHere::Scope(scope) => Some(MemberSite::Scope(scope)), - // This file says what the type is, and it is not something with - // members. No other file can override that, so nothing is recorded. - TypeHere::NotAUnit => None, - TypeHere::Absent => Some(MemberSite::Unit { - path: last_segment(type_name).to_string(), - surface: head_surface(symbol.kind), - }), - } -} - -/// Which member surface a link of a spine opens: the **hierarchical** one when -/// the link is an instance, the connection one for everything else. -/// -/// `u_x.sig` is a hierarchical path (IEEE 1800 §23.6) and `sig` may be any of -/// `sub`'s own declarations; `handle.field` is a member access on a type, and -/// `pkt_t` has one surface anyway. The distinction only ever matters for a -/// module — the one unit whose two surfaces differ — and it is settled here, -/// in the file that can see what the head is, because the path handed to the -/// workspace is only a spelling. -fn head_surface(kind: SymbolKind) -> Surface { - match kind { - SymbolKind::Instance => Surface::Hierarchical, - _ => Surface::Connection, - } -} - -/// `name` in a class (or interface) scope this file holds, then up its -/// `extends` chain as far as this file goes. -/// -/// `Ok` is the declaration; `Err(Some(base))` means the chain left this file -/// at `base`, which the workspace index chases further -/// ([`crate::WorkspaceIndex::base_of`]); `Err(None)` means the chain ended -/// here — every class on it is declared in this file and none of them binds -/// the name. -fn member_in_chain( - scopes: &[Scope], - symbols: &[Symbol], - scope: ScopeId, - name: &str, -) -> Result> { - let (chain, base) = extends_chain(scopes, symbols, scope); - for id in chain { - if let Some(found) = scopes[id.0 as usize].lookup_local(name) { - return Ok(found); - } - } - Err(base) -} - -/// **The walk [`member_in_chain`] does**, with the lookup left to the caller: -/// every scope a member of `scope` may be declared in, nearest first, and the -/// base the chain left this file at (`None` when it ended here — a class -/// extending nothing, a cycle, or a chain every link of which this file -/// declares). -/// -/// Split out so that a completion list of *all* the members and a resolution -/// of *one* of them cannot walk different chains: [`member_in_chain`] is this -/// function plus a `lookup_local` in each scope it names, in the same order, -/// which is the same first-hit-wins shadowing it always had. -/// -/// `extends` can be written in a cycle; the visited set is what makes this -/// terminate on `class a extends b; class b extends a;`. -pub(crate) fn extends_chain( - scopes: &[Scope], - symbols: &[Symbol], - scope: ScopeId, -) -> (Vec, Option) { - let mut visited: Vec = Vec::new(); - let mut current = scope; - loop { - if visited.contains(¤t) { - return (visited, None); - } - visited.push(current); - let Some(base) = &scopes[current.0 as usize].extends else { - return (visited, None); - }; - match type_here(scopes, symbols, enclosing(scopes, current), base) { - TypeHere::Scope(next) => current = next, - // Whether the base is absent from this file or declared here as - // something without a member scope — a `typedef class base;` - // forward declaration is exactly that — it is the workspace's to - // finish. `extends` names a class by the grammar's own claim, so - // asking the index about it is not the guess `member_of`'s - // `NotAUnit` arm refuses to make about a data declaration's type. - TypeHere::NotAUnit | TypeHere::Absent => return (visited, Some(base.clone())), - } - } -} - -/// The scope enclosing one — a class's base is resolved from *outside* it, as -/// `extends` itself is (class-semantics rule 5). -fn enclosing(scopes: &[Scope], scope: ScopeId) -> ScopeId { - scopes[scope.0 as usize].parent.unwrap_or(ScopeId(0)) -} - -/// What **this file** says about a type name — the three-way answer -/// `handle.member` needs, where a two-way one is a wrong answer waiting to -/// happen (QA finding 1, 2026-09-01). -enum TypeHere { - /// Declared here as something with members to look in: a class, a module, - /// or an interface — so `virtual clk_rst_if vif; vif.clk` reaches the - /// interface's signals. - Scope(ScopeId), - /// Declared here as something else — a struct, enum or alias `typedef`, a - /// parameter, a variable shadowing the name. This file has *answered* the - /// question "what is this type", and the answer is one with no members - /// this crate models (struct fields are round 2, `docs/topo.md` §2.9-13). - /// No other file can override that answer, so the workspace is never - /// asked — which is what keeps a locally-declared `bus_t` from being - /// looked up in a stranger's class of the same name. - NotAUnit, - /// Nothing in this file declares the name at all — the only case the - /// workspace's tables can honestly answer. - Absent, -} - -/// Look a written type name up in this file: on the lexical chain for its -/// first segment, then descended segment by segment for `pkg::cls`. -/// -/// The first segment goes through [`lexical`] itself — the same walk, the same -/// shadowing, the same import precedence the type *reference* took — so what -/// this says and what go-to-definition on the type name answers cannot -/// disagree. A qualified path then descends only through containers: a -/// package, class or module scope. A segment missing from a container this -/// file holds is [`TypeHere::NotAUnit`], not [`TypeHere::Absent`] — the -/// container is fully known here, the same reason [`unit_member`] answers a -/// missing package member with `NotFound` rather than sending it to the -/// workspace (vlog-semantic rule 6). -/// -/// A name landing on a `typedef` **that aliases another type** is followed to -/// what it aliases (`typedef c1 my_t;` → `c1`), from the typedef's own scope, -/// as many hops as are written; `seen` is what makes a chain of aliases that -/// meets itself terminate. A typedef with no aliased type — a `struct`, an -/// `enum`, an alias of a built-in, a `typedef class c;` forward declaration — -/// stays [`TypeHere::NotAUnit`] exactly as it was: this file has answered what -/// the type is, and the answer has no members this crate models. -fn type_here(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, path: &str) -> TypeHere { - type_here_seen(scopes, symbols, from, path, &mut Vec::new()) -} - -fn type_here_seen( - scopes: &[Scope], - symbols: &[Symbol], - from: ScopeId, - path: &str, - seen: &mut Vec, -) -> TypeHere { - let mut segments = path.split("::"); - let Some(head) = segments.next() else { - return TypeHere::Absent; - }; - let Resolution::Resolved(mut current) = lexical(scopes, from, head, false) else { - return TypeHere::Absent; - }; - for segment in segments { - let Some(scope) = container_scope(symbols, current) else { - return TypeHere::NotAUnit; - }; - match scopes.get(scope.0 as usize).and_then(|s| s.lookup_local(segment)) { - Some(next) => current = next, - None => return TypeHere::NotAUnit, - } - } - if let Some(scope) = member_scope(scopes, symbols, current) { - return TypeHere::Scope(scope); - } - match alias_target(symbols, current) { - Some((aliased, written_in)) if !seen.contains(¤t) => { - seen.push(current); - type_here_seen(scopes, symbols, written_in, &aliased, seen) - } - _ => TypeHere::NotAUnit, - } -} - -/// The type a `typedef` aliases, and the scope the alias is written in — -/// `None` for every other declaration, and for a typedef whose target names no -/// declaration at all (a `struct` or `enum` body, an alias of a built-in, a -/// forward class declaration). -fn alias_target(symbols: &[Symbol], id: SymbolId) -> Option<(String, ScopeId)> { - let symbol = symbols.get(id.0 as usize)?; - if symbol.kind != SymbolKind::Typedef { - return None; - } - Some((symbol.type_name.clone()?, symbol.scope)) -} - -/// The scope a symbol opens when it is a container a type path may pass -/// *through*: a package, a class or a module. -fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option { - let symbol = symbols.get(id.0 as usize)?; - matches!(symbol.kind, SymbolKind::Package | SymbolKind::Class) - .then_some(symbol.child_scope) - .or_else(|| symbol.kind.is_instantiable().then_some(symbol.child_scope))? -} - -/// The scope a symbol opens when a `.` may name its members: a class, a -/// module, or an interface — which is what makes `vif.sig` and `u.internal` -/// reach into one — a named block, which is what `g_lane[0].lane_q` and -/// `blk.tmp` reach into (IEEE 1800 §23.6), **or** a `struct`/`union` body, -/// whoever names it. A package is a container to pass through, never a thing -/// a handle can be. -/// -/// The struct half is deliberately written as "any symbol whose child scope is -/// a struct body", not "a `Typedef` whose child scope is one": the same rule -/// then serves all three ways a body gets named — the `typedef` that names it, -/// an **anonymous** aggregate's own declarator (`struct { logic a; } s;`), and -/// an **inline nested** member (`struct { struct { logic q; } ctrl; }`), where -/// no type name exists to look anything up by. `docs/features/struct-members/README.md`. -fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { - let symbol = symbols.get(id.0 as usize)?; - if symbol.kind == SymbolKind::Class - || symbol.kind == SymbolKind::Covergroup - || symbol.kind == SymbolKind::Block - || symbol.kind.is_instantiable() - { - return symbol.child_scope; - } - let child = symbol.child_scope?; - (scopes.get(child.0 as usize)?.kind == crate::model::ScopeKind::Struct).then_some(child) -} - -/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) — -/// the segment the workspace's member table is keyed by. -fn last_segment(path: &str) -> &str { - path.rsplit("::").next().unwrap_or(path) -} - /// Walk the scope chain outward: names declared in a scope first, then the /// packages that scope imports, then the enclosing scope. A miss inside a /// class whose header says `extends` becomes an inheritance candidate — the @@ -860,6 +251,63 @@ fn unit_member( } } +/// **The prefix of [`unit_member`]**: which unit `unit::` names, without +/// looking a member up in it. +/// +/// The same outward walk, with the same kind filter — a package or class +/// declared here answers with its own scope, a `typedef class c;` forward +/// declaration and a name nothing here declares answer with the workspace +/// unit, and a non-unit shadower is stepped over. A `pkg::cls` path descends +/// segment by segment afterwards, on [`types::type_here`]'s terms: a segment missing +/// from a container this file holds is `None`, because this file has answered +/// what the container holds. +pub(crate) fn unit_site( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + path: &str, +) -> Option { + let mut segments = path.split("::"); + let mut here = unit_scope(scopes, symbols, from, segments.next()?); + for segment in segments { + here = match here { + MemberSite::Scope(scope) => { + let id = scopes.get(scope.0 as usize)?.lookup_local(segment)?; + MemberSite::Scope(container_scope(symbols, id)?) + } + MemberSite::Unit { path, surface } => { + MemberSite::Unit { path: format!("{path}::{segment}"), surface } + } + }; + } + Some(here) +} + +/// One `::` segment: the scope this file opens for it, else the workspace +/// unit of that name. Never `None` — a name nothing here declares is exactly +/// what the index is for. +fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -> MemberSite { + let mut current = Some(from); + while let Some(id) = current { + let scope = &scopes[id.0 as usize]; + if let Some(sym) = scope.lookup_local(unit) { + match symbols[sym.0 as usize].kind { + SymbolKind::Package | SymbolKind::Class => { + if let Some(child) = symbols[sym.0 as usize].child_scope { + return MemberSite::Scope(child); + } + } + // `typedef class c;` promises the class lives elsewhere. + SymbolKind::Typedef => break, + // A non-unit shadower; keep walking outward. + _ => {} + } + } + current = scope.parent; + } + MemberSite::Unit { path: unit.to_string(), surface: Surface::Connection } +} + /// `this.x`: the enclosing class's own scope and the classes it extends — a /// member access cannot name a method local or an enclosing module net, but it /// can name an inherited member, and since 2026-09-01 the `extends` chain is diff --git a/crates/vlog_semantic/src/resolve/member.rs b/crates/vlog_semantic/src/resolve/member.rs new file mode 100644 index 0000000..52956d3 --- /dev/null +++ b/crates/vlog_semantic/src/resolve/member.rs @@ -0,0 +1,382 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The spine of a dotted path: where `head.mids…` puts the cursor +//! ([`member_site`]) and the member looked up there ([`member_of`]). +//! +//! One walk serves the resolution of `a.b.c`, the completion list after a +//! `.`, a `bind` connection's path rooted in the bind target +//! ([`bind_member`], [`in_bind_target`]) and the `mp` of a glued `bus_if.mp` +//! type name ([`type_member`]) — each link resolved on the terms `types` +//! states, so the spellings of one lookup cannot drift apart. + +use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind}; + +use super::types::{ + extends_chain, last_segment, member_in_chain, member_scope, type_here, TypeHere, +}; +use super::{is_instantiable, lexical, nearest_class, owning_scope, root}; + +/// The `member` of `head.mids….member`: the head is resolved on the ordinary +/// lexical chain, its **declared type** is resolved on the same chain, each +/// name in `mids` is looked up in that type's scope (and up its `extends` +/// chain) to give the next type, and the tail is looked up in the last one. +/// +/// `None` — no reference recorded at all — whenever this crate has nothing to +/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head +/// nothing in this file declares, a head that is neither typed nor a unit a +/// hierarchical name may start at (a `logic [3:0]`, a genvar, a +/// built-in), a type **this file declares** as something with no members to +/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a +/// member genuinely absent from a class this file declares whole. Recording a +/// `NotFound` for those would move `reference_at` under every `a.b` in the +/// corpus to answer "a name that resolves to nothing", which is a different +/// claim than "not modelled". **A link that cannot be resolved honestly stops +/// the chain**: nothing is recorded for it or for anything after it. +/// +/// Only a type name **nothing in this file declares** reaches the workspace. +/// The distinction is the whole of QA finding 1 (2026-09-01): a `bus_t` this +/// file declares as a struct typedef must not be asked about in a workspace +/// where some unrelated file declares a *class* `bus_t`, or `s.field` lands on +/// a stranger's property — a wrong answer, where recording nothing is merely a +/// missing one. +pub(super) fn member_of( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + head: &str, + mids: &[String], + name: &str, +) -> Option { + if head == root::ROOT && mids.is_empty() { + // `$root.tb`: the tail is the top module itself. + return Some(root::top_module(scopes, symbols, name)); + } + let site = spine_site(scopes, symbols, from, head, mids, HeadMiss::TopModule)?; + member_at(scopes, symbols, site, name, mids.is_empty()) +} + +/// The **tail** of a spine: `name` looked up in the site the links before it +/// landed on. +/// +/// `direct` says whether this is a plain `head.member` — the one shape that +/// may report an inherited candidate, because for a longer chain the base is +/// the owner of an earlier link, not of this name, and claiming it here would +/// send the overlay's inheritance chase after the wrong class. +/// +/// Shared with [`bind_member`], which walks the same links from a different +/// start: two spellings of this lookup would eventually answer one name two +/// ways. +fn member_at( + scopes: &[Scope], + symbols: &[Symbol], + site: MemberSite, + name: &str, + direct: bool, +) -> Option { + match site { + MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, name) { + Ok(id) => Some(Resolution::Resolved(id)), + // The chain leaves this file: the base, plus the path the + // workspace's member table answers it by. + Err(Some(base)) if direct => Some(Resolution::InheritedCandidate { + paths: vec![format!("{}::{name}", last_segment(&base))], + base, + }), + Err(Some(base)) => Some(Resolution::ExternalCandidate { + paths: vec![format!("{}::{name}", last_segment(&base))], + surface: Surface::Connection, + }), + // A class this file declares whole, with no such member: nothing + // to say that `NotFound` would not overstate. + Err(None) => None, + }, + // A type this file does not declare: the workspace's member table is + // the only layer that can say. The last `::` segment names the unit, + // the spelling `follow_one` turns back into `member(unit, name)`. + MemberSite::Unit { path, surface } => { + Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")], surface }) + } + } +} + +/// **The prefix of [`member_of`]**, and the whole of what a completion list +/// after a `.` needs: where `head.mids….` puts the cursor, with no tail +/// looked up yet. +/// +/// One walk, called by both — `member_of` is this function plus one lookup in +/// what it returns. Every stopping condition is therefore shared: a head +/// nothing here declares, a head with no type this crate can look members up +/// in, a mid that leaves the chain unfinishable. `None` means *nothing to +/// say*, which for a completion list means no popup and for a resolution +/// means no reference recorded. +/// +/// `this` and `super` are heads here even though [`crate::bind::Target::MemberOf`] never +/// carries them (the binder sends those to [`super::this_member`]/[`super::super_member`], +/// which resolve one member and stop): a `this.` popup is asking the same +/// question about the same class, and answering it from the same walk is what +/// keeps the two from drifting. `super` names the first hop of the `extends` +/// chain — the base's scope when this file declares it, the base's *name* +/// when it does not, which is the unit the overlay's own chase starts at. +/// +/// **One difference from the resolution walk**, and only one: a head this +/// file does not declare is *not* rooted at a top-level module here +/// ([`HeadMiss::Nothing`]), where [`member_of`] roots it at one +/// ([`HeadMiss::TopModule`], TODO §65.4). A popup after `no_such_handle.` has +/// always answered nothing so the ordinary completion tiers run, and a +/// workspace unit list after every unknown head would replace them with an +/// empty one; offering a top module's members after `tb.` is a completion +/// change the language server's member list must make knowingly +/// (`docs/features/top-rooted-paths/README.md`, Handshakes). `$root.tb.` is +/// rooted in both: it says what it is. +pub(crate) fn member_site( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + head: &str, + mids: &[String], +) -> Option { + spine_site(scopes, symbols, from, head, mids, HeadMiss::Nothing) +} + +/// What a spine's head that this file does not declare roots the spine at. +#[derive(Clone, Copy)] +enum HeadMiss { + /// Nothing: the spine stops (the completion walk). + Nothing, + /// The top-level module of that name (the resolution walk). + TopModule, +} + +/// [`member_site`]'s walk, with what a head miss means said by the caller. +fn spine_site( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + head: &str, + mids: &[String], + miss: HeadMiss, +) -> Option { + let (mut here, mids) = match (head, mids.split_first()) { + (root::ROOT, Some((top, rest))) => (root::top_site(scopes, symbols, top), rest), + _ => (head_site(scopes, symbols, from, head, miss)?, mids), + }; + for mid in mids { + here = descend(scopes, symbols, here, mid)?; + } + Some(here) +} + +/// One more link of a spine: where `here`'s member `link` puts the cursor. +/// +/// Shared with [`bind_member`] for the same reason [`member_at`] is — a +/// second spelling of the hop would eventually walk somewhere the first does +/// not. +fn descend( + scopes: &[Scope], + symbols: &[Symbol], + here: MemberSite, + link: &str, +) -> Option { + match here { + MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, link) { + Ok(id) => link_type(scopes, symbols, id), + // The chain leaves this file at a base class: everything from + // here on is one composed path for the workspace to walk. + Err(Some(base)) => Some(MemberSite::Unit { + path: format!("{}::{link}", last_segment(&base)), + surface: Surface::Connection, + }), + Err(None) => None, + }, + // Already outside this file — each further name is one more segment + // of the path `follow_one` walks member by member. + MemberSite::Unit { path, surface } => { + Some(MemberSite::Unit { path: format!("{path}::{link}"), surface }) + } + } +} + +/// Where the *first* segment of a spine puts the cursor. +fn head_site( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + head: &str, + miss: HeadMiss, +) -> Option { + match head { + // Neither is a name this crate binds, so neither goes through + // `lexical`; both are the enclosing class, one hop apart. + "this" => nearest_class(scopes, from).map(MemberSite::Scope), + "super" => { + let class = nearest_class(scopes, from)?; + let (chain, base) = extends_chain(scopes, symbols, class); + match chain.get(1) { + Some(&base_scope) => Some(MemberSite::Scope(base_scope)), + None => Some(MemberSite::Unit { + path: last_segment(&base?).to_string(), + surface: Surface::Connection, + }), + } + } + // `$root` alone, a system name, a macro: no unit to root a path at. + _ if head.starts_with(['$', '`']) => None, + _ => match lexical(scopes, from, head, false) { + Resolution::Resolved(id) => link_type(scopes, symbols, id), + // A plain miss where nothing unseen could declare the name is a + // top-level module's name — the very rule `Target::PathHead` + // applies to the head's own reference (`root::roots_at_top`), so + // the head and the segments after it agree. Anything else is + // doubt, and doubt roots nothing. + Resolution::NotFound + if matches!(miss, HeadMiss::TopModule) && root::roots_at_top(scopes, from) => + { + Some(root::unit_root(head)) + } + _ => None, + }, + } +} + +/// Where the members of one declaration live: its **declared type**'s scope +/// when this file declares that type, else the workspace path for it. +/// +/// A declaration with no declared type at all can still be a chain's head when +/// it opens a scope a `.` may name members of — a module or an interface, +/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a +/// top-level module name is the root of a hierarchical path), or a class, +/// where the answer can only ever be that very class's own member. Everything +/// else — a `logic` net, a genvar, a package — answers `None`, which stops +/// the chain. A block label has no type either, and opens its own scope the +/// way a module does. +fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { + let symbol = symbols.get(id.0 as usize)?; + let Some(type_name) = symbol.type_name.as_deref() else { + return member_scope(scopes, symbols, id).map(MemberSite::Scope); + }; + // The type name is looked up where the declaration is written, by the same + // walk the type *reference* itself took. + match type_here(scopes, symbols, symbol.scope, type_name) { + TypeHere::Scope(scope) => Some(MemberSite::Scope(scope)), + // This file says what the type is, and it is not something with + // members. No other file can override that, so nothing is recorded. + TypeHere::NotAUnit => None, + TypeHere::Absent => Some(MemberSite::Unit { + path: last_segment(type_name).to_string(), + surface: head_surface(symbol.kind), + }), + } +} + +/// Which member surface a link of a spine opens: the **hierarchical** one when +/// the link is an instance, the connection one for everything else. +/// +/// `u_x.sig` is a hierarchical path (IEEE 1800 §23.6) and `sig` may be any of +/// `sub`'s own declarations; `handle.field` is a member access on a type, and +/// `pkt_t` has one surface anyway. The distinction only ever matters for a +/// module — the one unit whose two surfaces differ — and it is settled here, +/// in the file that can see what the head is, because the path handed to the +/// workspace is only a spelling. +fn head_surface(kind: SymbolKind) -> Surface { + match kind { + SymbolKind::Instance => Surface::Hierarchical, + _ => Surface::Connection, + } +} + +/// The `mp` of a glued `bus_if.mp` type name: a member of the *type*, looked +/// up on exactly the terms [`member_of`]'s last link is. +/// +/// The interface's scope when this file declares it — a hit is the modport's +/// declaration, a miss is nothing at all, because this file has answered what +/// `bus_if` is and it holds no such modport. A name this file declares as +/// something without members ([`TypeHere::NotAUnit`]) is nothing either. Only a +/// name **nothing here declares** reaches the workspace, as the one composed +/// path `follow_one` reads back as `member(bus_if, mp)`. +pub(super) fn type_member( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + unit: &str, + name: &str, +) -> Option { + match type_here(scopes, symbols, from, unit) { + TypeHere::Scope(scope) => { + scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved) + } + TypeHere::NotAUnit => None, + TypeHere::Absent => Some(Resolution::ExternalCandidate { + paths: vec![format!("{}::{name}", last_segment(unit))], + surface: Surface::Connection, + }), + } +} + +/// A name written in the expression half of a `bind`'s connection, looked up +/// in the **target** scope (IEEE 1800 §23.11). +/// +/// The target's own declaration when this file holds it — and a miss there is +/// `None`, never `NotFound`: a module opens a scope per generate block, so a +/// connection may legitimately name something the module's *own* scope does +/// not hold, and "absent from this scope" is not "absent". The target +/// declared somewhere else is the same question a hierarchical tail asks of +/// the workspace — "is `name` a member of this module?" — in the +/// `unit::name` path spelling `follow_one` reads. +/// +/// The surface is the **hierarchical** one (IEEE 1800 §23.6): a bind's +/// connection may name any of the target's declarations, its internal nets +/// and variables included, which is exactly what `bind aes chk u +/// (.req(entropy_masking_req))` does and what the connection surface — ports +/// and parameters only — cannot answer. Asking the narrow surface is what +/// made such a connection resolve to nothing, and a `name`-less path is what +/// kept the miss silent: the warning scan names the unit a candidate was +/// searched in by splitting the path at its `::`. +pub(super) fn in_bind_target( + scopes: &[Scope], + symbols: &[Symbol], + target: &str, + name: &str, +) -> Option { + match owning_scope(scopes, symbols, target, is_instantiable) { + Some(scope) => scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved), + None => Some(Resolution::ExternalCandidate { + paths: vec![format!("{target}::{name}")], + surface: Surface::Hierarchical, + }), + } +} + +/// A hierarchical path written in a `bind`'s connection, rooted where the +/// directive elaborates rather than where it is written. +/// +/// `bind aes chk u (.s(u_aes_core.u_aes_prng_clearing.seed_en))` is +/// [`member_of`]'s walk with one substitution: the head starts in `aes`'s +/// scope instead of the writing scope's lexical chain. So `head` is simply +/// one more link of the spine, and the target is where the spine begins — its +/// own scope when this file declares the target, and otherwise the unit the +/// workspace answers hierarchical members of. +/// +/// `None` — no reference at all — wherever [`member_of`] would record none: +/// a link this file declares as something with no members to search, or a +/// name genuinely absent from a scope this file holds whole. +pub(super) fn bind_member( + scopes: &[Scope], + symbols: &[Symbol], + target: &str, + head: &str, + mids: &[String], + name: &str, +) -> Option { + let mut here = match owning_scope(scopes, symbols, target, is_instantiable) { + Some(scope) => MemberSite::Scope(scope), + None => MemberSite::Unit { path: target.to_string(), surface: Surface::Hierarchical }, + }; + for link in std::iter::once(head).chain(mids.iter().map(String::as_str)) { + here = descend(scopes, symbols, here, link)?; + } + // Never the `InheritedCandidate` shape: that is a class's business, and + // the head of this spine is a place in the design hierarchy. + member_at(scopes, symbols, here, name, false) +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_semantic/src/resolve/types.rs b/crates/vlog_semantic/src/resolve/types.rs new file mode 100644 index 0000000..2463846 --- /dev/null +++ b/crates/vlog_semantic/src/resolve/types.rs @@ -0,0 +1,224 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! What **this file** says about a type: a written type name looked up +//! here ([`TypeHere`]), the scopes a symbol opens for a path to pass through +//! or a `.` to reach into, and a class's `extends` chain as far as this file +//! declares it. +//! +//! Everything a member lookup needs to know about a type before it may ask +//! the workspace — and the three-way answer that keeps it from asking when +//! this file has already said what the type is. + +use crate::model::{Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind}; + +use super::lexical; + +/// What **this file** says about a type name — the three-way answer +/// `handle.member` needs, where a two-way one is a wrong answer waiting to +/// happen (QA finding 1, 2026-09-01). +pub(super) enum TypeHere { + /// Declared here as something with members to look in: a class, a module, + /// or an interface — so `virtual clk_rst_if vif; vif.clk` reaches the + /// interface's signals. + Scope(ScopeId), + /// Declared here as something else — a struct, enum or alias `typedef`, a + /// parameter, a variable shadowing the name. This file has *answered* the + /// question "what is this type", and the answer is one with no members + /// this crate models (struct fields are round 2, `docs/topo.md` §2.9-13). + /// No other file can override that answer, so the workspace is never + /// asked — which is what keeps a locally-declared `bus_t` from being + /// looked up in a stranger's class of the same name. + NotAUnit, + /// Nothing in this file declares the name at all — the only case the + /// workspace's tables can honestly answer. + Absent, +} + +/// Look a written type name up in this file: on the lexical chain for its +/// first segment, then descended segment by segment for `pkg::cls`. +/// +/// The first segment goes through [`lexical`] itself — the same walk, the same +/// shadowing, the same import precedence the type *reference* took — so what +/// this says and what go-to-definition on the type name answers cannot +/// disagree. A qualified path then descends only through containers: a +/// package, class or module scope. A segment missing from a container this +/// file holds is [`TypeHere::NotAUnit`], not [`TypeHere::Absent`] — the +/// container is fully known here, the same reason [`super::unit_member`] answers a +/// missing package member with `NotFound` rather than sending it to the +/// workspace (vlog-semantic rule 6). +/// +/// A name landing on a `typedef` **that aliases another type** is followed to +/// what it aliases (`typedef c1 my_t;` → `c1`), from the typedef's own scope, +/// as many hops as are written; `seen` is what makes a chain of aliases that +/// meets itself terminate. A typedef with no aliased type — a `struct`, an +/// `enum`, an alias of a built-in, a `typedef class c;` forward declaration — +/// stays [`TypeHere::NotAUnit`] exactly as it was: this file has answered what +/// the type is, and the answer has no members this crate models. +pub(super) fn type_here( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + path: &str, +) -> TypeHere { + type_here_seen(scopes, symbols, from, path, &mut Vec::new()) +} + +fn type_here_seen( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + path: &str, + seen: &mut Vec, +) -> TypeHere { + let mut segments = path.split("::"); + let Some(head) = segments.next() else { + return TypeHere::Absent; + }; + let Resolution::Resolved(mut current) = lexical(scopes, from, head, false) else { + return TypeHere::Absent; + }; + for segment in segments { + let Some(scope) = container_scope(symbols, current) else { + return TypeHere::NotAUnit; + }; + match scopes.get(scope.0 as usize).and_then(|s| s.lookup_local(segment)) { + Some(next) => current = next, + None => return TypeHere::NotAUnit, + } + } + if let Some(scope) = member_scope(scopes, symbols, current) { + return TypeHere::Scope(scope); + } + match alias_target(symbols, current) { + Some((aliased, written_in)) if !seen.contains(¤t) => { + seen.push(current); + type_here_seen(scopes, symbols, written_in, &aliased, seen) + } + _ => TypeHere::NotAUnit, + } +} + +/// The type a `typedef` aliases, and the scope the alias is written in — +/// `None` for every other declaration, and for a typedef whose target names no +/// declaration at all (a `struct` or `enum` body, an alias of a built-in, a +/// forward class declaration). +fn alias_target(symbols: &[Symbol], id: SymbolId) -> Option<(String, ScopeId)> { + let symbol = symbols.get(id.0 as usize)?; + if symbol.kind != SymbolKind::Typedef { + return None; + } + Some((symbol.type_name.clone()?, symbol.scope)) +} + +/// The scope a symbol opens when it is a container a type path may pass +/// *through*: a package, a class or a module. +pub(super) fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option { + let symbol = symbols.get(id.0 as usize)?; + matches!(symbol.kind, SymbolKind::Package | SymbolKind::Class) + .then_some(symbol.child_scope) + .or_else(|| symbol.kind.is_instantiable().then_some(symbol.child_scope))? +} + +/// The scope a symbol opens when a `.` may name its members: a class, a +/// module, or an interface — which is what makes `vif.sig` and `u.internal` +/// reach into one — a named block, which is what `g_lane[0].lane_q` and +/// `blk.tmp` reach into (IEEE 1800 §23.6), **or** a `struct`/`union` body, +/// whoever names it. A package is a container to pass through, never a thing +/// a handle can be. +/// +/// The struct half is deliberately written as "any symbol whose child scope is +/// a struct body", not "a `Typedef` whose child scope is one": the same rule +/// then serves all three ways a body gets named — the `typedef` that names it, +/// an **anonymous** aggregate's own declarator (`struct { logic a; } s;`), and +/// an **inline nested** member (`struct { struct { logic q; } ctrl; }`), where +/// no type name exists to look anything up by. `docs/features/struct-members/README.md`. +pub(super) fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { + let symbol = symbols.get(id.0 as usize)?; + if symbol.kind == SymbolKind::Class + || symbol.kind == SymbolKind::Covergroup + || symbol.kind == SymbolKind::Block + || symbol.kind.is_instantiable() + { + return symbol.child_scope; + } + let child = symbol.child_scope?; + (scopes.get(child.0 as usize)?.kind == crate::model::ScopeKind::Struct).then_some(child) +} + +/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) — +/// the segment the workspace's member table is keyed by. +pub(super) fn last_segment(path: &str) -> &str { + path.rsplit("::").next().unwrap_or(path) +} + +/// `name` in a class (or interface) scope this file holds, then up its +/// `extends` chain as far as this file goes. +/// +/// `Ok` is the declaration; `Err(Some(base))` means the chain left this file +/// at `base`, which the workspace index chases further +/// ([`crate::WorkspaceIndex::base_of`]); `Err(None)` means the chain ended +/// here — every class on it is declared in this file and none of them binds +/// the name. +pub(super) fn member_in_chain( + scopes: &[Scope], + symbols: &[Symbol], + scope: ScopeId, + name: &str, +) -> Result> { + let (chain, base) = extends_chain(scopes, symbols, scope); + for id in chain { + if let Some(found) = scopes[id.0 as usize].lookup_local(name) { + return Ok(found); + } + } + Err(base) +} + +/// **The walk [`member_in_chain`] does**, with the lookup left to the caller: +/// every scope a member of `scope` may be declared in, nearest first, and the +/// base the chain left this file at (`None` when it ended here — a class +/// extending nothing, a cycle, or a chain every link of which this file +/// declares). +/// +/// Split out so that a completion list of *all* the members and a resolution +/// of *one* of them cannot walk different chains: [`member_in_chain`] is this +/// function plus a `lookup_local` in each scope it names, in the same order, +/// which is the same first-hit-wins shadowing it always had. +/// +/// `extends` can be written in a cycle; the visited set is what makes this +/// terminate on `class a extends b; class b extends a;`. +pub(crate) fn extends_chain( + scopes: &[Scope], + symbols: &[Symbol], + scope: ScopeId, +) -> (Vec, Option) { + let mut visited: Vec = Vec::new(); + let mut current = scope; + loop { + if visited.contains(¤t) { + return (visited, None); + } + visited.push(current); + let Some(base) = &scopes[current.0 as usize].extends else { + return (visited, None); + }; + match type_here(scopes, symbols, enclosing(scopes, current), base) { + TypeHere::Scope(next) => current = next, + // Whether the base is absent from this file or declared here as + // something without a member scope — a `typedef class base;` + // forward declaration is exactly that — it is the workspace's to + // finish. `extends` names a class by the grammar's own claim, so + // asking the index about it is not the guess `member_of`'s + // `NotAUnit` arm refuses to make about a data declaration's type. + TypeHere::NotAUnit | TypeHere::Absent => return (visited, Some(base.clone())), + } + } +} + +/// The scope enclosing one — a class's base is resolved from *outside* it, as +/// `extends` itself is (class-semantics rule 5). +fn enclosing(scopes: &[Scope], scope: ScopeId) -> ScopeId { + scopes[scope.0 as usize].parent.unwrap_or(ScopeId(0)) +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/docs/features/hygiene-splits-r12/README.md b/docs/features/hygiene-splits-r12/README.md new file mode 100644 index 0000000..6ef77d7 --- /dev/null +++ b/docs/features/hygiene-splits-r12/README.md @@ -0,0 +1,612 @@ + + +# hygiene-splits-r12 — Round 12: pure-move splits and codebase hygiene + +## Goal + +Give every production file comfortable headroom under the 600-line ceiling +and clear the hygiene backlog the round names, **without changing what any +binary does**. Five files are split by responsibility (the four the plan +lists, plus `lexer.rs`, which the re-measurement showed is the one file +really over the ceiling); the inline `mod tests` blocks that dwarf their +file in `lucisv_server` move out to `/tests.rs`; every bare +`#[ignore]` says why; one timing test stops timing a copy of the code it +guards; one tool stops defaulting to another machine's home directory; and +the size measurement in `CLAUDE.md` is refreshed. The proof is the gates, +the per-crate test counts and names, the line-multiset check of every +move, and byte-identical formatter and linter output over OpenTitan. + +## Assumptions + +- "Production lines" is the `CLAUDE.md` metric: non-blank, non-comment + lines before the first `#[cfg(test)]` / `mod tests`, files under + `*/tests/` excluded. Where that rule is misled by a `#[cfg(test)]` + attribute that is not the test module (see the `lexer.rs` finding in the + work log) the **refined** count is given too: the same, but a + `#[cfg(test)]` item or an out-of-line `#[cfg(test)] mod x;` is skipped + rather than ending the count, and a file declared under `#[cfg(test)]` + is test code. +- A split is a pure move: function bodies byte-for-byte, no item renamed, + no signature changed, public paths kept by re-export. What a move may + add is `use`/`mod` lines, a visibility keyword, a module doc, the stamp + lines and — for a new file that continues an `impl` — the `impl … {` + wrapper and its `}`. +- `pub(super)` on a method or function is the only widening a production + move needed; nothing became `pub(crate)` or `pub` that was not already. + Where `pub(super)` pushed a signature past 100 columns, `rustfmt` + re-broke that one signature (two cases, listed below). The body under + it is untouched. +- An inline test module that "dwarfs its file" is taken to mean: the + file's inline test modules total at least 500 lines **and** at least + twice its production lines. 21 files of `lucisv_server` meet it; the + ones that do not are listed in the work log. +- A moved test module keeps its module name, so every test keeps its full + path (`nav::tests::…`) and the test list is comparable line for line. + Its body loses four spaces of indent — except lines that begin inside a + string literal, which are test *inputs* and stay byte-exact — and + `cargo fmt` then re-joins what fits at the new indent. +- Intra-doc links in the docs of crate-private items (`` [`member_of`] `` + written in `resolve.rs`, the item now in `resolve/member.rs`) are not + resolved by any gate: the items are private and `cargo test --doc` does + not check links. The moved docs are left byte-identical. +- `lucisv` (the CLI) does not link `lucisv_server`, so the OpenTitan + byte-identity proves the parser, semantic, formatter and linter moves; + the server-side moves are proven by the test list and counts. + +## Handshakes + +- **Consumes / promises: unchanged.** Every path another module imported + still resolves: `crate::resolve::{resolve, member_site, unit_site, + extends_chain, is_instantiable, owning_scope}` (re-exported from + `resolve.rs`), `vlog_parser::lexer::{tokenize, LexError}`, and the + `Parser` / `Fmt` methods, which are methods whatever file their `impl` + block is in. +- **Note for the lead — stale wording left byte-identical on purpose.** + `format/stmt.rs`, the doc of `stmt_kind`: "the forms that grew a layout + of their own (`if`, `case`) are the functions after it". `case` is now + `format/case.rs` (and `if` was already `branch.rs`). The module doc of + `stmt.rs` says where each lives; the function doc is moved text and was + not edited. +- **Note for the lead — parser tests not re-homed.** `parser/mod.rs` says + tests live in `parser/tests/`, "one file per grammar file they + exercise". The tests of the three new parser files stay where they were + (`tests/items.rs`, `tests/instance.rs`): moving them would be a second + move nobody asked for. +- **Request to the lead (not this lane's file):** + `crates/lucisv_mcp/tests/opentitan.rs:25` falls back to + `/Users/guoliangchen/repo/opentitan`, the same stale default + `tools/perf/sites.py:16` had. Only `sites.py` was in scope. +- **`TODO.md`**: no item names this round, so nothing was ticked. + +## Status / TODO + +- [x] Baseline pinned from `target/gates/r11/*.log` (trunk `a479faf`). +- [x] Split `vlog_semantic/src/resolve.rs` → `resolve.rs`, `resolve/member.rs`, `resolve/types.rs`. +- [x] Split `vlog_parser/src/parser/item.rs` → `item.rs`, `package.rs`, `generate.rs`. +- [x] Split `vlog_parser/src/parser/instance.rs` → `instance.rs`, `connection.rs`. +- [x] Split `vlog_formatter/src/format/stmt.rs` → `stmt.rs`, `case.rs`, `timing.rs`. +- [x] Split `vlog_parser/src/lexer.rs` (really 771, not 540) → `lexer.rs`, `lexer/number.rs`, `lexer/define_params.rs`, `lexer/attach.rs`. +- [x] 23 inline test modules of 21 `lucisv_server` files moved to `/.rs`. +- [x] `perf.rs` inspected, left whole (work log). +- [x] 12 bare `#[ignore]` given a reason (the handoff counted 11). +- [x] `large.rs` QA finding 4 fixed (test only) and shown to trip. +- [x] `tools/perf/sites.py:16` fixed. +- [x] `CLAUDE.md` measurement paragraph appended; `docs/topo.md` module lists updated. +- [x] `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets`, guarded `cargo test` for every crate touched, `tools/gates.sh --only cross`, `--only corpus`. +- [x] OpenTitan byte-identity against `a479faf`. + +## Work log + +### 2026-11-26 — the round (refactor dev, Fable) + +**Baseline** (`target/gates/r11/suite-*.log`, the lead's gate run on +`a479faf`), passed / ignored per crate: `vlog_parser` 527 / 2, +`vlog_semantic` 453 / 4, `vlog_refactor` 793 / 5, `vlog_formatter` +383 / 0, `vlog_linter` 710 / 0, `lucisv_core` 129 / 0, `lucisv` 162 / 0, +`lucisv_server` 2263 / 53, `lucisv_mcp` 400 / 3. + +#### 1. The splits + +Production lines after the move in brackets (rule = refined unless both +are given). + +**`vlog_semantic/src/resolve.rs`** (587) → + +| file | holds | +|---|---| +| `resolve.rs` [294] | Pass two's dispatch (`resolve`) and the walks that answer a name written by itself: on the lexical chain (`lexical`, `this_member`, `super_member`, `miss`), as a unit (`unit`, `unit_member`, `unit_site`, `unit_scope`), at file scope (`named_at_file_scope`, `owning_scope`, `file_symbol`). | +| `resolve/member.rs` [196] | The spine of a dotted path: where `head.mids…` puts the cursor and the member looked up there — `member_of`, `member_at`, `member_site`, `spine_site`, `descend`, `head_site`, `link_type`, and the two walks that share it, `type_member` and a `bind`'s (`in_bind_target`, `bind_member`). | +| `resolve/types.rs` [115] | What this file says about a type: a written type name looked up here (`TypeHere`, `type_here`, `alias_target`), the scopes a symbol opens (`container_scope`, `member_scope`), and a class's `extends` chain (`extends_chain`, `member_in_chain`). | +| `resolve/root.rs` [38] | untouched. | + +Forced `pub(super)`: `member::{member_of, type_member, in_bind_target, +bind_member}`; `types::{TypeHere, type_here, container_scope, +member_scope, last_segment, member_in_chain}`. Re-exported from +`resolve.rs`: `member_site`, `extends_chain` (both already `pub(crate)`). +`root.rs` still imports `super::{file_symbol, is_instantiable, lexical, +owning_scope}`, which stayed in `resolve.rs` — no edit there. + +**`vlog_parser/src/parser/item.rs`** (589) → + +| file | holds | +|---|---| +| `item.rs` [322] | From the file down to one item: the file loop, the item loop, the keyword → item dispatch, the identifier-led item, and the member-qualifier prefix. | +| `package.rs` [113] | Packages and what crosses their boundary: `package … endpackage`, the `import`/`export` path lists, DPI imports and exports. | +| `generate.rs` [160] | The `if`/`for`/`case` generate forms and the block each governs. | + +Forced `pub(super)`: `parse_package`, `parse_dpi_import`, `parse_export`, +`parse_gen_if`, `parse_gen_for`, `parse_gen_case`, `parse_gen_block` (the +dispatch in `item.rs` calls them). + +**`vlog_parser/src/parser/instance.rs`** (565) → + +| file | holds | +|---|---| +| `instance.rs` [353] | The items that instantiate or drive: continuous assignments, module and gate instantiations with their parameter overrides, `bind`; drive strengths and delay values. | +| `connection.rs` [218] | The connection list of an instantiation: named and ordered connections, the comments before the closing bracket, and the tolerant-mode read of a value whose bracket never closes. | + +Forced `pub(super)`: `parse_connections`. + +**`vlog_formatter/src/format/stmt.rs`** (570) → + +| file | holds | +|---|---| +| `stmt.rs` [400] | Statements: the `begin … end` block, a statement as the body of a header, and the `StmtKind` dispatch table (`stmt_kind`, 294 lines, whole on purpose). | +| `case.rs` [94] | `case` items: the label head (shared with generate `case` and `randsequence`), an item with its body, the `case … endcase` body, the optional `:` after `default`. | +| `timing.rs` [89] | Timing controls and sensitivity lists. | + +Forced `pub(super)`: `body_after` (called by `case_item`), +`timing_control`, `case_body` (called by `stmt_kind`). + +**`vlog_parser/src/lexer.rs`** (771 — see the finding below) → + +| file | holds | +|---|---| +| `lexer.rs` [497] | The raw phase's scanner (`RawLexer`, `next_raw`) and the entry point that fuses the two phases (`tokenize`). | +| `lexer/number.rs` [114] | Numeric literals: plain and real numbers, sized and based literals, time-unit suffixes. | +| `lexer/define_params.rs` [105; rule 6] | The formal-argument list of a function-like `` `define``, tracked incrementally (`DefineParams`). | +| `lexer/attach.rs` [54] | The attachment phase: a comment folded onto the real token it leads or trails. | + +Forced `pub(super)`: `lex_number`, `lex_based_part`, `is_base_intro`, +`DefineParams` with `new` and `open`, `Attaching`, `attach`. Forced **by +the inline tests of `lexer.rs`**, which re-derive the scan as an oracle +and read the walk counter: `define_params_start`, `ScanMode`, and the +fields `DefineParams::{scanned, walked}`; the test module gained one line, +`use super::define_params::{define_params_start, ScanMode};`. The lexer's +tests were not moved (700 lines against 497: not dwarfed). + +**Finding — `lexer.rs` was never under 600.** The 2026-11-26 paragraph in +`CLAUDE.md` gives `lexer.rs` 540; the three before it give 762, 763 and +771. Nothing was removed in between: `DefineParams` has a +`#[cfg(test)] walked: usize` **field** at line 723, and a count that stops +at the first `#[cfg(test)]` stops there, 230 production lines early. The +count to the test module is 771. It was the one production file over the +ceiling, so it is the fifth split. `lto = true` in the release profile, +so which module a function sits in does not decide what is inlined. + +The same artifact, both under the ceiling and only reported: +`vlog_refactor/src/rename/warnings.rs` (rule 80, refined 521) and +`rename/mod.rs` (rule 10, refined 494); `lucisv_server/src/state/rescan.rs` +(rule 12, refined 483); `candidates.rs` (rule 29, refined 443). + +**Move purity** (`purity.py` in the scratch dir: multiset of non-blank +lines of the old file at `a479faf` against the union of the new files). +For all five splits every residual line is a stamp, a module-doc line, a +`use`/`mod` line, a `pub(super)` prefix, or the `impl<'a> … {` / `}` +wrapper of a new file that continues an `impl` — plus exactly these: + +- `resolve/types.rs`: `pub(super) fn type_here(…)` is 102 columns on one + line, so `rustfmt` broke the signature over six lines. +- `parser/connection.rs`: `pub(super) fn parse_connections(…)`, 109 + columns, broken over four lines. +- `parser/generate.rs`: the three-line `// Generate constructs` section + banner is gone; it is the file's `//!` doc now. (The + `// DPI … and package export` banner in `package.rs` is kept.) + +How: `split.py` slices the old file (read from `git show a479faf:`) by +line range into the new files and asserts every non-blank old line is +carried exactly once or is a dropped header/wrapper line; imports and +widenings were then taken from the compiler. + +#### 2. Inline test modules, `lucisv_server` + +Moved, test module lines / production lines of the file before the move: +`nav` 2 697 / 423, `inline` 1 709 / 332, `hover` 933 + 100 + 340 / 323 +(three modules: `tests`, `qa_findings`, `qa_hover_declarations`, each its +own file), `pairs` 1 335 / 316, `type_def` 1 190 / 212, `ports` +1 177 / 377, `file_ops` 1 177 / 279, `index_cache` 1 167 / 397, `rename` +1 134 / 89, `tokens` 1 043 / 305, `type_hierarchy` 961 / 189, `settings` +866 / 295, `completion/member` 829 / 209, `hierarchy` 783 / 212, `format` +750 / 139, `completion/tiers` 709 / 162, `inlay` 701 / 122, `linked` +632 / 180, `lens` 627 / 68, `large` 593 / 199, `completion/module` +588 / 152. Each `#[cfg(test)] mod tests { … }` became +`#[cfg(test)] mod tests;` + `/tests.rs`, the convention +`same_file/tests.rs` and `state/port_grace/tests.rs` already follow. + +Not moved (under 2x, or under 500 lines), largest first: `candidates` +744 / 483, `main` 739 / 400, `on_type` 640 / 361, `lint` 607 / 362, +`includes` 499 + 112 / 341, `sync` 408 / 31, `completion/mod` 372 / 301, +`selection` 358 / 159, `convert` 343 / 102, `design_hierarchy` 335 / 117, +`code_action` 300 / 109, and everything smaller. + +**`perf.rs`** (907 lines, the whole file `#[cfg(test)]` from `main.rs`): +no inline test module; 19 `#[ignore]`d measurement tests, every one +already carrying a reason, over eight helpers (`mean`, `scratch` and six +generators of the trees they measure). Its one sentence is still its +first line. Left whole, as the decomposition-server README reasoned. + +**Proof.** `check_tests_move.py` compares each old module body with its +new file as token streams (string and char literals byte-exact, comments +exact but for leading whitespace, a `,` before a closing bracket +ignored): 23 modules, 151 982 tokens, **one** difference — in +`format/tests.rs` `rustfmt` dropped the braces of a closure that now fits +on one line (`|tab| { settings_with(…).config }` → +`|tab| settings_with(…).config`). The production remainder of each of the +21 files is byte-identical to the old file with the block replaced by +`mod ;`. The sorted `test … ok|ignored` lines of +`cargo test -p lucisv_server --all-targets` are **identical** to the +baseline log's, 2 316 lines (taken before the two hygiene edits below). + +#### 3. Hygiene + +**a. `#[ignore]`** — 12 bare ones, not 11: `lucisv_server` 8 +(`hierarchy`, `file_ops`, `includes`, `lens`, `inlay` x2, +`type_hierarchy`, `state/tests/incremental.rs`), `vlog_parser` +`tests/census.rs` x2, `vlog_refactor` `tests/rename_bind.rs` and +`tests/corpus.rs`. Each test was read; each reason says what the test +needs (`corpus/`, a generated tree, `CENSUS=`, +`SVA_LINES=`, the tree `LUCISV_BIND_ROOT` names) and how +it is run. No other byte of those tests changed. Zero bare `#[ignore]` +remain. + +**b. `large.rs` QA finding 4** is finding 4 of the QA log in +`docs/features/linux-test-portability/README.md`: "(low, pre-existing) +`large.rs` `references_on_one_giant_line…` times a copy of the +`Server::large_scan` loop (`server/large_file.rs:151`), not the production +code, so a regression there is not caught." **The one change in this +round that is not a move**, and test-only: the test now lives in +`server/tests/large_file.rs` (same name) and times the real +`textDocument/references` request through `Session`, at the same four +widths, under the same `assert_grows_linearly` / `fastest_of_five`. To +share those two helpers `large::tests` is `pub(crate) mod tests` and the +helpers `pub(crate)` (both still `#[cfg(test)]`; `perf::mean` is the +precedent). No production code changed. Count unchanged (one test moved +module); the test list differs from the baseline in exactly that one +path. +*Shown to trip:* with `large_scan` temporarily mapping each hit through +`positions.range(span)` instead of the walker, the test fails in all three +attempts at **58x** for 8x the input (limit 24x): 6.7 / 25.2 / 98.2 / +389.6 ms. Restored (`git diff` of `server/large_file.rs` empty) it reads +3.7 / 7.4 / 14.9 / 30.3 ms, 8.1x, three runs alike. + +**c. `tools/perf/sites.py:16`** defaulted `ROOT` to +`/Users/guoliangchen/repo/opentitan`, a home directory that exists on one +machine. Now `os.path.expanduser("~/repo/opentitan")` — the path +`tools/perf/README.md` already tells the reader to use (`OT=$HOME/repo/opentitan`), +and the same string as before on the machine it was written on. Verified: +`import sites` gives `/Users/lucio/repo/opentitan` here (a directory, and +`sites.path(sites.AES)` is a file), `/Users/guoliangchen/repo/opentitan` +under `HOME=/Users/guoliangchen`, and `OPENTITAN=…` still wins; +`bench.py --help` still parses. + +**d. `CLAUDE.md`**: one paragraph appended after the 2026-11-26 one. +`docs/topo.md`: the three module lists of §1.3 name the new modules and +the §3.3 measurement sentence is brought up to date; nothing else. + +#### 4. Verification + +- `cargo fmt --all -- --check`: clean. `cargo clippy --workspace + --all-targets -- -D warnings`: clean. +- Guarded `cargo test -p --all-targets` + (`tools/guard.sh -m 8 -t 600`, every run exit 0, no guard kill), passed + / ignored, on the final tree: `vlog_parser` 527 / 2, `vlog_semantic` + 453 / 4, `vlog_refactor` 793 / 5, `vlog_formatter` 383 / 0, + `lucisv_server` 2263 / 53 — each equal to the baseline. The sorted test + names of all five equal the baseline log's but for the one test of + §3b, which changed module. (`vlog_linter`, `lucisv_core`, `lucisv`, + `lucisv_mcp` have no changed file and were not re-run; the lead's full + gate covers them.) +- `tools/gates.sh --only corpus`: 814 / 6. `--only cross`: pass. + `python3 tools/stamp_author.py --check`: "would stamp 0 files" — it + reads tracked files only, so the 34 new files (33 `.rs`, this README) + were stamped by hand and their first and last lines checked by a + script against the two stamp lines. +- **OpenTitan, read-only** (`/Users/lucio/repo/opentitan/hw`, 4 046 + files; `--diff`, `--check` and `check` only, `--no-cache`, run from the + scratch dir): the release binary of `a479faf` (a detached worktree in + the scratch dir) against this tree's. `format --diff` in the default + style, `--style lowrisc` and `--style auto`; `format --check` in the + three styles; `format --check --output-format json`; `check`; `check + --output-format json` — stdout and stderr of all nine **byte-identical** + between the two binaries (SHA-256 in the dev's report). Both: 3 967 + would reformat + 72 unchanged + 7 failed = 4 046 (4 039 format cleanly; + 3 976 / 63 / 7 under `lowrisc`); `check`: 1 178 findings, 1 file not + checkable. `git -C /Users/lucio/repo/opentitan status --porcelain`: + empty before and after. Not a benchmark, only a sanity check on the + lexer move: `format --no-cache --check` over the tree, five runs each, + 1.03–1.07 s for the `a479faf` binary and 1.03–1.09 s for this one. + +## QA log + +### 2026-11-26 — QA (Opus 5.5) + +**Verdict: PASS-with-findings** (three low findings, none touches behaviour). +I wrote my own tools for this; I did not reuse the dev's scripts. Trunk is +`a479faf`, checked out as a detached worktree in the scratch dir. Every +cargo test, sweep and server run went through `tools/guard.sh`. No guard +killed anything. + +**1. Move purity, item by item.** I wrote a small Rust tokenizer. It +handles raw and byte strings, chars and lifetimes, and nested block +comments, and it keeps comments as tokens. On top of it sits an item +extractor for `fn`/`struct`/`enum`/`trait`/`type`/`const`/`static`. Each +item is keyed by kind and name. Its value is its attributes plus preceding +comments, then its body from the keyword to the closing brace, token for +token. Old file at `a479faf` against the union of the new files: + +| split | items old/new | items that differ | why they differ | +|---|---|---|---| +| `resolve.rs` | 40/40 | `type_here` | the `pub(super)` prefix, and the trailing `,` rustfmt added when it re-broke the signature | +| `parser/item.rs` | 23/23 | `parse_gen_if` | the three-line `// Generate constructs` banner is gone; everything else is equal | +| `parser/instance.rs` | 20/20 | `parse_connections` | `pub(super)`, and the re-break `,` | +| `format/stmt.rs` | 16/16 | none | — | +| `lexer.rs` | 95/95 | `DefineParams` | `pub(super)` on the struct and on the fields `scanned` and `walked` | + +The comparison covers every match arm, attribute and comment inside a +body. Besides the items, the only new tokens are stamps, `//!` module +docs, `use`/`mod` lines and `impl<'a> Parser<'a> {}` / `impl Fmt {}` +wrappers. The only tokens dropped outside items are the old module-doc +lines that the new docs replace, plus the one banner. No other comment +was lost. + +**2. Visibility.** I compared every `pub…` declaration per crate, +before and after. The only additions are the `pub(super)` items the +README lists, two `pub(crate) use` re-exports (`member_site` and +`extends_chain`, which were already `pub(crate)`), and in `lucisv_server` +`pub(crate) mod tests` plus the helpers `fastest_of_five` and +`assert_grows_linearly`. That module sits under `#[cfg(test)]` +(`large.rs:366-367`), so those three are test-only. No new `pub` and no +production `pub(crate)`. Every file in `git diff --stat` is accounted +for: moves, `mod` lines and docs, the 12 `#[ignore]` lines, +`server/tests/large_file.rs`, `CLAUDE.md`, `topo.md` and `sites.py`. + +**3. The 23 moved test modules.** I cut each `mod NAME { … }` out of +the trunk file and compared it with `/NAME.rs` token by token. +Every string literal was compared byte for byte, and each file's +production remainder was compared with trunk after replacing the block +by `mod NAME;`. 23 modules, 149 946 tokens, 171 multi-line string +literals: **every literal is byte-identical**, including the `\` +continuation lines in `large/tests.rs` that keep their old indent. The +token differences are: + +- trailing commas that rustfmt dropped (`completion/member`, `file_ops`, + `format`, `hierarchy`, `hover`, `inline`, `large`, `linked`, `nav`, + `pairs`, `rename`, `tokens`, `type_def`); +- the closure braces in `format/tests.rs`; +- the 6 in-module `#[ignore = …]` reasons; +- `large`: the relocated test is gone, and the `pub(crate)` lines. + +Each production remainder is byte-identical to trunk, except `large.rs`, +which gained two comment lines above `#[cfg(test)]`. + +**Test lists** (`cargo test -p --all-targets`, all nine crates, +passed/failed/ignored) are equal to `target/gates/r11`: + +| crate | passed/failed/ignored | +|---|---| +| `vlog_parser` | 527/0/2 | +| `vlog_semantic` | 453/0/4 | +| `vlog_refactor` | 793/0/5 | +| `vlog_formatter` | 383/0/0 | +| `vlog_linter` | 710/0/0 | +| `lucisv_core` | 129/0/0 | +| `lucisv` | 162/0/0 | +| `lucisv_server` | 2263/0/53 | +| `lucisv_mcp` | 400/0/3 | + +The sorted `test … ok|ignored` lines are equal too. The only differences +are the 12 `ignored, ` suffixes and the move of +`large::tests::references_on_one_giant_line…` to +`server::tests::large_file::…`. + +**4. `#[ignore]`.** Trunk had 12 bare `#[ignore]`; there are 0 now +(`grep -rnE '^\s*#\[ignore\]\s*$' crates`). I read every one of them, +and each reason is true: the probe prints timings and asserts only its +premises, and it needs `corpus/`, a generated tree, `CENSUS`, +`SVA_LINES` or `LUCISV_BIND_ROOT`. Runs: + +- `CENSUS=…/hw/ip/uart`: ok, 35 files. +- `SVA_LINES=`: ok. +- `rename_bind` with `LUCISV_BIND_ROOT` unset: skips (the run with it + set is a known trunk failure, topo #68, not re-run). +- The two `inlay` `qa_perf` probes: ok. +- The 6 corpus probes in `lucisv_server`, and `vlog_refactor --test + corpus`: ok in a scratch copy of the tree with `corpus` → + `~/.cache/lucisv-corpus` (860 files). + +*Observation, pre-existing:* in this checkout there is no `./corpus`. +`file_ops::tests::perf::…` (`file_ops/tests.rs:751`) and +`includes::tests::perf::…` (`includes.rs:980`) then panic on +`assert!(files > 500)`, where the other probes print "skipping". Their +reasons do say "over corpus/". I request no change. + +**5. The one non-move** (`server/tests/large_file.rs:261`). The test +sends `textDocument/references` through `Session`, and so the real +`Server::large_scan`. It asserts `hits == width + 1`, so it cannot pass +by answering nothing. `server/large_file.rs` and the production lines of +`large.rs` are unchanged against trunk. The old copy is gone: the test +name has exactly one definition. + +- *Flakiness:* 10 guarded runs passed on the first attempt, at 3.7 / + 7.4 / 14.9 / 30.0 ms (8.1x, limit 24x) every time. It also passed + inside the full `lucisv_server` suite at the default thread count. +- *Mutation*, in a scratch worktree copy of the tree: `large_scan` + mapped through `positions.range(span)` instead of the walker. The test + fails in all 3 attempts at **57.6x**: 6.7 / 25.3 / 98.0 / 387 ms. + +**6. Behaviour, OpenTitan** (`/Users/lucio/repo/opentitan/hw`, read-only, +`--no-cache`). Release binaries of trunk and of this tree, with stdout, +stderr and exit code compared for 10 commands: + +- `format --diff` in the default style, `--style lowrisc` and + `--style auto`; +- `format --check` in the same three styles; +- `--check --output-format json`, in the default style and in `lowrisc`; +- `check`, in text and in JSON. + +**All 30 outputs are byte-identical.** Every command exits 2. The +default style gives 3 967 would reformat, 72 unchanged and 7 failed +(4 046 files, 4 039 format cleanly); `check` gives 1 178 violations and 1 +file that cannot be checked. SHA-256 prefixes of stdout: + +| command | stdout SHA-256 prefix | +|---|---| +| `--diff` default | `6d408ffaa38a3fef` (46.1 MB) | +| `--diff` lowrisc | `beebd02e86e0a3f9` | +| `--diff` auto | `66c2d4dc749cdc29` | +| `--check` default | `92fe09236a27851a` (the same for auto) | +| `--check` lowrisc | `d6aec944645cc220` | +| `--check` JSON | `fd160c4c8362ca37` | +| `check` text | `9ac721f0bd782051` | +| `check` JSON | `28898c5a1765fd2f` | + +The server was compared two ways: + +- `tools/perf/rescan_diff.py`, with `aes_cipher_core.sv` and then + `uart_core.sv` open, 2 rescans each. All 94 lines are identical, + including the index store hash (`f268de99…`, 50 626 930 bytes, for + `uart`). +- My own probe over 53 sampled `hw/ip` and `vendor` files: + `semanticTokens/full`, `foldingRange`, `documentSymbol`, `formatting`, + `documentLink` and `inlayHint`. All 318 answers are identical. + +The CLI has no token-dump mode, so I ran no lexer token-dump +differential; the formatting and semantic-token answers exercise the +lexer. + +**7. Performance.** `format --no-cache --check` over `hw`, 7 runs, the +two binaries alternated, timed inside one guarded Python process (an +earlier run, timed around `guard.sh`, was skewed by its 1 s poll): + +| | trunk | tree | tree/trunk | +|---|---|---|---| +| min | 1.015 s | 1.024 s | +0.9 % | +| median | 1.034 s | 1.037 s | +0.3 % | + +`check --no-cache`, 15 runs: median 0.421 s on both, +0.1 %. No +regression over 3 %. + +**8. Size.** I measured all 440 `src` files of the tree. The naive count +stops at the first `#[cfg(test)]`; the refined count skips a +`#[cfg(test)]` item and stops at the inline test module. No production +file is over 600 by either count. The top production files are +`lucisv/src/main.rs` 574, `parser/module.rs` 568, `parser/split.rs` 554, +`sva.rs` 542, `extract/flow.rs` 535, `class.rs` 518, `covergroup.rs` 517, +`dispatch.rs` 515 and `discover.rs` 515, as the new `CLAUDE.md` +paragraph says. Over 600 there are only test-only files: `perf.rs` 907 +and 13 moved `tests.rs` files from 611 to 1 926 (`hierarchy/tests.rs` is +exactly 600). + +`lexer.rs` at trunk: 540 by the naive count, 771 counting every line +before `mod tests`, 757 by the refined count. **The dev's finding +holds:** it was the one production file over 600. The refined counts of +`warnings.rs` 521 / 80, `rename/mod.rs` 494 and `rescan.rs` 483 agree +with the dev's. + +**9. Hygiene.** + +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --workspace --all-targets -- -D warnings`: clean. +- `tools/gates.sh -o --only corpus,cross,docs,stamp`: PASS + (corpus 814/6). +- All 34 new files carry exactly the two stamp lines, first and last, + and end in a newline. +- `sites.py`: `ROOT` is `/Users/lucio/repo/opentitan` here, + `/Users/guoliangchen/…` under that `HOME`, and `OPENTITAN` still wins. +- The `topo.md` edits are accurate. +- This README has all seven sections, the tables and the list of + forced visibility changes. + +#### Findings + +1. **Low: one size figure is wrong.** `CLAUDE.md` (new paragraph) and + this README's lexer table both give `lexer/define_params.rs` **88**. + The README's own refined rule gives **105** (118 counting every line + before the tests, 6 by the naive count). The other figures in the + paragraph match my measurement. Reproduce with `size.py` (scratch), or + count by hand: 118 non-blank, non-comment lines, minus the 13 under + `#[cfg(test)]`. +2. **Low: new rustdoc warnings, ungated.** `cargo doc -p vlog_semantic -p + vlog_parser --no-deps --document-private-items` gives 6 warnings + trunk does not: + - 5 links in moved docs that no longer resolve, as the Assumptions + predict: `resolve/member.rs:113:53`, `:114:47`, `:114:63` (for + example `this_member`, `super_member`, `unit_member`), + `resolve/types.rs:46:54` and `resolve.rs:261:41`; + - 1 in text written this round: the new `//!` doc of `lexer.rs:11:45` + links to the private `` [`RawLexer`] `` from a public module ("public + documentation for `lexer` links to private item `RawLexer`"). The + Assumptions do not cover this one. + + No gate runs rustdoc lints, so nothing fails. +3. **For the lead to rule on: guidance in the measurement paragraph.** + `git diff CLAUDE.md` is one appended paragraph and nothing else. Two + sentences in it are guidance rather than measurement: + - "A `#[cfg(test)]` that is not the test module is stepped over, not + stopped at" changes the counting rule. + - "Test-only files over 600 (declared under `#[cfg(test)]`, so not + production)" states how moved `tests.rs` files are classified. + +**Notes, not findings:** + +- `DefineParams::scanned` is now `pub(super)` in production, although + only the lexer's tests read it from outside. That is the least the + move allows. +- Besides `crates/lucisv_mcp/tests/opentitan.rs:25`, the dev's request, + `/Users/guoliangchen` is hard-coded in archived scripts under + `docs/perf/review-052-20260909/*.py` and + `docs/perf/take5-review-20260908/*.py`, and in many docs. Reported, + not fixed. +- To rebuild rustdoc I `touch`ed `vlog_semantic/src/lib.rs` and + `vlog_parser/src/lib.rs`. Their content is unchanged. + +**Not verified:** `rename_bind` and `lucisv_mcp --test opentitan` with +OpenTitan set (known trunk failures, topo #68); the `perf.rs` probes; +the full `tools/gates.sh`, which the lead runs. + +## Review + +**2026-11-26 — lead: accepted on the first QA pass, with three lead edits.** + +- Delivered: five pure-move splits (`resolve.rs`, `parser/item.rs`, + `parser/instance.rs`, `format/stmt.rs`, `lexer.rs`), 23 inline test + modules of `lucisv_server` moved to their own files, reasons on all 12 + bare `#[ignore]` (the plan said 11), `tools/perf/sites.py` default root. + No production file is over 600. +- The fifth split is accepted: `lexer.rs` was really 771, and the 540 this + file's earlier paragraph records was a counting artifact (a + `#[cfg(test)]` field ended the count early). The dev's threshold for + moving a test module (≥ 500 lines and ≥ 2× its file) is accepted as this + round's working line, not as a rule. +- Proof: QA's own item-by-item token comparison (194 items) finds only + `pub(super)`, two rustfmt signature re-breaks and one banner comment; + 171 multi-line test inputs byte-identical; test counts equal to the + Round 11 gate logs in all nine crates; 30 OpenTitan outputs over 4 046 + files byte-identical to `a479faf` (dev and QA independently, same + hashes); server answers and index store identical; no timing change + over 1 %. +- The one non-move, test-only: `large.rs` finding 4 — the giant-line + references test now times the real request. QA's mutation fails it at + 57.6× against a 24× limit; 10 clean runs at 8.1×. +- Lead edits after QA: `define_params.rs` 88 → 105 in `CLAUDE.md` and this + README (QA finding 1); the five intra-doc links the moves broke and the + new `RawLexer` link repaired, doc text only (finding 2); the `CLAUDE.md` + sentence that read as a new counting rule reworded to describe how this + measurement was taken (finding 3) — whether to make it the rule is the + owner's call. +- Left: `crates/lucisv_mcp/tests/opentitan.rs:25` and archived perf scripts + still default to another user's home directory; two corpus probes panic + instead of skipping when `./corpus` is absent; parser tests for the new + parser files were not re-homed. + + diff --git a/docs/topo.md b/docs/topo.md index 6f9296c..b9ba51e 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -43,7 +43,7 @@ lint rules (`8` error, `24` warning, `43` style); persisted facts codec TODO §55 (`state/` decomposition), call hierarchy, top-rooted paths, range/selection formatting, sticky scroll, auto-`end` and instantiation highlighting, the eight-item overnight queue (TODO §71), `instance-folding` (TODO §72), and Round 1–3 correctness, -ordering, index-lifecycle, and MCP hardening items. After Rounds 4–11 (Round 11, `windows-uri-editors-r11`, touched no row), §2.9 keeps open handshakes `#67` (filed by Round 7), +ordering, index-lifecycle, and MCP hardening items. After Rounds 4–12 (Rounds 11 and 12 touched no row), §2.9 keeps open handshakes `#67` (filed by Round 7), `#68–70` (filed by Round 8) and `#71–74` (filed by Round 10). See [repository-analysis.md](repository-analysis.md) for evidence and validation. Feature QA logs and TODO checkboxes remain the acceptance authority; remote @@ -200,12 +200,12 @@ what a change on the pointed-to side must not silently break. ### 1.3 Intra-crate structure (what matters for parallel work) -**`vlog_parser`** — `lexer.rs` → `token.rs` (tokens + trivia attachment); +**`vlog_parser`** — `lexer.rs` (+ `lexer/`: `number`, `define_params`, `attach` — Round 12) → `token.rs` (tokens + trivia attachment); `parser/` (recursive descent, strict + tolerant entry points over one grammar, depth/chain budgets from recursion-limit — since the 2026-09-02 decomposition one module per grammar domain: `cursor`, `recover`, -`directive`, `split`, `verbatim`, `item`, `module`, `decl`, `tf`, -`instance`, `recover_list` (header/list-local tolerant recovery), `stmt`, `keyword_stmt`, `expr`, `primary`, `class`, +`directive`, `split`, `verbatim`, `item`, `package`, `generate`, `module`, `decl`, `tf`, +`instance`, `connection`, `recover_list` (header/list-local tolerant recovery), `stmt`, `keyword_stmt`, `expr`, `primary`, `class`, `covergroup`, `assertion`, `sva`, `randsequence`, tests in `parser/tests/`) → `ast/` (`mod` holds `Meta`/`Comment`/spans/`RawText`; `module`, `decl`, `stmt`, `expr`, `class`, `covergroup`, `sva`, `randsequence` hold the nodes, all re-exported as @@ -220,7 +220,7 @@ server queue and `lsp-server` I/O threads are proven not to parse. **`vlog_formatter`** — the pipeline is `format/` (per-node rules; since 2026-09-02 `mod` + `verbatim`, `comment`, `phrase`, `list`, `item`, `module`, -`instance`, `decl`, `routine`, `class`, `cover`, `sva`, `randsequence`, `stmt`, `expr`) → +`instance`, `decl`, `routine`, `class`, `cover`, `sva`, `randsequence`, `stmt`, `case`, `timing`, `expr`) → `doc.rs` (the Wadler IR) → `printer.rs` (width-aware printing); `verify.rs` (the runtime safety net: token equivalence + convergence — CLAUDE.md invariant #4 territory, see §3.3); `fence.rs` (format-off regions + @@ -237,7 +237,9 @@ an error means emit nothing. 2026-09-02 `mod` = the `Binder`, then `item`, `decl`, `class`, `cover`, `stmt`, `sva`, `expr`) → `model.rs`; `resolve.rs` (the lexical walk; misses become -`ExternalCandidate`/`InheritedCandidate` carrying candidate paths); +`ExternalCandidate`/`InheritedCandidate` carrying candidate paths) with +`resolve/` (`member` = the dotted-path spine, `types` = type names and the +`extends` chain, `root` = top-rooted paths); `workspace/` (`mod` = the tables, `index` = queries and `build`, `update` = incremental update and `fingerprint`, `record` = the `FileFacts` read-off, `external` = the overlay, `reexport` = cycle-guarded package member traversal; @@ -957,6 +959,9 @@ and `state/watched.rs`, and Round 2 (`index-lifecycle-r2`) extracted non-test production module is under 600 lines (including `lexer.rs` 540, `resolve.rs` 587, `parser/item.rs` 582), leaving only test-only `lucisv_server/src/perf.rs` (907, `#[cfg(test)]`) above 600. +Round 12 (`hygiene-splits-r12`, pure moves) split `resolve.rs`, `parser/item.rs`, +`parser/instance.rs`, `format/stmt.rs` and `lexer.rs` (really 771: the 540 was a +counting artifact); the largest production file is now `lucisv/src/main.rs` at 574. Additional shared boundaries are `vlog_refactor/src/check/ledger.rs` (every move/copy planner), `vlog_semantic/src/imports.rs` (linter and refactor usage agreement), and `Config` → core config → CLI/server settings → format cache diff --git a/tools/perf/sites.py b/tools/perf/sites.py index f01ebb0..f0d6fd2 100644 --- a/tools/perf/sites.py +++ b/tools/perf/sites.py @@ -13,7 +13,7 @@ opentitan `0098135264`. import os -ROOT = os.environ.get("OPENTITAN", "/Users/guoliangchen/repo/opentitan") +ROOT = os.environ.get("OPENTITAN", os.path.expanduser("~/repo/opentitan")) def path(relative):