Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea586d29bc | ||
|
|
e115f9fc8f | ||
|
|
d8119aa9c6 | ||
|
|
2854bcaa2f | ||
|
|
3598a9145e | ||
|
|
a8c4a2ecf8 |
No files matched your search
@@ -4,6 +4,42 @@ 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.63.0 — 2026-11-09
|
||||
|
||||
### Format Selection that fits where it stands; comment toggling in VS Code
|
||||
|
||||
(`docs/features/selection-formatting`; TODO §66.)
|
||||
|
||||
- **Format Selection lays out only the block you selected.** Selecting an
|
||||
`always` block, a `case` statement or a few statements used to re-lay the
|
||||
whole enclosing module-level item — at the formatter's own depth, so a
|
||||
block in a 4-space or tab-indented file moved, and the blank lines at the
|
||||
selection's edges were eaten. The new engine
|
||||
(`vlog_formatter::format_selection`) finds the smallest run of sibling
|
||||
items or statements the selected lines cover, lays out that run alone and
|
||||
puts it back starting at the leading whitespace it already has (tabs
|
||||
kept). The parent is not touched. `textDocument/rangeFormatting`,
|
||||
`rangesFormatting` and the on-type `;` all run on it.
|
||||
- **A parse error elsewhere in the file no longer refuses the request.** The
|
||||
selection is formatted when the error lies outside it, and refused only
|
||||
when it lies inside.
|
||||
- **How a selection picks its block.** Touching a block's first line takes
|
||||
the whole block; a selection that starts inside it takes only the
|
||||
statements it covers, even when it reaches the closing `end`; the `end`
|
||||
line alone takes the block it closes. A selection of whole module-level
|
||||
items behaves as before.
|
||||
- **Still verified.** Every result passes the whole-file equivalence check
|
||||
and a convergence replay, or the buffer is left unchanged; the verifier
|
||||
itself is unchanged. CRLF files keep every line ending.
|
||||
- The on-type `;` now tidies its statement in a buffer whose error is
|
||||
elsewhere, and no longer adds a final newline to a file without one.
|
||||
- The reply is still one whole-document edit; the CLI's `--lines` is
|
||||
unchanged (whole module-level items).
|
||||
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
|
||||
language's `//` and `/* */` comments, bracket pairs and auto-closing
|
||||
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
|
||||
Block Comment work on one line or a selection.
|
||||
|
||||
## 0.62.0 — 2026-10-19
|
||||
|
||||
### Paths rooted at a top-level module; a dependable release gate
|
||||
|
||||
@@ -139,6 +139,19 @@ Rules:
|
||||
|
||||
## Workflow
|
||||
|
||||
- **Agent models**: the lead plans and reviews; coding goes to one dev
|
||||
agent and verification to one QA agent, **both Claude Opus 5.5**
|
||||
(`model: "opus"`). This holds for a single lane and for each of two
|
||||
parallel lanes.
|
||||
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
|
||||
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
|
||||
`.claude/agents/`. Its brief says: no new tests beyond what the move
|
||||
forces, the gates are the proof, spend the effort on module
|
||||
boundaries, naming and readability. QA is unchanged (Opus 5.5).
|
||||
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
|
||||
When a fix round fails QA a **second** time on the same feature, redo
|
||||
the round with **Claude Fable 5.2 as both dev and QA**
|
||||
(`model: "fable"`).
|
||||
- Do **not** run `git commit` or `git push` — the lead reviews and
|
||||
commits all work.
|
||||
- Do not touch files outside your feature's stated scope. If you need a
|
||||
@@ -187,8 +200,9 @@ proven independent and run serially. Rules for a parallel wave:
|
||||
while lanes are in flight; the lead merges each lane back only after
|
||||
that lane's QA verdict and lead review, and re-runs the full gates on
|
||||
the merged tree before pushing.
|
||||
- **Roles per lane are unchanged**: one dev (Opus), then one QA
|
||||
(Sonnet) in the same worktree, then the lead's review — so at most
|
||||
- **Roles per lane are unchanged**: one dev, then one QA — **both
|
||||
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — in the
|
||||
same worktree, then the lead's review — so at most
|
||||
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
|
||||
its own dev is done. A QA rework loops inside its lane without
|
||||
blocking the other lane.
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.62.0"
|
||||
version = "0.63.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -7127,3 +7127,48 @@ completion should offer `tb.`'s hierarchical members, answering `None` when
|
||||
the index has no unit of that name. `docs/features/top-rooted-paths`.
|
||||
|
||||
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
|
||||
|
||||
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
|
||||
|
||||
Owner's report: *Format Selection* "fails more than half of the time". The
|
||||
usual selection is one whole `always` block or one whole `case` statement,
|
||||
often nested inside blocks the selection does not cover. Reproduced on trunk
|
||||
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
|
||||
a `case` re-lays the whole `always` around it; the block is re-indented to the
|
||||
formatter's own depth × width, so in a file indented any other way it no
|
||||
longer lines up with its neighbours; a selection inside `generate` re-lays the
|
||||
whole region; and a file with a parse error anywhere is refused outright.
|
||||
Owner's rule: do not worry about the parent — the selected block keeps the
|
||||
indentation level it starts at, and stays functionally the same.
|
||||
|
||||
### 66.1 VS Code language configuration (lead, done 2026-11-09)
|
||||
|
||||
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
|
||||
auto-closing and surrounding pairs) wired to both language ids in
|
||||
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
|
||||
without another Verilog extension installed.
|
||||
|
||||
### 66.2 Selection formatting (one lane: dev, then QA)
|
||||
|
||||
Feature README: `docs/features/selection-formatting/README.md`. Files:
|
||||
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
|
||||
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
|
||||
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
|
||||
`crates/lucisv_server/src/server/tests/formatting.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
|
||||
parser and the CLI's `--lines` are not touched.
|
||||
|
||||
- [x] `format_selection`: the smallest run of sibling items/statements the
|
||||
selected lines cover, laid out alone at the indentation it was written
|
||||
at, spliced into otherwise untouched bytes.
|
||||
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
|
||||
replaying the located target, not the line numbers.
|
||||
- [x] Fences outrank the selection; a module/package-level target defers to
|
||||
`format_range` (header/footer splitting).
|
||||
- [x] A file that does not parse: the target is located in the tolerant tree
|
||||
and refused when a diagnostic falls inside it.
|
||||
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
|
||||
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
|
||||
`generate`, inside a function), off-grid and tab indentation, partial
|
||||
selections, comments, fences, broken files, masked-corruption attacks on
|
||||
the splice.
|
||||
@@ -6,13 +6,16 @@
|
||||
//! output, or no edit at all and an error for the user to read. That holds for
|
||||
//! the range requests too — their output is verified over the whole buffer,
|
||||
//! and what makes a request a *range* format is which constructs it laid out,
|
||||
//! not which bytes it was allowed to replace.
|
||||
//! not which bytes it was allowed to replace. The range requests go through
|
||||
//! `format_selection`: the smallest run of sibling items or statements the
|
||||
//! selection covers, laid out at the indentation it was written at — see
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_formatter::{format_selection, format_source, Config, LineRanges};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Document;
|
||||
@@ -122,10 +125,12 @@ pub fn range_formatting(
|
||||
///
|
||||
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
|
||||
/// before the engine sees them, so overlapping, adjacent, repeated and
|
||||
/// unsorted input from the client all reach the same answer. No range is
|
||||
/// formatted on its own — one `format_range` call lays out the union, which is
|
||||
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
|
||||
/// rather than making it a promise per range.
|
||||
/// unsorted input from the client all reach the same answer. Each merged span
|
||||
/// selects its own target (targets that overlap are re-selected from the hull
|
||||
/// of their spans), but no range is formatted on its own — one
|
||||
/// `format_selection` call lays out and verifies them all, which is what keeps
|
||||
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
|
||||
/// making it a promise per range.
|
||||
///
|
||||
/// The reply is still one whole-document edit: the engine's contract is
|
||||
/// all-or-nothing over the file, and a partial run's output differs from the
|
||||
@@ -140,7 +145,7 @@ pub fn ranges_formatting(
|
||||
return Ok(None);
|
||||
}
|
||||
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
|
||||
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -700,6 +705,39 @@ mod tests {
|
||||
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
|
||||
@@ -802,7 +840,7 @@ mod tests {
|
||||
#[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_range` call away from the engine.
|
||||
// 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)]);
|
||||
|
||||
@@ -61,9 +61,9 @@ pub fn on_type_formatting(
|
||||
/// Lay out the statement the `;` just ended, through the range engine.
|
||||
///
|
||||
/// The range asked for is the `;`'s **own line** and nothing else. That is not
|
||||
/// a narrower request than "the statement's lines": `format_range` selects by
|
||||
/// *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
|
||||
/// a narrower request than "the statement's lines": `format_selection` selects
|
||||
/// by *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
|
||||
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
|
||||
/// and naming its enclosing node's lines there would ask for the whole module
|
||||
/// back on a keystroke.
|
||||
@@ -1174,7 +1174,19 @@ mod tests {
|
||||
#[test]
|
||||
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
|
||||
// Half-typed code is the normal case on this trigger, not a failure.
|
||||
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
|
||||
// The error is on the keystroke's own line: one elsewhere in the
|
||||
// buffer no longer refuses (selection-formatting, TODO §66.2).
|
||||
let text = "module m;\n wire a = ;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 13 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
|
||||
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1204,10 +1216,10 @@ mod tests {
|
||||
let at = Position { line: 1, character: 11 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
// The engine's own canonicalization adds the missing final newline —
|
||||
// exactly what `textDocument/rangeFormatting` would also do here, and
|
||||
// not a moved byte this path invented on its own.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
|
||||
// Only the statement moves: the file's tail is outside the splice, so
|
||||
// the missing final newline stays missing — exactly what
|
||||
// `textDocument/rangeFormatting` answers here too.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
|
||||
// The owner's report (TODO §66.2): a `case` selected inside an `always`
|
||||
// in a four-space file. Only the `case` moves, and it stays where it
|
||||
// starts; the statement after it and the parent keep their bytes.
|
||||
let tree = Tree::new("rangesnested");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
|
||||
assert_eq!(
|
||||
one[0]["newText"],
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
|
||||
"{one:#?}"
|
||||
);
|
||||
// The multi-range method gives the same answer for the same selection.
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
||||
// The two requests are the same engine, and a client must never have
|
||||
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
// The error sits on the keystroke's own line: since selection formatting
|
||||
// (TODO §66.2) an error on *another* line no longer refuses the request.
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
|
||||
@@ -278,6 +278,57 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Tab-indented, with a parse error after the block: the shape of a buffer
|
||||
/// mid-edit that "Format Selection" (TODO §66.2) must still serve.
|
||||
const TABBED_BROKEN: &str = "module m;\n\talways @* begin\n\t\tif (a) x=1;\n\t\telse x=2;\n\tend\n\tassign y = ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn range_formatting_lays_out_a_nested_selection_in_place_over_the_wire() {
|
||||
let dir = temp_dir("selectionfmt");
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, TABBED_BROKEN).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let request = |id: u32, sl: u32, el: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":0}},"end":{{"line":{el},"character":0}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(TABBED_BROKEN).expect("json")
|
||||
)),
|
||||
// The two statement lines inside the `always`.
|
||||
request(2, 2, 4),
|
||||
// The broken line itself: refused, no edit.
|
||||
request(3, 5, 6),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
assert_eq!(
|
||||
new_text(&messages, 2),
|
||||
"module m;\n\talways @* begin\n\t\tif (a) x = 1;\n\t\telse x = 2;\n\tend\n\tassign y = ;\nendmodule\n",
|
||||
"only the selected statement moves, tabs kept, error elsewhere ignored"
|
||||
);
|
||||
let refused = messages.iter().find(|m| m["id"] == 3).expect("response");
|
||||
assert!(
|
||||
refused.get("error").is_some()
|
||||
|| refused["result"].is_null()
|
||||
|| refused["result"] == serde_json::json!([]),
|
||||
"{refused}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Four items on four lines, so two ranges can straddle one they leave alone.
|
||||
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ mod stmt;
|
||||
mod sva;
|
||||
mod verbatim;
|
||||
|
||||
use crate::doc::{text, Doc};
|
||||
use crate::doc::{concat, text, Doc};
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::Printer;
|
||||
use crate::range::{self, Split};
|
||||
@@ -62,6 +62,10 @@ pub enum FormatError {
|
||||
Source(vlog_parser::Error),
|
||||
/// A safety check failed; the formatted text was discarded.
|
||||
Verification(VerificationError),
|
||||
/// A selection could not be laid out on its own — it reaches a parse
|
||||
/// error, or its target could not be found again in the output. Nothing
|
||||
/// was changed.
|
||||
Selection(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
@@ -69,6 +73,7 @@ impl std::fmt::Display for FormatError {
|
||||
match self {
|
||||
FormatError::Source(e) => write!(f, "{e}"),
|
||||
FormatError::Verification(e) => write!(f, "{e}"),
|
||||
FormatError::Selection(e) => write!(f, "{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +135,41 @@ pub fn format_range(
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// A sibling run a selection lays out on its own: items at their AST depth,
|
||||
/// or statements.
|
||||
pub(crate) enum Run<'t> {
|
||||
Items(&'t [Item], usize),
|
||||
Stmts(&'t [Stmt]),
|
||||
}
|
||||
|
||||
/// Lay out one run of `file` (parsed from `source`) exactly as the
|
||||
/// whole-file printers would, every line starting with `base`.
|
||||
///
|
||||
/// No final-newline normalization and no trailing whitespace: the result
|
||||
/// replaces the run's own bytes and nothing else. Fenced regions inside the
|
||||
/// run are emitted as written, as in a whole-file run.
|
||||
pub(crate) fn print_run(
|
||||
source: &str,
|
||||
file: &SourceFile,
|
||||
config: &Config,
|
||||
run: Run<'_>,
|
||||
base: &str,
|
||||
) -> String {
|
||||
let regions = fence::collect(source, file);
|
||||
let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() };
|
||||
let docs = match run {
|
||||
Run::Items(items, depth) => fmt.item_seq(items, depth),
|
||||
Run::Stmts(stmts) => fmt.stmt_seq(stmts),
|
||||
};
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print_at(&concat(docs), base);
|
||||
// Spaces and newlines only, exactly what `render` trims.
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
|
||||
@@ -6,8 +6,10 @@ pub mod fence;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod range;
|
||||
mod selection;
|
||||
pub mod verify;
|
||||
|
||||
pub use format::{format_range, format_source, Config, FormatError};
|
||||
pub use range::LineRanges;
|
||||
pub use selection::format_selection;
|
||||
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
@@ -18,9 +18,22 @@ pub struct Printer {
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
/// Render `doc` starting at column 0.
|
||||
pub fn print(&self, doc: &Doc) -> String {
|
||||
let mut out = String::new();
|
||||
let mut col = 0usize;
|
||||
self.print_at(doc, "")
|
||||
}
|
||||
|
||||
/// Render `doc` as if every line began with `base`: the text starts with
|
||||
/// `base`, every line break the printer writes repeats it before the
|
||||
/// indentation, and the width budget shrinks by it.
|
||||
///
|
||||
/// `base` is copied as written, tabs included, which is what lets a
|
||||
/// selection keep the indentation it was written at. Text that carries
|
||||
/// its own absolute indentation (`Doc::Verbatim`, `Doc::Inline`) is not
|
||||
/// shifted. With an empty `base` this is exactly [`Printer::print`].
|
||||
pub fn print_at(&self, doc: &Doc, base: &str) -> String {
|
||||
let mut out = base.to_string();
|
||||
let mut col = self.base_width(base);
|
||||
// Stack of (indent_level, mode, doc).
|
||||
let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)];
|
||||
|
||||
@@ -61,24 +74,22 @@ impl Printer {
|
||||
out.push(' ');
|
||||
col += 1;
|
||||
} else {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::SoftLine => {
|
||||
if mode == Mode::Break {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::HardLine => {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::BlankLine => {
|
||||
// Trim trailing spaces from the current line, add a blank.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push('\n');
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::IfBreak(s) => {
|
||||
if mode == Mode::Break {
|
||||
@@ -89,9 +100,7 @@ impl Printer {
|
||||
Doc::Verbatim(s) => {
|
||||
// Undo the indent the preceding line break wrote: these
|
||||
// bytes carry their own.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push_str(s);
|
||||
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
|
||||
}
|
||||
@@ -100,14 +109,20 @@ impl Printer {
|
||||
out
|
||||
}
|
||||
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize, base: &str) {
|
||||
trim_line_end(out, base);
|
||||
out.push('\n');
|
||||
out.push_str(base);
|
||||
let spaces = ind * self.indent_width;
|
||||
out.extend(std::iter::repeat_n(' ', spaces));
|
||||
*col = spaces;
|
||||
*col = self.base_width(base) + spaces;
|
||||
}
|
||||
|
||||
/// The columns `base` occupies. A tab counts as one indent level: the
|
||||
/// printer cannot know the reader's tab stop, and the width only steers
|
||||
/// which groups break.
|
||||
fn base_width(&self, base: &str) -> usize {
|
||||
base.chars().map(|c| if c == '\t' { self.indent_width } else { 1 }).sum()
|
||||
}
|
||||
|
||||
/// Would `items` (flat) followed by the rest of the work stack fit on
|
||||
@@ -194,6 +209,23 @@ impl Printer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the trailing spaces of the line being written. Under a non-empty
|
||||
/// `base` a line holding nothing but indentation is emptied entirely, so a
|
||||
/// blank line never keeps the base's tabs; with no base this is exactly the
|
||||
/// space trim the printer always did.
|
||||
fn trim_line_end(out: &mut String, base: &str) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
if base.is_empty() {
|
||||
return;
|
||||
}
|
||||
let bol = out.rfind('\n').map_or(0, |i| i + 1);
|
||||
if out[bol..].chars().all(|c| c == ' ' || c == '\t') {
|
||||
out.truncate(bol);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
items.iter().any(|d| match d {
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Finding the run of sibling units one selected line span names.
|
||||
//!
|
||||
//! The walk starts at the file scope and goes down while the selection sits
|
||||
//! inside a single unit below its first line and reaches into exactly one of
|
||||
//! its nested scopes; it then settles on the units met there. A run that cannot be cut
|
||||
//! out of its lines cleanly, or whose ends a fenced region covers, is trimmed
|
||||
//! or given up one level at a time. The result is a [`Target`]: a path of
|
||||
//! child indices plus a run, which is what lets the same units be found again
|
||||
//! in the formatted output.
|
||||
|
||||
use crate::fence::Region;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::scope::{Scope, Unit};
|
||||
|
||||
/// The units a selection lays out, by position in the tree.
|
||||
///
|
||||
/// `path` holds one `(unit index, child scope index)` step per scope the walk
|
||||
/// descended into; the run is `start..start + count` of the scope it ends in.
|
||||
/// Positions, not bytes, so the target can be replayed on a reformatted text
|
||||
/// whose tree is the same.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct Target {
|
||||
pub path: Vec<(usize, usize)>,
|
||||
pub start: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// What one selected line span comes to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) enum Found {
|
||||
/// No unit to lay out: blank lines, or everything met is fenced.
|
||||
Nothing,
|
||||
/// The run holds a module or package, or no run is line-clean: the
|
||||
/// request goes to `format_range` whole.
|
||||
Defer,
|
||||
Target(Target),
|
||||
}
|
||||
|
||||
/// The finder over one text and the tree parsed from it.
|
||||
pub(super) struct Locator<'s> {
|
||||
src: &'s str,
|
||||
index: LineIndex,
|
||||
regions: Vec<Region>,
|
||||
}
|
||||
|
||||
impl<'s> Locator<'s> {
|
||||
pub(super) fn new(src: &'s str, regions: Vec<Region>) -> Locator<'s> {
|
||||
Locator { src, index: LineIndex::new(src), regions }
|
||||
}
|
||||
|
||||
/// Locate the run the 1-based inclusive lines `first..=last` select.
|
||||
pub(super) fn locate(&self, root: Scope<'_>, (first, last): (u32, u32)) -> Found {
|
||||
let mut trail = vec![root];
|
||||
let mut path = Vec::new();
|
||||
let mut scope = root;
|
||||
let Some((mut a, mut b)) = self.met(scope, first, last) else { return Found::Nothing };
|
||||
while a == b {
|
||||
let Some((k, child)) = self.descend(scope, a, first, last) else { break };
|
||||
let Some(run) = self.met(child, first, last) else { break };
|
||||
path.push((a, k));
|
||||
trail.push(child);
|
||||
scope = child;
|
||||
(a, b) = run;
|
||||
}
|
||||
loop {
|
||||
let Some((a2, b2)) = self.trim_fences(scope, a, b) else { return Found::Nothing };
|
||||
if self.clean(scope, a2, b2) {
|
||||
return self.target(scope, path, a2, b2);
|
||||
}
|
||||
// Not cut cleanly at its lines: the enclosing unit is.
|
||||
trail.pop();
|
||||
let (Some((i, _)), Some(&parent)) = (path.pop(), trail.last()) else {
|
||||
return Found::Defer;
|
||||
};
|
||||
(scope, a, b) = (parent, i, i);
|
||||
}
|
||||
}
|
||||
|
||||
fn target(&self, scope: Scope<'_>, path: Vec<(usize, usize)>, a: usize, b: usize) -> Found {
|
||||
let contains_container =
|
||||
(a..=b).filter_map(|i| scope.unit(i)).any(|unit| unit.is_container());
|
||||
if contains_container {
|
||||
return Found::Defer;
|
||||
}
|
||||
Found::Target(Target { path, start: a, count: b - a + 1 })
|
||||
}
|
||||
|
||||
/// The first and last units of `scope` whose lines meet `first..=last`.
|
||||
fn met(&self, scope: Scope<'_>, first: u32, last: u32) -> Option<(usize, usize)> {
|
||||
let mut hit: Option<(usize, usize)> = None;
|
||||
for i in 0..scope.len() {
|
||||
let Some(unit) = scope.unit(i) else { continue };
|
||||
let (l0, l1) = self.lines(unit);
|
||||
if l0 <= last && first <= l1 {
|
||||
hit = Some(hit.map_or((i, i), |(a, _)| (a, i)));
|
||||
}
|
||||
}
|
||||
hit
|
||||
}
|
||||
|
||||
/// The nested scope to descend into from unit `i`: only when the
|
||||
/// selection does not touch the unit's first line, and reaches into
|
||||
/// exactly one of its scopes.
|
||||
///
|
||||
/// The last line is deliberately not asked about. A selection dragged
|
||||
/// over the final statements of a block and its closing `end` means those
|
||||
/// statements; taking the whole enclosing unit for it re-laid hundreds of
|
||||
/// unselected lines (QA note 2, lead ruling 2026-11-09). The closing line
|
||||
/// alone meets no nested unit, so it still names the unit it closes.
|
||||
fn descend<'t>(
|
||||
&self,
|
||||
scope: Scope<'t>,
|
||||
i: usize,
|
||||
first: u32,
|
||||
last: u32,
|
||||
) -> Option<(usize, Scope<'t>)> {
|
||||
let unit = scope.unit(i)?;
|
||||
let (l0, _) = self.lines(unit);
|
||||
if first <= l0 {
|
||||
return None;
|
||||
}
|
||||
let mut reached = unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, child)| self.met(*child, first, last).is_some());
|
||||
let only = reached.next()?;
|
||||
reached.next().is_none().then_some(only)
|
||||
}
|
||||
|
||||
/// The 1-based first and last lines of a unit's extent.
|
||||
fn lines(&self, unit: Unit<'_>) -> (u32, u32) {
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let first = self.index.line_col(start as u32).0;
|
||||
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// Drop units a fenced region of this scope reaches from both ends of the
|
||||
/// run, so no region is ever half inside the splice. `None` when nothing
|
||||
/// is left.
|
||||
fn trim_fences(&self, scope: Scope<'_>, mut a: usize, mut b: usize) -> Option<(usize, usize)> {
|
||||
while a <= b && self.fenced(scope, a) {
|
||||
a += 1;
|
||||
}
|
||||
while b > a && self.fenced(scope, b) {
|
||||
b -= 1;
|
||||
}
|
||||
(a <= b).then_some((a, b))
|
||||
}
|
||||
|
||||
/// Whether a region opened in this scope — not one nested inside the
|
||||
/// unit's own code — overlaps unit `i`'s extent.
|
||||
fn fenced(&self, scope: Scope<'_>, i: usize) -> bool {
|
||||
let Some(unit) = scope.unit(i) else { return true };
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let span = unit.span();
|
||||
let (code_start, code_end) = (span.start as usize, span.end as usize);
|
||||
self.regions.iter().any(|r| {
|
||||
let overlaps = r.start < end && start < r.end;
|
||||
let nested = r.start >= code_start && r.end <= code_end;
|
||||
overlaps && !nested
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether units `a..=b` can be replaced by whole lines: only indentation
|
||||
/// before the first, nothing after the last on its line, and no sibling
|
||||
/// or dangling comment of the scope inside the bytes between.
|
||||
fn clean(&self, scope: Scope<'_>, a: usize, b: usize) -> bool {
|
||||
let (Some(first), Some(last)) = (scope.unit(a), scope.unit(b)) else { return false };
|
||||
let (start, _) = first.extent(self.src);
|
||||
let (_, end) = last.extent(self.src);
|
||||
let bol = line_start(self.src, start);
|
||||
let indent_only = self.src.get(bol..start).is_some_and(|s| s.chars().all(is_indent));
|
||||
let eol =
|
||||
self.src.get(end..).map_or(end, |rest| end + rest.find('\n').unwrap_or(rest.len()));
|
||||
let rest_blank = self.src.get(end..eol).is_some_and(|s| s.chars().all(char::is_whitespace));
|
||||
let prev_clear = a == 0 || scope.unit(a - 1).is_some_and(|u| u.extent(self.src).1 <= start);
|
||||
let next_clear = scope.unit(b + 1).is_none_or(|u| u.extent(self.src).0 >= end);
|
||||
let dangling_clear = scope
|
||||
.dangling()
|
||||
.iter()
|
||||
.all(|c| c.span.end as usize <= start || c.span.start as usize >= end);
|
||||
indent_only && rest_blank && prev_clear && next_clear && dangling_clear
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes a resolved target replaces, and the run that replaces them.
|
||||
pub(super) struct Placed<'t> {
|
||||
pub run: crate::format::Run<'t>,
|
||||
/// Start of the first unit's line: where the splice begins.
|
||||
pub bol: usize,
|
||||
/// The base indentation every line of the layout starts with, as a byte
|
||||
/// range of the source: the leading whitespace of the run's first unit
|
||||
/// that is not a directive (see [`base_indent`]).
|
||||
pub base: (usize, usize),
|
||||
/// One past the last unit's last byte.
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
/// Find `target` again in a tree, and the bytes of `src` it occupies.
|
||||
pub(super) fn resolve<'t>(src: &str, root: Scope<'t>, target: &Target) -> Option<Placed<'t>> {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
scope = scope.unit(i)?.children().into_iter().nth(k)?;
|
||||
}
|
||||
let first = scope.unit(target.start)?;
|
||||
let last = scope.unit(target.start + target.count.checked_sub(1)?)?;
|
||||
let start = first.extent(src).0;
|
||||
let end = last.extent(src).1;
|
||||
let run = scope.run(target.start, target.count)?;
|
||||
let base = base_indent(src, scope, target, start);
|
||||
Some(Placed { run, bol: line_start(src, start), base, end })
|
||||
}
|
||||
|
||||
/// The indentation the run is laid out at: that of its first unit, unless
|
||||
/// that unit is a compiler directive and a later one is not. Directives are
|
||||
/// commonly written at column 0 while the code they guard is indented, and
|
||||
/// the code is what says where the block stands; the directive is then
|
||||
/// indented with it, as a whole-file run would.
|
||||
fn base_indent(src: &str, scope: Scope<'_>, target: &Target, start: usize) -> (usize, usize) {
|
||||
let code = (target.start..target.start + target.count)
|
||||
.filter_map(|i| scope.unit(i))
|
||||
.find(|u| !u.is_directive())
|
||||
.map(|u| u.extent(src).0);
|
||||
let own_line = |at: usize| {
|
||||
let bol = line_start(src, at);
|
||||
src.get(bol..at).is_some_and(|s| s.chars().all(is_indent)).then_some((bol, at))
|
||||
};
|
||||
code.and_then(own_line).unwrap_or((line_start(src, start), start))
|
||||
}
|
||||
|
||||
/// Every unit of a resolved target and everything nested in it, for the
|
||||
/// error-node check of a tolerant parse.
|
||||
pub(super) fn any_error(root: Scope<'_>, target: &Target) -> bool {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
let Some(next) = scope.unit(i).and_then(|u| u.children().into_iter().nth(k)) else {
|
||||
return true;
|
||||
};
|
||||
scope = next;
|
||||
}
|
||||
(target.start..target.start + target.count).any(|i| scope.unit(i).is_none_or(unit_has_error))
|
||||
}
|
||||
|
||||
fn unit_has_error(unit: Unit<'_>) -> bool {
|
||||
unit.is_error()
|
||||
|| unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.any(|s| (0..s.len()).any(|i| s.unit(i).is_none_or(unit_has_error)))
|
||||
}
|
||||
|
||||
/// The start of the line `at` is on.
|
||||
pub(super) fn line_start(src: &str, at: usize) -> usize {
|
||||
src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
fn is_indent(c: char) -> bool {
|
||||
c == ' ' || c == '\t'
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Selection formatting: lay out the smallest run of sibling items or
|
||||
//! statements the selected lines cover, at the indentation it was written
|
||||
//! at, and splice it into otherwise untouched bytes.
|
||||
//!
|
||||
//! This is what an editor's "Format Selection" wants. `format_range` (the
|
||||
//! CLI's `--lines`) re-lays whole module-level items at formatter depth;
|
||||
//! here the unit is whatever sibling list the selection lands in — a `case`
|
||||
//! inside an `always`, two statements of a function — and the parent is not
|
||||
//! touched at all. The run keeps the leading whitespace of its first line,
|
||||
//! tabs and off-grid indentation included. Every other byte of the file stays
|
||||
//! as written, the file tail included.
|
||||
//!
|
||||
//! The safety net is the usual one over the whole file: equivalence of the
|
||||
//! token streams, then convergence by replaying the located *target* (a path
|
||||
//! in the tree, not line numbers) on the output. Full spec:
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
mod locate;
|
||||
mod scope;
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::{format_range, print_run, Config, FormatError};
|
||||
use crate::range::LineRanges;
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use locate::{any_error, resolve, Found, Locator, Target};
|
||||
use scope::Scope;
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::ParseDiagnostic;
|
||||
|
||||
/// Format the smallest runs of sibling items or statements `lines` covers,
|
||||
/// each at the indentation its first line was written at, leaving every other
|
||||
/// byte of `source` as it is.
|
||||
///
|
||||
/// A selection reaching a module or package item as a whole is handed to
|
||||
/// [`format_range`] unchanged. A file that does not parse is formatted only
|
||||
/// where the selection is clear of every parse error; otherwise, as on any
|
||||
/// failed check, the caller gets an error and must keep the original text.
|
||||
///
|
||||
/// Same stack requirement as [`crate::format_source`].
|
||||
pub fn format_selection(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
lines: &LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
let tree = Tree::parse(source).map_err(FormatError::Source)?;
|
||||
let Some(root) = Scope::root(&tree.file) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
let locator = Locator::new(source, fence::collect(source, &tree.file));
|
||||
let Ok(targets) = select(&locator, root, source, lines) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Ok(source.to_string());
|
||||
}
|
||||
tree.check_clear(source, root, &targets)?;
|
||||
let output = splice(source, &tree.file, root, config, &targets)
|
||||
.ok_or_else(|| lost("the selection could not be cut out of its lines"))?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = replay(&output, config, &targets)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Format the output a second time with the same targets, found again by
|
||||
/// their position in its tree.
|
||||
fn replay(output: &str, config: &Config, targets: &[Target]) -> Result<String, FormatError> {
|
||||
let tree = Tree::parse(output).map_err(VerificationError::Reparse)?;
|
||||
let root = Scope::root(&tree.file).ok_or_else(|| lost("the output is not the same kind"))?;
|
||||
tree.check_clear(output, root, targets)?;
|
||||
splice(output, &tree.file, root, config, targets)
|
||||
.ok_or_else(|| lost("the selection could not be found again in the output"))
|
||||
}
|
||||
|
||||
fn lost(why: &str) -> FormatError {
|
||||
FormatError::Selection(format!("cannot format the selection: {why}"))
|
||||
}
|
||||
|
||||
/// A parsed text: strictly when it parses, tolerantly when it does not.
|
||||
struct Tree {
|
||||
file: SourceFile,
|
||||
/// The tolerant parse's diagnostics; empty for a strict parse.
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn parse(src: &str) -> Result<Tree, vlog_parser::Error> {
|
||||
match vlog_parser::parse_source(src) {
|
||||
Ok(file) => Ok(Tree { file, diagnostics: Vec::new() }),
|
||||
Err(e) => {
|
||||
let (file, diagnostics) = vlog_parser::parse_source_tolerant(src);
|
||||
// A tolerant parse that finds nothing wrong where the strict
|
||||
// one failed is not a tree to trust.
|
||||
if diagnostics.is_empty() {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Tree { file, diagnostics })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse when a parse error lies inside any target: its layout would
|
||||
/// rest on error recovery's guess.
|
||||
fn check_clear(
|
||||
&self,
|
||||
src: &str,
|
||||
root: Scope<'_>,
|
||||
targets: &[Target],
|
||||
) -> Result<(), FormatError> {
|
||||
if self.diagnostics.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for target in targets {
|
||||
let placed = resolve(src, root, target).ok_or_else(|| lost("internal: lost target"))?;
|
||||
let (lo, hi) = (placed.bol, placed.end);
|
||||
let hit = self
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|d| (d.span.start as usize) <= hi && lo <= d.span.end as usize);
|
||||
if let Some(d) = hit {
|
||||
return Err(FormatError::Selection(format!(
|
||||
"cannot format the selection: it contains a syntax error at {}:{}: {}",
|
||||
d.line, d.col, d.message
|
||||
)));
|
||||
}
|
||||
if any_error(root, target) {
|
||||
return Err(lost("it contains text that does not parse"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The request goes to `format_range` whole.
|
||||
struct Defer;
|
||||
|
||||
/// Locate one target per selected span; targets whose bytes overlap are
|
||||
/// re-selected from the hull of their spans.
|
||||
fn select(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
lines: &LineRanges,
|
||||
) -> Result<Vec<Target>, Defer> {
|
||||
let mut picked: Vec<Picked> = Vec::new();
|
||||
for &span in lines.spans() {
|
||||
picked.extend(pick(locator, root, src, span)?);
|
||||
}
|
||||
loop {
|
||||
picked.sort_by_key(|p| p.bytes.0);
|
||||
let Some(i) = (1..picked.len()).find(|&i| picked[i].bytes.0 < picked[i - 1].bytes.1) else {
|
||||
break;
|
||||
};
|
||||
let (a, b) = (picked.remove(i), picked.remove(i - 1));
|
||||
let hull = (a.span.0.min(b.span.0), a.span.1.max(b.span.1));
|
||||
picked.extend(pick(locator, root, src, hull)?);
|
||||
}
|
||||
Ok(picked.into_iter().map(|p| p.target).collect())
|
||||
}
|
||||
|
||||
/// One located target, with the line span that chose it and the bytes it
|
||||
/// replaces.
|
||||
struct Picked {
|
||||
span: (u32, u32),
|
||||
target: Target,
|
||||
bytes: (usize, usize),
|
||||
}
|
||||
|
||||
/// The target one span selects, if any.
|
||||
fn pick(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
span: (u32, u32),
|
||||
) -> Result<Option<Picked>, Defer> {
|
||||
match locator.locate(root, span) {
|
||||
Found::Nothing => Ok(None),
|
||||
Found::Defer => Err(Defer),
|
||||
Found::Target(target) => {
|
||||
// Resolving a target in the tree it was found in cannot fail; if
|
||||
// it ever did, the conservative answer is the old engine.
|
||||
let placed = resolve(src, root, &target).ok_or(Defer)?;
|
||||
Ok(Some(Picked { span, target, bytes: (placed.bol, placed.end) }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace every target's bytes with its layout, bottom-up so the earlier
|
||||
/// offsets stay valid. `None` when a target cannot be found or cut.
|
||||
fn splice(
|
||||
src: &str,
|
||||
file: &SourceFile,
|
||||
root: Scope<'_>,
|
||||
config: &Config,
|
||||
targets: &[Target],
|
||||
) -> Option<String> {
|
||||
let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::<Option<Vec<_>>>()?;
|
||||
placed.sort_by_key(|p| std::cmp::Reverse(p.bol));
|
||||
let mut out = src.to_string();
|
||||
let mut floor = src.len();
|
||||
for p in placed {
|
||||
let base = src.get(p.base.0..p.base.1)?;
|
||||
if p.end > floor || !base.chars().all(|c| c == ' ' || c == '\t') {
|
||||
return None;
|
||||
}
|
||||
let mut text = print_run(src, file, config, p.run, base);
|
||||
if uses_crlf(src, p.bol, p.end) {
|
||||
text = to_crlf(&text);
|
||||
}
|
||||
out = format!("{}{}{}", out.get(..p.bol)?, text, out.get(p.end..)?);
|
||||
floor = p.bol;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether the lines around a target end in `\r\n`: the line ending after
|
||||
/// it, or before it when it ends the file.
|
||||
fn uses_crlf(src: &str, bol: usize, end: usize) -> bool {
|
||||
match src.get(end..).and_then(|rest| rest.find('\n')) {
|
||||
Some(i) => src.get(..end + i).is_some_and(|s| s.ends_with('\r')),
|
||||
None => src.get(..bol).is_some_and(|s| s.ends_with("\r\n")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn every bare `\n` into `\r\n`; text copied from the source keeps the
|
||||
/// `\r\n` it already had.
|
||||
fn to_crlf(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len() + text.len() / 16);
|
||||
let mut prev = '\0';
|
||||
for c in text.chars() {
|
||||
if c == '\n' && prev != '\r' {
|
||||
out.push('\r');
|
||||
}
|
||||
out.push(c);
|
||||
prev = c;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The sibling lists a selection can land in, and the units they hold.
|
||||
//!
|
||||
//! A *scope* is a sibling list exactly as `fence.rs` defines one — an item
|
||||
//! list (file, module, package, generate region, generate `begin`…`end`,
|
||||
//! class) or a statement list (`begin`…`end`, `fork`…`join`, a function or
|
||||
//! task body). A *unit* is one item or statement of such a list. The match
|
||||
//! arms below mirror `fence::scan_nested` / `scan_nested_stmt` /
|
||||
//! `scan_gen_block`: a single-statement body or a block-less generate item is
|
||||
//! not a scope, so it is walked *through* to the scopes it reaches. An arm
|
||||
//! missing here only makes a selection coarser, never wrong.
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::Run;
|
||||
use vlog_parser::ast::{
|
||||
GenBlock, GenElse, GenIf, Item, ItemKind, Meta, SourceFile, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
/// One sibling list. Items carry the AST depth `item_seq` lays them out at.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Scope<'t> {
|
||||
Items(&'t [Item], &'t [Comment], usize),
|
||||
Stmts(&'t [Stmt], &'t [Comment]),
|
||||
}
|
||||
|
||||
/// One member of a scope.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Unit<'t> {
|
||||
Item(&'t Item, usize),
|
||||
Stmt(&'t Stmt),
|
||||
}
|
||||
|
||||
impl<'t> Scope<'t> {
|
||||
/// The scope a whole file is, or `None` for a fragment whose elements
|
||||
/// are not items or statements (enum members, cover items).
|
||||
pub(super) fn root(file: &'t SourceFile) -> Option<Scope<'t>> {
|
||||
match &file.fragment {
|
||||
None => Some(Scope::Items(&file.items, &file.dangling, 0)),
|
||||
Some(vlog_parser::ast::Fragment::Statements(stmts)) => {
|
||||
Some(Scope::Stmts(stmts, &file.dangling))
|
||||
}
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn len(&self) -> usize {
|
||||
match self {
|
||||
Scope::Items(items, ..) => items.len(),
|
||||
Scope::Stmts(stmts, _) => stmts.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn unit(&self, i: usize) -> Option<Unit<'t>> {
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(i).map(|item| Unit::Item(item, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(i).map(Unit::Stmt),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dangling(&self) -> &'t [Comment] {
|
||||
match *self {
|
||||
Scope::Items(_, dangling, _) | Scope::Stmts(_, dangling) => dangling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The units `start..start + count` as something the printers take.
|
||||
pub(super) fn run(&self, start: usize, count: usize) -> Option<Run<'t>> {
|
||||
let end = start.checked_add(count)?;
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(start..end).map(|s| Run::Items(s, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(start..end).map(Run::Stmts),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t> Unit<'t> {
|
||||
fn meta(&self) -> &'t Meta {
|
||||
match self {
|
||||
Unit::Item(item, _) => &item.meta,
|
||||
Unit::Stmt(stmt) => &stmt.meta,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn span(&self) -> TextRange {
|
||||
match self {
|
||||
Unit::Item(item, _) => item.span,
|
||||
Unit::Stmt(stmt) => stmt.span,
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's bytes: its first leading comment or attribute through the
|
||||
/// comments written after it on the same line.
|
||||
pub(super) fn extent(&self, src: &str) -> (usize, usize) {
|
||||
let meta = self.meta();
|
||||
let span = self.span();
|
||||
let mut start = span.start;
|
||||
if let Some(c) = meta.leading.first() {
|
||||
start = start.min(c.span.start);
|
||||
}
|
||||
if let Some(a) = meta.attrs.first() {
|
||||
start = start.min(a.span.start);
|
||||
}
|
||||
// In a CRLF file a trailing `//` comment's line ends `\r\n`, and the
|
||||
// scan above stops at the `\n`. The `\r` is the line ending, not the
|
||||
// unit: the layout does not write it, so the splice must not eat it.
|
||||
let mut end = fence::with_trailing_comments(src, span.end as usize);
|
||||
while end > span.end as usize && src.as_bytes().get(end - 1) == Some(&b'\r') {
|
||||
end -= 1;
|
||||
}
|
||||
(start as usize, end)
|
||||
}
|
||||
|
||||
/// Whether the unit is a construct `format_range` splits (a module or a
|
||||
/// package), which a selection defers to it.
|
||||
pub(super) fn is_container(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Unit::Item(Item { kind: ItemKind::Module(_) | ItemKind::Package { .. }, .. }, _)
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the unit is a compiler directive (`` `ifdef `` and kin),
|
||||
/// which is often written at column 0 whatever the code around it does.
|
||||
pub(super) fn is_directive(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Directive(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Directive(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the unit is a node error recovery made of unparsable text.
|
||||
pub(super) fn is_error(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Error(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Error(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes directly nested in this unit, in source order.
|
||||
pub(super) fn children(&self) -> Vec<Scope<'t>> {
|
||||
let mut out = Vec::new();
|
||||
match *self {
|
||||
Unit::Item(item, depth) => item_scopes(item, depth, &mut out),
|
||||
Unit::Stmt(stmt) => stmt_scopes(stmt, &mut out),
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes nested in one item at `depth`, at the depth `item_kind` lays
|
||||
/// their items out at.
|
||||
fn item_scopes<'t>(item: &'t Item, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => out.push(Scope::Items(&m.items, &m.dangling, depth + 1)),
|
||||
ItemKind::Package { items, dangling, .. }
|
||||
| ItemKind::GenerateRegion { items, dangling } => {
|
||||
out.push(Scope::Items(items, dangling, depth + 1))
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_scopes(b, depth, out),
|
||||
ItemKind::GenIf(g) => gen_if_scopes(g, depth, out),
|
||||
ItemKind::GenFor(g) => gen_block_scopes(&g.body, depth, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for i in &g.items {
|
||||
gen_block_scopes(&i.body, depth + 1, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Class(c) => out.push(Scope::Items(&c.items, &c.dangling, depth + 1)),
|
||||
ItemKind::Function(f) => out.push(Scope::Stmts(&f.stmts, &f.dangling)),
|
||||
ItemKind::Task(t) => out.push(Scope::Stmts(&t.stmts, &t.dangling)),
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
stmt_scopes(stmt, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_scopes<'t>(g: &'t GenIf, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
gen_block_scopes(&g.then, depth, out);
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => gen_if_scopes(inner, depth, out),
|
||||
Some(GenElse::Block(b)) => gen_block_scopes(b, depth, out),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `begin`…`end` is a scope one level in; a block-less body's
|
||||
/// one item is laid out one level in too, and walked through.
|
||||
fn gen_block_scopes<'t>(b: &'t GenBlock, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
if b.is_block {
|
||||
out.push(Scope::Items(&b.items, &b.dangling, depth + 1));
|
||||
} else {
|
||||
for item in &b.items {
|
||||
item_scopes(item, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement lists one statement holds, walking through every
|
||||
/// single-statement body.
|
||||
fn stmt_scopes<'t>(stmt: &'t Stmt, out: &mut Vec<Scope<'t>>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
|
||||
out.push(Scope::Stmts(stmts, dangling))
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
stmt_scopes(then, out);
|
||||
if let Some(e) = els {
|
||||
stmt_scopes(e, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
for s in then.iter().chain(els.iter()) {
|
||||
stmt_scopes(s, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for i in items {
|
||||
stmt_scopes(&i.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. }
|
||||
| StmtKind::Labeled { stmt: body, .. } => stmt_scopes(body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
stmt_scopes(inner, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Selection formatting (`format_selection`): the smallest run of sibling
|
||||
//! items or statements a selection covers is laid out at the indentation it
|
||||
//! was written at, and every other byte of the file stays as written.
|
||||
//!
|
||||
//! Spec: `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use vlog_formatter::{format_range, format_selection, verify_equivalence, Config, LineRanges};
|
||||
|
||||
fn select_with(src: &str, spec: &str, config: &Config) -> Result<String, String> {
|
||||
let lines = LineRanges::parse(spec).expect("line spec");
|
||||
format_selection(src, config, &lines).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn select(src: &str, spec: &str) -> String {
|
||||
select_with(src, spec, &Config::default()).expect("formats")
|
||||
}
|
||||
|
||||
/// Format, then format the result again with the same lines: the second run
|
||||
/// must change nothing.
|
||||
fn fixed(src: &str, spec: &str) -> String {
|
||||
let out = select(src, spec);
|
||||
assert_eq!(select(&out, spec), out, "a second run must change nothing");
|
||||
out
|
||||
}
|
||||
|
||||
/// Lines `first..=last` (1-based) of `src` are the target: everything before
|
||||
/// and after must come back byte for byte, and the returned middle is what
|
||||
/// replaced them.
|
||||
fn middle<'a>(src: &str, out: &'a str, first: usize, last: usize) -> &'a str {
|
||||
let lines: Vec<&str> = src.split_inclusive('\n').collect();
|
||||
let head: String = lines[..first - 1].concat();
|
||||
let tail: String = lines[last..].concat();
|
||||
assert!(out.starts_with(&head), "bytes before the target changed:\n{out}");
|
||||
assert!(out.ends_with(&tail), "bytes after the target changed:\n{out}");
|
||||
assert!(out.len() >= head.len() + tail.len(), "target overlaps the kept bytes:\n{out}");
|
||||
&out[head.len()..out.len() - tail.len()]
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The owner's shapes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A file indented four spaces, as many hand-written files are.
|
||||
const FOUR: &str = "\
|
||||
module m;
|
||||
reg [3:0] q;
|
||||
always @(posedge clk) begin
|
||||
if (rst) q<=0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q<=a;
|
||||
2'b01 : q <= b;
|
||||
default:q<=c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
assign y=q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_whole_always_keeps_its_indentation_in_a_four_space_file() {
|
||||
let out = fixed(FOUR, "3-12");
|
||||
let mid = middle(FOUR, &out, 3, 12);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" always @(posedge clk) begin
|
||||
if (rst) q <= 0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_case_inside_an_always_is_the_only_thing_laid_out() {
|
||||
let out = fixed(FOUR, "6-10");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_inside_a_generate_for_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
generate
|
||||
for (genvar i=0;i<4;i++) begin : g
|
||||
always @(posedge clk) q[i]<=d[i];
|
||||
assign w[i]=q[i];
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4");
|
||||
let mid = middle(src, &out, 4, 4);
|
||||
assert_eq!(mid, " always @(posedge clk) q[i] <= d[i];\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statements_inside_a_function_are_laid_out_without_the_function() {
|
||||
let src = "\
|
||||
module m;
|
||||
function automatic int f(input int a);
|
||||
int r;
|
||||
r=a+1;
|
||||
return r;
|
||||
endfunction
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4-5");
|
||||
let mid = middle(src, &out, 4, 5);
|
||||
assert_eq!(mid, " r = a + 1;\n return r;\n");
|
||||
assert!(out.contains(" int r;\n"), "the unselected statement stays: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_inside_an_else_branch_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
always @* begin
|
||||
if (a) x = 1;
|
||||
else begin
|
||||
y=2;
|
||||
z = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "5-6");
|
||||
let mid = middle(src, &out, 5, 6);
|
||||
assert_eq!(mid, " y = 2;\n z = 3;\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Indentation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn tab_indentation_is_reproduced_as_written() {
|
||||
let src = "module m;\n\talways @* begin\n\t\tx=1;\n\t\tif (a) begin\n\t\t\ty=2;\n\t\tend\n\tend\nendmodule\n";
|
||||
let out = fixed(src, "2-7");
|
||||
let mid = middle(src, &out, 2, 7);
|
||||
assert_eq!(
|
||||
mid,
|
||||
"\talways @(*) begin\n\t x = 1;\n\t if (a) begin\n\t y = 2;\n\t end\n\tend\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_grid_indentation_is_kept() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_misindented_parent_does_not_move_the_selection() {
|
||||
let src = "module m;\nalways @* begin\n x=1;\n y = 2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n");
|
||||
assert!(out.contains("\n y = 2;\n"), "the sibling is untouched: {out}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Partial selections
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn one_line_inside_a_case_lays_out_the_case() {
|
||||
let out = fixed(FOUR, "8");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert!(mid.starts_with(" case (sel)\n"), "{mid}");
|
||||
assert!(mid.contains(" 2'b01: q <= b;\n"), "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_only_range_formats_the_statement_under_it() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(out, "module m;\n always @* begin\n x=1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_ending_on_the_end_line_takes_only_the_statements_it_covers() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "4-5");
|
||||
assert_eq!(middle(src, &out, 4, 4), " y = 2;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_line_alone_takes_the_unit_it_closes() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "5");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_starting_on_the_first_line_takes_the_whole_unit() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "2-3");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_alone_change_nothing() {
|
||||
let src = "module m;\n wire a;\n\n\n wire b;\nendmodule\n";
|
||||
assert_eq!(select(src, "3-4"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_and_trailing_comments_travel_with_their_unit() {
|
||||
let src = "module m;\n always @* begin\n // why\n x=1; // what\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(middle(src, &out, 3, 4), " // why\n x = 1; // what\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_after_begin_is_not_line_clean_and_the_parent_is_taken() {
|
||||
let src = "module m;\n always @* begin // note\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n // note\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_statements_on_one_line_are_taken_together() {
|
||||
let src = "module m;\n always @* begin\n x=1; y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n y = 2;\n");
|
||||
assert!(out.contains(" z=3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_across_two_branches_takes_the_whole_if() {
|
||||
let src = "module m;\n always @* begin\n if (a) begin\n x=1;\n end else begin\n y=2;\n end\n end\nendmodule\n";
|
||||
let out = fixed(src, "4-6");
|
||||
let mid = middle(src, &out, 3, 7);
|
||||
assert_eq!(mid, " if (a) begin\n x = 1;\n end else begin\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Fences
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_fence_inside_the_target_is_emitted_as_written() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n // lucisv: off\n y = 2;\n // lucisv: on\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-8");
|
||||
assert!(out.contains(" y = 2;\n"), "{out}");
|
||||
assert!(out.contains(" x = 1;\n") && out.contains(" z = 3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_around_the_target_wins() {
|
||||
let src = "module m;\n // lucisv: off\n always @* begin\n x=1;\n end\n // lucisv: on\nendmodule\n";
|
||||
assert_eq!(select(src, "4"), src);
|
||||
assert_eq!(select(src, "3-5"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_straddling_the_target_trims_the_fenced_units() {
|
||||
let src = "module m;\n always @* begin\n a=1;\n b=2;\n // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n";
|
||||
// Lines 3-6 meet a, b, and c (fenced): c is trimmed off the end.
|
||||
let out = fixed(src, "3-6");
|
||||
assert_eq!(middle(src, &out, 3, 4), " a = 1;\n b = 2;\n");
|
||||
assert!(out.ends_with(
|
||||
" // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n"
|
||||
));
|
||||
// Lines 6-8 meet c (fenced) and d — whose extent starts at `on`: both go.
|
||||
assert_eq!(select(src, "6-8"), src);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Deferral to `format_range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_module_header_or_whole_module_selection_is_format_range() {
|
||||
let src = "module m(input a,output b);\n wire x;\n assign x=a;\nendmodule\nmodule n;\nendmodule\n";
|
||||
for spec in ["1", "1-4", "1-6", "4", "2-5"] {
|
||||
let lines = LineRanges::parse(spec).expect("spec");
|
||||
let range = format_range(src, &Config::default(), &lines).expect("range formats");
|
||||
assert_eq!(select(src, spec), range, "spec {spec}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Files that do not parse
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
const BROKEN: &str = "\
|
||||
module m;
|
||||
always @* begin
|
||||
x=1;
|
||||
end
|
||||
assign y = ;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn an_error_outside_the_target_does_not_stop_it() {
|
||||
let out = fixed(BROKEN, "3");
|
||||
assert_eq!(middle(BROKEN, &out, 3, 3), " x = 1;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_inside_the_target_refuses() {
|
||||
let err = select_with(BROKEN, "5", &Config::default()).expect_err("refused");
|
||||
assert!(err.contains("syntax error") || err.contains("parse"), "{err}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Idempotence and multiple ranges
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn formatting_the_same_target_twice_changes_nothing() {
|
||||
for spec in ["3-12", "6-10", "4", "8", "13"] {
|
||||
fixed(FOUR, spec);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_ranges_lay_out_two_targets_and_nothing_between() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3,5");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\n always @* begin\n x = 1;\n y=2;\n z = 3;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_targets_are_reselected_from_their_hull() {
|
||||
// `4` selects the inner statement, `2` the always holding it.
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2,4");
|
||||
assert_eq!(out, "module m;\n always @(*) begin\n x = 1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Masked-corruption attacks on the splice
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Either a correct result (equivalent to the input, a fixed point) or a
|
||||
/// refusal — never silently wrong.
|
||||
fn correct_or_refused(src: &str, spec: &str) -> Option<String> {
|
||||
let out = select_with(src, spec, &Config::default()).ok()?;
|
||||
verify_equivalence(src, &out).expect("the result is equivalent to the input");
|
||||
assert_eq!(select(&out, spec), out, "and a fixed point");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_on_the_last_line_survives() {
|
||||
let src = "module m;\n always @* begin\n x=1; /* a */ /* b */\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "3").expect("formats");
|
||||
assert!(out.contains("/* a */") && out.contains("/* b */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_are_kept() {
|
||||
let src = "module m;\r\n always @* begin\r\n x=1;\r\n y=2;\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\r\n always @* begin\r\n x = 1;\r\n y = 2;\r\n end\r\nendmodule\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending() {
|
||||
// QA finding 1: the `\r` after a trailing `//` comment is the line
|
||||
// ending, not part of the unit, so the splice leaves it in place.
|
||||
let src = "module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_block_comment_inside_the_target_survives() {
|
||||
let src =
|
||||
"module m;\n always @* begin\n /* one\n two */\n x=1;\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "2-6").expect("formats");
|
||||
assert!(out.contains("/* one\n two */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_string_inside_the_target_is_kept_or_refused() {
|
||||
let src =
|
||||
"module m;\n initial begin\n $display(\"a\\\n b\");\n x=1;\n end\nendmodule\n";
|
||||
if let Some(out) = correct_or_refused(src, "2-6") {
|
||||
assert!(out.contains("\"a\\\n b\""), "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_at_the_end_of_a_file_without_a_final_newline() {
|
||||
let src = "always @* begin\n x=1;\nend";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "always @* begin\n x = 1;\nend");
|
||||
let src = "wire a;\nassign b=a;";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "wire a;\nassign b = a;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_characters_before_the_target_do_not_shift_it() {
|
||||
let src = "module m;\n // café — ünïcode\n wire a; // ß\n assign b=a;\nendmodule\n";
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(middle(src, &out, 4, 4), " assign b = a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_safety_net_rejects_a_mis_spliced_output() {
|
||||
// An off-by-one at the end of the splice duplicates the `;`; at the
|
||||
// start it drops the trailing comment's first byte. Both must be caught.
|
||||
let src = "module m;\n always @* begin\n x=1; // c\n end\nendmodule\n";
|
||||
let duplicated = "module m;\n always @* begin\n x = 1;; // c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, duplicated).is_err());
|
||||
let dropped = "module m;\n always @* begin\n x = 1; c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, dropped).is_err());
|
||||
let crlf = "module m;\r\n always @* begin\r\n /* one\r\n two */\r\n x=1;\r\n end\r\nendmodule\r\n";
|
||||
let lost_comment_line =
|
||||
"module m;\r\n always @* begin\r\n /* one */\r\n x = 1;\r\n end\r\nendmodule\r\n";
|
||||
assert!(verify_equivalence(crlf, lost_comment_line).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_zero_directive_does_not_set_the_indentation_of_the_code_it_guards() {
|
||||
let src = "module m;\n`ifdef A\n wire a;\n`endif\n wire b;\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
// The code says where the block stands; the directives are indented with
|
||||
// it, as a whole-file run indents them.
|
||||
assert_eq!(middle(src, &out, 2, 4), " `ifdef A\n wire a;\n `endif\n");
|
||||
}
|
||||
@@ -364,6 +364,11 @@ is a leaf, as it was for fences.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- Editors' "Format Selection" no longer uses this engine: since TODO §66.2
|
||||
the LSP range requests call `format_selection`, which lays out the smallest
|
||||
sibling run in place — see `docs/features/selection-formatting/README.md`.
|
||||
The CLI's `--lines` still runs here, unchanged.
|
||||
|
||||
- [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and
|
||||
zero refused, past-EOF clamped) with unit tests for every spelling.
|
||||
- [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
# selection-formatting
|
||||
|
||||
## Goal
|
||||
|
||||
VS Code's "Format Selection" (`textDocument/rangeFormatting`) failed more than
|
||||
half the time on the selections people actually make — one whole `always`
|
||||
block, one whole `case`, usually nested in blocks the selection does not
|
||||
cover. The request went to `format_range` (the CLI's `--lines`), whose unit is
|
||||
a whole module-level item laid out at formatter depth: selecting a `case`
|
||||
re-laid the whole `always`, a block in a four-space or tab-indented file came
|
||||
back re-indented to two spaces, a selection inside `generate` or a function
|
||||
re-laid the whole region, and any parse error anywhere refused the request.
|
||||
`format_selection` lays out **only the smallest run of sibling items or
|
||||
statements the selection covers**, at the indentation its first line was
|
||||
written at, and splices it into otherwise untouched bytes. The owner's rule:
|
||||
don't worry about the parent; the selected block keeps the indentation level
|
||||
it starts at; the result must be functionally the same.
|
||||
|
||||
## Semantics
|
||||
|
||||
### Scopes and units
|
||||
|
||||
A *scope* is a sibling list exactly as `fence.rs` defines one: item lists
|
||||
(file, module, package, generate region, generate `begin`…`end`, class) and
|
||||
statement lists (`begin`…`end`, `fork`…`join*`, function and task bodies). A
|
||||
single-statement body (`if (a) x = 1;`, `always @* x = 1;`) or a block-less
|
||||
generate item is not a scope; it is walked *through* to the scopes it reaches.
|
||||
A *unit* is one item or statement with its whole extent: first leading comment
|
||||
or attribute through the comments written after it on the same line.
|
||||
|
||||
### Locating the target (`selection/locate.rs`)
|
||||
|
||||
For one selected line span, starting at the file scope:
|
||||
|
||||
1. Take the units whose lines meet the span. Blank lines select nothing; a
|
||||
span meeting no unit changes nothing.
|
||||
2. If exactly one unit is met, the span touches neither its first line nor its
|
||||
last, and exactly **one** of its nested scopes has a unit the span meets,
|
||||
descend into that scope and repeat.
|
||||
*(Lead ruling 2026-11-09, QA note 2: only the unit's **first** line is
|
||||
asked about. A selection over a block's last statements and its closing
|
||||
`end` descends and lays out those statements; the closing line alone
|
||||
meets no nested unit and still names the unit it closes.)*
|
||||
3. Otherwise the target is the run of consecutive units met — a partial
|
||||
selection expands to whole units.
|
||||
4. **Fences outrank the selection.** Units a fenced region *of this scope*
|
||||
reaches (a region nested inside a unit's own code does not count) are
|
||||
trimmed from both ends of the run; an empty run changes nothing. A region is
|
||||
never half inside the splice.
|
||||
5. **Line-clean or one level up.** The run must be replaceable by whole lines:
|
||||
only spaces/tabs before its first byte on that line, only whitespace after
|
||||
its last byte on that line, no sibling unit's extent and no dangling comment
|
||||
of the scope inside it. If not (`begin // note` makes the first statement's
|
||||
leading comment start on the `begin` line; `x = 1; y = 2;` with only `x`
|
||||
selected is fine because both are met), the enclosing unit is the target,
|
||||
checked the same way. At the file scope there is nowhere to go up to, and
|
||||
the request is deferred.
|
||||
6. **Big containers defer.** A run holding a `module`/`interface`/`program`
|
||||
or `package` item goes to `format_range(source, config, lines)` unchanged —
|
||||
header/footer splitting and whole-file selections behave exactly as before.
|
||||
|
||||
The located target is recorded as a **path** — `(unit index, child scope
|
||||
index)` per descent, plus the run's start and length — not as bytes or lines.
|
||||
|
||||
### Layout and splice (`selection/mod.rs`, `format::print_run`)
|
||||
|
||||
- `print_run` builds the ordinary `Fmt` over the whole source (fenced regions
|
||||
from `fence::collect`, no range splits) and calls `item_seq(run, depth)` or
|
||||
`stmt_seq(run)` on the sub-slice. `depth` is the AST depth `item_kind`
|
||||
would pass down (it only feeds the alignment width budget).
|
||||
- The **base indentation** is the leading whitespace of the run's first unit's
|
||||
line, as written (tabs included) — or, when that unit is a compiler directive
|
||||
and a later unit is not, the later unit's: directives are commonly written at
|
||||
column 0 while the code they guard is indented, and the code says where the
|
||||
block stands. The directive is then indented with the block, as a whole-file
|
||||
run indents it.
|
||||
- `Printer::print_at(doc, base)` starts the text with `base`, writes it after
|
||||
every line break before the indentation, and charges its width against the
|
||||
line budget (a tab counts as one indent width). `Doc::Verbatim` and
|
||||
`Doc::Inline` keep their own absolute indentation, and a line holding nothing
|
||||
but indentation is emptied so blank lines never keep the base's tabs.
|
||||
`print` is `print_at(doc, "")`, byte for byte the old printer.
|
||||
- The splice replaces `line start of the first unit .. end of the last unit's
|
||||
extent` with the printed text and nothing else: blank lines at the boundary,
|
||||
the rest of the last line and the file tail (final newline or not) are
|
||||
untouched. In a file whose lines end in `\r\n` (judged at the target), every
|
||||
line break the printer wrote becomes `\r\n`; source text copied through
|
||||
keeps the `\r\n` it had.
|
||||
|
||||
### Several ranges
|
||||
|
||||
Each merged span of `LineRanges` selects its own target. Targets whose byte
|
||||
ranges overlap are replaced by the target of the hull of their spans, until
|
||||
none overlap. They are spliced bottom-up and verified together, so the
|
||||
all-or-nothing contract covers the whole request. If any span defers, the
|
||||
whole request goes to `format_range`.
|
||||
|
||||
### Safety net (unchanged)
|
||||
|
||||
`verify_equivalence(source, output)` over the whole file, then convergence by
|
||||
**replaying the targets**: the output is parsed the same way, each path is
|
||||
resolved in its tree, laid out and spliced again, and `verify_convergence`
|
||||
must find nothing to change. `verify.rs` is not touched. Any failure — a target
|
||||
that cannot be found again or cut cleanly in the output included — is an error
|
||||
and no edit (`FormatError::Selection` for the selection's own refusals).
|
||||
|
||||
### A file that does not parse
|
||||
|
||||
`parse_source` first. If it fails, `parse_source_tolerant` builds the tree and
|
||||
the target is located in it the same way. The request is refused when any
|
||||
parse diagnostic lies inside `line start .. end` of a target, or any unit of
|
||||
the target (at any depth reachable through the scope walk) is an `Error` node.
|
||||
The replay parses the output the same way and applies the same check.
|
||||
|
||||
**Verdict:** sound and useful. Sound because the layout is token-verified over
|
||||
the whole file like every other path: recovery can only mis-guess the *nesting*
|
||||
around a target (an `assign` after a missing `end` becomes a statement), which
|
||||
changes at most how a clean run is laid out, never its tokens — and the target
|
||||
itself is required to be free of diagnostics and error nodes. Useful because
|
||||
in the corpus sweep below, with a broken line injected in every file, 75 % of
|
||||
selections still answered.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- A tab in the base indentation is worth one indent width for the line budget.
|
||||
The printer cannot know the reader's tab stop; only group breaking depends
|
||||
on it, and the replay uses the same rule, so it cannot break convergence.
|
||||
- Comment `col` is a byte column with a tab counting 1, so `raw_lines`'
|
||||
dedent-by-column cancels a base containing tabs exactly as it cancels
|
||||
spaces (exercised by the tab tests).
|
||||
- A parse diagnostic's span is the token the parser gave up on, not the extent
|
||||
of what it swallowed; the `Error`-node walk covers the latter at list level.
|
||||
An error node nested in an expression or header list is assumed to come with
|
||||
a diagnostic inside it. The safety net backs both.
|
||||
- The alignment of a sub-slice is planned over the sub-slice only (a run
|
||||
holding half of an alignment group aligns that half). Stable under replay.
|
||||
- With `uvm-utils-indent` on, a run holding a `` `uvm_*_utils_begin `` without
|
||||
its `_end` indents what follows it inside the run, as a whole-file run would.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `fence::collect`, `fence::region_at`-shaped regions,
|
||||
`fence::with_trailing_comments` (already `pub(crate)`), `Fmt::item_seq` /
|
||||
`Fmt::stmt_seq` (already `pub(super)` within `format`), `format_range`,
|
||||
`verify_equivalence`, `verify_convergence`, `vlog_parser::parse_source`,
|
||||
`parse_source_tolerant`.
|
||||
- **Provides** `vlog_formatter::format_selection(source, config, lines)` and
|
||||
`Printer::print_at(doc, base)`; `format::print_run` / `format::Run`
|
||||
(`pub(crate)`); a new `FormatError::Selection(String)` variant (every match
|
||||
on `FormatError` in the workspace already has a catch-all arm).
|
||||
- **Changed for the server:** `lucisv_server::format::{range_formatting,
|
||||
ranges_formatting}` now call `format_selection`. `on_type.rs`'s
|
||||
semicolon trigger calls `format::range_formatting`, so it changes too.
|
||||
- **Request (not done — outside this lane's files): `crates/lucisv_server/src/on_type.rs`.**
|
||||
Two of its unit tests pin behaviour this design changes on purpose, and fail:
|
||||
1. `a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all`
|
||||
(line ~1175) — its buffer's error (`wire ;`, line 3) is *outside* the
|
||||
keystroke's statement (line 2), so the request now formats line 2 (design
|
||||
step 7). Proposed fix: put the error on the keystroke's own line, e.g.
|
||||
`"module m;\n wire a = ;\nendmodule\n"` with the `;` at line 1,
|
||||
char 13 — the change made to the twin test in
|
||||
`server/tests/formatting.rs`.
|
||||
2. `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`
|
||||
(line ~1210) — the splice no longer adds a final newline (design step 5);
|
||||
the expected text becomes `"module m;\n wire a;\nendmodule"` and the
|
||||
comment above it should say the file tail is untouched.
|
||||
The module doc at line ~64 ("`format_range` selects by …") is also stale.
|
||||
- The CLI `--lines` keeps calling `format_range`; `range.rs` is unchanged.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `printer.rs`: `print_at(doc, base)`; `print` delegates with `""`.
|
||||
Whole-file output byte-identical (snapshot + idempotency suite green
|
||||
before any selection test existed).
|
||||
- [x] `format/mod.rs`: `Run`, `print_run`, `FormatError::Selection`.
|
||||
- [x] `selection/scope.rs`: scopes, units, extents, the nested-scope walk.
|
||||
- [x] `selection/locate.rs`: locate (descend, fences, line-clean, defer),
|
||||
path resolution, error-node walk, base indentation.
|
||||
- [x] `selection/mod.rs`: `format_selection`, multi-target hull merging,
|
||||
bottom-up splice, CRLF, tolerant path, replay.
|
||||
- [x] `tests/selection.rs` — 33 tests (incl. the directive-base test).
|
||||
- [x] Server: `ranges_formatting` → `format_selection`; 3 handler tests in
|
||||
`format.rs`, 1 dispatch test + 1 updated in `server/tests/formatting.rs`,
|
||||
1 e2e leg.
|
||||
- [x] `on_type.rs` test updates — Handshake request above (applied by the lead, 2026-11-09).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-09 — dev
|
||||
|
||||
- Built as designed, as a directory module (`selection/{mod,scope,locate}.rs`,
|
||||
each well under 300 production lines) rather than one file.
|
||||
- **Deviation 1 — multi-range lives in the engine.** The design put the
|
||||
per-span targets and hull re-selection in the LSP handler; `format_selection`
|
||||
takes a `LineRanges` anyway, so it does that itself and verifies all targets
|
||||
in one pass. The server only swaps `format_range` for `format_selection`.
|
||||
- **Deviation 2 — descent needs exactly one reached child scope.** A span
|
||||
covering both branches of an `if` reaches two scopes; it takes the `if`
|
||||
rather than one branch.
|
||||
- **Deviation 3 — directive base.** The base indentation is taken from the
|
||||
first non-directive unit of the run; found by a scratch run where a run
|
||||
starting at a column-0 `` `ifdef `` pulled the guarded code to column 0.
|
||||
- **Fence check** counts only regions opened in the run's own scope; a region
|
||||
nested in a unit's code is laid out verbatim by the printer as in a
|
||||
whole-file run, so it does not trim the unit.
|
||||
- **`FormatError::Selection(String)`** added for refusals that are neither a
|
||||
parse error nor a verification failure (a parse error inside the target, a
|
||||
target that cannot be found again).
|
||||
- **Server tests updated:** `a_keystroke_the_engine_refuses_is_answered_with_
|
||||
silence_and_not_a_popup` (`server/tests/formatting.rs`) — its buffer's error
|
||||
was on another line, which no longer refuses; the error now sits on the
|
||||
keystroke's own line. No `format.rs` test pinned over-reach: the existing
|
||||
range tests select whole module items and come out identical.
|
||||
- **Corpus sweep** (scratch test, release, under `tools/guard.sh`, not
|
||||
committed): 428 formattable files of `corpus/{common_cells,ibex,picorv32,
|
||||
opentitan/hw/ip}` (every ~2nd file), windows of 1, 2, 4 and 8 lines at a
|
||||
stride of 5+w: **33 438 calls, 21 473 changed, 11 965 unchanged, 0
|
||||
verification errors, 0 selection refusals, 0 source errors.** Same files
|
||||
with ` @@ broken = ;` injected at the middle line: 33 626 calls, 14 159
|
||||
changed, 10 954 unchanged, 4 281 refused because the target holds the
|
||||
error (or recovery swallowed the rest of the file into an error node), 4 232
|
||||
source errors (the span reached a module-level unit and was deferred to
|
||||
`format_range`, which parses strictly), 0 verification errors.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-09 — QA
|
||||
|
||||
**Gates (main checkout, all guarded, no guard kills):** `cargo fmt --all --check` clean;
|
||||
`cargo clippy --workspace --all-targets` 0 warnings; `cargo test`: `-p vlog_formatter`
|
||||
347 passed / 0 failed, `-p lucisv_server` 1881 passed / 0 failed / 40 ignored, `-p lucisv`
|
||||
143 passed / 0 failed. `verify.rs`, `range.rs`, `fence.rs`, `crates/lucisv` untouched
|
||||
(`git diff --stat`). No source or test files edited by QA; all experiments in a throwaway copy
|
||||
(deleted).
|
||||
|
||||
**Hand-written attack set:** 221 (source, selection) cases in 2/3/4-space and tab files
|
||||
(nested `generate for` / `always_ff` / `case`, mis-indented parents, `if`/`else` chains, `for`,
|
||||
`fork`/`join`, function and task bodies, case-item blocks, class methods, gen-if/gen-case),
|
||||
comments everywhere, `` `define `` with `\` continuations, `` `ifdef `` at run boundaries,
|
||||
escaped identifiers, attributes, labels, fences (enclosing / unmatched / straddling), CRLF, no
|
||||
final newline, multibyte, mixed whitespace, tabs, empty file, past-EOF, one-line/cursor-only,
|
||||
statements sharing a line, multi-range hulls, files with parse errors. Every window of each
|
||||
case was then run (24 719 calls): **0 panics, 0 token-nonequivalent outputs (independent
|
||||
`verify_equivalence`), 0 non-idempotent results, 0 verification errors except the CRLF finding
|
||||
below.** A "far" detector (changed lines not touching the selection) fired 573 times; every
|
||||
one inspected was the target growing to its whole unit (selection touching a unit's first/last
|
||||
line, a leading `///` comment line, or the module header deferral) as the spec says.
|
||||
|
||||
**Corpus sweep** (release, 409 files of `corpus/`, 12 random windows of 1-12 lines each,
|
||||
fixed seed): clean 4 908 calls: 3 611 changed / 1 265 unchanged / 32 refused / 0 verification
|
||||
errors / 0 panics / 0 non-equivalent. One random line replaced by ` @@ broken ( ;` (4 908
|
||||
calls): 1 005 changed / 617 unchanged / 3 286 refused (error inside target or swallowed by
|
||||
recovery) / 0 verification errors / 0 panics / 0 non-equivalent. CRLF-converted (818 calls): 594
|
||||
changed / 212 unchanged / 7 refused / **5 verification errors** and 1 mixed-EOL output (finding 1).
|
||||
(A shifted-window re-run flagged 18 "non-idempotent" calls; all were artifacts of the shifted
|
||||
window landing on the module header, i.e. a different target — not a defect.)
|
||||
|
||||
**Sabotage (copy only):** (A) splice tail skips the line after the target: 27 of 33
|
||||
`tests/selection.rs` tests fail; runtime net alone rejected 14 294 of 24 719 calls, 0 corrupted
|
||||
outputs returned. (B) base indentation prefixed onto every `Doc::Verbatim`: 1 test fails
|
||||
(`a_fence_inside_the_target_is_emitted_as_written`); runtime net (replay convergence)
|
||||
rejected 283 calls, 0 corrupted outputs returned; the whole-file suite cannot see it (empty
|
||||
base) — so one test is all that pins it. (C) fence trimming removed: 2 tests fail
|
||||
(`a_fence_around_the_target_wins`, `a_fence_straddling_the_target_trims_the_fenced_units`);
|
||||
net rejected 241 calls.
|
||||
|
||||
**Findings**
|
||||
|
||||
- SHOULD-FIX 1 — CRLF file + target whose last line ends in a `//` comment loses its `\r`.
|
||||
`print_run`'s `out.trim_end()` (`format/mod.rs`, `print_run`) strips the `\r` that the trailing
|
||||
comment's text carries while `Unit::extent` (`scope.rs`) includes it in the replaced
|
||||
bytes, so the line ends in a bare `\n`; the replay then often disagrees and the request is
|
||||
*refused* ("formatting is not idempotent; line N changed from "" to """), otherwise the file
|
||||
comes back with one bare-`\n` line. Repro: `"module m;\r\n initial begin\r\n a = 1; // c\r\n
|
||||
b = 2; // d\r\n end\r\nendmodule\r\n"`, lines `3-4` -> Err; `3-3` of a one-statement
|
||||
variant -> Err; corpus `opentitan/.../uart_tx_rx_vseq.sv` as CRLF, line `215-215` -> Ok with a
|
||||
bare `\n` on line 215. The LF twin of each is fine. Safe (no corruption) but Windows files
|
||||
with trailing comments cannot be range-formatted.
|
||||
- NOTE 2 — selecting interior statements together with the parent's closing `end` (e.g. the
|
||||
last statements of a generate `begin`…`end` plus its `end`) takes the whole parent: corpus
|
||||
`common_cells/src/rr_arb_tree.sv` lines `310-319` re-lays 116..292. By design (step 2/3)
|
||||
but it is the most common sloppy selection; consider whether the owner wants it.
|
||||
- NOTE 3 — inner indentation comes from `Config::indent_width` (2 for the library default),
|
||||
so the engine alone on a 4-space file gives a 4-space block with 2-space nesting inside
|
||||
(`gen-4sp` cases); the server passes the editor `tabSize`, so with `indent_width = 4` the
|
||||
owner's case comes out right (demo below). For tab files the nested levels are `\t…\t` plus
|
||||
spaces (`\t\t\t\t case`), same as the whole-file printer's no-tab model.
|
||||
- NOTE 4 — a selection spanning module-header ports and body items formats only the body
|
||||
items (the header lines are not units); header-only selections defer to `format_range`.
|
||||
- NOTE 5 — a column-0 directive in a run together with indented code is moved to the block's
|
||||
indentation (`` `endif `` + next statement selected -> `` `endif `` indented while `` `ifdef ``
|
||||
stays at column 0). Token-equivalent; cosmetic.
|
||||
- NOTE 6 — with a missing `end` the tolerant tree nests later statements into the open block, so
|
||||
they get laid out one level deeper than the (misplaced) `end` implies. Tokens identical.
|
||||
I could not construct a counterexample where a wrong parse changes meaning: only whitespace
|
||||
is chosen by layout, the token/comment stream is compared exactly, and line-sensitive
|
||||
tokens (`` `define ``, directives, line comments) are tokens whose text includes their line.
|
||||
|
||||
**Usability (owner's complaint)**, 4-space file, `generate for` -> `always_ff` -> `case`,
|
||||
`indent_width = 4`: selecting exactly the `case` lines (6-10), exactly the `always_ff` lines
|
||||
(5-11), one middle line (8) and the three case items (7-9) all yield the same correct result,
|
||||
and every byte outside the `case` is unchanged:
|
||||
|
||||
before after (selection 8-8)
|
||||
always_ff @(posedge clk) begin always_ff @(posedge clk) begin
|
||||
case (sel[i]) case (sel[i])
|
||||
2'b00: q[i]<=a; 2'b00: q[i] <= a;
|
||||
2'b01 : q[i] <= b; 2'b01: q[i] <= b;
|
||||
default:q[i]<=c; default: q[i] <= c;
|
||||
endcase endcase
|
||||
end end
|
||||
|
||||
**Not verified:** the editor (VS Code / Vim) end to end; opentitan sweep and the byte-identity
|
||||
corpus gates (the 347-test formatter suite incl. snapshots is green, which is the evidence for
|
||||
`print_at("")` == old `print`); files over 120 KB; non-ASCII-heavy corpora beyond the
|
||||
hand-written multibyte cases; `--release` gate script `tools/gates.sh`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-11-09 — lead. Verdict: accepted, with two fixes of mine after QA.**
|
||||
|
||||
1. **The design is a splice, not a second inverted fence**, and that is what
|
||||
answers the owner's complaint: the target keeps the indentation it was
|
||||
written at because nothing above it is laid out at all. The safety
|
||||
argument is the old one, unchanged — whole-file `verify_equivalence`
|
||||
(`verify.rs` untouched, so invariant #4 does not apply) plus a replay of
|
||||
the located target. QA's three sabotages were each caught, with zero
|
||||
corrupted outputs returned in 24,719 hand-case calls and 10,634 corpus
|
||||
calls; no panic.
|
||||
2. **QA SHOULD-FIX 1 (CRLF), fixed by the lead.** `Unit::extent` counted the
|
||||
`\r` after a trailing `//` comment as part of the unit, so the splice ate
|
||||
it. The extent now stops before it (`selection/scope.rs`); `print_run`
|
||||
trims spaces and newlines only, as `render` does. Pinned by
|
||||
`crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending`.
|
||||
3. **QA NOTE 2, ruled: only the first line stops the descent.** A selection
|
||||
over a block's last statements and its `end` re-laid 177 unselected lines
|
||||
of `rr_arb_tree.sv`. It now lays out the statements it covers; the `end`
|
||||
line alone still names the unit it closes. Three tests pin the three
|
||||
cases.
|
||||
4. **`on_type.rs`** (the dev's Handshake request): accepted. The `;` trigger
|
||||
shares the engine, so an error elsewhere in the buffer no longer silences
|
||||
it and the file tail is not normalized; two tests updated, one added.
|
||||
5. **Accepted as they are**: the dev's four deviations; NOTE 3 (nested levels
|
||||
use `indent_width`, which the server takes from the editor's `tabSize`);
|
||||
NOTE 4 and NOTE 5 (cosmetic, token-equivalent).
|
||||
6. **Open**: the LSP reply is still one whole-document edit; the engine now
|
||||
knows the exact bytes it replaced, so a minimal edit is possible. Not
|
||||
verified in a running editor.
|
||||
+2
-1
@@ -151,7 +151,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
|
||||
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `rename_traced_with(files, known: &dyn KnownFacts, …)` (perf5r-scope-reuse, 2026-09-09: the engine may build its index from a caller's record for a file **only** when `known.facts_for(path, text)` answers for exactly these bytes — the server answers from the index cache's store entry, record and FNV-1a content hash read from one place, never from the workspace index's record; a reused file is parsed anyway if a later stage reads its `Semantics`; `rename_traced` is the door with nothing known), `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), the parsed-input selectors `port_action_modules_in`/`imported_packages_in`/`extract_site_in`/`inline_site_in` (perf5-p1: the offer paths hand the document's own tolerant parse and diagnostics; the text forms are thin wrappers kept for standalone consumers and the every-offset parity test; a large-file buffer still takes the text form), `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
|
||||
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_selection`/`LineRanges` (range, ranges, on-type formatting — since TODO §66.2, 2026-11-09; `format_range` is now the CLI's `--lines` and the engine's own fallback for module/package-level selections), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); `rename`, `add_port`, `remove_port`, `find_references`, `instantiation_plan`, `module_definition`, `enclosing_module` (refactor); `format_source`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. **M7 (2026-09-23, the lean catalogue):** nine tools; `diff::unified`, `format_range` and the cursor refactorings (`expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `extract_module`) are no longer called — they stay in the CLI and the server. |
|
||||
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
|
||||
@@ -429,6 +429,7 @@ graph LR
|
||||
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
|
||||
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
|
||||
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
|
||||
| `selection-formatting ──▶ range-formatting / format-fences / lucisv-server` | depends | (2026-11-09, TODO §66.2) `format_selection` lays out the smallest run of sibling items/statements a line span covers at its written indentation and splices it in; defers to `format_range` for a module/package-level target; consumes `fence::collect`/`with_trailing_comments` and `Fmt::item_seq`/`stmt_seq`; adds `Printer::print_at` and `FormatError::Selection`. `verify.rs`, `range.rs`, `fence.rs` untouched. The server's range, ranges and on-type `;` requests all go through it. |
|
||||
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
|
||||
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
|
||||
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
|
||||
|
||||
@@ -5,6 +5,18 @@ 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.63.0 — 2026-11-09
|
||||
|
||||
- **Format Selection formats just what you selected.** Select an `always`
|
||||
block, a `case` statement or a few statements and only that block is laid
|
||||
out, starting at the indentation it already has; the code around it is
|
||||
left alone. It used to re-lay the whole enclosing module or top-level
|
||||
block.
|
||||
- **Format Selection works while another part of the file is broken.** A
|
||||
syntax error outside the selection no longer stops it.
|
||||
- **`Ctrl+/` (`Cmd+/`) toggles comments** on the current line or every
|
||||
selected line, and brackets and quotes auto-close.
|
||||
|
||||
## 0.62.0 — 2026-10-19
|
||||
|
||||
- **Find All References and Rename follow paths from a top-level module.**
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.62.0**. Its platform packages include
|
||||
The current release is **0.63.0**. Its platform packages include
|
||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||
[Agents (MCP)](#agents-mcp)):
|
||||
|
||||
@@ -406,6 +406,12 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.63.0 highlights
|
||||
|
||||
Version 0.63.0 makes **Format Selection** format just the block you selected,
|
||||
at the indentation it already has, and makes `Ctrl+/` (`Cmd+/`) toggle
|
||||
comments on the selected lines.
|
||||
|
||||
## Release 0.62.0 highlights
|
||||
|
||||
Version 0.62.0 lets references and rename follow a hierarchical path from a
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"comments": {
|
||||
"lineComment": "//",
|
||||
"blockComment": ["/*", "*/"]
|
||||
},
|
||||
"brackets": [
|
||||
["(", ")"],
|
||||
["[", "]"],
|
||||
["{", "}"]
|
||||
],
|
||||
"autoClosingPairs": [
|
||||
{ "open": "(", "close": ")" },
|
||||
{ "open": "[", "close": "]" },
|
||||
{ "open": "{", "close": "}" },
|
||||
{ "open": "\"", "close": "\"", "notIn": ["string", "comment"] },
|
||||
{ "open": "/*", "close": " */", "notIn": ["string"] }
|
||||
],
|
||||
"surroundingPairs": [
|
||||
["(", ")"],
|
||||
["[", "]"],
|
||||
["{", "}"],
|
||||
["\"", "\""]
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "lucisv",
|
||||
"version": "0.62.0",
|
||||
"version": "0.63.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "lucisv",
|
||||
"version": "0.62.0",
|
||||
"version": "0.63.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "9.0.1"
|
||||
|
||||
@@ -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.62.0",
|
||||
"version": "0.63.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -208,7 +208,8 @@
|
||||
"extensions": [
|
||||
".v",
|
||||
".vh"
|
||||
]
|
||||
],
|
||||
"configuration": "./language-configuration.json"
|
||||
},
|
||||
{
|
||||
"id": "systemverilog",
|
||||
@@ -219,7 +220,8 @@
|
||||
"extensions": [
|
||||
".sv",
|
||||
".svh"
|
||||
]
|
||||
],
|
||||
"configuration": "./language-configuration.json"
|
||||
}
|
||||
],
|
||||
"grammars": [
|
||||
|
||||
+10
-5
@@ -197,9 +197,11 @@ server.stdin.end(
|
||||
params: { textDocument: { uri }, options: { tabSize: 2, insertSpaces: true } },
|
||||
}),
|
||||
// Multi-range formatting (LSP 3.18): two ranges, one round trip. Lines 2
|
||||
// and 8 of SOURCE (0-based 1 and 7) are `wire a;` and `initial fork`; only
|
||||
// the first moves under `indent = 4`, so the answer proves both that the
|
||||
// request is served and that it left the range between them alone.
|
||||
// and 8 of SOURCE (0-based 1 and 7) are `wire a;` and `initial fork`. Each
|
||||
// named block is laid out where it stands (selection formatting keeps a
|
||||
// block's own leading whitespace): the wire is already laid out, the fork
|
||||
// is re-laid under `indent = 4` from its two written spaces, and the
|
||||
// `initial begin` between them keeps its bytes.
|
||||
frame({
|
||||
jsonrpc: '2.0',
|
||||
id: 7,
|
||||
@@ -389,8 +391,11 @@ server.on('close', (code) => {
|
||||
fail(`expected one edit from rangesFormatting, got ${JSON.stringify(ranged.result)}`);
|
||||
}
|
||||
const partial = ranged.result[0].newText;
|
||||
if (!partial.includes('\n wire a;')) {
|
||||
fail(`the named line was not laid out:\n${partial}`);
|
||||
if (!partial.includes('\n initial\n fork\n c = 1;\n join\n')) {
|
||||
fail(`the named block was not laid out at its own indentation:\n${partial}`);
|
||||
}
|
||||
if (!partial.includes('\n wire a;')) {
|
||||
fail(`a named line must keep the indentation it was written at:\n${partial}`);
|
||||
}
|
||||
if (!partial.includes('\n initial begin')) {
|
||||
fail(`a line no range named must keep its own bytes:\n${partial}`);
|
||||
|
||||
Reference in new issue
Block a user