diff --git a/CHANGELOG.md b/CHANGELOG.md index 1324264..f40e1fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.66.1 — 2026-11-19 + +### Sticky scroll pins the module instance + +- **A module instantiation folds, so its header lines stay pinned** (TODO + §72, `docs/features/instance-folding`). `textDocument/foldingRange` answers + one range per multi-line instantiation from its module-type line, and one + more per instance from the line its name is on when that is a later line, + so both `aes_control_fsm #(` and `) u_aes_control_fsm (` are pinned while + the reader is in the connection list. The closing `);` line stays visible. + What is an instantiation comes from `vlog_semantic::instantiations::sites`; + where it closes is re-read from the tokens, and a statement whose tokens + are not exactly that shape folds nothing. +- Every fold answered before is unchanged and first on a shared start line + (0.66.0 against this tree on 4 933 files: 75 256 ranges identical once the + instance folds are removed). OpenTitan `hw`: 18 200 multi-line + instantiations, none without its fold. Worst file about 2 ms per request + (1.1 ms before). +- Not folded: two-dimensional instance arrays; an instance whose head an + `` `ifdef `` splits. + ## 0.66.0 — 2026-11-19 ### The overnight queue, complete diff --git a/Cargo.lock b/Cargo.lock index c1cc288..a8e4fcb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.66.0" +version = "0.66.1" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.66.0" +version = "0.66.1" [[package]] name = "lucisv_mcp" -version = "0.66.0" +version = "0.66.1" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.66.0" +version = "0.66.1" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.66.0" +version = "0.66.1" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.66.0" +version = "0.66.1" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.66.0" +version = "0.66.1" [[package]] name = "vlog_refactor" -version = "0.66.0" +version = "0.66.1" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.66.0" +version = "0.66.1" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 365a05f..aaed4b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.66.0" +version = "0.66.1" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index 34ce96a..44a074d 100644 --- a/TODO.md +++ b/TODO.md @@ -7498,3 +7498,29 @@ indexing, collide with each other and with §70's test files, and wait for between a settled session and a fresh server on OpenTitan). - [ ] The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found. + +## 72. Sticky scroll pins the module instance (planned 2026-11-19, owner's order) + +Owner: "only the module definition is floating. I want to extend this a +little so that the module instance would be floating as well." Folds come +only from keyword pairs and `` `ifdef `` branches, so nothing delimited by +`( )` pins. Surveyed on OpenTitan `hw` (4 047 files): 162 instances of 50+ +lines, none pinned; 132 of them write `#(` on the type line, so the instance +name sits on a later `) u_name (` line. Example: +`hw/ip/aes/rtl/aes_control_fsm_n.sv:382-594`. One lane (dev, then QA), +feature README `docs/features/instance-folding/README.md`. + +- [x] `crates/lucisv_server/src/folding/instances.rs` (new): one fold per + multi-line module instantiation from its module-type line, and one more + per instance from the line its name is on when that is a different + line, so both `aes_control_fsm #(` and `) u_aes_control_fsm (` pin + while the reader is in the connection list. The closing line stays + visible, as for every scope fold. +- [x] `crates/lucisv_server/src/folding.rs`: the third source merged through + `in_answer_order`; every fold the server answered before is still + there, unchanged and first on a shared start line. +- [x] Tests in the same change, and `folding/opentitan_sweep.rs` extended: + instances counted independently, existing folds proven unchanged. +- [x] `editors/vscode/README.md`: the sticky-scroll row names the instance. +- [x] Seen in a running VS Code (owner, 2026-11-19, on the local 0.66.1 + build). Shipped as 0.66.1. diff --git a/crates/lucisv_server/src/folding.rs b/crates/lucisv_server/src/folding.rs index 7aaef5f..5402acc 100644 --- a/crates/lucisv_server/src/folding.rs +++ b/crates/lucisv_server/src/folding.rs @@ -6,12 +6,16 @@ //! This module is the fourth consumer of the first and the second of the //! second. See `docs/features/references-nav/README.md`. The third source, //! the branches of `` `ifdef `` regions, is [`directives`] -//! (`docs/features/ifdef-folding/README.md`). +//! (`docs/features/ifdef-folding/README.md`); the fourth, module +//! instantiations, is [`instances`] (`docs/features/instance-folding/README.md`). mod directives; #[cfg(test)] mod ifdef_tests; #[cfg(test)] +mod instance_tests; +mod instances; +#[cfg(test)] mod opentitan_sweep; use std::collections::HashSet; @@ -24,8 +28,8 @@ use crate::pairs::analyze; use crate::state::Document; /// Every foldable region in a buffer: one per matched scope pair, one per -/// branch of a closed `` `ifdef `` region, plus every block comment that spans -/// more than one line. +/// branch of a closed `` `ifdef `` region, one or more per multi-line module +/// instantiation, plus every block comment that spans more than one line. /// /// A keyword whose counterpart never arrived is **not** foldable — `analyze` /// leaves it out of `pairs`, and folding to the end of the file because an @@ -35,7 +39,8 @@ use crate::state::Document; pub fn folding_ranges(doc: &Document) -> Vec { let scopes = scope_and_comment_folds(doc); let branches = branch_folds(doc, &scopes); - in_answer_order(scopes, branches) + let instances = instance_folds(doc, &scopes, &branches); + in_answer_order([scopes, branches, instances]) } /// The scope-pair and block-comment folds, exactly as they were before @@ -80,26 +85,57 @@ fn branch_folds(doc: &Document, existing: &[FoldingRange]) -> Vec out } +/// One fold per multi-line module instantiation, from its module-type line, +/// and one per instance whose name is on a later line, sorted by start line. +/// The closing line stays visible, as for a scope. An instance fold whose two +/// lines are exactly an existing fold's is left out, as a branch fold is; of +/// two instance folds on one start line only the longer is kept, since VS +/// Code would show only one of them anyway. +fn instance_folds( + doc: &Document, + scopes: &[FoldingRange], + branches: &[FoldingRange], +) -> Vec { + let mut out = Vec::new(); + for (start, through) in + instances::instance_spans(&doc.tree.items, &doc.tokens, |offset| line(doc, offset)) + { + let taken = |folds| has_lines(folds, start, through); + if !taken(scopes) && !taken(branches) { + push(&mut out, start, through, FoldingRangeKind::Region); + } + } + out.sort_by_key(|range| (range.start_line, std::cmp::Reverse(range.end_line))); + out.dedup_by_key(|range| range.start_line); + out +} + +/// Whether `folds`, sorted by start line, has one on exactly these two lines. +fn has_lines(folds: &[FoldingRange], start: u32, end: u32) -> bool { + let from = folds.partition_point(|range| range.start_line < start); + let mut same_start = folds[from..].iter().take_while(|range| range.start_line == start); + same_start.any(|range| range.end_line == end) +} + /// The one place the answer's order is defined: by start line; on a shared -/// start line, every scope or comment fold (in their own `(start, end)` -/// order) before any branch fold. +/// start line, by source in the order given — every scope or comment fold (in +/// their own `(start, end)` order), then every branch fold, then every +/// instance fold. /// /// The order is load-bearing. VS Code keeps only the *first* range it /// receives for a start line (`sanitizeRanges`), so whatever comes first is -/// the fold the user gets and the line sticky scroll pins. Putting existing -/// folds first means a branch fold never costs the user a fold they had +/// the fold the user gets and the line sticky scroll pins. Putting the older +/// sources first means a newer fold never costs the user a fold they had /// before — on `module m; `ifdef A` the `module` fold survives and the branch -/// yields. See `docs/features/ifdef-folding/README.md`. -fn in_answer_order(existing: Vec, branches: Vec) -> Vec { - let mut out = Vec::with_capacity(existing.len() + branches.len()); - let mut branches = branches.into_iter().peekable(); - for range in existing { - while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) { - out.push(branch); - } - out.push(range); - } - out.extend(branches); +/// yields; on `begin sub u (` the `begin` survives and the instance yields. +/// See `docs/features/ifdef-folding/README.md` and +/// `docs/features/instance-folding/README.md`. +/// +/// A stable sort by start line over the sources laid end to end is exactly +/// that: equal start lines keep the order they were laid down in. +fn in_answer_order(sources: [Vec; N]) -> Vec { + let mut out: Vec = sources.into_iter().flatten().collect(); + out.sort_by_key(|range| range.start_line); out } diff --git a/crates/lucisv_server/src/folding/instance_tests.rs b/crates/lucisv_server/src/folding/instance_tests.rs new file mode 100644 index 0000000..e9b1b7f --- /dev/null +++ b/crates/lucisv_server/src/folding/instance_tests.rs @@ -0,0 +1,613 @@ +//! Module-instantiation folds, through the whole [`folding_ranges`] answer so +//! every test also sees how they sit beside the scope, comment and branch +//! folds — and, on every text, that the answer without them is exactly the +//! answer the server gave before they existed. + +use lsp_types::{FoldingRange, FoldingRangeKind}; +use vlog_semantic::WorkspaceIndex; + +use super::{branch_folds, folding_ranges, instance_folds, scope_and_comment_folds}; +use crate::state::Document; + +fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) +} + +/// The answer before instance folds existed: the two-way merge +/// `in_answer_order` was, verbatim, kept here as the oracle the generalised +/// one is checked against. +fn previous_answer(doc: &Document) -> Vec { + let existing = scope_and_comment_folds(doc); + let branches = branch_folds(doc, &existing); + let mut out = Vec::with_capacity(existing.len() + branches.len()); + let mut branches = branches.into_iter().peekable(); + for range in existing { + while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) { + out.push(branch); + } + out.push(range); + } + out.extend(branches); + out +} + +/// Every fold as `(start line, end line)`, after checking the promises every +/// answer keeps: sorted by start line, `start < end`, region kind for every +/// instance fold, and — with the instance folds taken out — byte-identical to +/// [`previous_answer`], in the same order. +fn folds(text: &str) -> Vec<(u32, u32)> { + let doc = doc_of(text); + let ranges = folding_ranges(&doc); + assert!(ranges.windows(2).all(|w| w[0].start_line <= w[1].start_line), "{ranges:?}"); + assert!(ranges.iter().all(|r| r.start_line < r.end_line), "{ranges:?}"); + let scopes = scope_and_comment_folds(&doc); + let branches = branch_folds(&doc, &scopes); + let instances = instance_folds(&doc, &scopes, &branches); + assert!(instances.iter().all(|r| r.kind == Some(FoldingRangeKind::Region))); + let rest: Vec = + ranges.iter().filter(|r| !instances.contains(r)).cloned().collect(); + assert_eq!(rest, previous_answer(&doc), "the old answer must survive unchanged"); + assert_eq!(ranges.len(), rest.len() + instances.len(), "{ranges:?}"); + ranges.iter().map(|r| (r.start_line, r.end_line)).collect() +} + +/// The instance folds alone, as `(start, end)`. +fn instance_lines(text: &str) -> Vec<(u32, u32)> { + folds(text); + let doc = doc_of(text); + let scopes = scope_and_comment_folds(&doc); + let branches = branch_folds(&doc, &scopes); + instance_folds(&doc, &scopes, &branches).iter().map(|r| (r.start_line, r.end_line)).collect() +} + +#[test] +fn a_parameterised_instance_pins_its_type_line_and_its_name_line() { + // The owner's shape (`aes_control_fsm_n.sv`): the statement folds from the + // type line, the connection list from the `) u_name (` line, and the `);` + // stays visible under both. + let text = concat!( + "module top;\n", // 0 + " aes_control_fsm #(\n", // 1 + " .AESGCMEnable ( AESGCMEnable ),\n", // 2 + " .SecMasking ( SecMasking )\n", // 3 + " ) u_aes_control_fsm (\n", // 4 + " .clk_i ( clk_i ),\n", // 5 + " .rst_ni ( rst_ni )\n", // 6 + " );\n", // 7 + "endmodule\n", // 8 + ); + assert_eq!(folds(text), vec![(0, 7), (1, 6), (4, 6)]); +} + +#[test] +fn an_instance_without_parameters_folds_once() { + let text = concat!( + "module top;\n", // 0 + " sub u_sub (\n", // 1 + " .a(a),\n", // 2 + " .b(b)\n", // 3 + " );\n", // 4 + "endmodule\n", // 5 + ); + assert_eq!(folds(text), vec![(0, 4), (1, 3)]); +} + +#[test] +fn a_one_line_instance_folds_nothing() { + let text = concat!( + "module top;\n", + " sub u (.a(a));\n", + " sub #(.W(8)) v (.a(a), .b(b));\n", + "endmodule\n", + ); + assert_eq!(folds(text), vec![(0, 2)], "the module only"); +} + +#[test] +fn the_closer_on_its_own_line_after_the_list_stays_visible() { + // `)` and `;` on different lines: the statement stops before the `;` + // line, the instance before the `)` line. + let text = concat!( + "module top;\n", // 0 + " sub u (\n", // 1 + " .a(a)\n", // 2 + " )\n", // 3 + " ;\n", // 4 + "endmodule\n", // 5 + ); + assert_eq!(folds(text), vec![(0, 4), (1, 3)]); +} + +#[test] +fn every_later_instance_of_a_statement_gets_its_own_fold() { + let text = concat!( + "module top;\n", // 0 + " sub a (\n", // 1 + " .x(x)\n", // 2 + " ), b (\n", // 3 + " .x(y)\n", // 4 + " ),\n", // 5 + " c (\n", // 6 + " .x(z)\n", // 7 + " );\n", // 8 + "endmodule\n", // 9 + ); + // `a` is on the statement's own line, so it adds nothing; `b` and `c` do. + assert_eq!(folds(text), vec![(0, 8), (1, 7), (3, 4), (6, 7)]); +} + +#[test] +fn two_instances_named_on_one_line_add_one_fold() { + let text = concat!( + "module top;\n", // 0 + " sub #(\n", // 1 + " .W(8)\n", // 2 + " ) a (.x(x)), b (\n", // 3 + " .x(y)\n", // 4 + " );\n", // 5 + "endmodule\n", // 6 + ); + // `a` closes on its own line, so it has nothing to hide and starts no + // fold; `b`, named on that same line, does. + assert_eq!(folds(text), vec![(0, 5), (1, 4), (3, 4)]); +} + +#[test] +fn an_instance_array_folds_from_its_name_line() { + let text = concat!( + "module top;\n", // 0 + " sub #(\n", // 1 + " .W(8)\n", // 2 + " ) u_x [3:0] (\n", // 3 + " .a(a)\n", // 4 + " );\n", // 5 + " sub u_y [N-1:0] (\n", // 6 + " .a(a)\n", // 7 + " );\n", // 8 + "endmodule\n", // 9 + ); + assert_eq!(folds(text), vec![(0, 8), (1, 4), (3, 4), (6, 7)]); +} + +#[test] +fn a_two_dimensional_instance_array_is_not_an_instantiation_to_the_tree() { + // `u [1:0][2] (` does not parse as an `Instantiation` (the tree has no + // site for it), so it folds nothing rather than something guessed from + // tokens. Pinned so a parser change that starts reading it shows up here. + let text = "module top;\n sub u [1:0][2] (\n .a(a)\n );\nendmodule\n"; + assert!(instance_lines(text).is_empty()); +} + +#[test] +fn instances_in_generate_blocks_fold_and_the_blocks_keep_theirs() { + let text = concat!( + "module top;\n", // 0 + " if (A) begin : g_a\n", // 1 + " sub #(\n", // 2 + " .W(8)\n", // 3 + " ) u_sub (\n", // 4 + " .a(a)\n", // 5 + " );\n", // 6 + " end\n", // 7 + " for (genvar i = 0; i < 2; i++) begin : g_f\n", // 8 + " sub u_f (\n", // 9 + " .a(a[i])\n", // 10 + " );\n", // 11 + " end\n", // 12 + "endmodule\n", // 13 + ); + assert_eq!(folds(text), vec![(0, 12), (1, 6), (2, 5), (4, 5), (8, 11), (9, 10)]); +} + +#[test] +fn instances_in_a_generate_region_a_case_and_an_else_are_reached() { + let text = concat!( + "module top;\n", // 0 + " generate\n", // 1 + " case (K)\n", // 2 + " 0: begin : g0\n", // 3 + " sub u0 (\n", // 4 + " .a(a)\n", // 5 + " );\n", // 6 + " end\n", // 7 + " endcase\n", // 8 + " if (A) begin\n", // 9 + " end else begin\n", // 10 + " sub u1 (\n", // 11 + " .a(a)\n", // 12 + " );\n", // 13 + " end\n", // 14 + " endgenerate\n", // 15 + "endmodule\n", // 16 + ); + assert_eq!(instance_lines(text), vec![(4, 5), (11, 12)]); +} + +#[test] +fn instances_in_interfaces_and_programs_are_reached() { + let text = concat!( + "interface bus_if;\n", // 0 + " sub u (\n", // 1 + " .a(a)\n", // 2 + " );\n", // 3 + "endinterface\n", // 4 + "program p;\n", // 5 + " sub v (\n", // 6 + " .a(a)\n", // 7 + " );\n", // 8 + "endprogram\n", // 9 + ); + assert_eq!(instance_lines(text), vec![(1, 2), (6, 7)]); +} + +#[test] +fn an_instance_sharing_a_line_with_a_begin_yields_to_it() { + // VS Code keeps the first range per start line: the `begin` fold was + // there first and stays first; the instance fold rides behind it. + let text = concat!( + "module top;\n", // 0 + " if (A) begin : g sub u (\n", // 1 + " .a(a)\n", // 2 + " );\n", // 3 + " end\n", // 4 + "endmodule\n", // 5 + ); + assert_eq!(folds(text), vec![(0, 4), (1, 3), (1, 2)]); +} + +#[test] +fn an_instance_with_exactly_a_begins_lines_is_left_out() { + let text = concat!( + "module top;\n", // 0 + " if (A) begin : g sub u (\n", // 1 + " .a(a)\n", // 2 + " ); end\n", // 3 + "endmodule\n", // 4 + ); + assert_eq!(folds(text), vec![(0, 3), (1, 2)], "the begin's own fold, once"); + assert!(instance_lines(text).is_empty()); +} + +#[test] +fn an_instance_sharing_a_line_with_an_ifdef_branch_comes_after_it() { + let text = concat!( + "module top;\n", // 0 + " sub u ( `ifdef X\n", // 1 + " .a(a)\n", // 2 + " `else\n", // 3 + " .a(b)\n", // 4 + " `endif\n", // 5 + " );\n", // 6 + "endmodule\n", // 7 + ); + assert_eq!(folds(text), vec![(0, 6), (1, 2), (1, 5), (3, 4)]); +} + +#[test] +fn an_ifdef_inside_the_connection_list_keeps_its_branch_folds() { + let text = concat!( + "module top;\n", // 0 + " sub u (\n", // 1 + " .a(a),\n", // 2 + "`ifdef X\n", // 3 + " .b(b)\n", // 4 + "`else\n", // 5 + " .b(c)\n", // 6 + "`endif\n", // 7 + " );\n", // 8 + "endmodule\n", // 9 + ); + assert_eq!(folds(text), vec![(0, 8), (1, 7), (3, 4), (5, 6)]); +} + +#[test] +fn an_ifdef_around_a_whole_instance_nests_its_fold() { + let text = concat!( + "module top;\n", // 0 + "`ifdef X\n", // 1 + " sub u (\n", // 2 + " .a(a)\n", // 3 + " );\n", // 4 + "`endif\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(folds(text), vec![(0, 5), (1, 4), (2, 3)]); +} + +#[test] +fn ordered_connections_fold_like_named_ones() { + let text = concat!( + "module top;\n", // 0 + " sub #(8, 16)\n", // 1 + " u (\n", // 2 + " a,\n", // 3 + " ,\n", // 4 + " b\n", // 5 + " );\n", // 6 + "endmodule\n", // 7 + ); + assert_eq!(folds(text), vec![(0, 6), (1, 5), (2, 5)]); +} + +#[test] +fn a_wildcard_or_empty_list_folds_only_what_spans_lines() { + let text = concat!( + "module top;\n", // 0 + " sub #(\n", // 1 + " .W(8)\n", // 2 + " ) u (.*);\n", // 3 + " sub #(\n", // 4 + " .W(8)\n", // 5 + " ) v ();\n", // 6 + " sub w (\n", // 7 + " .*\n", // 8 + " );\n", // 9 + "endmodule\n", // 10 + ); + assert_eq!(instance_lines(text), vec![(1, 2), (4, 5), (7, 8)]); +} + +#[test] +fn comments_between_the_pieces_do_not_move_a_line() { + let text = concat!( + "module top;\n", // 0 + " sub /* c */ #( // why\n", // 1 + " .W(8)\n", // 2 + " ) /* name */ u_sub\n", // 3 + " /* before list */ (\n", // 4 + " .a(a), // a\n", // 5 + " /* two\n", // 6 + " lines */\n", // 7 + " .b(b)\n", // 8 + " ) /* end */ ;\n", // 9 + "endmodule\n", // 10 + ); + assert_eq!(folds(text), vec![(0, 9), (1, 8), (3, 8), (6, 7)]); +} + +#[test] +fn crlf_line_ends_give_the_same_lines() { + let text = concat!( + "module top;\r\n", + " sub #(\r\n", + " .W(8)\r\n", + " ) u_sub (\r\n", + " .a(a)\r\n", + " );\r\n", + "endmodule\r\n", + ); + assert_eq!(folds(text), vec![(0, 5), (1, 4), (3, 4)]); +} + +#[test] +fn an_instance_cut_off_by_the_end_of_the_file_folds_nothing() { + let text = concat!("module top;\n", " sub #(\n", " .W(8)\n", " ) u (\n", " .a(a),\n"); + assert!(instance_lines(text).is_empty(), "{:?}", folds(text)); + let text = concat!("module top;\n", " sub #(\n", " .W(8)\n"); + assert!(instance_lines(text).is_empty(), "{:?}", folds(text)); +} + +#[test] +fn an_instance_missing_its_closer_or_its_semicolon_folds_nothing() { + let no_paren = concat!( + "module top;\n", + " sub u (\n", + " .a(b)\n", + " ;\n", + " wire w;\n", + "endmodule\n", + ); + let no_semi = concat!( + "module top;\n", + " sub u (\n", + " .a(b)\n", + " )\n", + " wire w;\n", + "endmodule\n" + ); + let half_typed = concat!("module top;\n", " sub u (.a(\n", "\n", " wire w;\n", "endmodule\n"); + let no_param_close = concat!( + "module top;\n", + " sub #(\n", + " .W(8)\n", + " u (\n", + " .a(b)\n", + " );\n", + "endmodule\n", + ); + for text in [no_paren, no_semi, half_typed, no_param_close] { + assert!(instance_lines(text).is_empty(), "{text:?}: {:?}", folds(text)); + } +} + +#[test] +fn calls_macros_declarations_and_gates_are_not_instances() { + let text = concat!( + "module top;\n", // 0 + " initial begin\n", // 1 + " foo(\n", // 2 + " a,\n", // 3 + " b\n", // 4 + " );\n", // 5 + " end\n", // 6 + " `MY_MACRO(\n", // 7 + " a,\n", // 8 + " b)\n", // 9 + " logic [3:0] x = f(\n", // 10 + " a,\n", // 11 + " b);\n", // 12 + " and g1 (\n", // 13 + " q,\n", // 14 + " a\n", // 15 + " );\n", // 16 + " assign y = g(\n", // 17 + " a);\n", // 18 + "endmodule\n", // 19 + ); + assert!(instance_lines(text).is_empty(), "{:?}", folds(text)); +} + +#[test] +fn a_bind_folds_like_the_instantiation_it_carries() { + let text = concat!( + "bind top sub u_b (\n", // 0 + " .a(a)\n", // 1 + ");\n", // 2 + ); + assert_eq!(folds(text), vec![(0, 1)]); +} + +#[test] +fn a_large_file_still_folds_nothing() { + let text = "module top;\n sub u (\n .a(a)\n );\nendmodule\n".to_string(); + assert!(folding_ranges(&Document::large(None, text)).is_empty()); +} + +// ---------------------------------------------------------------------- +// QA (2026-11-19): adversarial inputs and the README's untested assumptions +// ---------------------------------------------------------------------- + +/// A text with most shapes at once: generate block, `#(` list with a string +/// and a comment holding `)` and `;`, `` `ifdef `` inside a connection list, +/// an instance array, a second instance, a block comment ending on the type +/// line, a nested call in a connection, `)` and `;` on separate lines, and a +/// macro use ending on the type line. +const RICH: &str = concat!( + "module top;\n", // 0 + " if (A) begin : g\n", // 1 + " sub #(\n", // 2 + " .W(8), // ) ;\n", // 3 + " .S(\")(;\")\n", // 4 + " ) u_a (\n", // 5 + " .a(a[1:0]),\n", // 6 + "`ifdef X\n", // 7 + " .b({b, c})\n", // 8 + "`else\n", // 9 + " .b(d)\n", // 10 + "`endif\n", // 11 + " ), u_b [3:0] (\n", // 12 + " .a(a)\n", // 13 + " );\n", // 14 + " end\n", // 15 + " /* x\n", // 16 + " */ sub v (\n", // 17 + " .a(f(\n", // 18 + " 1))\n", // 19 + " )\n", // 20 + " ;\n", // 21 + " `M(x) sub w (.*\n", // 22 + " );\n", // 23 + "endmodule\n", // 24 +); + +/// Every fold ends inside the text, and every instance fold of `text` is one +/// the whole of [`RICH`] has: damage never invents a fold. +fn assert_only_whole_text_folds(text: &str, whole: &[(u32, u32)]) { + let lines = text.split('\n').count() as u32; + assert!(folds(text).iter().all(|&(_, end)| end < lines), "{text:?}"); + for fold in instance_lines(text) { + assert!(whole.contains(&fold), "{fold:?} not in {whole:?}: {text:?}"); + } +} + +#[test] +fn every_cut_and_every_blanked_token_folds_only_what_the_whole_text_does() { + let whole = instance_lines(RICH); + assert_eq!(whole, vec![(2, 13), (5, 11), (12, 13), (17, 20)]); + // Mid-typing: the text cut off at every character. + for cut in (0..=RICH.len()).filter(|&cut| RICH.is_char_boundary(cut)) { + assert_only_whole_text_folds(&RICH[..cut], &whole); + } + // One token blanked to spaces, so every line keeps its number. + for token in &doc_of(RICH).tokens { + let (start, end) = (token.span.start as usize, token.span.end as usize); + let mut text = RICH.to_string(); + text.replace_range(start..end, &" ".repeat(end - start)); + assert_only_whole_text_folds(&text, &whole); + } +} + +#[test] +fn a_macro_in_type_position_and_an_attribute_do_not_move_the_fold() { + let text = concat!( + "module top;\n", // 0 + " `MY_MOD u (\n", // 1 + " .a(a)\n", // 2 + " );\n", // 3 + " (* keep = \"true\" *) sub #(\n", // 4 + " .W(8)\n", // 5 + " ) v (\n", // 6 + " .a(a)\n", // 7 + " );\n", // 8 + "endmodule\n", // 9 + ); + assert_eq!(instance_lines(text), vec![(1, 2), (4, 7), (6, 7)]); +} + +#[test] +fn brackets_and_semicolons_in_strings_and_comments_are_not_closers() { + let text = concat!( + "module top;\n", // 0 + " sub #(\n", // 1 + " .S(\")(;\")\n", // 2 + " ) u ( // ) ;\n", // 3 + " /* ( */ .a(a)\n", // 4 + " );\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(instance_lines(text), vec![(1, 4), (3, 4)]); +} + +#[test] +fn a_udp_instance_folds_and_a_wrapped_bind_starts_on_its_type_line() { + // README: UDP instances fold (indistinguishable from a module without + // resolving the name); a wrapped `bind` pins the bound module's type line. + let text = concat!( + "module top;\n", // 0 + " my_udp u (\n", // 1 + " q,\n", // 2 + " a, b);\n", // 3 + "endmodule\n", // 4 + "bind top\n", // 5 + " sub u_b (\n", // 6 + " .a(a)\n", // 7 + " );\n", // 8 + ); + assert_eq!(instance_lines(text), vec![(1, 2), (6, 7)]); +} + +#[test] +fn class_and_procedural_lookalikes_are_not_instances() { + let text = concat!( + "package p;\n", + " class c;\n", + " foo #(int) x = new(\n", + " 1,\n", + " 2);\n", + " covergroup cg (int a);\n", + " endgroup\n", + " cg cg_i = new(\n", + " 1);\n", + " function void f();\n", + " void'(h(\n", + " 3));\n", + " endfunction\n", + " endclass\n", + "endpackage\n", + "module top;\n", + " typedef logic [3:0] nib_t;\n", + " nib_t x = f(\n", + " 1);\n", + " a_label: assert property (\n", + " @(posedge clk) a |-> b\n", + " ) else $error(\n", + " \"x\");\n", + " initial begin\n", + " my_task (\n", + " a,\n", + " b);\n", + " end\n", + "endmodule\n", + ); + assert!(instance_lines(text).is_empty(), "{:?}", folds(text)); +} diff --git a/crates/lucisv_server/src/folding/instances.rs b/crates/lucisv_server/src/folding/instances.rs new file mode 100644 index 0000000..bbde25a --- /dev/null +++ b/crates/lucisv_server/src/folding/instances.rs @@ -0,0 +1,138 @@ +//! Folding for module instantiations, so sticky scroll pins the instance a +//! reader is wiring up: one range per multi-line instantiation statement, from +//! its module-type line, and one more per instance whose name sits on a later +//! line (`) u_name (` under a `#(` parameter list). +//! +//! **What** is an instantiation comes from the parse tree, through the walk +//! the call hierarchy and the inlay hints already share +//! ([`vlog_semantic::instantiations::sites`]): generate blocks, interfaces and +//! programs included, gate primitives excluded. **Where** its lines are comes +//! from the token stream, because the tolerant parser keeps an instantiation +//! whose `)` or `;` is missing — mid-typing — and its spans then end wherever +//! it gave up. So every bracket and the `;` are re-read from the tokens, and a +//! statement whose shape is not exactly what the tree says folds nothing. +//! See `docs/features/instance-folding/README.md`. + +use vlog_parser::ast::{Instance, Instantiation, Item}; +use vlog_parser::token::{Token, TokenKind}; +use vlog_semantic::instantiations::sites; + +use crate::state::first_token_from; + +/// `(first line, last line)` of every instantiation fold in `items`, in +/// 0-based lines, given the line a byte offset falls on. +/// +/// Per statement: one span from the module-type line through the line before +/// the `;`, then one per instance from its name's line through the line before +/// its connection list's `)` — left out when it has nothing to hide or when +/// the name is on a line this statement already starts a span on. A statement +/// span with nothing between its two lines comes back too (`last <= first`); +/// the caller drops it. +pub(super) fn instance_spans( + items: &[Item], + tokens: &[Token], + line_of: impl Fn(u32) -> u32, +) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + for site in sites(items) { + let Some(shape) = shape(site.inst, tokens) else { continue }; + let first = line_of(site.inst.module_span.start); + out.push((first, line_of(shape.semi).saturating_sub(1))); + // The lines this statement already starts a non-empty span on. + let mut starts = vec![first]; + for (instance, close) in site.inst.instances.iter().zip(shape.closes) { + let at = line_of(instance.name_span.start); + let last = line_of(close).saturating_sub(1); + if last > at && !starts.contains(&at) { + starts.push(at); + out.push((at, last)); + } + } + } + out +} + +/// Where an instantiation's closers are, as byte offsets of their first byte. +struct Shape { + /// The `)` closing each instance's connection list, in instance order. + closes: Vec, + /// The `;` ending the statement. + semi: u32, +} + +/// The closers of `inst`, read off the tokens, or `None` unless the tokens +/// spell exactly `type [#( … )] name [dims] ( … ) {, name [dims] ( … )} ;` +/// with every bracket matched where the tree says it is. +fn shape(inst: &Instantiation, tokens: &[Token]) -> Option { + let mut at = first_token_from(tokens, inst.module_span.end); + if inst.params.is_some() { + let first_name = inst.instances.first()?.name_span.start; + at = params_end(tokens, at, first_name)?; + } + let mut closes = Vec::with_capacity(inst.instances.len()); + for (i, instance) in inst.instances.iter().enumerate() { + if i > 0 { + at = expect(tokens, at, ",")?; + } + let close = instance_close(instance, tokens, at)?; + closes.push(tokens.get(close)?.span.start); + at = close + 1; + } + let semi = tokens.get(at).filter(|t| t.is_sym(";"))?; + Some(Shape { closes, semi: semi.span.start }) +} + +/// The index just past a `#( … )` parameter list that starts at `at` and +/// closes before the first instance's name at byte `limit`. +fn params_end(tokens: &[Token], at: usize, limit: u32) -> Option { + let open = expect(tokens, at, "#")?; + tokens.get(open).filter(|t| t.is_sym("("))?; + Some(matching(tokens, open, limit, ("(", ")"))? + 1) +} + +/// The index of the `)` closing `instance`'s connection list, when its name +/// token is at `at` and that `)` is the one the tree's span ends on. +fn instance_close(instance: &Instance, tokens: &[Token], at: usize) -> Option { + let name = tokens.get(at)?; + if name.span.start != instance.name_span.start { + return None; + } + let mut open = at + 1; + let limit = instance.span.end; + while tokens.get(open).is_some_and(|t| t.is_sym("[")) { + open = matching(tokens, open, limit, ("[", "]"))? + 1; + } + tokens.get(open).filter(|t| t.is_sym("("))?; + let close = matching(tokens, open, limit, ("(", ")"))?; + (tokens.get(close)?.span.end == instance.span.end).then_some(close) +} + +/// The index after the token at `at`, when that token is the symbol `sym`. +fn expect(tokens: &[Token], at: usize, sym: &str) -> Option { + tokens.get(at).filter(|t| t.is_sym(sym)).map(|_| at + 1) +} + +/// The index of the `close` matching the `open` at `at`, counting only that +/// pair, among the tokens that start before byte `limit` — the end of the +/// construct the tree says the brackets belong to, so a broken statement +/// costs its own length and never a scan to the end of the file. `None` when +/// the brackets are not closed by then: an unclosed list never folds. +fn matching(tokens: &[Token], at: usize, limit: u32, pair: (&str, &str)) -> Option { + let (open, close) = pair; + let mut depth = 0usize; + let within = tokens.iter().enumerate().skip(at).take_while(|(_, t)| t.span.start < limit); + for (i, token) in within { + if token.kind != TokenKind::Symbol { + continue; + } + if token.text == open { + depth += 1; + } else if token.text == close { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(i); + } + } + } + None +} diff --git a/crates/lucisv_server/src/folding/opentitan_sweep.rs b/crates/lucisv_server/src/folding/opentitan_sweep.rs index def04b7..deef494 100644 --- a/crates/lucisv_server/src/folding/opentitan_sweep.rs +++ b/crates/lucisv_server/src/folding/opentitan_sweep.rs @@ -1,6 +1,7 @@ -//! The real-world proof for `` `ifdef `` folding: every `.sv`/`.svh`/`.v` -//! file under an OpenTitan `hw` tree, through [`folding_ranges`], with the -//! ranges checked against the file and the directives counted independently. +//! The real-world proof for `` `ifdef `` and instantiation folding: every +//! `.sv`/`.svh`/`.v` file under an OpenTitan `hw` tree, through +//! [`folding_ranges`], with the ranges checked against the file and the +//! directives and instantiations counted independently. //! //! `#[ignore]`: it parses four thousand files. Run with //! `LUCISV_OPENTITAN_HW=/path/to/opentitan/hw tools/guard.sh -- cargo test @@ -16,7 +17,9 @@ use vlog_semantic::WorkspaceIndex; use lsp_types::FoldingRange; -use super::{branch_folds, directives, folding_ranges, line, scope_and_comment_folds}; +use super::{ + branch_folds, directives, folding_ranges, instance_folds, line, scope_and_comment_folds, +}; use crate::state::Document; /// The tree: `LUCISV_OPENTITAN_HW`, else the full-tree cache. @@ -98,6 +101,8 @@ struct Tally { shared_start: usize, folding: Duration, branches: Duration, + /// The instantiation half, counted by [`check_instances`]. + instances: InstanceTally, } #[test] @@ -111,24 +116,29 @@ fn every_opentitan_file_folds_its_ifdef_branches_validly() { sources(&root, &mut files); files.sort(); let mut tally = Tally::default(); - let mut slowest: Vec<(Duration, Duration, PathBuf)> = Vec::new(); + let mut slowest: Vec<(Duration, Duration, Duration, PathBuf)> = Vec::new(); for path in &files { let Ok(text) = std::fs::read_to_string(path) else { continue }; - let (folding, branches) = sweep_one(path, text, &mut tally); - slowest.push((folding, branches, path.clone())); + let (folding, branches, instances) = sweep_one(path, text, &mut tally); + slowest.push((folding, branches, instances, path.clone())); } slowest.sort_by_key(|entry| std::cmp::Reverse(entry.0)); eprintln!("opentitan_sweep: {tally:#?}"); - for (folding, branches, path) in slowest.iter().take(5) { - eprintln!(" {folding:?} (branches {branches:?}) {}", path.display()); + for (folding, branches, instances, path) in slowest.iter().take(5) { + eprintln!( + " {folding:?} (branches {branches:?}, instances {instances:?}) {}", + path.display() + ); } assert!(tally.files > 0); assert_eq!(tally.spans, tally.nexts_matched + tally.closes_matched, "{tally:#?}"); + assert_instances_complete(&tally.instances); } /// Fold one file, check its ranges, and add it to `tally`. Returns the time -/// the whole answer took and the time the branch pass alone took. -fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration) { +/// the whole answer took and the times the branch and instance passes alone +/// took. +fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration, Duration) { tally.files += 1; let by_text = text_count(&text); tally.text_lines += by_text; @@ -153,6 +163,7 @@ fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duratio assert!(range.end_line < lines, "{}: {range:?} past line {lines}", path.display()); } check_existing_unchanged(&doc, &ranges, path, tally); + let instances = check_instances(&doc, &ranges, path, &mut tally.instances); let before = tally.tokens; let directive_lines = check_directives(&doc, path, tally); if tally.tokens - before != by_text { @@ -169,7 +180,7 @@ fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duratio path.display() ); } - (folding, branches) + (folding, branches, instances) } /// Count the directive tokens into `tally` and return the lines they start on. @@ -217,9 +228,14 @@ fn check_existing_unchanged( ) { let existing = scope_and_comment_folds(doc); let branches = branch_folds(doc, &existing); - let rest: Vec<&FoldingRange> = ranges.iter().filter(|r| !branches.contains(r)).collect(); + let instances = instance_folds(doc, &existing, &branches); + let rest: Vec = + ranges.iter().filter(|r| !instances.contains(r)).cloned().collect(); + assert_eq!(rest, previous_answer(existing.clone(), branches.clone()), "{}", path.display()); + let rest: Vec<&FoldingRange> = rest.iter().filter(|r| !branches.contains(r)).collect(); assert_eq!(rest, existing.iter().collect::>(), "{}", path.display()); - assert_eq!(ranges.len(), existing.len() + branches.len(), "{}", path.display()); + let all = existing.len() + branches.len() + instances.len(); + assert_eq!(ranges.len(), all, "{}", path.display()); let spans = directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)); let kept = spans.iter().filter(|(s, e)| e > s).count(); tally.same_lines_as_existing += kept - branches.len(); @@ -230,3 +246,303 @@ fn check_existing_unchanged( } } } + +/// The answer before instance folds existed: the two-way merge +/// `in_answer_order` was until then, kept verbatim as the oracle. +fn previous_answer(existing: Vec, branches: Vec) -> Vec { + let mut out = Vec::with_capacity(existing.len() + branches.len()); + let mut branches = branches.into_iter().peekable(); + for range in existing { + while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) { + out.push(branch); + } + out.push(range); + } + out.extend(branches); + out +} + +// ---------------------------------------------------------------------- +// Instantiations, counted on the token stream by a rule of their own +// ---------------------------------------------------------------------- + +/// The instantiation half of the sweep. +#[derive(Default, Debug)] +struct InstanceTally { + /// Statements the token rule finds, and those of them spanning lines. + statements: usize, + multi_line: usize, + /// Instances in those statements whose name is on a later line than the + /// type and whose connection list spans lines — each owed a fold. + later_names: usize, + /// Expected folds present in the answer, statement and instance alike. + present: usize, + /// Expected folds left out because an older fold has the same two lines. + same_lines_as_existing: usize, + /// Expected folds missing from the answer: the tree disagrees with the + /// token rule. Each is printed. + missing: usize, + /// Instance folds in the answer that the token rule did not expect. + unexpected: usize, + /// Instance folds sharing a start line with an older fold (they yield). + shared_start: usize, + /// Statements whose head an `` `ifdef `` splits (`) u (` / `` `else `` / + /// `type u (`): owed no fold, since which arm's head is real is not + /// known. Any fold the answer has for one is counted `unexpected`. + split_heads: usize, + /// Statements of 50+ lines, the owner's survey count. + long: usize, + /// Time spent in the instance pass alone. + time: Duration, +} + +/// One instantiation statement as the token rule reads it: 0-based lines of +/// the type name and the `;`, and of each instance's name and `)`. +struct Counted { + type_line: u32, + semi_line: u32, + instances: Vec<(u32, u32)>, + /// The type follows an `` `else ``/`` `elsif `` whose previous arm ended + /// on an open `(`: this is the second spelling of a split head. + split_head: bool, +} + +impl Counted { + /// The folds this statement is owed, statement first: what the feature + /// promises, re-derived here from the lines alone. + fn expected(&self) -> Vec<(u32, u32)> { + let mut out = vec![(self.type_line, self.semi_line.saturating_sub(1))]; + let mut starts = vec![self.type_line]; + for &(name, close) in &self.instances { + let through = close.saturating_sub(1); + if through > name && !starts.contains(&name) { + starts.push(name); + out.push((name, through)); + } + } + out.retain(|(start, end)| end > start); + out + } +} + +/// Count `doc`'s instantiations by the token rule and check the answer +/// against them. Returns the time the instance pass alone took. +fn check_instances( + doc: &Document, + ranges: &[FoldingRange], + path: &Path, + t: &mut InstanceTally, +) -> Duration { + let existing = scope_and_comment_folds(doc); + let branches = branch_folds(doc, &existing); + let started = Instant::now(); + let produced = instance_folds(doc, &existing, &branches); + let time = started.elapsed(); + t.time += time; + if path.ends_with("hw/ip/aes/rtl/aes_control_fsm_n.sv") { + check_owner_example(ranges); + } + let older: Vec<(u32, u32)> = + existing.iter().chain(&branches).map(|r| (r.start_line, r.end_line)).collect(); + let mut owed = Vec::new(); + for counted in counted_statements(doc) { + t.statements += 1; + if counted.split_head { + t.split_heads += 1; + eprintln!(" split head at line {}: {}", counted.type_line + 1, path.display()); + continue; + } + if counted.semi_line > counted.type_line { + t.multi_line += 1; + } + t.long += usize::from(counted.semi_line >= counted.type_line + 49); + let expected = counted.expected(); + t.later_names += expected.len().saturating_sub(1); + owed.extend(expected); + } + for &(start, end) in &owed { + if older.contains(&(start, end)) { + t.same_lines_as_existing += 1; + } else if ranges.iter().any(|r| (r.start_line, r.end_line) == (start, end)) { + t.present += 1; + } else { + t.missing += 1; + eprintln!(" instance fold {}..{} missing: {}", start + 1, end + 1, path.display()); + } + } + for range in &produced { + let lines = (range.start_line, range.end_line); + if !owed.contains(&lines) { + t.unexpected += 1; + eprintln!(" unexpected instance fold {lines:?}: {}", path.display()); + } + if older.iter().any(|&(start, _)| start == range.start_line) { + t.shared_start += 1; + eprintln!(" instance fold shares line {}: {}", range.start_line + 1, path.display()); + } + } + time +} + +/// Every statement the token rule calls an instantiation: +/// `type [#( … )] name [ […] … ] ( … ) {, name [ […] … ] ( … )} ;`, where the +/// type is a plain identifier not written after a keyword that would make it +/// something else (a function's return type, a `virtual` interface). +fn counted_statements(doc: &Document) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < doc.tokens.len() { + match statement_at(doc, i) { + Some((counted, next)) => { + out.push(counted); + i = next; + } + None => i += 1, + } + } + out +} + +/// The statement starting at token `i`, and the index after its `;`. +fn statement_at(doc: &Document, i: usize) -> Option<(Counted, usize)> { + let tokens = &doc.tokens; + if !is_plain_name(tokens.get(i)?) || !may_start_after(tokens, i) { + return None; + } + let mut j = i + 1; + if is(tokens, j, "#") { + if !is(tokens, j + 1, "(") { + return None; + } + j = closer(tokens, j + 1)? + 1; + } + let mut instances = Vec::new(); + loop { + if !is_plain_name(tokens.get(j)?) { + return None; + } + let name_line = line(doc, tokens[j].span.start); + j += 1; + while is(tokens, j, "[") { + j = closer(tokens, j)? + 1; + } + if !is(tokens, j, "(") { + return None; + } + let close = closer(tokens, j)?; + instances.push((name_line, line(doc, tokens[close].span.start))); + j = close + 1; + if is(tokens, j, ",") { + j += 1; + } else if is(tokens, j, ";") { + break; + } else { + return None; + } + } + let counted = Counted { + type_line: line(doc, tokens[i].span.start), + semi_line: line(doc, tokens[j].span.start), + instances, + split_head: splits_a_head(tokens, i), + }; + Some((counted, j + 1)) +} + +/// Whether the type at `i` follows an `` `else `` or `` `elsif `` that itself +/// follows an open `(` — the previous arm wrote its own head. +fn splits_a_head(tokens: &[Token], i: usize) -> bool { + let Some(directive) = i.checked_sub(1).map(|p| &tokens[p]) else { return false }; + let next_arm = directive.kind == TokenKind::Directive + && (directive.text.starts_with("`else") || directive.text.starts_with("`elsif")); + next_arm && i >= 2 && is(tokens, i - 2, "(") +} + +/// An identifier that is not a macro use. +fn is_plain_name(token: &Token) -> bool { + token.kind == TokenKind::Ident && !token.text.starts_with('`') +} + +/// Whether an instantiation's type name may follow the token before it: not a +/// keyword (other than one ending a block or a declaration), not a `.`, `::`, +/// `#` or `'`, and not the `:` of a block's end label (`end : name`), which +/// would make the label look like a type. +fn may_start_after(tokens: &[Token], i: usize) -> bool { + let Some(previous) = i.checked_sub(1).map(|p| &tokens[p]) else { return true }; + match (previous.kind, previous.text.as_str()) { + (TokenKind::Keyword, word) => matches!( + word, + "begin" + | "end" + | "else" + | "generate" + | "endgenerate" + | "endcase" + | "endfunction" + | "endtask" + | "endclocking" + | "endproperty" + | "endsequence" + | "endgroup" + ), + (TokenKind::Symbol, ":") => i < 2 || tokens[i - 2].kind != TokenKind::Keyword, + (TokenKind::Symbol, text) => !matches!(text, "." | "::" | "#" | "'"), + _ => true, + } +} + +/// Whether token `at` is the symbol `text`. +fn is(tokens: &[Token], at: usize, text: &str) -> bool { + tokens.get(at).is_some_and(|t| t.kind == TokenKind::Symbol && t.text == text) +} + +/// The index of the bracket closing the one at `at`, every bracket kind +/// matched on one stack; `None` on a mismatch or the end of the file. +fn closer(tokens: &[Token], at: usize) -> Option { + let mut stack: Vec<&str> = Vec::new(); + for (i, token) in tokens.iter().enumerate().skip(at) { + if token.kind != TokenKind::Symbol { + continue; + } + match token.text.as_str() { + "(" => stack.push(")"), + "[" => stack.push("]"), + "{" | "'{" => stack.push("}"), + text @ (")" | "]" | "}") => { + if stack.pop()? != text { + return None; + } + if stack.is_empty() { + return Some(i); + } + } + _ => {} + } + } + None +} + +/// The owner's example, `aes_control_fsm_n.sv:382-486` (1-based): the +/// statement folds from `aes_control_fsm #(` and the connection list from +/// `) u_aes_control_fsm (`, both through the line before `);`. +fn check_owner_example(ranges: &[FoldingRange]) { + let around: Vec<(u32, u32)> = ranges + .iter() + .filter(|r| (370..490).contains(&r.start_line)) + .map(|r| (r.start_line + 1, r.end_line + 1)) + .collect(); + eprintln!( + "opentitan_sweep: aes_control_fsm_n.sv folds from lines 371-490 (1-based): {around:?}" + ); + assert!(around.contains(&(382, 485)), "{around:?}"); + assert!(around.contains(&(385, 485)), "{around:?}"); +} + +/// Print the instance counts and the owner's example, and require that the +/// tree and the token rule agree everywhere. +fn assert_instances_complete(t: &InstanceTally) { + eprintln!("opentitan_sweep instances: {t:#?}"); + assert!(t.multi_line > 0, "{t:#?}"); + assert_eq!(t.missing, 0, "{t:#?}"); + assert_eq!(t.unexpected, 0, "{t:#?}"); +} diff --git a/docs/features/instance-folding/README.md b/docs/features/instance-folding/README.md new file mode 100644 index 0000000..20e97ac --- /dev/null +++ b/docs/features/instance-folding/README.md @@ -0,0 +1,315 @@ +# instance-folding + +## Goal + +Owner: "only the module definition is floating. I want to extend this a little +so that the module instance would be floating as well." VS Code's sticky scroll +follows the server's `textDocument/foldingRange` answer (the extension sets +`editor.stickyScroll.defaultModel: foldingProviderModel`, TODO §67) and pins +the start line of every fold around the top of the viewport. Folds came from +keyword pairs, block comments and `` `ifdef `` branches only, so a 200-line +instance pinned nothing. This feature adds a fourth fold source, +`crates/lucisv_server/src/folding/instances.rs`: one fold per multi-line +instantiation statement from its module-type line, and one more per instance +whose name sits on a later line (`) u_name (` under a `#(` list), so inside a +connection list both `aes_control_fsm #(` and `) u_aes_control_fsm (` are +pinned. Server-side only (TODO §72). + +## Assumptions + +- **Fold shape.** Statement: from the line of the module-type name through the + line before the `;` — the `);` stays visible, the rule every scope fold + follows. Instance: from the line of its name through the line before its + connection list's `)`. An instance fold is added only when its name is on a + line this statement has not already started a non-empty fold on and when it + hides at least one line, so `sub u (` (name on the type line) folds once and + `) a (.x(x)), b (` gives `b` its own fold. Inside the `#( … )` list only the + statement fold encloses the reader, so only the type line is pinned there. + `aes_control_fsm_n.sv` (1-based): type `aes_control_fsm #(` 382, + `) u_aes_control_fsm (` 385, `);` 486 → folds `382–485` and `385–485` + (0-based `(381, 484)`, `(384, 484)`). The brief said 382–594; the statement + ends at 486 in the checked-out tree (594 is a later `prim_buf #(`). +- **What is an instantiation: the parse tree.** Found through + `vlog_semantic::instantiations::sites`, the walk the call hierarchy, the + inlay hints and the workspace index already share — no new visitor. It + descends into modules, interfaces, programs (all `ItemKind::Module`), + packages, `generate` regions, generate `if`/`else if`/`else`/`for`/`case` + blocks, with or without `generate`. + - **Not instances (tested):** task/function calls (statements, not items), + macro calls (one `Ident` token with its arguments), declarations with an + initialiser (`logic x = f(…)`), continuous assignments, gate primitives + (`and g (…)` is `ItemKind::GateInstantiation`, which the shared walk + excludes on purpose — it names no module). + - **UDP instances fold.** `my_udp u (q, a, b);` is syntactically a module + instantiation; nothing short of resolving the name tells them apart, and + folding a multi-line UDP instance is harmless and arguably right. + - **`bind` folds** (the shared walk includes the instantiation a `bind` + carries). Its statement fold starts on the line of the bound module's type + name, which is the `bind` line unless the bind is wrapped. Tested. + - **Two-dimensional instance arrays** (`u [1:0][2] (`) are not an + `Instantiation` in the tolerant tree (no site), so they fold nothing. + Pinned by a test; a parser change that reads them will flip it. Not a + request — none in OpenTitan. +- **Where its lines are: the token stream.** The tolerant parser keeps an + instantiation whose `)` or `;` is missing (`close_list` and + `expect_after_recovery` accept the gap), and its spans then end wherever it + gave up — on a nested `.a(b)`'s `)`, for instance. So `instances.rs` + re-reads the statement from the tokens: from the token after the type name, + `#` `(` … matched `)` when the tree has a parameter list, then per instance + the name token at exactly `name_span.start`, any `[ … ]` dimensions, `(` … + matched `)` whose end is exactly `Instance::span.end`, `,` between + instances, and `;` right after the last. Anything else and the whole + statement folds nothing. Bracket matching only looks at tokens that start + before the construct's end as the tree has it (the first instance name for + `#( … )`, `Instance::span.end` for a connection list), so a broken statement + costs its own length and can never match a bracket past it — no fold to the + end of the file, no `end < start` (`push` drops `end <= start` anyway). + Comments are trivia and attributes `(* *)` are one token, so neither moves + a line; a macro use carries its arguments in its own token. +- **`` `ifdef `` inside a statement.** Directives are tokens. Inside a + connection or parameter list they are skipped by the bracket matcher, so + branch folds nest inside the instance fold (tested). An `` `ifdef `` that + splits the head (`) dut (` / `` `else `` / `chip dut (` — OpenTitan + `top_*/dv/tb/tb.sv`) does not have the shape and folds nothing: which arm's + head is real is not knowable here. +- **No existing fold is lost or changed** (the lead's rule from + ifdef-folding, applied again): + - an instance fold with exactly the two lines of a scope, comment or branch + fold is not added — that fold keeps its kind (tested: `begin sub u (` … + `); end`); + - **order on a shared start line: scope/comment folds, then branch folds, + then instance folds.** Branch folds were in the answer before this + feature, so they are "existing" too and the instance fold yields to them + as well. VS Code keeps only the first range per start line, so on + `begin : g sub u (` the `begin` keeps its fold and its pin, and on + `sub u ( `ifdef X` the branch keeps its fold (both tested). The instance + fold is still sent, behind them; + - two instance folds on one start line (only possible across two + statements written on one line) keep only the longer, since VS Code would + keep only one anyway. +- **`in_answer_order` is still the one place the order is defined**, + generalised from a two-way merge to a stable sort by start line over the + sources laid end to end (`[scopes, branches, instances]`). For two sources + that is exactly the old merge (equal starts keep the order they were laid + down in; each source is already sorted). Proven, not asserted: the old + two-way merge is kept verbatim as the oracle in `instance_tests.rs` + (`previous_answer`, checked on every test text) and in the OpenTitan sweep + (every file). +- **Kind `region`**, like scope and branch folds (*Fold All Regions* folds + them; `imports` would auto-collapse). +- **Large-file fast path: unchanged.** A `Document::large` has no tokens and + the empty file's tree, so the walk finds no site and the answer stays `[]` + (tested; also `server/tests/large_file.rs`). + +## Handshakes + +- **Consumes** (read-only, no change): `vlog_semantic::instantiations::sites` + (the shared instantiation census; `Site::inst`), `vlog_parser::ast:: + {Instantiation, Instance}` (`module_span`, `params.is_some()`, + `instances[].name_span`, `instances[].span`), `vlog_parser::token::Token` + (`is_sym`, `kind`, `span`), `crate::state::first_token_from`, + `Document::{tree, tokens, line_index}`. No parser change. +- **Promises** `folding::folding_ranges` (only caller `server/dispatch.rs`, + unchanged): sorted by start line; on a tie scope/comment folds (old + `(start, end)` order), then branch folds, then instance folds; every range + `start < end` and inside the file; instance folds kind `region`; with the + instance folds removed the answer is exactly the 0.66.0 answer, same order + and kinds (asserted per test and per OpenTitan file). +- **No requests.** (Noted, not requested: 2-D instance arrays are not an + `Instantiation` in the tolerant tree.) + +## Status / TODO + +- [x] Find how instantiations are reached (shared `sites` walk) and where the + tree's spans can lie (tolerant recovery of `)`/`;`). +- [x] `folding/instances.rs`: statement + per-instance spans, token-verified. +- [x] `folding.rs`: `instance_folds` (drop same-lines, one per start), + `in_answer_order` generalised to N sources. +- [x] Unit tests `folding/instance_tests.rs` (25), with the old-answer oracle + on every text. +- [x] OpenTitan sweep extended: independent token-rule count, every owed fold + present, no unexpected fold, old answer unchanged per file, aes example. +- [x] Timing before/after. +- [x] `editors/vscode/README.md` sticky-scroll row. +- [ ] Seen in a running VS Code (owner): scroll into `aes_control_fsm_n.sv`'s + connection list and see both header lines pinned; scroll into the + parameter list and see only the type line. + +## Work log + +### 2026-11-19 — dev + +- Reused `vlog_semantic::instantiations::sites` for *what* (it already + covers generate blocks, interfaces, programs, `bind`, and excludes gates); + tokens for *where*, because the tolerant tree keeps a half-typed + instantiation with spans ending at whatever it last consumed. `shape()` + re-reads the whole statement; any disagreement with the tree → no fold. +- `folding.rs`: `instance_folds` (same-lines check by binary search on the + already-sorted scope and branch folds — a `HashSet` first, swapped after + timing), `in_answer_order` = stable sort by start line over the + concatenated sources. +- Tests (`folding/instance_tests.rs`, 25): owner's shape exact; no `#(`; + one-liners; `)` and `;` on separate lines; multi-instance; two names on one + line; instance arrays (and the 2-D non-site); generate `if`/`for` with + `begin`, `generate` region + `case` + `else`; interface and program; shared + start with a `begin` (yields) and identical lines (dropped); shared start + with an `` `ifdef `` branch (yields); `` `ifdef `` inside the list and + around the instance; ordered connections; `.*`/`()`; comments everywhere + incl. a multi-line one in the list; CRLF; cut off at EOF; missing `)`, + missing `;`, half-typed `.a(`, missing `)` of `#(`; calls/macros/ + declarations/gates/assigns; `bind`; large file. Every test text also goes + through the invariant checks (sorted, `start < end`, region kind, + answer minus instance folds == the old two-way merge verbatim). +- First sweep run found the *token rule* (the sweep's independent count) too + loose, not the code: `end : label` followed by `task_call();` and + `endfunction`/`endtask` before an instantiation. Fixed the rule; then 2 + remaining "missing" were the split heads in `top_*/dv/tb/tb.sv`, now + classified (`split_heads`) and owed nothing. +- **OpenTitan sweep** (`LUCISV_OPENTITAN_HW=/Users/lucio/repo/opentitan/hw + tools/guard.sh -- cargo test --release -p lucisv_server opentitan_sweep -- + --ignored --nocapture`, 4 047 files, passed): token rule finds 18 724 + instantiation statements, 18 200 multi-line, 164 of 50+ lines, 2 split + heads; 16 277 later-name instance folds owed; **34 450 owed folds, all + present, 0 missing, 0 unexpected** (every instance fold the answer has is + one the rule owed), 0 identical to an older fold, 0 sharing a start line + with an older fold. Old answer unchanged on every file (the verbatim + two-way merge as oracle), branch counts unchanged (1 852 directive tokens, + 1 072 spans, 1 066 ranges). `aes_control_fsm_n.sv` lines 371–490 now answer + exactly `[(382, 485), (385, 485)]` (1-based), asserted. +- **Timing** (`folding_ranges`, release, same machine, load ~3): before (base + tree, same sweep) whole tree 35.1 ms, slowest `top_earlgrey/.../ + pinmux_reg_top.sv` 1.07 ms; after, two runs: whole tree 45.1–46.3 ms, + slowest the same file 1.95–1.97 ms, of which the instance pass is + 0.62–0.66 ms (the whole tree's instance pass: 7.1–7.3 ms). The rest of the + growth is the bigger answer (≈ +8.5 folds per file on average) and its sort. +- Test counts: `lucisv_server` lib 1 999 passed + 47 ignored before → 2 024 + + 47 after (+25); e2e 106, grammar 3, ifdef_folding 1 unchanged. +- Not touched: `vlog_parser`, `vlog_semantic`, dispatch, `large.rs`, + versions, changelogs, `docs/topo.md`. + +## QA log + +### 2026-11-19 — QA (Opus 5.5) + +**Verdict: PASS.** No defect found; two info-level notes below. + +**Gates, run by QA** (all through `tools/guard.sh`, no kill): +- `cargo fmt --all -- --check` clean; `cargo clippy --all-targets -- -D warnings` + exit 0 (only the pre-existing `workspace.package.authors` manifest warning). +- `cargo test -p lucisv_server`: lib 2 024 passed + 47 ignored as delivered + (2 029 after QA's 5 tests), e2e 106, grammar 3, ifdef_folding 1, + opentitan_references 0 + 2 ignored; all green. +- OpenTitan sweep (release, `--ignored`): passed, 4 047 files; instances + 18 724 statements, 18 200 multi-line, 16 277 later names, 34 450 present, + 0 missing, 0 unexpected, 0 shared start, 2 split heads, 164 long. + `aes_control_fsm_n.sv` → `[(382, 485), (385, 485)]` (1-based); checked by + hand against the file (type 382, `) u_aes_control_fsm (` 385, `);` 486). + +**Old answer unchanged, independently of the dev's oracle.** Two temporary +`git worktree`s in the scratchpad (HEAD = 0.66.0, and HEAD + this diff), each +with a throwaway `#[ignore]` dumper (never in the real tree; worktrees removed +after), release builds in separate target dirs. Dumped the full ordered answer +for 4 933 files (OpenTitan `hw` 4 069 incl. `.vh`, `~/.cache/lucisv-corpus` +860, repo fixtures). New answer with the instance folds removed is +**byte-identical, same order and kinds, to the 0.66.0 answer** on every file +(75 256 old ranges). Across the new answer (111 226 ranges, 35 970 instance +folds in 1 308 files): 0 unsorted, 0 `start >= end`, 0 past the last line, +0 instance folds sharing a start line with an older fold or with another +instance fold, every instance fold `region`. + +**Is the sweep's count independent?** Mostly. It shares no code with +`instances.rs` (own bracket matcher over all bracket kinds, own token walk, +no `sites`), but it does share the lucisv lexer, `line()`, and it restates the +fold-shape rule (`Counted::expected`) — so a lexer bug, or a wrong shape rule +in the spec, would cancel out; and it was loosened/tightened after the first +run to match. Cross-checked with QA's own counter +(scratchpad `count_inst.py`: own comment/string/attribute stripper, own lexer, +statements split on depth-0 `;` and block keywords, not lucisv's tokens): +OpenTitan 18 679 statements, 18 173 multi-line, 164 long, 34 417 owed folds; +**every fold it owes is in the answer**; the answer has 29 folds it does not +own, every one inspected and a limitation of QA's script (hierarchical / macro +/ `: inst` `bind` targets, `` `ifdef `` lines in `top_*/dv/tb/tb.sv`), each +fold correct against the source. Answer total on the 4 069 files 34 446 vs the +sweep's 34 450: the sweep follows the one symlinked file +(`hw/ip/tlul/rtl/tlul_adapter_shim.sv`), `find -type f` does not. + +**Attacks** (probe files dumped through the new build, each answer read +against the source; no wrong fold, no panic anywhere): +- Cut at every character and every token blanked to spaces of a text with + most shapes (generate, `#(` with string/comment holding `)`/`;`, `` `ifdef `` + in the list, array, second instance, `*/ sub v (`, nested call, `)`/`;` split, + `` `M(x) sub w ( ``): every fold inside the file, start < end, old answer + unchanged, and no instance fold the whole text does not have. Also every + single character blanked (scratch only): 0 violations. Kept as a test. +- Folds right: `` `MY_MOD u ( ``, `` `MY_MOD #( ``, macro with multi-line args + inside `#(`, `(* attr *) sub #(`, `endgenerate sub y (`, `begin end sub k (`, + `*/ sub v (`, `) ;; ;`, CRLF + tabs + UTF-8 in comments, nested generate + with array + second instance, interface/program, `bind` plain and wrapped, + UDP, `sub u8 ( … )\n ;`, `.a((b)\n ));`, `my_class #(.T(int)) obj (` in a + module (syntactically an instantiation — right). +- Fold nothing (right or harmless): `` `ifdef `` between `)` and the name and + around `#( … )`; `foo #(int) x = new(`, `cg cg_i = new(`, `void'(h(`, + multi-line task/function calls, typedef'd declaration with initialiser, + labelled `assert property ( … ) else $error(`; `)),` and `)) u (` and + `.W((8)` unbalanced; a statement after `garbage ( ( ( ;` and after a + statement missing its `;` (recovery swallows them — under-fold only). +- Same-line probes: on `generate if (A) begin : g sub u (` … `); end` the + instance fold equals the `begin`'s and is dropped (as designed). + +**Timing** (release, same machine, two runs each, sweep's own clock): +0.66.0 whole tree 33.4 / 34.8 ms, slowest `pinmux_reg_top.sv` 1.05–1.10 ms; +this tree 45.3 / 46.3 ms, slowest the same file 1.86–2.04 ms (instance pass +0.60–0.70 ms). Dev's 35.1 → ~46 ms and 1.07 → 1.96 ms hold. Per-edit worst +case is that file (`pinmux_reg_top.sv`, the three tops), ~2 ms per request. + +**Standards.** No `unwrap`/`expect()`/`panic!` in library code (`expect` in +`instances.rs` is a local helper's name; `panic!` only in `mod tests`), no +`#[allow]`, doc comments present. Production lines (non-blank, non-comment, +before `mod tests`): `folding.rs` ~86 (66 at 0.66.0), `instances.rs` 89. +Longest new production function `instance_spans` 23 lines. README has every +required section and matches the code. `in_answer_order`: inputs are sorted +by start (scopes by `(start, end)`, branches by start, stable), so the stable +sort equals the old merge — confirmed by the cross-build diff above. + +**Findings** (none blocking): +1. *Info — README claim / dead branch.* `folding.rs:108-109` + (`sort_by_key` + `dedup_by_key` on start line) and the Assumptions line + "two instance folds on one start line (only possible across two statements + written on one line) keep only the longer": not reachable. A non-empty fold + of one statement ends at least one line before its `)`/`;`, so the next + statement's type line is always after every non-empty fold start of the + previous one; within a statement `starts` already prevents it. The sweep + and the cross-build dump agree (0 cases in 35 970). Harmless; the dev may + reword the README or keep the code as a guard. +2. *Info — pre-existing, not this feature.* Code on the same line after + `` `ifdef X `` or `` `endif `` (`` `ifdef X sub w ( `` …, `` `endif sub z ( ``) + is not an instantiation in the tree, so it gets no instance fold (the + branch fold is unchanged). Repro: probe `module top;\n`endif sub z (\n .a(a)\n );\nendmodule`. + +**Assumptions vs tests.** Previously untested README assumptions now tested by +QA: UDP instances fold, a wrapped `bind` starts on its type line, attributes +`(* *)` and a macro in type position do not move a line, brackets/`;` in +strings and comments. All others were already covered by the dev's tests. + +**Fixed / added directly:** five tests appended to +`folding/instance_tests.rs` (QA section): every cut / every blanked token of a +rich text; macro type + attribute; strings/comments with closers; UDP and +wrapped `bind`; class/procedural lookalikes. No production code touched. + +**Not verified:** behaviour in a running VS Code (owner's checkbox); the +request path through `server/dispatch.rs` was not exercised beyond the +existing e2e suite (QA called `folding_ranges` directly). + +## Review + +- **2026-11-19 (lead).** Accepted. Read `folding/instances.rs` and the + `folding.rs` diff: the tree says what is an instantiation, the tokens say + where it closes, and a statement whose tokens are not exactly the tree's + shape folds nothing — the right side to fail on. `in_answer_order` is still + the one place order is defined. QA's independent 0.66.0-vs-tree dump (4 933 + files, 75 256 ranges identical once instance folds are removed) is the proof + that no earlier fold moved. `tools/gates.sh` on the tree: PASS, every step + (`target/gates/20261119-230338`). QA note 1 (the same-start-line dedup can + never fire) stays as a guard. Edge recorded in `docs/topo.md`. Open: seen in + a running VS Code (owner); 2-D instance arrays need the parser to read them + as instantiations first. diff --git a/docs/topo.md b/docs/topo.md index b7f10c5..f6d7925 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -690,6 +690,7 @@ engine-lane features are listed above; this table is the server-internal web. | `viewport-highlight ◀──▶ scan-ordering / semantic-tokens-delta / large-file-mode` | handshake | (2026-11-19, TODO §71.3, 0.65.10) The first exemption from held-request order: before `process_batch` holds a `semanticTokens/{range,full,full/delta}` request, it is answered through `answer_flushed` (dispatch minus `flush_dirty`) when its buffer's text is current. **Since 0.65.11 the decision is fast-actions' `Server::answer_from_the_buffer` in `server/ahead.rs`** (moved there from `viewport.rs` as a pure move, with `set_aside` and `open_then_widen`), so clauses (a)/(b) are shared with every early answer: the buffer open, `behind == 0`, and nothing older in `held` or in the burst `ahead` of it that `REACH`/`Server::can_reach` cannot clear (a watcher event still does not hold a colour; a settings push now does — before, a notification naming no buffer passed for harmless, QA's S1). What stays the colours' own (`viewport.rs`): `colours_may_go_ahead` (without `refreshSupport` only `range` goes), a dirty buffer waits instead of being analyzed, they go during staging, never ahead of a notification about to be applied (`answer_ahead_of` takes `same_file` requests only), and `coloured_ahead` marks a range taken off an unsettled index. Reads that one `Document`, its overlay as of the last publish, `has_large_documents`/`Document::large`/`token_server_cancel`, and the remembered tokens — never the index, another buffer, a flush or a publish. Every whole answer goes through `remember_tokens`, so a `previousResultId` always names data the client holds. Responses leave out of arrival order for these three methods and fast-actions' `same_file::METHODS` only. | | `viewport-highlight ──▶ index-scope / scan-interleave` (widen and refresh) | depends | A `didOpen` that widens is applied through `open_then_widen`: `Viewport::defers_widen` records the widen, the burst's colouring requests are answered, then `reindex_widened` runs and `answer_ahead_mid_widen` (`server/ahead.rs`, 0.65.11; `answer_colours_mid_widen` before) drains between files (what can go ahead answered — colours and, since 0.65.11, `same_file` requests — everything else to `held`). `refresh_tokens_if_stale`, called by `run` once `held` is empty, sends at most one `workspace/semanticTokens/refresh` per `hierarchy_revision`, only if a buffer answered while `index_unsettled` (scan running/owed, `Viewport::widening`, or — since 0.65.11 — anything held) would colour differently (`early`) or was painted by a range (`guessed`). `semantic_tokens_in_range` classifies the range's lines (`large::line_window`, `overrides_within`) and still equals the full answer filtered. | | `ifdef-folding ──▶ references-nav (folding) / editor-scopes / large-file-mode` | depends | (2026-11-19, TODO §71.4, 0.65.4) `folding/directives.rs::branch_spans` reads the lexer's `TokenKind::Directive` tokens (so comments, strings and `` `define `` bodies never fold) and yields one `region` fold per `` `ifdef ``/`` `ifndef ``/`` `elsif ``/`` `else `` branch; `folding_ranges` = `scope_and_comment_folds` (the old answer, verbatim) + `branch_folds` (dropping any `(start, end)` an existing fold has), merged by `in_answer_order` (start line, existing first on a tie). Sticky scroll pins the branch line through the extension's `foldingProviderModel` (§67). A large buffer has no tokens and still answers `[]`. The directive-word rule is a private copy (also in `parser/directive.rs` and `on_type/auto_end.rs`). | +| `instance-folding ──▶ ifdef-folding / references-nav (folding) / call-hierarchy (`instantiations::sites`) / large-file-mode` | depends | (2026-11-19, TODO §72) `folding/instances.rs::instance_spans` takes *what* is an instantiation from `vlog_semantic::instantiations::sites` (the walk the call hierarchy, inlay hints and index share; gate primitives excluded) and *where* its closers are from the token stream, folding nothing unless the tokens spell exactly the shape the tree says. One `region` fold from the module-type line to the line before `;`, one more per instance from its name line to the line before its `)`. `folding_ranges` = scopes/comments + branches + instances through `in_answer_order` (now a stable sort by start line over the sources in that order), so on a shared start line an instance fold yields to both older sources and the pre-§72 answer is an unchanged subsequence. A large buffer still answers `[]`. Not folded: 2-D instance arrays (the parser does not read them as instantiations), an instance whose head an `` `ifdef `` splits. | | `comment-highlighting ◀──▶ editor-packaging` (grammar) | handshake | (2026-11-19, TODO §71.8, 0.65.3) Extension only: `commentScan.js` re-implements the grammar's `comments` and `strings` rules to find comment bodies; `commentScan_test.js` fails on any change to those two rules, on a reordering that moves them off the top, or on another top-level rule that could match `/` or `"` — a grammar edit updates `commentScan.js` in the same change (the `tests/grammar.rs` keyword lock is separate and untouched). `commentKeywords.js` paints visible lines ±50, honours `editor.maxTokenizationLineLength`. Server side: nothing — the three `lucisv.commentKeywords.*` keys arrive in `didChangeConfiguration` and `settings.rs` ignores them; semantic tokens were measured to colour nothing inside a comment. | | `format-styles ◀──▶ editor-settings / format-cache / selection-formatting / on-type-formatting` | handshake | (2026-11-19, TODO §71.5, 0.65.5) One name list, three pins: `PRESETS` (`vlog_formatter/src/style.rs`) + `auto` = `lucisv_core::config::STYLE_NAMES` (`args::tests::the_core_style_names_are_the_formatter_presets`) = the manifest's `lucisv.format.style` enum and descriptions (`settings::tests::the_style_drop_down_is_the_style_names`). Ladder: explicit `indent`/`line-length` over the style's numbers; `lucisv.toml` over the editor. Server: `auto_style.rs::AutoStyles` remembers per document the preset `format_auto` chose; whole-document formats set it, range/ranges/on-type/selection reuse it (`concrete`); forgotten on open/close/rename/delete, a whole-buffer replacement, a named-style format, any settings change and a `lucisv.toml` event — three call lines in `notification.rs` (`notice`, `changed`, `forget_all`). The cache entry carries the style, so changing it invalidates verdicts. | | `hierarchy-current-path ──▶ vscode-hierarchy-sidebar / dut-hierarchy` | depends | (2026-11-19, TODO §71.6, 0.65.2) Extension only, no server request: `hierarchyCurrent.js` (`matchingFiles`, `currentPath` — BFS up `hierarchySections.parentIndex`, nearer distance wins — `rowLevels`, `levelChanges`, `LIT_COLORS`/`litLevel`/`cssVariableFor`) reads the schema-2 snapshot's `definition.file`. `hierarchyView.js` follows `onDidChangeActiveTextEditor` and posts `{type:'lit', changes}`; a rendered row carries `lit: 0..4` only when lit, so an unlit pane's rows are byte-identical to before. `media/hierarchy.{js,css}` set `data-lit`. Matching compares the model's URIs, so a case-differing folder or a UNC path (server `uri.rs` writes `file:////srv/…`) never lights. | diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index f11f35c..76c1ed5 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,13 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.66.1 — 2026-11-19 + +- **Sticky scroll pins the module instance you are inside.** The instance's + type line stays at the top of the editor, and so does its `) u_name (` line + once you are in the connection list. Instances fold too; the closing `);` + stays visible. + ## 0.66.0 — 2026-11-19 - **Rolls up 0.65.2–0.65.11:** saving no longer re-indexes the workspace; diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 242497f..3788f5d 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -154,7 +154,7 @@ enabling both paths formats twice. | Document and workspace symbols | Hierarchical outline plus indexed symbol search across the design | | Include links | Resolvable `` `include`` paths become clickable using local and filelist `+incdir+` search rules | | Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries; every branch of an `` `ifdef``/`` `ifndef`` region folds on its own, from its directive to the line before the next `` `elsif``/`` `else``/`` `endif``, which stays visible | -| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if`, the `` `ifdef``/`` `else`` branch — stays pinned at the top of the editor, up to ten lines deep | +| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if`, the `` `ifdef``/`` `else`` branch, the module instance (its type line, and its `) u_name (` line once you are in its connections) — stays pinned at the top of the editor, up to ten lines deep | | Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites | | Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site | | Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” | diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 7fa7611..2e7baf9 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.66.0", + "version": "0.66.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.66.0", + "version": "0.66.1", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index b323ee2..2f9ec06 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.66.0", + "version": "0.66.1", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",