Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move
TODO §53.1 (docs/features/extract-inline-module), the fourth §8
refactoring; §53.2 inline module is unstarted and runs as its own lane.
`vlog_refactor::extract` (region, flow, boundary, render): a selection
of whole module items becomes a new module — a name declared outside
and read inside is an `input`, written inside an `output` (assign and
procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`,
an initialiser, an output/inout connection through the index), written
on both sides refused; parameters passed through `#(.P(P))`, used
imports copied, the port's type taken from the declaration's own text;
the selection replaced by an instantiation rendered from the new
module's text. Forty-three refusal sentences. `RefactorEdit::created`;
the server emits `CreateFile` document changes when the client reads
both halves of the capability, else writes the module below its source;
`refactor.extract` action carrying `lucisv.extractModule [uri, range,
name]`, and a name prompt in the VS Code extension through the language
client's middleware.
The verifier's never-dropped ledger follows the move (review rework of
QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece
deleted inside the moved region must land exactly once in the file the
move names, a deletion outside the region stays an ordinary deletion,
four equations, twelve attack pairs through the production entry;
`check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface`
and `program` bodies are refused (one AST node, gated on `kw`). QA's
re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is
filed as topo §2.9-32.
Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart,
spi_host,hmac}` 5 / 5, the unresolved-name census held for every
accepted extraction. 0 of 820 corpus files differ from 0.46.0.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
e6eaf53c35
commit
acf20f7e62
36 files changed
+6365
-669
No files matched your search
@@ -710,7 +710,7 @@ section only tracks the milestones.
|
||||
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
(the define-table README's promised follow-up); version 0.5.0 with a
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (extract module, inline, ~~`.*` expansion~~, ~~ANSI
|
||||
- [ ] Backlog (~~extract module~~, inline, ~~`.*` expansion~~, ~~ANSI
|
||||
conversion~~, ~~organize imports~~, …) — triaged in the umbrella README after M5.
|
||||
**`.*` expansion shipped 2026-09-05 (§50,
|
||||
`docs/features/expand-wildcard/README.md`)**: the wildcard written out as
|
||||
@@ -743,6 +743,21 @@ section only tracks the milestones.
|
||||
holding a macro call or a `` `include ``**, which lucisv refuses to judge at
|
||||
all: 32 of the corpus's 40 multi-import scopes and 33 of 33 OpenTitan UVM env
|
||||
packages.
|
||||
**Extract module shipped 2026-09-05 (§53.1,
|
||||
`docs/features/extract-inline-module/README.md`)**: a selection of whole
|
||||
module items becomes a module of its own, with ports and parameters inferred
|
||||
from the dataflow across the boundary, the `import`s it needs carried across,
|
||||
and the instantiation that replaces it rendered from the new module's own
|
||||
text — into a file beside its own where the editor can create one, below the
|
||||
module it came from where it cannot. `refactor.extract` plus
|
||||
`lucisv.extractModule`, whose name comes from an input box the VS Code
|
||||
extension puts in front of it. **Inline module (§53.2) is not started**, so
|
||||
the backlog line above keeps it. Extract leaves four things behind, added to
|
||||
this backlog: **a task or function used on both sides** of the selection,
|
||||
which would have to move or be duplicated; **a hierarchical reference**
|
||||
crossing the boundary, which no port can carry; **an `initial`/`final`
|
||||
block**, whose meaning is when it runs; and **an unpacked-array or
|
||||
interface-typed name** crossing, which the port renderer will not write.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
@@ -4625,8 +4640,10 @@ lead, a release every two or three sections:
|
||||
0.44.0 → §47 `DataType` spans, retire `scan.rs` (topo 2) → §48 package
|
||||
re-exports (topo 16) → §49 cross-file instance-member tail in rename
|
||||
(topo 23) → 0.45.0 → §50 `.*` expansion → §51 non-ANSI → ANSI ports →
|
||||
0.46.0 → §52 organize imports → §53 extract / inline module → 0.47.0 →
|
||||
§54 coverage gaps L3/L6/L10 → 0.48.0. Sections after §46 are planned when
|
||||
0.46.0 → §52 organize imports → §53.1 extract module → 0.47.0 →
|
||||
**§56 DUT-centred hierarchy view (owner request 2026-09-06) → 0.48.0** →
|
||||
§53.2 inline module (its own lane; 53.1 consumed the round, as planned)
|
||||
→ §54 coverage gaps L3/L6/L10 → 0.49.0. Sections after §46 are planned when
|
||||
reached.
|
||||
|
||||
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
|
||||
@@ -5263,12 +5280,167 @@ imports copied into `M` if `M` lacks them.
|
||||
a `lucisv check --select unused-signal,undriven-net` census over the
|
||||
result is unchanged in count from the original two files.
|
||||
|
||||
- [ ] 53.1 extract: dataflow ports, parameters, imports, the new file,
|
||||
- [x] 53.1 extract: dataflow ports, parameters, imports, the new file,
|
||||
refusals, action + command + extension input box
|
||||
- [ ] 53.2 inline: substitution, prefixing, refusals, action + command
|
||||
- [ ] the extract → inline round trip pinned
|
||||
- [ ] docs; §8 lines annotated; site rows (lead)
|
||||
- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks
|
||||
- [ ] QA: dataflow direction attacked (every statement kind that writes
|
||||
— **unstarted**; §53.1 alone took the round
|
||||
- [ ] the extract → inline round trip pinned — blocked on 53.2
|
||||
- [x] docs; §8 line annotated (extract only); site rows (lead — see the
|
||||
feature README's "Docs to apply at merge")
|
||||
- [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks
|
||||
- [x] QA: dataflow direction attacked (every statement kind that writes
|
||||
a name), boundary-crossing shapes, collisions, the round trip, the
|
||||
client-capability fallback, opentitan scratch trials
|
||||
|
||||
## 54. Coverage gaps L3, L6, L10 (planned 2026-09-06) — the owner's "do all three"
|
||||
|
||||
One lane after 0.47.0, §36's protocol. Feature README:
|
||||
`docs/features/coverage-gaps-l/README.md`. Ships in 0.48.0. Every item is
|
||||
a grammar arm with its formatter twin, the snapshot + idempotency suite,
|
||||
strict/tolerant parity, and the byte-identity gates; none of these shapes
|
||||
occur in the corpus or opentitan (say so per item with the grep), so the
|
||||
acceptance is hand-written cases plus the fuzzers.
|
||||
|
||||
### 54.1 L6 — the language shapes
|
||||
|
||||
- `->>` non-blocking event trigger (`->> e;`, `->> #5 e;`, `->> @(posedge clk) e;`).
|
||||
- Stream operator `with [range]` (`{<< {a with [0:3]}}`, `[i+:4]`, `[i-:4]`).
|
||||
- Cast bases other than a name or system call: a parenthesised width
|
||||
`(W+1)'(x)`, a sized literal `4'(x)`, a type with dims `logic [3:0]'(x)`
|
||||
— the LRM's `casting_type` (§6.24.1).
|
||||
- Drive strength on a net declaration: `wire (strong0, weak1) w = a;`,
|
||||
`wire (supply0, supply1) [7:0] v;` — `DataDecl` gains the strength the way
|
||||
`ContAssign` already carries one (`parse_opt_drive_strength` exists).
|
||||
- `let` at statement position (a `let` declared inside a sequential block
|
||||
/ procedural scope, IEEE 1800 §11.13).
|
||||
- `#(min:typ:max)` clocking skew: `default input #(1:2:3) output #(2:3:4);`
|
||||
and per-signal skews.
|
||||
Each: parser arm, AST field with comment slots where a gap opens (the
|
||||
comment-slots gap fuzzer's zero-failure bar), formatter arm, cases file,
|
||||
strict/tolerant parity, `size_pins` unmoved.
|
||||
|
||||
### 54.2 L3 — `randsequence` bodies
|
||||
|
||||
`randsequence (main) main : first second; first : { $display("a"); };
|
||||
second : third | fourth := 2; …; endsequence` — a production grammar (IEEE
|
||||
1800 §18.17): productions with optional return types and arguments,
|
||||
weighted alternatives `:=`, `rand join`, `repeat`, `if`/`case`, code
|
||||
blocks, `break`/`return`. Today an opaque `Verbatim` leaf? Check
|
||||
(`grep -rn randsequence crates/vlog_parser/src`). Ruling: model the
|
||||
production list and alternatives as real nodes (a `RandSequence` statement
|
||||
with `Production { name, ret_type, args, alternatives: Vec<Alternative {
|
||||
weight, items }> }`, items being production references or a code block
|
||||
parsed as a statement block); the formatter prints one production per
|
||||
line, alternatives aligned after `:` / `|`; comment slots per production.
|
||||
Zero corpus occurrences — a pure-LRM feature; the LRM's own examples are
|
||||
the cases.
|
||||
|
||||
### 54.3 L10 — cosmetics
|
||||
|
||||
- An enum body one-lined when short: `typedef enum {A, B, C} e_t;` stays on
|
||||
one line when it fits the width and has no comments — today it always
|
||||
breaks? Confirm with a case; make the group breakable the way a port list
|
||||
is (`Doc::Group`), so long bodies still break one per line. **Byte
|
||||
identity WILL change** for corpus files with short enums: measure the
|
||||
count, list them, and the lead rules at review whether the change is
|
||||
wanted (the corpus has ibex/opentitan enums — likely dozens of files).
|
||||
- `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin ``
|
||||
column: macro statements between `_begin`/`_end` are plain macro items
|
||||
with no block for the formatter to see; a targeted rule — a macro
|
||||
statement whose name matches `uvm_object_utils_begin`/`uvm_component_utils_begin`
|
||||
opens an indent level closed by `uvm_object_utils_end`/`uvm_component_utils_end`
|
||||
— in the item/statement sequence printer, gated on exactly those names.
|
||||
Byte identity changes for UVM files that already indent them — measure
|
||||
and list.
|
||||
Both cosmetics are **off by default behind a config key** if the corpus
|
||||
count is large: `[format] enum-one-line = true|false`, `[format]
|
||||
uvm-utils-indent = true|false`, default false, so 0.48.0 changes no
|
||||
byte for anyone who does not opt in; the lead decides the defaults at
|
||||
review from the counts.
|
||||
|
||||
- [ ] 54.1 the six L6 shapes, each with cases + parity + fuzzers
|
||||
- [ ] 54.2 `randsequence` as real nodes
|
||||
- [ ] 54.3 the two cosmetics behind config keys, corpus impact measured
|
||||
- [ ] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead)
|
||||
- [ ] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys
|
||||
off); opentitan sweep unchanged
|
||||
- [ ] QA: every shape with comments in every gap; the fuzzers; the keys on
|
||||
over the corpus in a scratch copy (idempotent, comments kept)
|
||||
|
||||
## 56. DUT-centred hierarchy view (owner request 2026-09-06)
|
||||
|
||||
The next lane after 0.47.0 ships — ahead of §53.2 and §54, at the owner's
|
||||
request. One lane, §36's protocol; dev Opus 5, QA Sonnet 5. Feature README:
|
||||
`docs/features/dut-hierarchy/README.md`. Ships in 0.48.0.
|
||||
|
||||
**What the owner asked for, verbatim in substance.** A design holds many
|
||||
modules and one (or a few) is the DUT — the module that matters most. It
|
||||
usually has DV above it (a testbench that instantiates it). The hierarchy
|
||||
pane should let the user right-click any module and **star it as DUT**.
|
||||
With one DUT starred the pane shows three sections: **the DUT with its
|
||||
children** (its instance subtree, the DUT at the very top), **the DUT's
|
||||
parents** (every module that instantiates it, transitively — typically the
|
||||
DV — as a tree explored upward from the DUT), and **all other modules**
|
||||
(everything that is neither below nor above any DUT), each section
|
||||
collapsible. Two DUTs starred → five sections: DUT1 + children, DUT1
|
||||
parents, DUT2 + children, DUT2 parents, all other modules. Unstar from the
|
||||
same menu.
|
||||
|
||||
**Where it lives.** Entirely in the extension over the existing flat
|
||||
snapshot (`lucisv/moduleHierarchy`: `files`, `modules`, `instances`;
|
||||
`hierarchyModel.js::buildHierarchy` already builds the forward tree and
|
||||
chooses roots) — the server changes nothing. The reverse map (module →
|
||||
instantiating modules, via each instance's owning module) is one pass over
|
||||
the same snapshot in the model. DUT choices persist per workspace in
|
||||
`workspaceState` (a list of module names, in the order starred), the way
|
||||
the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`).
|
||||
|
||||
- **Model** (`hierarchyModel.js`): `sections(model, duts)` returning, in
|
||||
order, for each starred DUT `{ kind: 'dut', name, root }` (the DUT's
|
||||
forward subtree, exactly the node the plain view would show for it) and
|
||||
`{ kind: 'parents', name, root }` (an upward tree: the DUT as the root,
|
||||
each child a module that instantiates the parent node — with the
|
||||
instance name that does it — recursing up until a module nothing
|
||||
instantiates; cycles cut with a visited set), then
|
||||
`{ kind: 'others', roots }` = today's roots minus every module that is in
|
||||
any DUT's subtree or ancestor chain (a module both below DUT1 and above
|
||||
DUT2 appears in both DUT sections and not in others). A starred name the
|
||||
snapshot no longer holds (renamed/deleted) keeps its section with an
|
||||
empty "not in the index" row rather than vanishing silently.
|
||||
- **View** (`hierarchyView.js`): section nodes as collapsible tree items
|
||||
with icons (`debug-start`-style for a DUT, an upward arrow for parents,
|
||||
a folder for others), the DUT section expanded by default, others
|
||||
collapsed; DUT rows carry a `contextValue` so the menu shows
|
||||
"Unstar DUT" on a starred module and "Star as DUT" on any other; the
|
||||
existing search, reveal-on-open and bookmark behaviour work inside every
|
||||
section; when no DUT is starred the pane looks exactly as today (pin it
|
||||
— the snapshot-to-tree output byte-identical to the current tests).
|
||||
- **Commands + menus** (`package.json`): `lucisv.hierarchy.starDut`,
|
||||
`lucisv.hierarchy.unstarDut`, `lucisv.hierarchy.clearDuts`; `view/item/context`
|
||||
entries gated on `viewItem`; a `view/title` "Clear DUTs". Also a setting
|
||||
`lucisv.hierarchy.duts` (string array) as the second way to set them
|
||||
(a checked-in `.vscode/settings.json` for a team) — the union with the
|
||||
starred list, the setting's entries shown with a lock icon and not
|
||||
unstar-able from the menu (say so in a tooltip).
|
||||
- **Tests** (`node --test editors/vscode/*_test.js`, the existing model
|
||||
tests' harness): sections for zero, one and two DUTs on a fixture with a
|
||||
DV bench above a DUT above three leaves plus two unrelated modules; a
|
||||
module both below one DUT and above another; a cycle (`a` instantiates
|
||||
`b` instantiates `a`) in the parents walk; a starred name absent from the
|
||||
snapshot; the others section excludes exactly the right set; the plain
|
||||
view unchanged with no DUT; persistence round trip through a fake
|
||||
`workspaceState`; the setting union and lock; the menu `when` clauses.
|
||||
Manual: a checklist entry in `docs/manual-acceptance.md` (star aes in
|
||||
opentitan → three sections; star aes and hmac → five; unstar).
|
||||
- Docs: the extension README's hierarchy section, the site's editors page
|
||||
(lead applies), the feature README.
|
||||
|
||||
- [ ] 56.1 model: reverse map, `sections()`, others-exclusion, cycle cut
|
||||
- [ ] 56.2 view: section nodes, icons, context values, persistence,
|
||||
setting union
|
||||
- [ ] 56.3 commands, menus, package.json, tests, acceptance checklist row
|
||||
- [ ] docs (lead applies README/site)
|
||||
- [ ] Gates: `node --test editors/vscode/*_test.js`; vsix smoke; the plain
|
||||
view pinned unchanged
|
||||
- [ ] QA: every section shape attacked on the fixture and on opentitan
|
||||
(real snapshot, read-only); persistence; the setting; menus
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Extract a selection into a module of its own, on the wire:
|
||||
//! `textDocument/codeAction` under LSP's own `refactor.extract`, and
|
||||
//! `workspace/executeCommand` for the editors that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::extract_module`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit`, and turns its refusal into a request error.
|
||||
//!
|
||||
//! **The action carries a command, not an edit** — which is what makes it the
|
||||
//! laziest of the lot rather than merely a lazy one. Extracting needs a *name*
|
||||
//! for the new module, and LSP has no prompt: a code action can carry an
|
||||
//! `edit`, a `command`, or both, and only a command can be intercepted by a
|
||||
//! client that wants to ask the user something first. So the offer is one
|
||||
//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming
|
||||
//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code
|
||||
//! extension registers a client-side command of the same name that shows an
|
||||
//! input box and calls the server's with what the user typed, and every other
|
||||
//! client runs the command as sent and gets the default. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
//!
|
||||
//! **The new file.** A module extracted into a file of its own is a
|
||||
//! `CreateFile` resource operation, which only a client that advertises
|
||||
//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations`
|
||||
//! containing `create` can apply. That capability is read at `initialize`
|
||||
//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the
|
||||
//! choice between the two homes: a client that can create files gets `N.sv`
|
||||
//! beside `M`'s file, and every other client gets `N` written below `M` in the
|
||||
//! file it came from. The engine says which happened in its warnings.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation,
|
||||
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp,
|
||||
TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{Home, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Extract a selection into a module: `[uri, range, name]`.
|
||||
pub const EXTRACT_MODULE: &str = "lucisv.extractModule";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![EXTRACT_MODULE.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for an extraction, which is what an editor's
|
||||
/// "Refactor…" menu asks for by name.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::REFACTOR_EXTRACT
|
||||
}
|
||||
|
||||
/// The action for a selection, carrying the command that will ask for a name.
|
||||
///
|
||||
/// One parse of the buffer and nothing else: the engine's cheap gate answers
|
||||
/// "there is nothing here" for almost every selection, and where it does find
|
||||
/// something the offer is a `Command`, so no workspace is read until the user
|
||||
/// has picked the action *and* named the module.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
if doc.path.is_none() {
|
||||
// An `untitled:` buffer has no directory to put `N.sv` beside and no
|
||||
// path for the engine's file set; nothing is offered rather than
|
||||
// offered and refused.
|
||||
return Vec::new();
|
||||
}
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range).unwrap_or(Value::Null),
|
||||
Value::String(site.default_name.clone()),
|
||||
];
|
||||
let title = vlog_refactor::extract_title();
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: title.clone(),
|
||||
kind: Some(kind()),
|
||||
command: Some(Command {
|
||||
title,
|
||||
command: EXTRACT_MODULE.to_string(),
|
||||
arguments: Some(arguments),
|
||||
}),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// Run `lucisv.extractModule`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
create_files: bool,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri = argument(arguments, 0, "a document URI")?;
|
||||
let range: Range = argument(arguments, 1, "a range")?;
|
||||
let name: String = argument(arguments, 2, "a name for the new module")?;
|
||||
let doc = ws
|
||||
.document(&uri)
|
||||
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine looks up every module the selection instantiates and every
|
||||
// package it imports, so the file set is those units' own fan-out — plus
|
||||
// the new name's, so a workspace that already declares it is a workspace
|
||||
// the engine can refuse over.
|
||||
let mut units = site.units;
|
||||
units.push(name.clone());
|
||||
let files = ws.module_sources(&path, &units);
|
||||
let home = match create_files {
|
||||
true => Home::NewFile,
|
||||
false => Home::SameFile,
|
||||
};
|
||||
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// A whole extraction as a `WorkspaceEdit`.
|
||||
///
|
||||
/// `documentChanges` rather than `changes` whenever a file is created: a
|
||||
/// creation is a resource operation, and the two shapes cannot be mixed in one
|
||||
/// edit. An extraction that creates nothing goes through the ordinary
|
||||
/// `changes` map, which every client understands.
|
||||
pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<WorkspaceEdit, String> {
|
||||
if refactoring.created.is_empty() {
|
||||
return crate::ports::workspace_edit(ws, refactoring);
|
||||
}
|
||||
let mut operations: Vec<DocumentChangeOperation> = Vec::new();
|
||||
for path in &refactoring.created {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
|
||||
uri,
|
||||
options: None,
|
||||
annotation_id: None,
|
||||
})));
|
||||
}
|
||||
for (path, edits) in &refactoring.edits {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
// A file the edit creates has no text yet, and the one insertion into
|
||||
// it is at 0:0 — which is what `Positions` over an empty text says.
|
||||
let created = refactoring.created.iter().any(|created| created == path);
|
||||
let text = match created {
|
||||
true => String::new(),
|
||||
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
|
||||
};
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
|
||||
edits: edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
OneOf::Left(TextEdit {
|
||||
range: positions.range(edit.range),
|
||||
new_text: edit.new_text.clone(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}));
|
||||
}
|
||||
Ok(WorkspaceEdit {
|
||||
document_changes: Some(DocumentChanges::Operations(operations)),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn argument<T: serde::de::DeserializeOwned>(
|
||||
arguments: &[Value],
|
||||
n: usize,
|
||||
what: &str,
|
||||
) -> Result<T, String> {
|
||||
arguments
|
||||
.get(n)
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1))
|
||||
}
|
||||
|
||||
fn unaddressable(path: &std::path::Path) -> String {
|
||||
format!("lucisv could not address {} as a document; no edits were made.", path.display())
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is nothing to extract at this selection.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::Position;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_extract_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + b;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The range of `assign s = a + b;`, as the client speaks it.
|
||||
fn selection() -> Range {
|
||||
Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 19 },
|
||||
}
|
||||
}
|
||||
|
||||
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
|
||||
actions
|
||||
.into_iter()
|
||||
.filter_map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => Some(action),
|
||||
CodeActionOrCommand::Command(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = only(code_actions(&ws, &uri, selection()));
|
||||
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
|
||||
assert_eq!(action.title, "lucisv: extract selection into module…");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
|
||||
assert!(action.edit.is_none(), "the offer reads no workspace");
|
||||
let command = action.command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, EXTRACT_MODULE);
|
||||
let arguments = command.arguments.as_ref().expect("arguments");
|
||||
assert_eq!(arguments.len(), 3);
|
||||
assert_eq!(arguments[2], Value::String("top_extracted".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_covers_no_whole_item_is_offered_nothing() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let half = Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 8 },
|
||||
};
|
||||
assert!(code_actions(&ws, &uri, half).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_creates_the_new_file_for_a_client_that_can() {
|
||||
let tree = Tree::new("create");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts");
|
||||
assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}");
|
||||
let Some(DocumentChanges::Operations(ops)) = edit.document_changes else {
|
||||
panic!("a creating edit speaks documentChanges: {edit:?}")
|
||||
};
|
||||
let creates = ops
|
||||
.iter()
|
||||
.filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_))))
|
||||
.count();
|
||||
assert_eq!(creates, 1, "one file is created: {ops:?}");
|
||||
assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() {
|
||||
let tree = Tree::new("same");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("did not say it can create files")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(edit.document_changes.is_none(), "no resource operation is needed");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "one file is touched");
|
||||
assert_eq!(changes.get(&uri).expect("this file").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_extract() {
|
||||
let tree = Tree::new("refuse");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Range {
|
||||
start: Position { line: 0, character: 0 },
|
||||
end: Position { line: 0, character: 3 },
|
||||
})
|
||||
.expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_wants_all_three_of_its_arguments() {
|
||||
let tree = Tree::new("arguments");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let short = vec![serde_json::to_value(&uri).expect("uri")];
|
||||
let message = execute(&ws, &short, true).expect_err("a refusal");
|
||||
assert!(message.contains("argument 2"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_refactor_extract_is_answered() {
|
||||
let filter = [CodeActionKind::REFACTOR_EXTRACT];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod extract;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
@@ -60,11 +61,12 @@ use lsp_types::{
|
||||
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
||||
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
|
||||
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
|
||||
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability,
|
||||
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
||||
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
|
||||
TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions,
|
||||
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
@@ -128,6 +130,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
create_files: create_files_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -262,6 +265,7 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::new(code_action::FIX_ALL),
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
imports::kind(),
|
||||
extract::kind(),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
@@ -404,6 +408,7 @@ fn capabilities() -> ServerCapabilities {
|
||||
fn commands() -> Vec<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(imports::commands());
|
||||
commands.extend(extract::commands());
|
||||
commands.extend(instantiate::commands());
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
@@ -526,6 +531,32 @@ fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client can apply a `WorkspaceEdit` that **creates a file** —
|
||||
/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations`
|
||||
/// list containing `create`.
|
||||
///
|
||||
/// Both halves, because a creation is a resource operation and a resource
|
||||
/// operation can only be sent inside `documentChanges`: a client with one and
|
||||
/// not the other cannot apply the edit at all. A client that says nothing gets
|
||||
/// the extracted module written below the one it came from, in the file it
|
||||
/// came from, which needs no capability of any kind
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
fn create_files_support(params: &InitializeParams) -> bool {
|
||||
let Some(edits) = params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.workspace_edit.as_ref())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let creates = edits
|
||||
.resource_operations
|
||||
.as_ref()
|
||||
.is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create));
|
||||
edits.document_changes.unwrap_or(false) && creates
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1182,6 +1213,51 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_files_support_needs_both_halves_of_the_capability() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities,
|
||||
WorkspaceEditClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!create_files_support(&InitializeParams::default()),
|
||||
"silence means the module goes below the one it came from"
|
||||
);
|
||||
|
||||
let saying = |document_changes: Option<bool>, ops: Option<&[ResourceOperationKind]>| {
|
||||
InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
workspace_edit: Some(WorkspaceEditClientCapabilities {
|
||||
document_changes,
|
||||
resource_operations: ops.map(<[_]>::to_vec),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let create = [ResourceOperationKind::Create];
|
||||
let rename = [ResourceOperationKind::Rename];
|
||||
assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends");
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), Some(&rename))),
|
||||
"a client that can rename but not create cannot apply the creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), None)),
|
||||
"no resource operations at all is no creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(None, Some(&create))),
|
||||
"a resource operation can only be sent inside `documentChanges`"
|
||||
);
|
||||
assert!(!create_files_support(&saying(Some(false), Some(&create))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
|
||||
@@ -44,9 +44,9 @@ use serde_json::Value;
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover,
|
||||
imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection,
|
||||
signature, symbols, tokens, type_def, type_hierarchy,
|
||||
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
|
||||
hover, imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename,
|
||||
selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
impl Server {
|
||||
@@ -278,6 +278,14 @@ impl Server {
|
||||
false => imports::code_actions(&self.workspace, &uri, offset),
|
||||
});
|
||||
}
|
||||
// Extracting a selection into a module of its own. This one
|
||||
// answers for the *range*, not the cursor, and carries a
|
||||
// command rather than an edit — it needs a name for the new
|
||||
// module, and only a command can be intercepted by a client
|
||||
// that wants to ask the user for one.
|
||||
if code_action::wanted(only.as_deref(), &extract::kind()) {
|
||||
actions.extend(extract::code_actions(&self.workspace, &uri, p.range));
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// The edit for an action offered without one. An action that
|
||||
@@ -360,6 +368,22 @@ impl Server {
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
// Extracting takes the client's own capability with it: only
|
||||
// a client that can apply a `CreateFile` gets the new module
|
||||
// in a file of its own.
|
||||
if p.command == extract::EXTRACT_MODULE {
|
||||
return match extract::execute(
|
||||
&self.workspace,
|
||||
&p.arguments,
|
||||
self.abilities.create_files,
|
||||
) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
self.deliver(&p.command, edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
match ports::execute(&self.workspace, &p.command, &p.arguments) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
|
||||
@@ -111,6 +111,13 @@ pub struct ClientAbilities {
|
||||
/// which is what every client got before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
pub code_action_resolve: bool,
|
||||
/// Whether the client can apply a `WorkspaceEdit` that creates a file —
|
||||
/// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations`
|
||||
/// list containing `create`. Only then does an extracted module get a
|
||||
/// file of its own; a client that said nothing gets it written below the
|
||||
/// module it came from
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
pub create_files: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
|
||||
@@ -0,0 +1,888 @@
|
||||
//! The lexical half of the splice contract: the pieces a file is made of, the
|
||||
//! comparison that says an edit wrote exactly what it promised, and the ledger
|
||||
//! of the pieces that are never dropped.
|
||||
//!
|
||||
//! [`super::verify_splice`] and [`super::verify_move`] are the callers, and the
|
||||
//! difference between them lives here: a splice balances every never-dropped
|
||||
//! piece inside one file, while a move is allowed to carry the pieces of one
|
||||
//! region into the file that receives them — [`Transit`] is that allowance and
|
||||
//! the whole of it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
use crate::rename::display;
|
||||
use crate::TextEdit;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// lexical splice
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// One lexical piece of a file, in source order: a code token, or a comment.
|
||||
/// Comments are pieces of their own rather than trivia hanging off a token,
|
||||
/// because an insertion can legitimately move which token a comment attaches
|
||||
/// to without moving the comment itself.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Piece {
|
||||
Code(TokenKind, String),
|
||||
Comment(String),
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// How the piece is named in a refusal.
|
||||
fn describe(&self) -> String {
|
||||
match self {
|
||||
Piece::Code(_, text) => format!("the token `{text}`"),
|
||||
Piece::Comment(text) => format!("the comment `{text}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every piece of a file with the bytes it occupies, in source order.
|
||||
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
|
||||
let tokens = tokenize(text).ok()?;
|
||||
let mut out: Vec<(TextRange, Piece)> = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in &token.leading {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
if token.kind != TokenKind::Eof {
|
||||
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// One file's three streams of pieces: what it had, what it has, and what the
|
||||
/// edits themselves spell.
|
||||
pub(super) struct Split {
|
||||
old: Vec<(TextRange, Piece)>,
|
||||
new: Vec<(TextRange, Piece)>,
|
||||
written: Vec<Vec<(TextRange, Piece)>>,
|
||||
}
|
||||
|
||||
impl Split {
|
||||
/// Lex all three, or say which one lucisv could not read.
|
||||
pub(super) fn read(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<Split, String> {
|
||||
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
|
||||
return Err(format!(
|
||||
"{} would no longer lex after {what}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
};
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
|
||||
for edit in edits {
|
||||
let Some(pieces) = pieces(&edit.new_text) else {
|
||||
return Err(format!(
|
||||
"{what} would write text that does not lex; no edits were made."
|
||||
));
|
||||
};
|
||||
written.push(pieces);
|
||||
}
|
||||
Ok(Split { old, new, written })
|
||||
}
|
||||
|
||||
/// The edited file must lex to the original's pieces with the edits' own
|
||||
/// pieces written in where the edits are — and to nothing else.
|
||||
pub(super) fn positions_match(
|
||||
&self,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
|
||||
pieces
|
||||
.iter()
|
||||
.map(|(_, piece)| match piece {
|
||||
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
|
||||
Piece::Comment(text) => Piece::Comment(text.clone()),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut expected: Vec<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
for (span, piece) in &self.old {
|
||||
while let (Some(edit), Some(pieces)) = (edits.get(next), self.written.get(next)) {
|
||||
if edit.range.start > span.start {
|
||||
break;
|
||||
}
|
||||
expected.extend(clone(pieces));
|
||||
next += 1;
|
||||
}
|
||||
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)) {
|
||||
continue;
|
||||
}
|
||||
expected.push(piece.clone());
|
||||
}
|
||||
while let Some(pieces) = self.written.get(next) {
|
||||
expected.extend(clone(pieces));
|
||||
next += 1;
|
||||
}
|
||||
|
||||
let actual = clone(&self.new);
|
||||
for (n, expected) in expected.iter().enumerate() {
|
||||
match actual.get(n) {
|
||||
Some(actual) if actual == expected => {}
|
||||
Some(actual) => {
|
||||
return Err(format!(
|
||||
"{what} would write {} where {} belongs in {}; no edits were made.",
|
||||
actual.describe(),
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"{what} would lose {} in {}; no edits were made.",
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
if actual.len() > expected.len() {
|
||||
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
|
||||
return Err(format!(
|
||||
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-file contract: the never-dropped ledger, checked on the spot, and
|
||||
/// then the positional comparison. The order is the one that gives the most
|
||||
/// useful sentence — a dropped comment is said as a dropped comment rather
|
||||
/// than as a piece that went missing from position 47.
|
||||
pub(super) fn pieces_match(
|
||||
split: &Split,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let ledger = Ledger::of(split, edits, TextRange::empty(0));
|
||||
ledger.check(&display(path), what, &Tally::new())?;
|
||||
split.positions_match(edits, path, what)
|
||||
}
|
||||
|
||||
/// The range the move takes text out of file `i`, if it names that file at all:
|
||||
/// a source's own region, or the empty range that says "this one only
|
||||
/// receives". A file the move does not name has none, and keeps the per-file
|
||||
/// contract.
|
||||
pub(super) fn region_of(moving: &[(usize, TextRange)], i: usize) -> Option<TextRange> {
|
||||
moving.iter().find(|(file, _)| *file == i).map(|(_, region)| *region)
|
||||
}
|
||||
|
||||
/// Whether a piece sits inside the bytes a move takes out of its file. An
|
||||
/// empty region holds nothing: a destination has no region, and a piece that
|
||||
/// only *overlaps* a region is one the move did not wholly carry, so it is an
|
||||
/// ordinary deletion and has to be written back where it was.
|
||||
fn within(region: TextRange, span: TextRange) -> bool {
|
||||
!region.is_empty() && region.start <= span.start && span.end <= region.end
|
||||
}
|
||||
|
||||
/// The pieces an edit may never lose, gain or duplicate: a **comment**
|
||||
/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`.
|
||||
///
|
||||
/// The piece comparison above cannot see either on its own. A piece inside a
|
||||
/// deleted range disappears from *both* sides of it — from `expected`, because
|
||||
/// pieces inside an edit are skipped, and from `actual`, because it is really
|
||||
/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass
|
||||
/// unnoticed. An attribute is a code token rather than trivia, but a deletion
|
||||
/// hides it exactly the way it hides a comment, and losing one changes what a
|
||||
/// synthesizer does; so both are counted here, by exact text.
|
||||
///
|
||||
/// Three equations, over every text that appears on any side. `had` and `has`
|
||||
/// are the file's counts before and after, `gone` counts the old pieces a
|
||||
/// non-empty edit range covers, `wrote` counts the pieces lexed out of the
|
||||
/// edits' own inserted text, and `out` counts the pieces of `gone` that a move
|
||||
/// carried out of this file — zero for every file that is not the source of
|
||||
/// one, which is every file but an extraction's.
|
||||
///
|
||||
/// 1. **`has + out >= had`** — nothing is ever lost. This is the whole of
|
||||
/// invariant 3 and the only half the rule this replaced had; a file may end
|
||||
/// up short only by exactly what left through its own moved region.
|
||||
/// 2. **`wrote <= gone - out + in`**, unless the text is one a refactoring
|
||||
/// [`generated`] itself — a piece is written back *where it was deleted*,
|
||||
/// and nowhere else. This refuses a planner that takes the comment on
|
||||
/// `input a, b;` and writes it onto *both* ports (one really did, on the
|
||||
/// way — see the work log), and equally one that duplicates the text of a
|
||||
/// comment it never touched. `in` is the transit a **destination** of a
|
||||
/// move may receive and is zero everywhere else, so a deletion outside the
|
||||
/// moved region has to be written back in its own file as it always did.
|
||||
/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the
|
||||
/// edits say, transit out counted as gone and transit in as wrote. An
|
||||
/// application that grew a second copy of a comment the edits write once is
|
||||
/// masked corruption the first two equations would forgive.
|
||||
///
|
||||
/// Where each piece now *sits* is the piece comparison's business, not this
|
||||
/// one's; between them a moved comment is verified as exactly as a stationary
|
||||
/// one.
|
||||
///
|
||||
/// **A ledger is one file's**, always. [`pieces_match`] checks it with no
|
||||
/// transit at all, which is the contract every refactoring that stays inside
|
||||
/// one file has always had. [`super::verify_move`] gives the source of a move its
|
||||
/// region — so the comment carried out of `M.sv` is `out` rather than lost —
|
||||
/// and the destination the allowance to receive it, and then [`Transit`] holds
|
||||
/// the two halves to each other. See
|
||||
/// `docs/features/extract-inline-module/README.md` for the attack pairs.
|
||||
#[derive(Default)]
|
||||
struct Ledger {
|
||||
/// The pieces the file had before the edits.
|
||||
before: Tally,
|
||||
/// The pieces it has after them.
|
||||
after: Tally,
|
||||
/// The old pieces a non-empty edit range covers.
|
||||
deleted: Tally,
|
||||
/// Of those, the ones inside the region a move takes out of this file.
|
||||
out: Tally,
|
||||
/// The pieces the edits' own inserted text spells.
|
||||
writes: Tally,
|
||||
}
|
||||
|
||||
impl Ledger {
|
||||
/// Count one file's streams. `region` is the bytes a move carries out of
|
||||
/// it — empty for every file that keeps the per-file contract, and for a
|
||||
/// file that only receives.
|
||||
fn of(split: &Split, edits: &[TextEdit], region: TextRange) -> Ledger {
|
||||
let covered = |span: TextRange| {
|
||||
edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span))
|
||||
};
|
||||
let mut out = Ledger::default();
|
||||
tally_into(&mut out.before, split.old.iter().map(|(_, piece)| piece));
|
||||
tally_into(&mut out.after, split.new.iter().map(|(_, piece)| piece));
|
||||
tally_into(
|
||||
&mut out.deleted,
|
||||
split.old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece),
|
||||
);
|
||||
tally_into(
|
||||
&mut out.out,
|
||||
split
|
||||
.old
|
||||
.iter()
|
||||
.filter(|(span, _)| covered(*span) && within(region, *span))
|
||||
.map(|(_, piece)| piece),
|
||||
);
|
||||
tally_into(&mut out.writes, split.written.iter().flatten().map(|(_, piece)| piece));
|
||||
out
|
||||
}
|
||||
|
||||
/// The three equations, for this one file. `where_` names it, already
|
||||
/// quoted for a sentence; `receives` is the transit it may be handed by
|
||||
/// the rest of the move, and is empty for every file that is not a
|
||||
/// destination of one.
|
||||
fn check(&self, where_: &str, what: &str, receives: &Tally) -> Result<(), String> {
|
||||
let mut texts: Vec<&Kept> =
|
||||
self.before.keys().chain(self.after.keys()).chain(self.writes.keys()).collect();
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0);
|
||||
// `out` is a subset of `deleted`, so the subtraction cannot go under —
|
||||
// saturating rather than plain because an arithmetic panic is not a
|
||||
// refusal, and this is a safety net.
|
||||
let ordinary = |key: &Kept| count(&self.deleted, key).saturating_sub(count(&self.out, key));
|
||||
|
||||
// Three passes rather than three tests in one pass, so that the
|
||||
// sentence the user reads is the worst thing wrong with the edit
|
||||
// rather than whichever text sorted first.
|
||||
if let Some(Kept(noun, text)) = texts
|
||||
.iter()
|
||||
.find(|key| count(&self.after, key) + count(&self.out, key) < count(&self.before, key))
|
||||
{
|
||||
return Err(format!(
|
||||
"{what} would delete the {noun} `{text}` in {where_}; {noun}s are never dropped, so nothing was edited."
|
||||
));
|
||||
}
|
||||
if let Some(key) = texts.iter().find(|key| {
|
||||
count(&self.writes, key) > ordinary(key) + count(receives, key) && !generated(&key.1)
|
||||
}) {
|
||||
let Kept(noun, text) = key;
|
||||
let (gone, wrote) = (ordinary(key), count(&self.writes, key));
|
||||
let deletes = match gone {
|
||||
0 => "without deleting it".to_string(),
|
||||
gone => format!("where it deletes it {}", times(gone)),
|
||||
};
|
||||
return Err(format!(
|
||||
"{what} would write the {noun} `{text}` {} in {where_} {deletes}; {noun}s are never duplicated, so nothing was edited.",
|
||||
times(wrote)
|
||||
));
|
||||
}
|
||||
// `deleted` is a subset of `before`, so the subtraction cannot go
|
||||
// under — saturating rather than plain because an arithmetic panic is
|
||||
// not a refusal, and this is a safety net.
|
||||
let accounted = |key: &Kept| {
|
||||
count(&self.before, key).saturating_sub(count(&self.deleted, key))
|
||||
+ count(&self.writes, key)
|
||||
};
|
||||
if let Some(key) = texts.iter().find(|key| count(&self.after, key) != accounted(key)) {
|
||||
let Kept(noun, text) = key;
|
||||
return Err(format!(
|
||||
"{what} would leave the {noun} `{text}` in {where_} {}, where its edits account for it {}; nothing was edited.",
|
||||
times(count(&self.after, key)),
|
||||
times(accounted(key))
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many more of a piece this file's edits write than they delete —
|
||||
/// what a destination of a move has to have received.
|
||||
fn gained(&self, key: &Kept) -> i64 {
|
||||
let count = |tally: &Tally| tally.get(key).copied().unwrap_or(0) as i64;
|
||||
count(&self.writes) - count(&self.deleted)
|
||||
}
|
||||
}
|
||||
|
||||
/// The files a move names, and the never-dropped pieces travelling between
|
||||
/// them: a **source** loses the pieces inside its own region, and a
|
||||
/// **destination** — a file the move names with an empty range — is the only
|
||||
/// place they may land.
|
||||
///
|
||||
/// This is the whole of the widening [`super::verify_move`] exists for, and
|
||||
/// the whole of what it is allowed to forgive: the allowance is bound to the
|
||||
/// bytes that move, so a piece deleted anywhere else in one of these files is
|
||||
/// an ordinary deletion its own ledger holds it to.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Transit {
|
||||
files: Vec<Moved>,
|
||||
}
|
||||
|
||||
/// One file of a move: what a refusal calls it, whether it receives rather
|
||||
/// than sends, and its own ledger.
|
||||
struct Moved {
|
||||
where_: String,
|
||||
receives: bool,
|
||||
ledger: Ledger,
|
||||
}
|
||||
|
||||
impl Transit {
|
||||
/// Take one file's counts, with the region the move carries text out of.
|
||||
pub(super) fn add(
|
||||
&mut self,
|
||||
where_: &str,
|
||||
region: TextRange,
|
||||
split: &Split,
|
||||
edits: &[TextEdit],
|
||||
) {
|
||||
self.files.push(Moved {
|
||||
where_: where_.to_string(),
|
||||
receives: region.is_empty(),
|
||||
ledger: Ledger::of(split, edits, region),
|
||||
});
|
||||
}
|
||||
|
||||
/// The three equations per file — the destinations, and only they, holding
|
||||
/// the transit as their allowance — and then rule 4 over the move whole.
|
||||
pub(super) fn check(&self, what: &str) -> Result<(), String> {
|
||||
let mut sent = Tally::new();
|
||||
for file in &self.files {
|
||||
for (key, n) in &file.ledger.out {
|
||||
*sent.entry(key.clone()).or_insert(0) += n;
|
||||
}
|
||||
}
|
||||
let nothing = Tally::new();
|
||||
for file in &self.files {
|
||||
let receives = match file.receives {
|
||||
true => &sent,
|
||||
false => ¬hing,
|
||||
};
|
||||
file.ledger.check(&file.where_, what, receives)?;
|
||||
}
|
||||
self.lands(&sent, what)
|
||||
}
|
||||
|
||||
/// Rule 4: what left a region has to land, exactly once in total, in the
|
||||
/// files the move named as destinations. Rule 2 lets each destination
|
||||
/// receive the transit; this is what says the move as a whole received it
|
||||
/// once — two destinations that each write the comment are two comments.
|
||||
fn lands(&self, sent: &Tally, what: &str) -> Result<(), String> {
|
||||
let names = |receives: bool| -> Vec<String> {
|
||||
self.files.iter().filter(|f| f.receives == receives).map(|f| f.where_.clone()).collect()
|
||||
};
|
||||
let mut texts: Vec<&Kept> = sent.keys().collect();
|
||||
texts.sort_unstable();
|
||||
for key in texts {
|
||||
let out = sent.get(key).copied().unwrap_or(0);
|
||||
let landed: i64 =
|
||||
self.files.iter().filter(|f| f.receives).map(|f| f.ledger.gained(key)).sum();
|
||||
if landed == out as i64 {
|
||||
continue;
|
||||
}
|
||||
let Kept(noun, text) = key;
|
||||
let rule = match landed < out as i64 {
|
||||
true => format!("{noun}s are never dropped"),
|
||||
false => format!("{noun}s are never duplicated"),
|
||||
};
|
||||
let (sources, destinations) = (names(false), names(true));
|
||||
let landing = match landed > 0 {
|
||||
true => format!("{} into {}", times(landed as usize), and_list(&destinations)),
|
||||
false => "nowhere".to_string(),
|
||||
};
|
||||
return Err(format!(
|
||||
"{what} would move the {noun} `{text}` out of {} {} and write it back {landing}; {rule}, so nothing was edited.",
|
||||
and_list(&sources),
|
||||
times(out)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One never-dropped piece, keyed for counting: the noun a refusal calls it by
|
||||
/// (`comment` or `attribute`) and its exact text.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct Kept(&'static str, String);
|
||||
|
||||
type Tally = HashMap<Kept, usize>;
|
||||
|
||||
/// How many of each never-dropped piece a stream of pieces holds. Every other
|
||||
/// piece is a code token the comparison above already pins position by
|
||||
/// position, so it is not counted here.
|
||||
fn tally_into<'p>(out: &mut Tally, pieces: impl Iterator<Item = &'p Piece>) {
|
||||
for piece in pieces {
|
||||
let key = match piece {
|
||||
Piece::Comment(text) => Kept("comment", text.clone()),
|
||||
Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()),
|
||||
Piece::Code(..) => continue,
|
||||
};
|
||||
*out.entry(key).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The comments a refactoring writes itself rather than moves, which it may
|
||||
/// therefore write however many times it needs and even where the file already
|
||||
/// has one. `add_port` and `propagate_ports` both leave
|
||||
/// `/* TODO: connect */` at a connection they cannot name a signal for, and a
|
||||
/// module gains its ports one at a time — so the second addition to a file
|
||||
/// finds the first one's placeholder already sitting there. Everything else a
|
||||
/// refactoring writes has to be a piece it is deleting somewhere else.
|
||||
fn generated(text: &str) -> bool {
|
||||
text == "/* TODO: connect */"
|
||||
}
|
||||
|
||||
/// A count, in prose, so a refusal reads like a sentence.
|
||||
fn times(n: usize) -> String {
|
||||
match n {
|
||||
0 => "never".to_string(),
|
||||
1 => "once".to_string(),
|
||||
2 => "twice".to_string(),
|
||||
n => format!("{n} times"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
|
||||
/// overlap nothing: they replace no text, so they delete nothing.
|
||||
pub(super) fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/// A list of file names as a sentence reads them: `a.sv`, `a.sv` and `b.sv`,
|
||||
/// `a.sv`, `b.sv` and `c.sv`.
|
||||
fn and_list(names: &[String]) -> String {
|
||||
let quoted: Vec<String> = names.iter().map(|name| format!("`{name}`")).collect();
|
||||
match quoted.split_last() {
|
||||
None => "no files".to_string(),
|
||||
Some((last, [])) => last.clone(),
|
||||
Some((last, head)) => format!("{} and {last}", head.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
|
||||
/// The per-file splice contract, over texts — one lex plus the production
|
||||
/// [`super::pieces_match`], so every attack below asks the real question.
|
||||
fn pieces_match(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let split = Split::read(before, after, edits, path, what)?;
|
||||
super::pieces_match(&split, edits, path, what)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the splice verifier, and the attacks on it
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A module whose port list is one per line, with a comment on each port —
|
||||
/// the shape every one of the attacks below tries to damage.
|
||||
const PORTS: &str =
|
||||
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
|
||||
|
||||
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
|
||||
/// comment and the new port after it.
|
||||
fn add_edits() -> Vec<TextEdit> {
|
||||
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
|
||||
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
|
||||
TextEdit {
|
||||
range: TextRange::empty(after_comment),
|
||||
new_text: "\n input logic [7:0] cfg".into(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn splice_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_splice_the_engine_actually_produces_verifies() {
|
||||
let honest = apply(PORTS, &add_edits());
|
||||
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
|
||||
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
|
||||
// `,` nobody will ever see.
|
||||
let corrupted = PORTS
|
||||
.replace("// the clock", "// the clock,")
|
||||
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
|
||||
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
|
||||
// The same tokens, spliced one port earlier: every piece is accounted
|
||||
// for, but not in the order the edits promised.
|
||||
let corrupted = apply(PORTS, &add_edits())
|
||||
.replace("input clk,", "input clk, input logic [7:0] cfg,")
|
||||
.replace(",\n input logic [7:0] cfg\n)", "\n)");
|
||||
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_dropped_a_comment_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
|
||||
let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_inside_a_string_is_rejected() {
|
||||
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
|
||||
let at = text.find("hello").expect("string") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
|
||||
let corrupted = apply(text, &edits);
|
||||
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
|
||||
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_would_swallow_a_comment_is_refused() {
|
||||
// The one rule the piece comparison cannot see on its own: a comment
|
||||
// inside a deleted range disappears from *both* sides.
|
||||
let start = PORTS.find("input rst").expect("rst") as u32;
|
||||
let end = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(PORTS, &edits);
|
||||
let outcome =
|
||||
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
|
||||
let message = outcome.expect_err("a deleted comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_whose_result_does_not_lex_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4)
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// 2026-09-05: `comments_kept` replaced "no deletion may cover a comment",
|
||||
// so that `ports::ansi` can move a body declaration's comment onto the
|
||||
// ANSI port that declaration becomes. Every attack below is a crafted
|
||||
// (input, corrupted output) pair the relaxation could plausibly forgive.
|
||||
|
||||
/// A Verilog-2001 header whose two declarations each carry a comment —
|
||||
/// the shape the ANSI conversion has to move a comment out of.
|
||||
const MOVED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n";
|
||||
|
||||
/// The edits `convert_to_ansi` really produces for `MOVED`.
|
||||
fn move_edits() -> Vec<TextEdit> {
|
||||
let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())];
|
||||
let at = MOVED.find("module m").expect("header") as u32;
|
||||
let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at)
|
||||
.expect("the conversion the attacks corrupt");
|
||||
edit.edits.into_iter().next().expect("one file").1
|
||||
}
|
||||
|
||||
fn move_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(
|
||||
MOVED,
|
||||
corrupted,
|
||||
&move_edits(),
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_moved_comments_the_engine_actually_writes_verify() {
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
assert_eq!(move_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}");
|
||||
assert!(honest.contains("input a, // the note"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() {
|
||||
// The exact hole the character budget exists for: one of the two
|
||||
// `// the note`s is dropped, and a search for its text still finds
|
||||
// the other one.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1);
|
||||
let message = move_attack(&corrupted).expect_err("one comment short is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() {
|
||||
// Same character count, different text: the budget alone would
|
||||
// forgive this one, and the per-comment search does not.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_shortened_a_comment_is_rejected() {
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_left_the_comment_where_it_was_is_rejected() {
|
||||
// The deletion really deleted, but the comment was written back into
|
||||
// the *body* rather than into the header: every comment is still
|
||||
// there, and the piece order is not what the edits promised.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let corrupted = honest
|
||||
.replace("input a, // the note", "input a,")
|
||||
.replace("endmodule", "// the note\nendmodule");
|
||||
// `never_dropped` passes this one: every count is equal on both sides
|
||||
// (the comment really was deleted and really was written back once).
|
||||
// The *piece comparison* is the guard, because where a comment lands
|
||||
// is bound to where the edits put it — which is also the answer to
|
||||
// "a comment deleted here and written back somewhere unrelated".
|
||||
let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal");
|
||||
assert!(message.contains("where the comment `// the note` belongs"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() {
|
||||
// The bug this half of the rule was added for, reproduced as the edits
|
||||
// that caused it: one declaration declares two ports, and its comment
|
||||
// is written onto *both*. Nothing is dropped, and the piece comparison
|
||||
// cannot object — it checks the edits against themselves, and the
|
||||
// duplicate is in the edits. Only counting the file's comments sees it.
|
||||
const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" input a,"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a doubled comment is a refusal");
|
||||
assert!(message.contains("would write the comment"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() {
|
||||
// The old rule's own case, restated: no edit writes the comment, so
|
||||
// the relaxation must not reach it.
|
||||
let start = MOVED.find("input a;").expect("a") as u32;
|
||||
let end = MOVED.find("\n output").expect("output") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(MOVED, &edits);
|
||||
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a deleted comment nothing writes back is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 2026-09-05 rework: the duplication half, the equation, and attributes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() {
|
||||
// QA's V-1 pair. Nothing deletes — or even overlaps — the body's own
|
||||
// `// shared`, and two pure insertions each write it again. Every
|
||||
// count only grows, so "before is a subset of after" forgives it, and
|
||||
// the piece comparison cannot object because the duplicates are in the
|
||||
// edits. Only `wrote <= gone` sees it.
|
||||
const SHARED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: " // shared".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: " // shared".into() },
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a duplicated comment is a refusal");
|
||||
assert!(message.contains("comments are never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() {
|
||||
// The whitelist, and the whole of it. `add_port` and
|
||||
// `propagate_ports` write `/* TODO: connect */` themselves, and a
|
||||
// module gains its ports one at a time — so the second addition to a
|
||||
// file finds the first one's placeholder already sitting there and
|
||||
// writes another. `wrote > gone` with nothing deleted, and legitimate.
|
||||
let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n";
|
||||
let at = source.find("))").expect("list") as u32 + 1;
|
||||
let edits = vec![TextEdit {
|
||||
range: TextRange::empty(at),
|
||||
new_text: ", .b(/* TODO: connect */)".into(),
|
||||
}];
|
||||
let spliced = apply(source, &edits);
|
||||
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
|
||||
let outcome =
|
||||
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
|
||||
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() {
|
||||
// Masked corruption of the third kind: the edits are honest — they
|
||||
// delete both `// the note`s and write both back — and the *applied*
|
||||
// text carries a third. Neither "nothing is lost" nor "written back
|
||||
// where it was deleted" can see that; only the equation can.
|
||||
let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule");
|
||||
let message = move_attack(&corrupted).expect_err("an invented copy is a refusal");
|
||||
assert!(message.contains("where its edits account for it"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() {
|
||||
// A `//` is only a comment where the lexer says it is. Written back
|
||||
// inside a string literal, or swallowed into the comment next to it,
|
||||
// the text is present in the file and absent from its pieces — which
|
||||
// is exactly the substring search this rule refuses to be.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let in_string = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("endmodule", " initial $display(\"// the note\");\nendmodule");
|
||||
let message = move_attack(&in_string).expect_err("a string is not a comment");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
|
||||
let nested = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("// the note", "// the note // the note");
|
||||
let message = move_attack(&nested).expect_err("one comment is not two");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
/// A body declaration carrying an attribute instance. `Item.span` covers
|
||||
/// the `(* keep *)`, so a deletion hides it from *both* sides of the piece
|
||||
/// comparison exactly the way it hides a comment — QA's finding V-2.
|
||||
const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n";
|
||||
|
||||
/// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus
|
||||
/// whatever `written` says) before the header name, and the whole body
|
||||
/// declaration gone.
|
||||
fn attribute_edits(written: &str) -> Vec<TextEdit> {
|
||||
let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" (* keep *)"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
|
||||
let corrupted = apply(ATTRIBUTED, edits);
|
||||
pieces_match(
|
||||
ATTRIBUTED,
|
||||
&corrupted,
|
||||
edits,
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_an_attribute_is_rejected() {
|
||||
// The planner refuses this one first (`ports::ansi::attributes_clear`,
|
||||
// pinned in `tests/ansi.rs`); this is the verifier saying so a second
|
||||
// time, from the edits alone, for whatever writes them next.
|
||||
let message = attribute_attack(&attribute_edits("input "))
|
||||
.expect_err("a dropped attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
assert!(message.contains("`(* keep *)`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_moves_an_attribute_verifies() {
|
||||
// What the refusal above is protecting: an edit that really does carry
|
||||
// the attribute over is not what this rule is for.
|
||||
let edits = attribute_edits("(* keep *) input ");
|
||||
assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute");
|
||||
assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_rewrote_an_attribute_is_rejected() {
|
||||
// `(* keep *)` and `(* keep=1 *)` are not the same instruction to a
|
||||
// synthesizer, and an attribute is matched by exact text.
|
||||
let message = attribute_attack(&attribute_edits("(* keep=1 *) input "))
|
||||
.expect_err("a rewritten attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,469 @@
|
||||
//! Which names cross the selection's boundary, and what the new module's
|
||||
//! header is therefore made of.
|
||||
//!
|
||||
//! `flow` says what is *done* to each name on each side; this says what each
|
||||
//! crossing name **becomes** — a port, a parameter, a copied `import`, or a
|
||||
//! refusal. Three closures run here, and they are one closure really: the
|
||||
//! signals the selection reads and drives, the parameters they and their own
|
||||
//! types depend on, and the imports the whole of that needs to resolve.
|
||||
//!
|
||||
//! The last of the three is the subtle one. What the new module has to be able
|
||||
//! to resolve is not "the names the selection writes down" but that *plus the
|
||||
//! type names of its own header* — a port declared `input logic [N-1:0] a`
|
||||
//! names `N` even though no statement in the selection does, and a port typed
|
||||
//! `word_t` needs whatever import supplied it. Both were found by the corpus
|
||||
//! and opentitan trials rather than by reasoning; see the feature README's
|
||||
//! work log.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{ItemKind, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
|
||||
|
||||
use crate::rename::display;
|
||||
|
||||
use super::flow;
|
||||
use super::region::Region;
|
||||
use super::render::{self, Param, Port};
|
||||
use super::{count, escaped, header_names, inside, inside_module, lost_name};
|
||||
use super::{outside_module, outside_module_member};
|
||||
use super::{slice, unmovable};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the boundary
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Everything that crosses the selection's boundary, classified.
|
||||
pub(super) struct Crossing {
|
||||
pub(super) ports: Vec<Port>,
|
||||
pub(super) params: Vec<Param>,
|
||||
pub(super) imports: Vec<String>,
|
||||
}
|
||||
|
||||
impl Crossing {
|
||||
pub(super) fn read(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
flow: &flow::Flow,
|
||||
packages: &[(String, TextRange)],
|
||||
new_file: bool,
|
||||
) -> Result<Crossing, String> {
|
||||
let mut ports: Vec<(TextRange, Port)> = Vec::new();
|
||||
let mut params: Vec<(TextRange, Param)> = Vec::new();
|
||||
let module = region.module_name().to_string();
|
||||
let mut wanted: Vec<String> = Vec::new();
|
||||
// Names a `package` of this file declares. `N` reaches one the way
|
||||
// `M` does — through a qualified spelling, or through an import of
|
||||
// that package which the new module is given a copy of.
|
||||
let mut from_package: Vec<(String, String)> = Vec::new();
|
||||
|
||||
for (n, symbol) in semantics.symbols().iter().enumerate() {
|
||||
let sides = flow.sides(SymbolId(n as u32));
|
||||
let declared_inside = inside(region, symbol.name_span);
|
||||
if declared_inside {
|
||||
if sides.used_outside() {
|
||||
return Err(escaped(&symbol.name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !sides.used_inside() {
|
||||
continue;
|
||||
}
|
||||
// A module, an interface and a package are visible from every
|
||||
// file of the design, so one declared beside `M` is one `N` can
|
||||
// reach too — they never become ports and never refuse.
|
||||
if matches!(
|
||||
symbol.kind,
|
||||
SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if !inside_module(region, symbol.name_span) {
|
||||
// Not a port: a name the module itself does not declare is
|
||||
// one the new module reaches the way `M` did, or one `visible`
|
||||
// below refuses because a file of its own would not see it.
|
||||
if let Some(package) = package_of(packages, symbol.name_span) {
|
||||
from_package.push((package.to_string(), symbol.name.clone()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match symbol.kind {
|
||||
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var => {
|
||||
let dir = direction(&symbol.name, sides)?;
|
||||
let Some(site) = render::site_of(region.module, &symbol.name) else {
|
||||
return Err(lost_name(&symbol.name));
|
||||
};
|
||||
let port = render::port(text, &module, &symbol.name, &site, dir)?;
|
||||
ports.push((symbol.name_span, port));
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::LocalParam => wanted.push(symbol.name.clone()),
|
||||
kind => return Err(unmovable(&symbol.name, &module, kind)),
|
||||
}
|
||||
}
|
||||
|
||||
// A **port's own type** may name a parameter — `input logic [N-1:0] a`
|
||||
// — and that parameter crosses the boundary as squarely as one the
|
||||
// selection reads, or the new module's header names nothing. So does
|
||||
// a parameter's type, and a parameter's default; the three are one
|
||||
// closure, run below until nothing new is wanted.
|
||||
let declared = declarations(semantics, region);
|
||||
for (_, port) in &ports {
|
||||
for word in &port.names {
|
||||
depends(&declared, &module, &port.name, word, &mut wanted)?;
|
||||
}
|
||||
}
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(name) = wanted.pop() {
|
||||
if seen.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
let Some(site) = render::site_of(region.module, &name) else {
|
||||
return Err(lost_name(&name));
|
||||
};
|
||||
let param = render::param(text, &module, &name, &site)?;
|
||||
for word in ¶m.names {
|
||||
depends(&declared, &module, &name, word, &mut wanted)?;
|
||||
}
|
||||
let span = span_of(semantics, region, &name);
|
||||
params.push((span, param));
|
||||
seen.push(name);
|
||||
}
|
||||
|
||||
ports.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
params.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
let needed = needed(text, semantics, flow, &ports, ¶ms);
|
||||
visible(text, semantics, region, packages, &needed, &module, new_file)?;
|
||||
let imports = imports(semantics, region, packages, &needed);
|
||||
reachable(text, &needed, &from_package, &imports)?;
|
||||
Ok(Crossing {
|
||||
ports: ports.into_iter().map(|(_, port)| port).collect(),
|
||||
params: params.into_iter().map(|(_, param)| param).collect(),
|
||||
imports,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn warnings(
|
||||
&self,
|
||||
new_name: &str,
|
||||
created: &Option<PathBuf>,
|
||||
file: &Path,
|
||||
) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
out.push(match created {
|
||||
Some(path) => format!(
|
||||
"`{new_name}` was written to a new file, `{}`.",
|
||||
display(path)
|
||||
),
|
||||
None => format!(
|
||||
"`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.",
|
||||
display(file)
|
||||
),
|
||||
});
|
||||
out.push(format!(
|
||||
"lucisv gave `{new_name}` {} and {} from the names the selection reads and drives; check the directions before you rely on them.",
|
||||
count(self.ports.len(), "port"),
|
||||
count(self.params.len(), "parameter"),
|
||||
));
|
||||
if !self.imports.is_empty() {
|
||||
out.push(format!(
|
||||
"`{new_name}` imports {}, which the selection needed.",
|
||||
self.imports.iter().map(|path| format!("`{path}`")).collect::<Vec<_>>().join(", ")
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction one crossing signal's port gets, or the sentence saying why
|
||||
/// lucisv will not decide.
|
||||
fn direction(name: &str, sides: flow::Sides) -> Result<&'static str, String> {
|
||||
if sides.inside_unknown {
|
||||
return Err(format!(
|
||||
"the selection passes `{name}` to a task or function, and only that routine's declaration says whether it is an argument in or out; lucisv will not guess a port direction from it."
|
||||
));
|
||||
}
|
||||
if !sides.inside_write {
|
||||
return Ok("input");
|
||||
}
|
||||
if sides.outside_write {
|
||||
return Err(format!("`{name}` is driven on both sides of the selection."));
|
||||
}
|
||||
if sides.outside_unknown {
|
||||
return Err(format!(
|
||||
"the selection drives `{name}`, and something outside it passes the same name to a task or function, which may drive it too; lucisv will not make it an output over that."
|
||||
));
|
||||
}
|
||||
Ok("output")
|
||||
}
|
||||
|
||||
/// One identifier written in a header lucisv is about to move: a parameter it
|
||||
/// has to carry across too, a keyword or a package name it can ignore, or a
|
||||
/// declaration of `M`'s that a header in another module could not name.
|
||||
fn depends(
|
||||
declared: &HashMap<&str, SymbolKind>,
|
||||
module: &str,
|
||||
owner: &str,
|
||||
word: &str,
|
||||
wanted: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
match declared.get(word) {
|
||||
// A keyword (`logic`, `int`), a system function, or a name that comes
|
||||
// from somewhere `visible` and `reachable` judge on their own terms.
|
||||
None => Ok(()),
|
||||
Some(SymbolKind::Param | SymbolKind::LocalParam) => {
|
||||
wanted.push(word.to_string());
|
||||
Ok(())
|
||||
}
|
||||
Some(_) => Err(header_names(module, owner, word)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name the module's own scope declares, with its kind — what a
|
||||
/// parameter default is checked against.
|
||||
fn declarations<'s>(semantics: &'s Semantics, region: &Region<'_>) -> HashMap<&'s str, SymbolKind> {
|
||||
semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|symbol| inside_module(region, symbol.name_span))
|
||||
.map(|symbol| (symbol.name.as_str(), symbol.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the module declares `name`, for ordering a header the way the source
|
||||
/// orders its declarations.
|
||||
fn span_of(semantics: &Semantics, region: &Region<'_>, name: &str) -> TextRange {
|
||||
semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.find(|symbol| symbol.name == name && inside_module(region, symbol.name_span))
|
||||
.map_or(TextRange::empty(0), |symbol| symbol.name_span)
|
||||
}
|
||||
|
||||
/// Every name the new module has to be able to resolve for itself: the names
|
||||
/// the selection writes down, plus the type names its own header will carry.
|
||||
///
|
||||
/// A header type is matched by the *text* the declaration wrote — the port's
|
||||
/// prefix is that text — so a `word_t` in a port list is the same reference the
|
||||
/// import judgement asks about, and not a second reading of it.
|
||||
fn needed<'s>(
|
||||
text: &str,
|
||||
semantics: &'s Semantics,
|
||||
flow: &flow::Flow,
|
||||
ports: &[(TextRange, Port)],
|
||||
params: &[(TextRange, Param)],
|
||||
) -> Vec<&'s vlog_semantic::Reference> {
|
||||
let mut out: Vec<&vlog_semantic::Reference> =
|
||||
flow.inside.iter().filter_map(|n| semantics.references().get(*n)).collect();
|
||||
let header: Vec<&str> = ports
|
||||
.iter()
|
||||
.map(|(_, port)| port.prefix.as_str())
|
||||
.chain(params.iter().map(|(_, param)| param.prefix.as_str()))
|
||||
.collect();
|
||||
for reference in semantics.references() {
|
||||
let written = slice(text, reference.name_span);
|
||||
if written.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if header.iter().any(|prefix| prefix.split_whitespace().any(|word| word == written)) {
|
||||
out.push(reference);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `import` paths the new module gets: the ones written in `M` that one of
|
||||
/// the names it needs could have come through.
|
||||
fn imports(
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
packages: &[(String, TextRange)],
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
) -> Vec<String> {
|
||||
let Some(scope) = semantics
|
||||
.symbol_at(region.module.name_span.start)
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.and_then(|symbol| symbol.child_scope)
|
||||
.and_then(|id| semantics.scope(id))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for import in &scope.imports {
|
||||
let path = import.path();
|
||||
if out.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if needed.iter().any(|r| supplied_by(semantics, packages, import, r)) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a use of a name could have come through an import of `package`.
|
||||
///
|
||||
/// Two shapes, because the binder answers them differently. A package
|
||||
/// **another file** declares leaves an [`Resolution::ExternalCandidate`] whose
|
||||
/// `paths` name it; a package **this file** declares is resolved on the spot,
|
||||
/// and what says so is that the declaration sits inside that package's own
|
||||
/// item span.
|
||||
fn supplied_by(
|
||||
semantics: &Semantics,
|
||||
packages: &[(String, TextRange)],
|
||||
import: &vlog_semantic::Import,
|
||||
reference: &vlog_semantic::Reference,
|
||||
) -> bool {
|
||||
if !import.supplies(&reference.name) {
|
||||
return false;
|
||||
}
|
||||
let package = import.package.as_str();
|
||||
match &reference.resolution {
|
||||
// The binder writes the import paths it walked into `paths`, in the
|
||||
// spelling the source wrote them (`p::*`, `p::w_t`) — so the question
|
||||
// is whether this very import is one of them, not whether some path
|
||||
// happens to end in the name.
|
||||
Resolution::ExternalCandidate { paths, .. }
|
||||
| Resolution::InheritedCandidate { paths, .. } => {
|
||||
paths.iter().any(|path| *path == import.path())
|
||||
}
|
||||
Resolution::Resolved(symbol) => semantics
|
||||
.symbol(*symbol)
|
||||
.and_then(|symbol| package_of(packages, symbol.name_span))
|
||||
.is_some_and(|declared_in| declared_in == package),
|
||||
Resolution::NotFound => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name the new module needs has to be one a file of its own can see: a
|
||||
/// declaration of `M`'s own (which becomes a port or a parameter), a unit of
|
||||
/// the design (a module, an interface, a package), or a member of a package.
|
||||
///
|
||||
/// What this refuses is the rest — a `typedef`, a `localparam` or a class
|
||||
/// written at the **file scope** of `M`'s file, which is a compilation-unit
|
||||
/// declaration and reaches exactly the files that were compiled with it. It
|
||||
/// runs over the names the new module writes down *and* the type names of its
|
||||
/// own header, so a port typed with a file-scope `typedef` is refused as
|
||||
/// squarely as a body reference to one.
|
||||
fn visible(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
packages: &[(String, TextRange)],
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
module: &str,
|
||||
new_file: bool,
|
||||
) -> Result<(), String> {
|
||||
if !new_file {
|
||||
return Ok(());
|
||||
}
|
||||
for reference in needed {
|
||||
let Resolution::Resolved(id) = reference.resolution else { continue };
|
||||
let Some(symbol) = semantics.symbol(id) else { continue };
|
||||
if inside_module(region, symbol.name_span) {
|
||||
continue;
|
||||
}
|
||||
if package_of(packages, symbol.name_span).is_some() {
|
||||
continue;
|
||||
}
|
||||
if matches!(symbol.kind, SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package) {
|
||||
continue;
|
||||
}
|
||||
// A field of a struct and a signal of an interface each have a
|
||||
// declaration of their own, and naming it is not what the user needs
|
||||
// to read: what crosses the boundary is `s` or `bus`, and `f` is a
|
||||
// name of *its* type. So the head goes first when there is one.
|
||||
return Err(match access_head(text, reference.name_span) {
|
||||
Some(head) => outside_module_member(head, &symbol.name, module),
|
||||
None => outside_module(&symbol.name, module),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The head of a member access, if the reference is one: `s` in `s.f`, `bus`
|
||||
/// in `bus.data`, and `u` in `u.v.w`.
|
||||
///
|
||||
/// Read from the text rather than from the tree because that is where the
|
||||
/// question is cheap and exact: a reference's own span is the field, and what
|
||||
/// precedes it — a `.` and an identifier — is the thing the field belongs to.
|
||||
fn access_head(text: &str, span: TextRange) -> Option<&str> {
|
||||
let (mut at, mut head) = dotted_word_before(text, span.start as usize)?;
|
||||
while let Some((start, word)) = dotted_word_before(text, at) {
|
||||
at = start;
|
||||
head = word;
|
||||
}
|
||||
Some(head)
|
||||
}
|
||||
|
||||
/// The identifier written immediately before `at` and a `.`, with where it
|
||||
/// starts: `("s", …)` for `s.` and nothing at all for anything else.
|
||||
fn dotted_word_before(text: &str, at: usize) -> Option<(usize, &str)> {
|
||||
let rest = text.get(..at)?.trim_end().strip_suffix('.')?.trim_end();
|
||||
let start = rest
|
||||
.char_indices()
|
||||
.rev()
|
||||
.take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '$')
|
||||
.last()
|
||||
.map(|(i, _)| i)?;
|
||||
let word = rest.get(start..)?;
|
||||
match word.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
true => None,
|
||||
false => Some((start, word)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name a `package` of this file declares reaches the new module only if the
|
||||
/// new module can spell it: either every use writes the package out
|
||||
/// (`w_pkg::word_t`), or `M` imports it and lucisv copied that import across.
|
||||
fn reachable(
|
||||
text: &str,
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
from_package: &[(String, String)],
|
||||
imports: &[String],
|
||||
) -> Result<(), String> {
|
||||
for (package, name) in from_package {
|
||||
let unqualified = needed
|
||||
.iter()
|
||||
.filter(|reference| reference.name == *name)
|
||||
.any(|reference| !qualified(text, reference.name_span));
|
||||
if !unqualified {
|
||||
continue;
|
||||
}
|
||||
let imported = imports
|
||||
.iter()
|
||||
.any(|path| path == &format!("{package}::*") || path == &format!("{package}::{name}"));
|
||||
if !imported {
|
||||
return Err(format!(
|
||||
"the selection uses `{name}`, which `{package}` declares, without writing `{package}::` in front of it and without an `import` lucisv could carry across; write the package out, or import it where the new module can see it."
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a name is written with its package in front of it: `w_pkg::word_t`.
|
||||
fn qualified(text: &str, span: TextRange) -> bool {
|
||||
text.get(..span.start as usize).is_some_and(|head| head.trim_end().ends_with("::"))
|
||||
}
|
||||
|
||||
/// The `package` of this file whose body holds `span`, if any.
|
||||
fn package_of(packages: &[(String, TextRange)], span: TextRange) -> Option<&str> {
|
||||
packages
|
||||
.iter()
|
||||
.find(|(_, at)| at.start <= span.start && span.end <= at.end)
|
||||
.map(|(name, _)| name.as_str())
|
||||
}
|
||||
|
||||
/// Every `package` this file declares, with the bytes it occupies.
|
||||
pub(super) fn packages(tree: &SourceFile) -> Vec<(String, TextRange)> {
|
||||
tree.items
|
||||
.iter()
|
||||
.filter_map(|item| match &item.kind {
|
||||
ItemKind::Package { name, .. } => Some((name.clone(), item.span)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
//! Which names cross the selection's boundary, and in which direction.
|
||||
//!
|
||||
//! The whole of "what ports does the new module need" is here, and it is one
|
||||
//! question asked of two tables: `vlog_semantic`'s references say *which
|
||||
//! declaration* each name in the module means, and the tree says whether each
|
||||
//! use of it is a **write** or a **read**. A name declared outside the
|
||||
//! selection and used inside it becomes a port — `input` when the selection
|
||||
//! only reads it, `output` when the selection writes it.
|
||||
//!
|
||||
//! **A name is written by the selection when, and only when, it is:** the
|
||||
//! left-hand side of a continuous assignment; the left-hand side of a
|
||||
//! blocking or non-blocking assignment (or of a `for` initialiser or step, or
|
||||
//! the target of a `++`/`--`) anywhere inside an `always` block; the target of
|
||||
//! a `force`, a `release` or a `deassign`; the target of a `-> ev`; the
|
||||
//! declarator's own initialiser; or connected to an `output` or `inout` port
|
||||
//! of an instantiated module — which is a fact only that module's own
|
||||
//! declaration holds, so it is looked up through the workspace index and the
|
||||
//! extraction is **refused** when the index cannot answer. Everything else is
|
||||
//! a read. Two positions are neither, and both refuse rather than guess: an
|
||||
//! argument of a task or function call, whose direction only the routine's
|
||||
//! prototype knows, and a positional or `.*` connection, which names no port
|
||||
//! at all.
|
||||
//!
|
||||
//! Nothing here edits. It answers, or it refuses with a sentence.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Connections, Expr, ExprKind, ForStep, Instantiation, Item, ItemKind, ListElem, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Reference, Resolution, Semantics, Surface, SymbolId, SymbolKind};
|
||||
|
||||
use crate::instantiate::{instantiation_plan, module_definition};
|
||||
use crate::rename::Scope;
|
||||
|
||||
use super::region::Region;
|
||||
|
||||
/// What one use of a name is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Use {
|
||||
Read,
|
||||
Write,
|
||||
/// A position whose direction lucisv cannot know: a call argument, a
|
||||
/// connection to a port it could not read.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Everything done to one declaration, on each side of the boundary.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(super) struct Sides {
|
||||
pub(super) inside_read: bool,
|
||||
pub(super) inside_write: bool,
|
||||
pub(super) inside_unknown: bool,
|
||||
pub(super) outside_read: bool,
|
||||
pub(super) outside_write: bool,
|
||||
pub(super) outside_unknown: bool,
|
||||
}
|
||||
|
||||
impl Sides {
|
||||
pub(super) fn used_inside(&self) -> bool {
|
||||
self.inside_read || self.inside_write || self.inside_unknown
|
||||
}
|
||||
|
||||
pub(super) fn used_outside(&self) -> bool {
|
||||
self.outside_read || self.outside_write || self.outside_unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// The boundary table: what each declaration the module holds has done to it
|
||||
/// on each side of the selection, and which of the module's own references sit
|
||||
/// inside it.
|
||||
pub(super) struct Flow {
|
||||
sides: HashMap<SymbolId, Sides>,
|
||||
/// The references written inside the region, in source order.
|
||||
pub(super) inside: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
pub(super) fn sides(&self, symbol: SymbolId) -> Sides {
|
||||
self.sides.get(&symbol).copied().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify every use of every name in the module, on both sides of the
|
||||
/// selection.
|
||||
pub(super) fn read(
|
||||
scope: &Scope<'_>,
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
) -> Result<Flow, String> {
|
||||
let mut marks = Marks::default();
|
||||
marks.items(scope, region, ®ion.module.items)?;
|
||||
|
||||
// Every reference in the file, placed on its side of the boundary and
|
||||
// given the direction the tree marked its span with.
|
||||
let mut sides: HashMap<SymbolId, Sides> = HashMap::new();
|
||||
let mut inside = Vec::new();
|
||||
for (n, reference) in semantics.references().iter().enumerate() {
|
||||
let span = reference.name_span;
|
||||
let within = region.span.start <= span.start && span.end <= region.span.end;
|
||||
if within {
|
||||
inside.push(n);
|
||||
}
|
||||
let Resolution::Resolved(symbol) = reference.resolution else { continue };
|
||||
let use_ = marks.use_of(span);
|
||||
let entry = sides.entry(symbol).or_default();
|
||||
match (within, use_) {
|
||||
(true, Use::Read) => entry.inside_read = true,
|
||||
(true, Use::Write) => entry.inside_write = true,
|
||||
(true, Use::Unknown) => entry.inside_unknown = true,
|
||||
(false, Use::Read) => entry.outside_read = true,
|
||||
(false, Use::Write) => entry.outside_write = true,
|
||||
(false, Use::Unknown) => entry.outside_unknown = true,
|
||||
}
|
||||
}
|
||||
// A declarator's own initialiser writes the declaration rather than
|
||||
// referring to it, so it is not in the reference table at all.
|
||||
for (span, within) in marks.initialised.drain(..) {
|
||||
let Some(symbol) = semantics.symbol_at(span.start) else { continue };
|
||||
let entry = sides.entry(symbol).or_default();
|
||||
match within {
|
||||
true => entry.inside_write = true,
|
||||
false => entry.outside_write = true,
|
||||
}
|
||||
}
|
||||
let _ = text;
|
||||
Ok(Flow { sides, inside })
|
||||
}
|
||||
|
||||
/// Whether any reference inside the region is a **hierarchical** one whose
|
||||
/// head instance the region does not itself declare — `u_x.sig` reaching out
|
||||
/// of the selection, which lucisv will not move across a module boundary.
|
||||
///
|
||||
/// The §49 surface is what says a tail is hierarchical at all
|
||||
/// ([`Surface::Hierarchical`] is recorded exactly when the head resolved to an
|
||||
/// instance); the head is then the nearest reference before it that resolved
|
||||
/// to an [`SymbolKind::Instance`] with nothing but the dots of the path
|
||||
/// between them.
|
||||
pub(super) fn hierarchical_escape(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
) -> Option<String> {
|
||||
let refs = semantics.references();
|
||||
for reference in refs {
|
||||
let span = reference.name_span;
|
||||
if span.start < region.span.start || region.span.end < span.end {
|
||||
continue;
|
||||
}
|
||||
let Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } =
|
||||
&reference.resolution
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
match head_of(text, semantics, refs, reference) {
|
||||
// The instance the path starts at moves with the selection, so
|
||||
// the path is not crossing anything. It is the *declaration* that
|
||||
// has to move, not the mention of it.
|
||||
Some(head) if declared_inside(semantics, region, head) => continue,
|
||||
Some(head) => return Some(format!("{}.{}", head.name, reference.name)),
|
||||
None => return Some(format!("\u{2026}.{}", reference.name)),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The instance a hierarchical tail hangs off: the nearest earlier reference
|
||||
/// that resolved to an instance, with only a dotted path between the two.
|
||||
fn head_of<'r>(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
refs: &'r [Reference],
|
||||
tail: &Reference,
|
||||
) -> Option<&'r Reference> {
|
||||
let mut best: Option<&Reference> = None;
|
||||
for candidate in refs {
|
||||
if candidate.name_span.end > tail.name_span.start {
|
||||
continue;
|
||||
}
|
||||
let is_instance = candidate
|
||||
.resolved()
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.is_some_and(|symbol| symbol.kind == SymbolKind::Instance);
|
||||
if !is_instance {
|
||||
continue;
|
||||
}
|
||||
if best.is_none_or(|found| candidate.name_span.end > found.name_span.end) {
|
||||
best = Some(candidate);
|
||||
}
|
||||
}
|
||||
let head = best?;
|
||||
let between = text.get(head.name_span.end as usize..tail.name_span.start as usize)?;
|
||||
// A dotted path, index selects included: `u_a.u_b`, `u_q[0].sig`.
|
||||
let dotted = between
|
||||
.chars()
|
||||
.all(|c| c == '.' || c == '[' || c == ']' || c == ':' || c.is_alphanumeric() || c == '_');
|
||||
dotted.then_some(head)
|
||||
}
|
||||
|
||||
fn inside(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.span.start <= span.start && span.end <= region.span.end
|
||||
}
|
||||
|
||||
/// Whether the declaration a reference names is written inside the region.
|
||||
fn declared_inside(semantics: &Semantics, region: &Region<'_>, reference: &Reference) -> bool {
|
||||
reference
|
||||
.resolved()
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.is_some_and(|symbol| inside(region, symbol.name_span))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// marking the tree
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Where the tree says a name is written, and where it says lucisv cannot
|
||||
/// know. Both are sets of *name spans*, which is what lets the reference table
|
||||
/// be read straight off them.
|
||||
#[derive(Default)]
|
||||
struct Marks {
|
||||
writes: Vec<TextRange>,
|
||||
unknown: Vec<TextRange>,
|
||||
/// `(declared name's span, inside the region)` for every declarator whose
|
||||
/// own initialiser drives it.
|
||||
initialised: Vec<(TextRange, bool)>,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
fn use_of(&self, span: TextRange) -> Use {
|
||||
if self.unknown.iter().any(|marked| covers(*marked, span)) {
|
||||
return Use::Unknown;
|
||||
}
|
||||
match self.writes.contains(&span) {
|
||||
true => Use::Write,
|
||||
false => Use::Read,
|
||||
}
|
||||
}
|
||||
|
||||
fn items(
|
||||
&mut self,
|
||||
scope: &Scope<'_>,
|
||||
region: &Region<'_>,
|
||||
items: &[Item],
|
||||
) -> Result<(), String> {
|
||||
for item in items {
|
||||
self.item(scope, region, item)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn item(&mut self, scope: &Scope<'_>, region: &Region<'_>, item: &Item) -> Result<(), String> {
|
||||
match &item.kind {
|
||||
ItemKind::DataDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
if declarator.init.is_some() {
|
||||
self.initialised
|
||||
.push((declarator.name_span, inside(region, declarator.name_span)));
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::ContAssign(assign) => {
|
||||
for pair in &assign.assigns {
|
||||
self.write(&pair.lhs);
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } => self.body(stmt),
|
||||
ItemKind::Initial(stmt) | ItemKind::Final(stmt) => self.body(stmt),
|
||||
ItemKind::Function(decl) => {
|
||||
for stmt in &decl.stmts {
|
||||
self.body(stmt);
|
||||
}
|
||||
}
|
||||
ItemKind::Task(decl) => {
|
||||
for stmt in &decl.stmts {
|
||||
self.body(stmt);
|
||||
}
|
||||
}
|
||||
ItemKind::Instantiation(inst) => self.instantiation(scope, region, inst)?,
|
||||
ItemKind::GateInstantiation(gates) => {
|
||||
for instance in &gates.instances {
|
||||
for arg in &instance.args {
|
||||
self.unknown.push(arg.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(scope, region, items)?,
|
||||
ItemKind::GenBlock(block) => self.items(scope, region, &block.items)?,
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(scope, region, &gen_if.then.items)?;
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
vlog_parser::ast::GenElse::If(_, nested) => {
|
||||
self.items(scope, region, &nested.then.items)?;
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
vlog_parser::ast::GenElse::Block(block) => {
|
||||
self.items(scope, region, &block.items)?;
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => self.items(scope, region, &gen_for.body.items)?,
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
self.items(scope, region, &case_item.body.items)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every write inside one procedural block, at any statement depth.
|
||||
fn body(&mut self, stmt: &Stmt) {
|
||||
walk(stmt, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs),
|
||||
StmtKind::EventTrigger(expr) => self.write(expr),
|
||||
StmtKind::For { init, step, .. } => {
|
||||
for entry in init {
|
||||
self.write(&entry.assign.lhs);
|
||||
}
|
||||
for entry in step {
|
||||
match entry {
|
||||
ForStep::Assign(assign) => self.write(&assign.lhs),
|
||||
ForStep::Expr(expr) => match increment_target(expr) {
|
||||
Some(target) => self.write(target),
|
||||
None => self.unknown.push(expr.span),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
// `x++;` is a write; every other expression statement is a call,
|
||||
// whose arguments may be `output` arguments.
|
||||
StmtKind::ExprStmt(expr) => match increment_target(expr) {
|
||||
Some(target) => self.write(target),
|
||||
None => self.unknown.push(expr.span),
|
||||
},
|
||||
_ => {}
|
||||
});
|
||||
// A call written anywhere in the block — in a condition, on the
|
||||
// right-hand side of an assignment — passes arguments whose direction
|
||||
// only the routine's own prototype knows.
|
||||
walk(stmt, &mut |stmt| stmt_exprs(stmt, &mut |expr| self.calls(expr)));
|
||||
}
|
||||
|
||||
/// An instantiation's connections, whose direction the instantiated
|
||||
/// module's declaration holds.
|
||||
fn instantiation(
|
||||
&mut self,
|
||||
scope: &Scope<'_>,
|
||||
region: &Region<'_>,
|
||||
inst: &Instantiation,
|
||||
) -> Result<(), String> {
|
||||
let touches = inst.instances.iter().any(|instance| inside(region, instance.name_span));
|
||||
for instance in &inst.instances {
|
||||
match &instance.conns {
|
||||
Connections::Ordered(conns) => {
|
||||
if touches {
|
||||
return Err(positional(&inst.module, &instance.name));
|
||||
}
|
||||
for conn in conns {
|
||||
self.unknown.push(match conn {
|
||||
ListElem::Ok(conn) => conn.span,
|
||||
ListElem::Error(raw) => raw.span,
|
||||
});
|
||||
}
|
||||
}
|
||||
Connections::Named(conns) => {
|
||||
let ports = match touches {
|
||||
true => Some(ports_of(scope, &inst.module)?),
|
||||
false => None,
|
||||
};
|
||||
for conn in conns {
|
||||
let conn = match conn {
|
||||
ListElem::Ok(conn) => conn,
|
||||
ListElem::Error(raw) => {
|
||||
if touches {
|
||||
return Err(unreadable(&inst.module, &instance.name));
|
||||
}
|
||||
self.unknown.push(raw.span);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(ports) = ports.as_deref() else {
|
||||
self.unknown.push(conn.span);
|
||||
continue;
|
||||
};
|
||||
if conn.name == "*" {
|
||||
return Err(wildcard(&inst.module, &instance.name));
|
||||
}
|
||||
// `.p` with no expression connects the same-named
|
||||
// signal, whose own name is not written down here;
|
||||
// the connection's port name is the signal's name.
|
||||
let Some(port) = ports.iter().find(|(name, _)| *name == conn.name) else {
|
||||
return Err(no_such_port(&inst.module, &conn.name));
|
||||
};
|
||||
let Some(expr) = &conn.expr else {
|
||||
return Err(implicit(&inst.module, &instance.name, &conn.name));
|
||||
};
|
||||
match port.1.as_str() {
|
||||
"output" | "inout" => self.write(expr),
|
||||
"input" => {}
|
||||
_ => return Err(no_direction(&inst.module, &conn.name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every argument of every call in an expression, marked unknown.
|
||||
fn calls(&mut self, expr: &Expr) {
|
||||
walk_expr(expr, &mut |expr| {
|
||||
if let ExprKind::Call { args, .. } = &expr.kind {
|
||||
for arg in args {
|
||||
self.unknown.push(arg.span);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Records every name an assignment's left-hand side writes.
|
||||
fn write(&mut self, lhs: &Expr) {
|
||||
lvalue_targets(lhs, &mut self.writes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `outer` covers `inner` entirely.
|
||||
fn covers(outer: TextRange, inner: TextRange) -> bool {
|
||||
outer.start <= inner.start && inner.end <= outer.end
|
||||
}
|
||||
|
||||
/// The names one left-hand side writes. `a.b[3] = x` writes `a`, which is
|
||||
/// what resolves.
|
||||
fn lvalue_targets(expr: &Expr, out: &mut Vec<TextRange>) {
|
||||
match &expr.kind {
|
||||
ExprKind::Ident(_) => out.push(expr.span),
|
||||
ExprKind::Paren { inner, .. } => lvalue_targets(inner, out),
|
||||
ExprKind::Cast { expr, .. } => lvalue_targets(expr, out),
|
||||
ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => lvalue_targets(base, out),
|
||||
ExprKind::Member { base, .. } => lvalue_targets(base, out),
|
||||
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
|
||||
for item in items {
|
||||
lvalue_targets(&item.expr, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The target of `x++` / `x--` / `++x`, which is a write dressed as an
|
||||
/// expression.
|
||||
fn increment_target(expr: &Expr) -> Option<&Expr> {
|
||||
match &expr.kind {
|
||||
ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. }
|
||||
if op == "++" || op == "--" =>
|
||||
{
|
||||
Some(expr)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ports of an instantiated module: name and direction, read from the
|
||||
/// file the workspace index says declares it.
|
||||
fn ports_of(scope: &Scope<'_>, module: &str) -> Result<Vec<(String, String)>, String> {
|
||||
let path =
|
||||
module_definition(scope.index(), module).map_err(|_| unknown_module(module))?.to_path_buf();
|
||||
let Some(text) = scope.index_of(&path).and_then(|i| scope.text(i)) else {
|
||||
return Err(unknown_module(module));
|
||||
};
|
||||
let plan = instantiation_plan(module, text, None).map_err(|_| unknown_module(module))?;
|
||||
Ok(plan.ports.into_iter().map(|port| (port.name, port.dir)).collect())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// walks
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn walk(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) {
|
||||
f(stmt);
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
for stmt in stmts {
|
||||
walk(stmt, f);
|
||||
}
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
walk(then, f);
|
||||
if let Some(els) = els {
|
||||
walk(els, f);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for item in items {
|
||||
walk(&item.stmt, f);
|
||||
}
|
||||
}
|
||||
StmtKind::Labeled { stmt, .. } => walk(stmt, f),
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => walk(body, f),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
walk(inner, f)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then {
|
||||
walk(then, f);
|
||||
}
|
||||
if let Some(els) = els {
|
||||
walk(els, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The expressions one statement writes directly — not its children's.
|
||||
fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Assign { lhs, rhs, .. } => {
|
||||
f(lhs);
|
||||
f(rhs);
|
||||
}
|
||||
StmtKind::If { cond, .. } | StmtKind::While { cond, .. } | StmtKind::Wait { cond, .. } => {
|
||||
f(cond)
|
||||
}
|
||||
StmtKind::DoWhile { cond, .. } => f(cond),
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
f(expr);
|
||||
for item in items {
|
||||
for label in &item.labels {
|
||||
f(&label.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Repeat { count, .. } => f(count),
|
||||
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => f(expr),
|
||||
StmtKind::ForceRelease { lhs, rhs, .. } => {
|
||||
f(lhs);
|
||||
if let Some(rhs) = rhs {
|
||||
f(rhs);
|
||||
}
|
||||
}
|
||||
StmtKind::For { init, cond, step, .. } => {
|
||||
for entry in init {
|
||||
f(&entry.assign.rhs);
|
||||
}
|
||||
if let Some(cond) = cond {
|
||||
f(cond);
|
||||
}
|
||||
for entry in step {
|
||||
match entry {
|
||||
ForStep::Assign(assign) => f(&assign.rhs),
|
||||
ForStep::Expr(expr) => f(expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Return { expr: Some(expr), .. } => f(expr),
|
||||
StmtKind::Assert { cond, .. } => f(cond),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_expr(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
|
||||
f(expr);
|
||||
match &expr.kind {
|
||||
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => walk_expr(expr, f),
|
||||
ExprKind::Binary { lhs, rhs, .. } => {
|
||||
walk_expr(lhs, f);
|
||||
walk_expr(rhs, f);
|
||||
}
|
||||
ExprKind::Ternary { cond, then, els, .. } => {
|
||||
walk_expr(cond, f);
|
||||
walk_expr(then, f);
|
||||
walk_expr(els, f);
|
||||
}
|
||||
ExprKind::Call { callee, args, .. } => {
|
||||
walk_expr(callee, f);
|
||||
for arg in args {
|
||||
walk_expr(&arg.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Index { base, index, .. } => {
|
||||
walk_expr(base, f);
|
||||
walk_expr(index, f);
|
||||
}
|
||||
ExprKind::Range { base, msb, lsb, .. } => {
|
||||
walk_expr(base, f);
|
||||
walk_expr(msb, f);
|
||||
walk_expr(lsb, f);
|
||||
}
|
||||
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => walk_expr(base, f),
|
||||
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
|
||||
for item in items {
|
||||
walk_expr(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner, .. } => {
|
||||
walk_expr(count, f);
|
||||
for item in inner {
|
||||
walk_expr(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Paren { inner, .. } => walk_expr(inner, f),
|
||||
ExprKind::Cast { expr, .. } => walk_expr(expr, f),
|
||||
ExprKind::New(inner) => walk_expr(inner, f),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn positional(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}` by position, so lucisv cannot tell which of its connections are outputs; convert it to named connections first."
|
||||
)
|
||||
}
|
||||
|
||||
fn wildcard(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}` with `.*`, which names no signals; expand the `.*` first (lucisv offers that as its own refactoring)."
|
||||
)
|
||||
}
|
||||
|
||||
fn implicit(module: &str, instance: &str, port: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}`'s `{port}` implicitly (`.{port}`), which names no expression for lucisv to move; write the signal out first."
|
||||
)
|
||||
}
|
||||
|
||||
fn unreadable(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"lucisv could not read one of `{instance}`'s connections to `{module}`, so it cannot tell what the selection drives."
|
||||
)
|
||||
}
|
||||
|
||||
fn unknown_module(module: &str) -> String {
|
||||
format!(
|
||||
"the selection instantiates `{module}`, and lucisv has no single indexed declaration of it, so it cannot tell which of its connections are outputs."
|
||||
)
|
||||
}
|
||||
|
||||
fn no_such_port(module: &str, port: &str) -> String {
|
||||
format!(
|
||||
"the selection connects `.{port}`, which `{module}`'s declaration does not name, so lucisv cannot tell whether it is driven."
|
||||
)
|
||||
}
|
||||
|
||||
fn no_direction(module: &str, port: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{port}` without a direction, so lucisv cannot tell whether the selection drives it."
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
//! Extract a selection of whole module items into a module of its own.
|
||||
//!
|
||||
//! The user selects one or more contiguous items of a module `M` — an
|
||||
//! `always` block, an `assign`, an instantiation, a declaration, a generate
|
||||
//! construct — and names the module `N` they want them in. lucisv works out
|
||||
//! `N`'s ports from the dataflow across the selection's boundary, writes `N`
|
||||
//! into a file of its own beside `M`'s (or below `M`, for a client that cannot
|
||||
//! create files), and replaces the selection with an instantiation of `N`
|
||||
//! **rendered from `N`'s own text**, so the skeleton and the module can never
|
||||
//! disagree about what `N`'s ports are.
|
||||
//!
|
||||
//! Three files, one question each:
|
||||
//!
|
||||
//! * `region` — *what does the selection cover?* The module, the run of whole
|
||||
//! items, and the item kinds lucisv will not carry into another module.
|
||||
//! * `flow` — *which names cross the boundary, and in which direction?* The
|
||||
//! dataflow rule, and the two positions it refuses to guess at.
|
||||
//! * `render` — *what does lucisv write?* A port's type as its declaration
|
||||
//! spells it, the new module, and the instantiation.
|
||||
//!
|
||||
//! This file is the plan: the entry points, the classification of each
|
||||
//! crossing name into a port, a parameter or a refusal, the edits, and the
|
||||
//! verification. Everything is one [`check::verify_move`] over the whole edit,
|
||||
//! which for a new file is the ordinary splice contract plus one deliberate
|
||||
//! widening: the comments the selection carries are deleted in `M`'s file and
|
||||
//! written in `N`'s, so the never-dropped ledger is kept over the pair rather
|
||||
//! than over each file alone. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
mod boundary;
|
||||
mod flow;
|
||||
mod region;
|
||||
mod render;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, SourceFile};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{analyze, SymbolKind};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
use boundary::Crossing;
|
||||
use region::Region;
|
||||
|
||||
/// Where the extracted module is written.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Home {
|
||||
/// A file `N.sv` beside `M`'s own — what a client that advertises
|
||||
/// `workspace.workspaceEdit.documentChanges` with `CreateFile` support
|
||||
/// gets, because only such a client can apply the creation.
|
||||
NewFile,
|
||||
/// Below `M`, in `M`'s own file — the fallback for every other client,
|
||||
/// and for a caller that asked for it.
|
||||
SameFile,
|
||||
}
|
||||
|
||||
/// What the cheap gate found: the selection is in a module, and these are the
|
||||
/// units whose files the engine needs read.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ExtractSite {
|
||||
/// The module the selection is written in.
|
||||
pub module: String,
|
||||
/// The name the action proposes when the caller has none: `M_extracted`.
|
||||
pub default_name: String,
|
||||
/// Every unit whose declaration the engine will look up: the module
|
||||
/// itself, the modules the selection instantiates, and the packages the
|
||||
/// module imports.
|
||||
pub units: Vec<String>,
|
||||
}
|
||||
|
||||
/// Whether a selection is one lucisv could extract, and what it would need to
|
||||
/// read to try.
|
||||
///
|
||||
/// **The cheap gate**: one parse of one buffer, no workspace and no I/O — the
|
||||
/// bargain `port_action_modules` and `imported_packages` strike, and for the
|
||||
/// same reason (a `textDocument/codeAction` arrives on every cursor move).
|
||||
/// Empty exactly where [`extract_module`] would refuse for want of a module or
|
||||
/// a whole item to move.
|
||||
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
|
||||
let module = region.module_name().to_string();
|
||||
let mut units = vec![module.clone()];
|
||||
for item in ®ion.items {
|
||||
collect_instantiated(item, &mut units);
|
||||
}
|
||||
for import in ®ion.module.imports {
|
||||
for path in &import.paths {
|
||||
push(&mut units, path.pkg.text.clone());
|
||||
}
|
||||
}
|
||||
for item in ®ion.module.items {
|
||||
if let ItemKind::Import(paths) = &item.kind {
|
||||
for path in paths {
|
||||
push(&mut units, path.pkg.text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(ExtractSite { default_name: format!("{module}_extracted"), module, units })
|
||||
}
|
||||
|
||||
/// The lightbulb's text, written here so every front end says the same thing.
|
||||
pub fn extract_title() -> String {
|
||||
"lucisv: extract selection into module…".to_string()
|
||||
}
|
||||
|
||||
/// Extract the items `[start, end)` covers out of the module that holds them,
|
||||
/// into a module called `new_name`.
|
||||
pub fn extract_module(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
start: u32,
|
||||
end: u32,
|
||||
new_name: &str,
|
||||
home: Home,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
plain_identifier(new_name)?;
|
||||
// The new file joins the in-scope set as an *empty* file, so that every
|
||||
// question below — the index, the analysis, the verification — is asked
|
||||
// about it exactly the way it is asked about a file that was always there.
|
||||
let mut sources: Vec<(PathBuf, String)> = files.to_vec();
|
||||
let created = match home {
|
||||
Home::SameFile => None,
|
||||
Home::NewFile => {
|
||||
let path = beside(file, new_name);
|
||||
match sources.iter().find(|(held, _)| *held == path) {
|
||||
Some((_, text)) if !text.trim().is_empty() => return Err(occupied(&path)),
|
||||
Some(_) => {}
|
||||
None => sources.push((path.clone(), String::new())),
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
};
|
||||
let plan = Extraction::plan(&sources, file, start, end, new_name, created.clone())?;
|
||||
Ok(RefactorEdit {
|
||||
edits: plan.edits,
|
||||
warnings: plan.warnings,
|
||||
created: created.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// What the extraction produced, before it is dressed as a [`RefactorEdit`].
|
||||
struct Extraction {
|
||||
edits: Vec<(PathBuf, Vec<TextEdit>)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Extraction {
|
||||
fn plan(
|
||||
sources: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
start: u32,
|
||||
end: u32,
|
||||
new_name: &str,
|
||||
created: Option<PathBuf>,
|
||||
) -> Result<Extraction, String> {
|
||||
let mut scope = Scope::build(sources);
|
||||
let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
if let Some(problem) = diagnostics.first() {
|
||||
return Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
));
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end))?;
|
||||
let module = region.module_name().to_string();
|
||||
declared_once(&scope, &module)?;
|
||||
undeclared(&scope, new_name)?;
|
||||
if new_name == module {
|
||||
return Err(format!("`{module}` is already the name of the module you are in."));
|
||||
}
|
||||
if created.is_some() {
|
||||
no_directive(&tree, text, ®ion)?;
|
||||
}
|
||||
let semantics = analyze(&tree, text);
|
||||
if let Some(path) = flow::hierarchical_escape(text, &semantics, ®ion) {
|
||||
return Err(hierarchical(&path));
|
||||
}
|
||||
let flow = flow::read(&scope, text, &semantics, ®ion)?;
|
||||
let packages = boundary::packages(&tree);
|
||||
let crossing =
|
||||
Crossing::read(text, &semantics, ®ion, &flow, &packages, created.is_some())?;
|
||||
|
||||
// The new module, then the instantiation read back out of it.
|
||||
let body = format!("{}{}", region.indent, slice(text, region.span));
|
||||
let module_text = render::new_module(
|
||||
new_name,
|
||||
&crossing.imports,
|
||||
&crossing.params,
|
||||
&crossing.ports,
|
||||
&ensure_newline(&body),
|
||||
);
|
||||
let instance = render::instantiation(new_name, &module_text, ®ion.indent)?;
|
||||
|
||||
let mut edits: Vec<(usize, Vec<TextEdit>)> = Vec::new();
|
||||
// What the verifier is allowed to let travel, and between which bytes:
|
||||
// `M`'s file loses exactly the pieces inside the region, and the new
|
||||
// file — named with an empty range, because it has no region of its
|
||||
// own — is the only place they may land.
|
||||
let mut moving: Vec<(usize, TextRange)> = Vec::new();
|
||||
let replace = TextEdit { range: region.span, new_text: instance };
|
||||
match &created {
|
||||
Some(path) => {
|
||||
let Some(there) = scope.index_of(path) else { return Err(not_in_scope(path)) };
|
||||
edits.push((here, vec![replace]));
|
||||
edits.push((
|
||||
there,
|
||||
vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }],
|
||||
));
|
||||
moving = vec![(here, region.span), (there, TextRange::empty(0))];
|
||||
}
|
||||
None => {
|
||||
let append = TextEdit {
|
||||
range: TextRange::empty(region.module_span.end),
|
||||
new_text: format!("\n\n{module_text}"),
|
||||
};
|
||||
edits.push((here, vec![replace, append]));
|
||||
}
|
||||
}
|
||||
edits.sort_by_key(|(i, _)| *i);
|
||||
moving.sort_by_key(|(i, _)| *i);
|
||||
|
||||
let what = format!("extracting `{new_name}` out of `{module}`");
|
||||
check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?;
|
||||
confirm(&scope, &edits, new_name, &crossing, &what)?;
|
||||
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
for (i, file_edits) in edits {
|
||||
let Some(path) = scope.path(i) else { return Err(lost(&what)) };
|
||||
out.push((path.to_path_buf(), file_edits));
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the edited text back and require the new module to declare exactly the
|
||||
/// ports and parameters the plan promised.
|
||||
///
|
||||
/// `verify_move` proves the edit is lexically and semantically honest; nothing
|
||||
/// in it proves the header lucisv wrote is the header it meant to write.
|
||||
fn confirm(
|
||||
scope: &Scope<'_>,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
new_name: &str,
|
||||
crossing: &Crossing,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
for (i, file_edits) in edits {
|
||||
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
|
||||
return Err(lost(what));
|
||||
};
|
||||
let edited = crate::apply(text, file_edits);
|
||||
let Ok(plan) = crate::instantiate::instantiation_plan(new_name, &edited, None) else {
|
||||
continue;
|
||||
};
|
||||
let ports: Vec<&str> = plan.ports.iter().map(|port| port.name.as_str()).collect();
|
||||
let params: Vec<&str> = plan.params.iter().map(|param| param.name.as_str()).collect();
|
||||
let wanted_ports: Vec<&str> = crossing.ports.iter().map(|p| p.name.as_str()).collect();
|
||||
let wanted_params: Vec<&str> = crossing.params.iter().map(|p| p.name.as_str()).collect();
|
||||
if ports != wanted_ports || params != wanted_params {
|
||||
return Err(format!(
|
||||
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(lost(what))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// odds and ends
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn inside(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.span.start <= span.start && span.end <= region.span.end
|
||||
}
|
||||
|
||||
fn inside_module(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.module_span.start <= span.start && span.end <= region.module_span.end
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
fn ensure_newline(text: &str) -> String {
|
||||
match text.ends_with('\n') {
|
||||
true => text.to_string(),
|
||||
false => format!("{text}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(out: &mut Vec<String>, name: String) {
|
||||
if !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every module an item instantiates, nested generate constructs included.
|
||||
fn collect_instantiated(item: &Item, out: &mut Vec<String>) {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => push(out, inst.module.clone()),
|
||||
ItemKind::GenerateRegion { items, .. } => {
|
||||
for item in items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(block) => {
|
||||
for item in &block.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
for item in &gen_if.then.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
vlog_parser::ast::GenElse::If(_, nested) => {
|
||||
for item in &nested.then.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
vlog_parser::ast::GenElse::Block(block) => {
|
||||
for item in &block.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => {
|
||||
for item in &gen_for.body.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
for item in &case_item.body.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file the new module goes in: `N.sv`, beside the file it came out of.
|
||||
fn beside(file: &Path, new_name: &str) -> PathBuf {
|
||||
let parent = file.parent().map_or_else(PathBuf::new, Path::to_path_buf);
|
||||
parent.join(format!("{new_name}.sv"))
|
||||
}
|
||||
|
||||
/// A module name lucisv will write into a file name and a header: a plain
|
||||
/// identifier, never an escaped one.
|
||||
fn plain_identifier(name: &str) -> Result<(), String> {
|
||||
let mut chars = name.chars();
|
||||
let head = chars.next().filter(|c| c.is_ascii_alphabetic() || *c == '_');
|
||||
let tail = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
match head.is_some() && tail {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"`{name}` is not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module the selection is in must be declared exactly once in the
|
||||
/// workspace: an extraction rewrites *this* `M`, and two of them means lucisv
|
||||
/// does not know whose ports the selection reads.
|
||||
fn declared_once(scope: &Scope<'_>, module: &str) -> Result<(), String> {
|
||||
let defs = scope.index().units(module).iter().filter(|def| def.kind.is_instantiable()).count();
|
||||
match defs {
|
||||
1 => Ok(()),
|
||||
0 => Err(format!("lucisv indexes no module named `{module}`.")),
|
||||
_ => Err(format!(
|
||||
"`{module}` is declared in more than one indexed file, so lucisv cannot tell which one the selection belongs to."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn undeclared(scope: &Scope<'_>, name: &str) -> Result<(), String> {
|
||||
match scope.index().units(name).is_empty() {
|
||||
true => Ok(()),
|
||||
false => {
|
||||
Err(format!("the workspace already declares `{name}`; pick a name nothing else uses."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `timescale` or a `default_nettype` in force where `M` is written does not
|
||||
/// follow the items into a file of their own, and silently changing either one
|
||||
/// changes what the design does.
|
||||
fn no_directive(tree: &SourceFile, text: &str, region: &Region<'_>) -> Result<(), String> {
|
||||
for item in &tree.items {
|
||||
let ItemKind::Directive(raw) = &item.kind else { continue };
|
||||
if item.span.start > region.module_span.end {
|
||||
continue;
|
||||
}
|
||||
let word = raw.text.split_whitespace().next().unwrap_or("");
|
||||
if word == "`timescale" || word == "`default_nettype" || word == "`resetall" {
|
||||
return Err(format!(
|
||||
"`{}` writes `{word}` before the module the selection is in, and a new file would not inherit it; extract into the same file, or move the directive into an include both files use.",
|
||||
first_line(text, item.span.start)
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The file's own name is not to hand here, so a directive refusal names the
|
||||
/// line the directive is on instead.
|
||||
fn first_line(text: &str, at: u32) -> String {
|
||||
let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1;
|
||||
format!("line {line}")
|
||||
}
|
||||
|
||||
fn count(n: usize, noun: &str) -> String {
|
||||
match n {
|
||||
1 => format!("1 {noun}"),
|
||||
n => format!("{n} {noun}s"),
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn not_in_scope(file: &Path) -> String {
|
||||
format!("{} is not one of the files lucisv was given.", display(file))
|
||||
}
|
||||
|
||||
fn occupied(path: &Path) -> String {
|
||||
format!("there is already a `{}` beside this file; pick another name.", display(path))
|
||||
}
|
||||
|
||||
fn escaped(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared inside the selection and used outside it; move the declaration of `{name}` out of the selection first."
|
||||
)
|
||||
}
|
||||
|
||||
fn outside_module(name: &str, module: &str) -> String {
|
||||
format!(
|
||||
"the selection uses `{name}`, which is declared outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// The same refusal for a **member access**, which names the head first.
|
||||
/// `s.f` and `bus.data` cross the boundary as `s` and `bus` — the port or the
|
||||
/// variable — and `f` and `data` are names of *their* types; a sentence that
|
||||
/// leads with the field reads as if the field were a signal of `M`'s own.
|
||||
fn outside_module_member(head: &str, name: &str, module: &str) -> String {
|
||||
format!(
|
||||
"the selection uses `{head}.{name}`, and `{head}` is declared with a type written outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn unmovable(name: &str, module: &str, kind: SymbolKind) -> String {
|
||||
let what = match kind {
|
||||
SymbolKind::Genvar => "a `genvar`",
|
||||
SymbolKind::Function => "a function",
|
||||
SymbolKind::Task => "a task",
|
||||
SymbolKind::Typedef => "a type",
|
||||
SymbolKind::EnumVariant => "an enumeration member",
|
||||
SymbolKind::Instance => "an instance",
|
||||
SymbolKind::Modport => "a modport",
|
||||
SymbolKind::Clocking => "a clocking block",
|
||||
SymbolKind::Class => "a class",
|
||||
SymbolKind::Block => "a named block",
|
||||
_ => "a declaration",
|
||||
};
|
||||
format!(
|
||||
"the selection uses `{name}`, {what} `{module}` declares outside it; lucisv makes ports out of signals and parameters and nothing else, so it made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn header_names(module: &str, owner: &str, word: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{owner}` with something that names `{word}`, which is neither a parameter nor a name a module in another file could reach; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn hierarchical(path: &str) -> String {
|
||||
format!(
|
||||
"the selection reads `{path}` through the design hierarchy, and a hierarchical path does not survive being moved into another module; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn lost_name(name: &str) -> String {
|
||||
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
|
||||
}
|
||||
|
||||
fn lost(what: &str) -> String {
|
||||
format!("lucisv could not name one of the files it edited for {what}.")
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! What the selection covers: the module it is written in, the run of whole
|
||||
//! module items it spans, and the bytes the extraction will delete.
|
||||
//!
|
||||
//! Nothing here reads the symbol table — this is the *shape* half of the
|
||||
//! refusal list, answered from the tree and the text alone: the selection has
|
||||
//! to cover whole items, and the items it covers have to be ones lucisv can
|
||||
//! move without changing what they mean where they land.
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, Module, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// The selection, resolved.
|
||||
pub(super) struct Region<'t> {
|
||||
/// The module the selection is written in.
|
||||
pub(super) module: &'t Module,
|
||||
/// Where that module is written, `module` keyword to `endmodule`.
|
||||
pub(super) module_span: TextRange,
|
||||
/// The items the selection covers, in source order.
|
||||
pub(super) items: Vec<&'t Item>,
|
||||
/// The bytes the extraction deletes from the module's file: the covered
|
||||
/// items and whatever of their own comments the selection covers too.
|
||||
pub(super) span: TextRange,
|
||||
/// The whitespace the region's first line begins with — what the
|
||||
/// instantiation written in its place is laid out against.
|
||||
pub(super) indent: String,
|
||||
}
|
||||
|
||||
impl<'t> Region<'t> {
|
||||
/// Read the selection, or say why lucisv will not extract it.
|
||||
pub(super) fn read(
|
||||
tree: &'t SourceFile,
|
||||
text: &str,
|
||||
selection: TextRange,
|
||||
) -> Result<Region<'t>, String> {
|
||||
let (module, module_span) =
|
||||
module_at(&tree.items, selection).ok_or_else(|| NO_MODULE.to_string())?;
|
||||
extractable(module)?;
|
||||
// A cursor is a selection of one item: an editor sends the caret's
|
||||
// own empty range when nothing is selected, and "extract the thing I
|
||||
// am standing on" is what the user means by it.
|
||||
let selection = match selection.is_empty() {
|
||||
false => selection,
|
||||
true => module
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.span)
|
||||
.find(|span| span.contains(selection.start) || span.end == selection.start)
|
||||
.ok_or_else(|| EMPTY.to_string())?,
|
||||
};
|
||||
let mut items: Vec<&Item> = Vec::new();
|
||||
let mut span: Option<TextRange> = None;
|
||||
for item in &module.items {
|
||||
let extent = extent(item, selection);
|
||||
if !overlaps(extent, selection) {
|
||||
continue;
|
||||
}
|
||||
if extent.start < selection.start || selection.end < extent.end {
|
||||
return Err(PARTIAL.to_string());
|
||||
}
|
||||
span = Some(match span {
|
||||
None => extent,
|
||||
Some(so_far) => TextRange::new(so_far.start, extent.end),
|
||||
});
|
||||
items.push(item);
|
||||
}
|
||||
let Some(span) = span else { return Err(EMPTY.to_string()) };
|
||||
for item in &items {
|
||||
movable(item)?;
|
||||
}
|
||||
Ok(Region { module, module_span, items, span, indent: indent_at(text, span.start) })
|
||||
}
|
||||
|
||||
/// The module's name.
|
||||
pub(super) fn module_name(&self) -> &str {
|
||||
&self.module.name
|
||||
}
|
||||
}
|
||||
|
||||
/// The `module`, `interface` or `program` whose body covers the whole
|
||||
/// selection — the parser writes all three as one node, and [`extractable`] is
|
||||
/// what says only the first is one lucisv extracts out of.
|
||||
fn module_at(items: &[Item], selection: TextRange) -> Option<(&Module, TextRange)> {
|
||||
for item in items {
|
||||
let ItemKind::Module(module) = &item.kind else { continue };
|
||||
if !item.span.contains(selection.start) {
|
||||
continue;
|
||||
}
|
||||
if selection.end > item.span.end {
|
||||
return None;
|
||||
}
|
||||
return Some((module, item.span));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Only a `module` is a thing lucisv extracts out of.
|
||||
///
|
||||
/// The parser gives a `module`, an `interface` and a `program` one node —
|
||||
/// their headers and bodies are the same grammar (IEEE 1800 §25.3) — and
|
||||
/// [`Module::kw`] is the only thing that says which was written. Extracting is
|
||||
/// a dataflow question about a boundary, and neither of the other two has the
|
||||
/// boundary this rule assumes: an `interface`'s signals *are* its surface,
|
||||
/// named by whoever instantiates it and driven from anywhere, so "what does
|
||||
/// this region drive" does not answer what a port should be; a `program`'s
|
||||
/// items are testbench code whose meaning depends on when they run.
|
||||
fn extractable(module: &Module) -> Result<(), String> {
|
||||
match module.kw.as_str() {
|
||||
"module" | "macromodule" => Ok(()),
|
||||
"interface" => Err(INTERFACE.to_string()),
|
||||
"program" => Err(PROGRAM.to_string()),
|
||||
kw => Err(format!(
|
||||
"the selection is inside a `{kw}`, and lucisv extracts module items out of a `module`, so it made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes one item owns for the purpose of the selection: the item itself,
|
||||
/// plus every comment and attribute of its own that the selection also covers.
|
||||
///
|
||||
/// A comment the user left *outside* the selection stays where it is, which is
|
||||
/// what makes a selection that starts on the item's own line do the obvious
|
||||
/// thing and one that starts a line earlier take the note with it.
|
||||
fn extent(item: &Item, selection: TextRange) -> TextRange {
|
||||
let mut spans = vec![item.span];
|
||||
spans.extend(item.meta.leading.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.before_sep.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.trailing.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.attrs.iter().map(|a| a.span));
|
||||
let mut out = item.span;
|
||||
for span in spans {
|
||||
if span.start < selection.start || selection.end < span.end {
|
||||
continue;
|
||||
}
|
||||
out = TextRange::new(out.start.min(span.start), out.end.max(span.end));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/// The item kinds lucisv will not carry into another module, each with the
|
||||
/// sentence saying why.
|
||||
fn movable(item: &Item) -> Result<(), String> {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(_) => Err(kind_refusal("a port declaration")),
|
||||
ItemKind::ParamDecl(decl) => Err(kind_refusal(match decl.kw.as_str() {
|
||||
"localparam" => "a `localparam` declaration",
|
||||
_ => "a `parameter` declaration",
|
||||
})),
|
||||
ItemKind::Genvar(_) => Err(kind_refusal("a `genvar` declaration")),
|
||||
ItemKind::Bind(_) => Err(kind_refusal("a `bind` directive")),
|
||||
ItemKind::Initial(_) => Err(
|
||||
"the selection holds an `initial` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Final(_) => Err(
|
||||
"the selection holds a `final` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::MacroItem(_) => Err(
|
||||
"the selection holds a macro invocation, and lucisv does not expand macros, so it cannot tell what would move with it."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Directive(_) => Err(
|
||||
"the selection holds a compiler directive, and lucisv does not evaluate one, so it cannot tell what the selection means in another module."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Verbatim(_) => Err(
|
||||
"the selection holds a block lucisv keeps verbatim (an assertion, a `property`, a `sequence`, a `constraint` or a `covergroup` body it could not read), so it cannot tell which names cross the boundary."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Error(_) => Err(
|
||||
"part of the selection did not parse, so lucisv cannot tell what it would be moving."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_) => {
|
||||
Err(kind_refusal("a declaration of its own"))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_refusal(what: &str) -> String {
|
||||
format!(
|
||||
"the selection holds {what}, which belongs to the module that wrote it; lucisv does not move one into a new module."
|
||||
)
|
||||
}
|
||||
|
||||
/// The whitespace the line holding `at` begins with.
|
||||
fn indent_at(text: &str, at: u32) -> String {
|
||||
let start = text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n + 1);
|
||||
text.get(start..at as usize)
|
||||
.unwrap_or("")
|
||||
.chars()
|
||||
.take_while(|c| *c == ' ' || *c == '\t')
|
||||
.collect()
|
||||
}
|
||||
|
||||
const NO_MODULE: &str =
|
||||
"the selection is not inside one module's body, so there is nothing for lucisv to extract from.";
|
||||
const PARTIAL: &str =
|
||||
"the selection cuts an item in half; lucisv extracts whole module items, so select from the start of the first one to the end of the last.";
|
||||
const EMPTY: &str = "the selection covers no module item, so there is nothing to extract.";
|
||||
const INTERFACE: &str =
|
||||
"the selection is inside an `interface`, whose signals are its surface — every one of them is driven and read by whatever instantiates it — so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`.";
|
||||
const PROGRAM: &str =
|
||||
"the selection is inside a `program`, whose items are testbench code whose meaning depends on when it runs; lucisv extracts out of a `module`.";
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Writing the new module, and the instantiation that stands where its items
|
||||
//! used to be.
|
||||
//!
|
||||
//! Two rules govern everything here. A **port's type is the declaration's own
|
||||
//! text**, reassembled from the tree in the order `vlog_formatter`'s ANSI port
|
||||
//! printer writes it (direction, net, type, signing, packed dimensions, name),
|
||||
//! so what lucisv writes is what the formatter would; anything the tree says is
|
||||
//! not a plain name-signing-dimensions type — an anonymous aggregate, a
|
||||
//! parameterized reference, a virtual interface, an unpacked dimension — is
|
||||
//! refused rather than approximated. And the **instantiation is rendered from
|
||||
//! the new module's own text**, through
|
||||
//! [`instantiation_plan`](crate::instantiate::instantiation_plan), so the two
|
||||
//! halves of the edit cannot disagree about what `N`'s ports are.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, DataDecl, DataType, Declarator, Dim, ItemKind, ListElem, Module, ParamDecl,
|
||||
ParamPort, PortDecl, PortList,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::instantiate::{instantiation_plan, Layout};
|
||||
|
||||
/// Where a name that crosses the boundary is declared in the module.
|
||||
pub(super) enum Site<'t> {
|
||||
/// An ANSI port of the header.
|
||||
Ansi(&'t AnsiPort),
|
||||
/// A name-only header port, with the body declarations that describe it.
|
||||
NonAnsi(&'t PortDecl, &'t Declarator, Option<(&'t DataDecl, &'t Declarator)>),
|
||||
/// A net or variable declared in the body.
|
||||
Data(&'t DataDecl, &'t Declarator),
|
||||
/// A parameter or localparam declared in the body.
|
||||
Param(&'t ParamDecl, &'t Declarator),
|
||||
/// A parameter declared in the header's `#( ... )`.
|
||||
ParamPort(&'t ParamPort),
|
||||
}
|
||||
|
||||
/// Every declaration of the module that a crossing name could name.
|
||||
pub(super) fn site_of<'t>(module: &'t Module, name: &str) -> Option<Site<'t>> {
|
||||
if let PortList::Ansi(ports) = &module.ports {
|
||||
if let Some(port) = ports.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
|
||||
return Some(Site::Ansi(port));
|
||||
}
|
||||
}
|
||||
if let Some(params) = &module.param_ports {
|
||||
if let Some(param) = params.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
|
||||
return Some(Site::ParamPort(param));
|
||||
}
|
||||
}
|
||||
let mut port: Option<(&PortDecl, &Declarator)> = None;
|
||||
let mut data: Option<(&DataDecl, &Declarator)> = None;
|
||||
for item in &module.items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
port = Some((decl, d));
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
data = Some((decl, d));
|
||||
}
|
||||
}
|
||||
ItemKind::ParamDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
return Some(Site::Param(decl, d));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match (port, data) {
|
||||
(Some((decl, declarator)), other) => Some(Site::NonAnsi(decl, declarator, other)),
|
||||
(None, Some((decl, declarator))) => Some(Site::Data(decl, declarator)),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One port of the new module, ready to be written.
|
||||
pub(super) struct Port {
|
||||
pub(super) name: String,
|
||||
/// `input logic [7:0] `, the name's own text excluded.
|
||||
pub(super) prefix: String,
|
||||
/// Every identifier that prefix spells — the direction and the type
|
||||
/// keywords among them. A port whose width is `[N-1:0]` names `N`, and
|
||||
/// `N` has to cross the boundary with it or the new module names nothing.
|
||||
pub(super) names: Vec<String>,
|
||||
}
|
||||
|
||||
/// One parameter of the new module.
|
||||
pub(super) struct Param {
|
||||
pub(super) name: String,
|
||||
/// `parameter int `, the name's own text excluded.
|
||||
pub(super) prefix: String,
|
||||
/// The default as `M` writes it, or an empty string when it writes none.
|
||||
pub(super) default: String,
|
||||
/// Every identifier its type and its default name, for the closure that
|
||||
/// carries the parameters one parameter depends on across with it.
|
||||
pub(super) names: Vec<String>,
|
||||
}
|
||||
|
||||
/// The declaration of a crossing signal, written as an ANSI port of the new
|
||||
/// module.
|
||||
pub(super) fn port(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
site: &Site<'_>,
|
||||
dir: &str,
|
||||
) -> Result<Port, String> {
|
||||
let (net, ty, unpacked) = match site {
|
||||
Site::Ansi(port) => (port.net.as_deref(), &port.ty, port.unpacked.as_slice()),
|
||||
Site::NonAnsi(decl, declarator, var) => {
|
||||
let (net, ty) = match var {
|
||||
Some((data, _)) if decl.net.is_none() && decl.ty.name.is_empty() => {
|
||||
(data.net.as_deref().or(decl.net.as_deref()), &data.ty)
|
||||
}
|
||||
_ => (decl.net.as_deref(), &decl.ty),
|
||||
};
|
||||
if let Some((data, other)) = var {
|
||||
if !data.qualifiers.is_empty() {
|
||||
return Err(qualified(module, name));
|
||||
}
|
||||
if !other.unpacked.is_empty() {
|
||||
return Err(unpacked_refusal(module, name));
|
||||
}
|
||||
}
|
||||
(net, ty, declarator.unpacked.as_slice())
|
||||
}
|
||||
Site::Data(decl, declarator) => {
|
||||
if !decl.qualifiers.is_empty() {
|
||||
return Err(qualified(module, name));
|
||||
}
|
||||
if decl.delay.is_some() {
|
||||
return Err(delayed(module, name));
|
||||
}
|
||||
(decl.net.as_deref(), &decl.ty, declarator.unpacked.as_slice())
|
||||
}
|
||||
Site::Param(..) | Site::ParamPort(_) => return Err(lost(name)),
|
||||
};
|
||||
if !unpacked.is_empty() {
|
||||
return Err(unpacked_refusal(module, name));
|
||||
}
|
||||
let ty = type_text(text, module, name, ty)?;
|
||||
let mut prefix = String::new();
|
||||
let mut word = |part: &str| {
|
||||
prefix.push_str(part);
|
||||
prefix.push(' ');
|
||||
};
|
||||
word(dir);
|
||||
if let Some(net) = net {
|
||||
word(net);
|
||||
}
|
||||
if !ty.is_empty() {
|
||||
word(&ty);
|
||||
}
|
||||
let names = words(&prefix);
|
||||
Ok(Port { name: name.to_string(), prefix, names })
|
||||
}
|
||||
|
||||
/// The declaration of a crossing parameter, written as a parameter of the new
|
||||
/// module.
|
||||
pub(super) fn param(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
site: &Site<'_>,
|
||||
) -> Result<Param, String> {
|
||||
let (is_type, ty, default) = match site {
|
||||
Site::Param(decl, declarator) => {
|
||||
(decl.is_type, &decl.ty, declarator.init.as_ref().map(|e| e.span))
|
||||
}
|
||||
Site::ParamPort(param) => {
|
||||
(param.is_type, ¶m.ty, param.default.as_ref().map(|e| e.span))
|
||||
}
|
||||
_ => return Err(lost(name)),
|
||||
};
|
||||
if is_type {
|
||||
return Err(format!(
|
||||
"`{module}`'s `{name}` is a type parameter, and lucisv does not carry one into a new module this round."
|
||||
));
|
||||
}
|
||||
let ty = type_text(text, module, name, ty)?;
|
||||
let mut prefix = String::from("parameter ");
|
||||
if !ty.is_empty() {
|
||||
prefix.push_str(&ty);
|
||||
prefix.push(' ');
|
||||
}
|
||||
let default = default.map(|span| slice(text, span).trim().to_string()).unwrap_or_default();
|
||||
if default.contains('\n') {
|
||||
return Err(format!(
|
||||
"`{module}` writes `{name}`'s default across several lines, and lucisv does not re-flow one into a new module's header."
|
||||
));
|
||||
}
|
||||
let mut names = words(&prefix);
|
||||
names.extend(words(&default));
|
||||
Ok(Param { name: name.to_string(), prefix, default, names })
|
||||
}
|
||||
|
||||
/// Everything a declaration writes between the direction and the name, as the
|
||||
/// source spells it: `logic [7:0]`, `my_pkg::word_t`, `signed [31:0]`.
|
||||
fn type_text(text: &str, module: &str, name: &str, ty: &DataType) -> Result<String, String> {
|
||||
if ty.virt.is_some() || ty.extra.is_some() {
|
||||
return Err(format!(
|
||||
"`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface)."
|
||||
));
|
||||
}
|
||||
let mut out = String::new();
|
||||
for part in [ty.name.as_str(), ty.signing.as_deref().unwrap_or("")] {
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(part);
|
||||
}
|
||||
let packed = dims(text, &ty.packed);
|
||||
if !packed.is_empty() {
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(&packed);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn dims(text: &str, list: &[Dim]) -> String {
|
||||
list.iter().map(|dim| slice(text, dim.span)).collect()
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Every whole word of an expression's text — what a parameter default may
|
||||
/// depend on.
|
||||
fn words(text: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
if !is_word_byte(bytes[i]) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let start = i;
|
||||
while i < bytes.len() && is_word_byte(bytes[i]) {
|
||||
i += 1;
|
||||
}
|
||||
let leading_digit = bytes[start].is_ascii_digit();
|
||||
let after_tick = start > 0 && bytes[start - 1] == b'\'';
|
||||
if !leading_digit && !after_tick {
|
||||
if let Some(word) = text.get(start..i) {
|
||||
out.push(word.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn is_word_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the two texts
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The whole new module: header, the imports it needs, and the selection's own
|
||||
/// bytes, verbatim.
|
||||
///
|
||||
/// Verbatim is the point. The items are module items in `M` and module items
|
||||
/// in `N`, at the same nesting depth, so the source's own indentation is
|
||||
/// already right — and every comment, every attribute and every string travels
|
||||
/// byte for byte, which is what lets the splice verifier count them.
|
||||
pub(super) fn new_module(
|
||||
name: &str,
|
||||
imports: &[String],
|
||||
params: &[Param],
|
||||
ports: &[Port],
|
||||
body: &str,
|
||||
) -> String {
|
||||
let mut out = format!("module {name}");
|
||||
for path in imports {
|
||||
out.push_str("\n import ");
|
||||
out.push_str(path);
|
||||
out.push(';');
|
||||
}
|
||||
// A header import is written on its own line, which is where the formatter
|
||||
// puts one; the list after it then starts a line of its own rather than
|
||||
// continuing with a space.
|
||||
let sep = match imports.is_empty() {
|
||||
true => " ",
|
||||
false => "\n",
|
||||
};
|
||||
if !params.is_empty() {
|
||||
out.push_str(sep);
|
||||
out.push_str("#(\n");
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
out.push_str(" ");
|
||||
out.push_str(¶m.prefix);
|
||||
out.push_str(¶m.name);
|
||||
if !param.default.is_empty() {
|
||||
out.push_str(" = ");
|
||||
out.push_str(¶m.default);
|
||||
}
|
||||
out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
out.push(')');
|
||||
}
|
||||
let sep = match params.is_empty() {
|
||||
true => sep,
|
||||
false => " ",
|
||||
};
|
||||
match ports.is_empty() {
|
||||
true => {
|
||||
out.push_str(sep);
|
||||
out.push_str("();\n");
|
||||
}
|
||||
false => {
|
||||
out.push_str(sep);
|
||||
out.push_str("(\n");
|
||||
for (i, port) in ports.iter().enumerate() {
|
||||
out.push_str(" ");
|
||||
out.push_str(&port.prefix);
|
||||
out.push_str(&port.name);
|
||||
out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
out.push_str(");\n");
|
||||
}
|
||||
}
|
||||
out.push_str(body);
|
||||
if !body.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str("endmodule\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// The instantiation that replaces the selection, read back out of the new
|
||||
/// module's own text.
|
||||
///
|
||||
/// Every port connects to the signal of the same name — which is what the
|
||||
/// extraction just made true — and every parameter to the parameter of the
|
||||
/// same name.
|
||||
pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result<String, String> {
|
||||
let mut plan = instantiation_plan(name, module_text, None)?;
|
||||
for port in &mut plan.ports {
|
||||
port.auto_connect = true;
|
||||
}
|
||||
let params = plan.params.len();
|
||||
let names: Vec<String> = plan.params.iter().map(|param| param.name.clone()).collect();
|
||||
let layout = Layout { base: indent.to_string(), step: " ".to_string() };
|
||||
Ok(plan.render_with(&layout, &mut |n, default| match n <= params {
|
||||
true => names.get(n - 1).cloned().unwrap_or_default(),
|
||||
false => default.to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn unpacked_refusal(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` crosses the selection's boundary and `{module}` declares it with an unpacked dimension; lucisv does not turn one into a port this round."
|
||||
)
|
||||
}
|
||||
|
||||
fn qualified(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{name}` with a qualifier (`var`, `const`, `automatic`), and lucisv does not move a qualifier into a port list."
|
||||
)
|
||||
}
|
||||
|
||||
fn delayed(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{name}` with a net delay, and lucisv does not move a delay into a port list."
|
||||
)
|
||||
}
|
||||
|
||||
fn lost(name: &str) -> String {
|
||||
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
|
||||
}
|
||||
@@ -161,7 +161,8 @@ fn organize(
|
||||
let plan = vec![(i, edits)];
|
||||
check::verify_splice(&mut scope, &plan, "", what)?;
|
||||
let Some((_, edits)) = plan.into_iter().next() else { return Err(not_in_scope(file)) };
|
||||
let edit = RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings };
|
||||
let edit =
|
||||
RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings, created: Vec::new() };
|
||||
Ok((edit, removed, sorted))
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
//! spans instead of edits — see `docs/features/references-nav/README.md`.
|
||||
|
||||
mod check;
|
||||
mod extract;
|
||||
mod imports;
|
||||
mod instantiate;
|
||||
mod ports;
|
||||
@@ -35,6 +36,7 @@ mod references;
|
||||
mod rename;
|
||||
mod scope;
|
||||
|
||||
pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home};
|
||||
pub use imports::{
|
||||
imported_packages, organize_counts, organize_imports, organize_title, unused_imports,
|
||||
};
|
||||
@@ -80,6 +82,13 @@ pub struct RefactorEdit {
|
||||
/// for (macro bodies, `endmodule :` labels). Informational only — a
|
||||
/// result with warnings is still safe to apply.
|
||||
pub warnings: Vec<String>,
|
||||
/// Files the refactoring **creates**. Each one also appears in `edits`,
|
||||
/// with exactly one insertion at offset 0 writing the whole file, so a
|
||||
/// caller that cannot create files can ignore this and get nothing; a
|
||||
/// caller that can (LSP's `CreateFile`) creates each of these first and
|
||||
/// then applies the edits as it applies every other one. Empty for every
|
||||
/// refactoring but [`extract_module`].
|
||||
pub created: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl RefactorEdit {
|
||||
|
||||
@@ -428,7 +428,7 @@ fn finish(
|
||||
edits.push((path.to_path_buf(), file_edits));
|
||||
}
|
||||
edits.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok((RefactorEdit { edits, warnings: plan.warnings }, plan.sites))
|
||||
Ok((RefactorEdit { edits, warnings: plan.warnings, created: Vec::new() }, plan.sites))
|
||||
}
|
||||
|
||||
/// What one file says about a module's signature: the module's own declared
|
||||
|
||||
@@ -171,7 +171,7 @@ pub fn rename(
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(RefactorEdit { edits: out, warnings })
|
||||
Ok(RefactorEdit { edits: out, warnings, created: Vec::new() })
|
||||
}
|
||||
|
||||
/// A new name must lex as exactly one identifier and must not be a keyword.
|
||||
|
||||
@@ -12,8 +12,8 @@ use std::time::Instant;
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
|
||||
use vlog_refactor::{
|
||||
add_port, convert_to_ansi, expand_wildcard, instantiation_plan, module_definition,
|
||||
port_actions, prepare_rename, rename, Layout, ModuleRef,
|
||||
add_port, convert_to_ansi, expand_wildcard, extract_module, instantiation_plan,
|
||||
module_definition, port_actions, prepare_rename, rename, Home, Layout, ModuleRef,
|
||||
};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
@@ -796,3 +796,155 @@ fn refusal_kind(said: &str) -> &'static str {
|
||||
];
|
||||
KINDS.iter().find(|(needle, _)| said.contains(needle)).map_or("other", |(_, kind)| *kind)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// extracting a module out of real RTL (TODO §53.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Where the extraction trial reads its design from. `corpus/` by default;
|
||||
/// `LUCISV_EXTRACT_ROOT` points it at a **copy** of another tree — which is how
|
||||
/// the opentitan trial is run without touching that checkout.
|
||||
fn extract_root() -> Option<Vec<PathBuf>> {
|
||||
let root = match std::env::var("LUCISV_EXTRACT_ROOT") {
|
||||
Ok(path) => PathBuf::from(path),
|
||||
Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"),
|
||||
};
|
||||
if !root.is_dir() {
|
||||
eprintln!("{} not checked out — skipping", root.display());
|
||||
return None;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
Some(files)
|
||||
}
|
||||
|
||||
/// The first `always` block or continuous assignment of each module, as a
|
||||
/// selection an extraction could be asked about.
|
||||
fn regions(text: &str) -> Vec<(String, u32, u32)> {
|
||||
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for item in &tree.items {
|
||||
let ItemKind::Module(module) = &item.kind else { continue };
|
||||
let found = module.items.iter().find(|item| {
|
||||
matches!(item.kind, ItemKind::Always { .. } | ItemKind::ContAssign(_))
|
||||
&& item.meta.leading.is_empty()
|
||||
});
|
||||
if let Some(region) = found {
|
||||
out.push((module.name.clone(), region.span.start, region.span.end));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many of a design's names fail to resolve. The census the trial holds
|
||||
/// fixed: an extraction moves items and writes a header, so the number of
|
||||
/// names nothing binds may not grow.
|
||||
fn unresolved_over(sources: &[(PathBuf, String)]) -> usize {
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut out = 0usize;
|
||||
for (_, text) in sources {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let external = vlog_semantic::resolve_external(&semantics, &index);
|
||||
for (n, reference) in semantics.references().iter().enumerate() {
|
||||
if reference.resolved().is_some() {
|
||||
continue;
|
||||
}
|
||||
let id = vlog_semantic::ReferenceId(n as u32);
|
||||
if !matches!(external.get(id), Some(vlog_semantic::ExternalTarget::Resolved(_))) {
|
||||
out += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_regions_of_real_rtl_extract_into_modules_that_parse_format_and_converge() {
|
||||
let Some(files) = extract_root() else { return };
|
||||
let sources = read(&files);
|
||||
assert!(!sources.is_empty(), "the tree exists but holds no Verilog");
|
||||
let config = vlog_formatter::Config::default();
|
||||
let before = unresolved_over(&sources);
|
||||
|
||||
let started = Instant::now();
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
let mut refusals = 0usize;
|
||||
'files: for (path, text) in &sources {
|
||||
for (module, start, end) in regions(text) {
|
||||
if done.len() == 5 {
|
||||
break 'files;
|
||||
}
|
||||
let name = format!("{module}_lucisv_extracted");
|
||||
let edit = match extract_module(&sources, path, start, end, &name, Home::NewFile) {
|
||||
Ok(edit) => edit,
|
||||
// Printed, not only counted: which regions the trial refuses
|
||||
// and why is the other half of a reproducible run (2026-09-06
|
||||
// rework — the opentitan numbers in the feature README are
|
||||
// this list).
|
||||
Err(said) => {
|
||||
refusals += 1;
|
||||
println!(" refused {} `{module}`: {said}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// The two halves, as the editor would write them.
|
||||
let mut after: Vec<(PathBuf, String)> = sources.clone();
|
||||
for created in &edit.created {
|
||||
after.push((created.clone(), String::new()));
|
||||
}
|
||||
for (file, edits) in &edit.edits {
|
||||
let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else {
|
||||
panic!("{} edits {} which is not in scope", name, file.display())
|
||||
};
|
||||
let mut out = slot.1.clone();
|
||||
for one in edits.iter().rev() {
|
||||
out.replace_range(
|
||||
one.range.start as usize..one.range.end as usize,
|
||||
&one.new_text,
|
||||
);
|
||||
}
|
||||
slot.1 = out;
|
||||
}
|
||||
|
||||
// Both files parse, format, and formatting them again is a no-op.
|
||||
for (file, edits) in &edit.edits {
|
||||
let text = &after.iter().find(|(held, _)| held == file).expect("edited").1;
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
assert!(
|
||||
diagnostics.is_empty(),
|
||||
"{name}: {} no longer parses: {diagnostics:?}\n{text}",
|
||||
file.display()
|
||||
);
|
||||
let once = vlog_formatter::format_source(text, &config).unwrap_or_else(|e| {
|
||||
panic!("{name}: the formatter refuses {}: {e}", file.display())
|
||||
});
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "{name}: {} does not converge", file.display());
|
||||
let _ = edits;
|
||||
}
|
||||
|
||||
// The census over the whole design, the two files together.
|
||||
let now = unresolved_over(&after);
|
||||
assert!(now <= before, "{name}: {} names went unresolved, up from {before}", now);
|
||||
// Printed, not only asserted: the trial's numbers are what the
|
||||
// feature README records, and a census that merely *held* is the
|
||||
// evidence the extraction was honest (2026-09-06 rework).
|
||||
println!(" {name} in {}: census {before} -> {now}", path.display());
|
||||
done.push(name);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"extract over {} files: {} regions extracted, {} refused, in {:.2}s",
|
||||
sources.len(),
|
||||
done.len(),
|
||||
refusals,
|
||||
started.elapsed().as_secs_f64()
|
||||
);
|
||||
assert_eq!(done.len(), 5, "five real regions must extract: {done:?}");
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
//! Extracting a selection of whole module items into a module of its own —
|
||||
//! TODO §53.1.
|
||||
//!
|
||||
//! Three groups. What the extraction *writes* (a combinational region, a
|
||||
//! sequential one, one carrying a parameter and an import, the two homes the
|
||||
//! new module can have); every **refusal**, one test per sentence; and the
|
||||
//! acceptance checks that say the result is real Verilog — it parses, the
|
||||
//! formatter accepts it, formatting it twice changes nothing, and the two
|
||||
//! files together name every signal the one file named.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{extract_module, extract_site, Home, RefactorEdit};
|
||||
|
||||
const M: &str = "/rtl/m.sv";
|
||||
|
||||
fn files(text: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![(PathBuf::from(M), text.to_string())]
|
||||
}
|
||||
|
||||
fn workspace(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
entries.iter().map(|(p, t)| (PathBuf::from(*p), t.to_string())).collect()
|
||||
}
|
||||
|
||||
/// The byte range of `needle` in `text`.
|
||||
fn at(text: &str, needle: &str) -> (u32, u32) {
|
||||
let start = text.find(needle).expect("needle") as u32;
|
||||
(start, start + needle.len() as u32)
|
||||
}
|
||||
|
||||
/// One file's text after the edit. A file the extraction creates starts empty.
|
||||
fn applied(text: &str, edit: &RefactorEdit, path: &str) -> String {
|
||||
let created = edit.created.iter().any(|created| created == Path::new(path));
|
||||
let mut out = match created {
|
||||
true => String::new(),
|
||||
false => text.to_string(),
|
||||
};
|
||||
for one in edit.edits_for(Path::new(path)).iter().rev() {
|
||||
out.replace_range(one.range.start as usize..one.range.end as usize, &one.new_text);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Extract `needle` out of `text` into `name`, into a file of its own.
|
||||
fn extract(text: &str, needle: &str, name: &str) -> Result<RefactorEdit, String> {
|
||||
let (start, end) = at(text, needle);
|
||||
extract_module(&files(text), Path::new(M), start, end, name, Home::NewFile)
|
||||
}
|
||||
|
||||
/// The two halves of an extraction, as the editor would have them.
|
||||
fn halves(text: &str, needle: &str, name: &str) -> (String, String) {
|
||||
let edit = extract(text, needle, name).expect("extracts");
|
||||
let new = format!("/rtl/{name}.sv");
|
||||
(applied(text, &edit, M), applied(text, &edit, &new))
|
||||
}
|
||||
|
||||
/// Every result has to be Verilog the formatter accepts and leaves alone the
|
||||
/// second time — the acceptance bar every refactoring in this crate meets.
|
||||
fn accepted(label: &str, text: &str) {
|
||||
let config = vlog_formatter::Config::default();
|
||||
let once = vlog_formatter::format_source(text, &config)
|
||||
.unwrap_or_else(|e| panic!("the formatter refuses {label}: {e}\n{text}"));
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "formatting {label} does not converge");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what it writes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const COMB: &str = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + b; // the sum
|
||||
assign q = s ^ 8'hFF;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_combinational_region_reads_two_names_and_drives_one() {
|
||||
let (old, new) = halves(COMB, "assign s = a + b; // the sum", "sum");
|
||||
assert_eq!(
|
||||
new,
|
||||
"\
|
||||
module sum (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] s
|
||||
);
|
||||
assign s = a + b; // the sum
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
assert!(old.contains("sum u_sum (\n .a(a),\n .b(b),\n .s(s)\n );"), "{old}");
|
||||
// The comment travelled: it is in the new file and gone from the old one.
|
||||
assert!(!old.contains("// the sum"), "{old}");
|
||||
accepted("the new module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
const SEQ: &str = "\
|
||||
module m (
|
||||
input logic clk,
|
||||
input logic rst_n,
|
||||
input logic [7:0] d,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] r;
|
||||
always_ff @(posedge clk or negedge rst_n) begin
|
||||
if (!rst_n) r <= '0;
|
||||
else r <= d;
|
||||
end
|
||||
assign q = r;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_sequential_region_makes_the_clock_an_input_and_the_register_an_output() {
|
||||
let start = SEQ.find("always_ff").expect("always") as u32;
|
||||
let end = SEQ.find(" end\n").expect("end") as u32 + 5;
|
||||
let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(SEQ, &edit, "/rtl/reg_stage.sv");
|
||||
assert!(new.contains("input logic clk,"), "{new}");
|
||||
assert!(new.contains("input logic rst_n,"), "{new}");
|
||||
assert!(new.contains("input logic [7:0] d,"), "{new}");
|
||||
assert!(new.contains("output logic [7:0] r"), "{new}");
|
||||
accepted("the sequential module", &new);
|
||||
accepted("what is left", &applied(SEQ, &edit, M));
|
||||
}
|
||||
|
||||
const PARAM: &str = "\
|
||||
package w_pkg;
|
||||
typedef logic [7:0] word_t;
|
||||
endpackage
|
||||
|
||||
module m #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input word_t a,
|
||||
output word_t q
|
||||
);
|
||||
import w_pkg::*;
|
||||
localparam int MASK = W - 1;
|
||||
word_t t;
|
||||
assign t = a & word_t'(MASK);
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_region_using_a_parameter_and_an_import_carries_both() {
|
||||
let (old, new) = halves(PARAM, "assign t = a & word_t'(MASK);", "masker");
|
||||
// The `localparam` the selection reads becomes a parameter of the new
|
||||
// module, and so does the parameter *its own default* names.
|
||||
assert!(new.contains("parameter int W = 8,"), "{new}");
|
||||
assert!(new.contains("parameter int MASK = W - 1"), "{new}");
|
||||
assert!(new.contains("import w_pkg::*;"), "{new}");
|
||||
assert!(new.contains("input word_t a,"), "{new}");
|
||||
assert!(new.contains("output word_t t"), "{new}");
|
||||
assert!(old.contains(".W(W),"), "{old}");
|
||||
assert!(old.contains(".MASK(MASK)"), "{old}");
|
||||
accepted("the parameterized module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_a_ports_own_width_names_crosses_with_it() {
|
||||
// The corpus found this one: `binary_to_gray`'s `N` is read by no
|
||||
// statement the selection carries — only by the *type* of the port the
|
||||
// extraction is about to write — so a closure over the region's
|
||||
// references alone left the new module naming nothing.
|
||||
let text = "\
|
||||
module m #(
|
||||
parameter int N = -1
|
||||
) (
|
||||
input logic [N-1:0] a,
|
||||
output logic [N-1:0] q
|
||||
);
|
||||
assign q = a ^ (a >> 1);
|
||||
endmodule
|
||||
";
|
||||
let (old, new) = halves(text, "assign q = a ^ (a >> 1);", "gray");
|
||||
assert!(new.contains("parameter int N = -1"), "{new}");
|
||||
assert!(new.contains("input logic [N-1:0] a,"), "{new}");
|
||||
assert!(new.contains("output logic [N-1:0] q"), "{new}");
|
||||
assert!(old.contains(".N(N)"), "{old}");
|
||||
accepted("the new module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_import_in_the_header_is_carried_across() {
|
||||
// The opentitan trial found this one: the binder records a wildcard
|
||||
// import in a reference's `paths` as `p::*` — the spelling the source
|
||||
// wrote — not as `p::<name>`, so a judgement matching on the latter
|
||||
// copied no import at all and the new file named a package's types with
|
||||
// nothing importing them.
|
||||
let pkg = "package p;\n typedef logic [1:0] w_t;\n parameter int W = 2;\nendpackage\n";
|
||||
let top = "\
|
||||
module m import p::*;
|
||||
(
|
||||
input logic [W-1:0] a,
|
||||
output w_t q
|
||||
);
|
||||
assign q = w_t'(a);
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/p.sv", pkg), (M, top)]);
|
||||
let (start, end) = at(top, "assign q = w_t'(a);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/caster.sv");
|
||||
assert!(new.contains("import p::*;"), "{new}");
|
||||
assert!(new.contains("input logic [W-1:0] a,"), "{new}");
|
||||
assert!(new.contains("output w_t q"), "{new}");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("`p::*`")), "{:?}", edit.warnings);
|
||||
accepted("the new module", &new);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_import_is_carried_across_only_when_the_name_it_supplies_is_needed() {
|
||||
let a = "package a_pkg;\n typedef logic [1:0] a_t;\nendpackage\n";
|
||||
let b = "package b_pkg;\n typedef logic [3:0] b_t;\nendpackage\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic [1:0] i,
|
||||
output logic [1:0] o
|
||||
);
|
||||
import a_pkg::a_t;
|
||||
import b_pkg::b_t;
|
||||
assign o = a_t'(i);
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/a.sv", a), ("/rtl/b.sv", b), (M, top)]);
|
||||
let (start, end) = at(top, "assign o = a_t'(i);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/caster.sv");
|
||||
assert!(new.contains("import a_pkg::a_t;"), "{new}");
|
||||
assert!(!new.contains("b_pkg"), "an import nothing moved needs is not copied: {new}");
|
||||
accepted("the new module", &new);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_declared_in_the_module_that_a_crossing_ports_type_names_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] i,
|
||||
output logic [7:0] o
|
||||
);
|
||||
typedef logic [7:0] local_t;
|
||||
local_t mid;
|
||||
assign mid = i;
|
||||
assign o = mid;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign mid = i;");
|
||||
assert!(message.contains("`local_t`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_create_files_gets_the_module_below_the_one_it_came_from() {
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, end, "sum", Home::SameFile)
|
||||
.expect("extracts");
|
||||
assert!(edit.created.is_empty(), "nothing is created");
|
||||
assert_eq!(edit.file_count(), 1, "one file is touched");
|
||||
let text = applied(COMB, &edit, M);
|
||||
assert!(text.contains("endmodule\n\nmodule sum ("), "{text}");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("did not say it can create files")));
|
||||
accepted("the one-file result", &text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_module_is_named_in_the_warnings_with_the_file_it_went_to() {
|
||||
let edit = extract(COMB, "assign s = a + b; // the sum", "sum").expect("extracts");
|
||||
assert_eq!(edit.created, vec![PathBuf::from("/rtl/sum.sv")]);
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("`sum.sv`")), "{:?}", edit.warnings);
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("3 ports")), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_whose_module_the_index_knows_gives_its_outputs_the_right_direction() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
logic mid;
|
||||
sub u_sub (.i(i), .o(mid));
|
||||
assign o = mid;
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (.i(i), .o(mid));");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "wrap", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/wrap.sv");
|
||||
assert!(new.contains("input logic i,"), "{new}");
|
||||
assert!(new.contains("output logic mid"), "{new}");
|
||||
accepted("the wrapper", &new);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The sentence an extraction of `needle` refuses with.
|
||||
fn refusal(text: &str, needle: &str) -> String {
|
||||
extract(text, needle, "n").expect_err("a refusal")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_an_item_is_refused() {
|
||||
let (start, _) = at(COMB, "assign s = a + b;");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, start + 8, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("cuts an item in half"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_outside_every_module_is_refused() {
|
||||
let text = "package p;\n typedef int t;\nendpackage\n";
|
||||
let (start, end) = at(text, "typedef int t;");
|
||||
let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("not inside one module's body"));
|
||||
}
|
||||
|
||||
/// The same three items, written as each of the three declarations the parser
|
||||
/// gives one node to.
|
||||
const INTERFACE: &str =
|
||||
"interface bus_if;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendinterface\n";
|
||||
const PROGRAM: &str = "program p;\n logic a;\n logic q;\n assign q = a;\nendprogram\n";
|
||||
const MODULE: &str = "module m;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_an_interface_or_a_program_is_refused() {
|
||||
// `vlog_parser` writes a `module`, an `interface` and a `program` as one
|
||||
// `ItemKind::Module`, and only `Module::kw` says which — so the gate has
|
||||
// to ask. QA's finding V2: without it an `interface` body extracted into a
|
||||
// module instantiated inside what remained an `interface`, and four names
|
||||
// in opentitan's `aes_masking_reseed_if.sv` stopped resolving.
|
||||
let said = refusal(INTERFACE, "assign q = a;");
|
||||
assert!(said.contains("inside an `interface`"), "{said}");
|
||||
assert!(said.contains("signals are its surface"), "{said}");
|
||||
|
||||
let said = refusal(PROGRAM, "assign q = a;");
|
||||
assert!(said.contains("inside a `program`"), "{said}");
|
||||
assert!(said.contains("testbench code"), "{said}");
|
||||
|
||||
// The same three items written as a module still extract.
|
||||
assert!(extract(MODULE, "assign q = a;", "n").is_ok(), "a `module` is still extractable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_is_not_offered_inside_an_interface_or_a_program() {
|
||||
// The cheap gate reads the same `Region`, so the lightbulb never appears
|
||||
// where the engine would refuse.
|
||||
for text in [INTERFACE, PROGRAM] {
|
||||
let (start, end) = at(text, "assign q = a;");
|
||||
assert!(extract_site(text, start, end).is_none(), "not offered in: {text}");
|
||||
}
|
||||
let (start, end) = at(MODULE, "assign q = a;");
|
||||
assert!(extract_site(MODULE, start, end).is_some(), "and still offered in a module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_a_parameter_a_genvar_and_a_bind_are_each_refused_by_name() {
|
||||
let non_ansi = "module m (a);\n input a;\n wire b;\n assign b = a;\nendmodule\n";
|
||||
assert!(refusal(non_ansi, "input a;").contains("a port declaration"));
|
||||
|
||||
let param = "module m;\n localparam int W = 8;\n wire [W-1:0] x;\nendmodule\n";
|
||||
assert!(refusal(param, "localparam int W = 8;").contains("a `localparam` declaration"));
|
||||
|
||||
let genvar = "module m;\n genvar g;\nendmodule\n";
|
||||
assert!(refusal(genvar, "genvar g;").contains("a `genvar` declaration"));
|
||||
|
||||
let bind = "module m;\n bind m sub u_s ();\nendmodule\n";
|
||||
assert!(refusal(bind, "bind m sub u_s ();").contains("a `bind` directive"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_call_and_a_compiler_directive_are_refused() {
|
||||
let macro_item = "module m;\n `ASSERT(a, b)\n wire w;\nendmodule\n";
|
||||
assert!(refusal(macro_item, "`ASSERT(a, b)").contains("macro invocation"));
|
||||
|
||||
let directive = "module m;\n`ifdef FOO\n`endif\n wire w;\nendmodule\n";
|
||||
assert!(refusal(directive, "`ifdef FOO").contains("compiler directive"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initial_and_a_final_block_are_refused_as_testbench_code() {
|
||||
let initial = "module m;\n logic x;\n initial x = 1'b0;\nendmodule\n";
|
||||
assert!(refusal(initial, "initial x = 1'b0;").contains("`initial` block"));
|
||||
|
||||
let last = "module m;\n logic x;\n final $display(\"%d\", x);\nendmodule\n";
|
||||
assert!(refusal(last, "final $display(\"%d\", x);").contains("`final` block"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_inside_the_selection_and_used_outside_it_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
wire t;
|
||||
assign t = a;
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
// `t`'s declaration is in the selection; `assign q = t;` is not.
|
||||
let (start, _) = at(text, "wire t;");
|
||||
let (_, end) = at(text, "assign t = a;");
|
||||
let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile);
|
||||
let message = edit.expect_err("a refusal");
|
||||
assert!(
|
||||
message.contains("move the declaration of `t` out of the selection first"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_driven_on_both_sides_of_the_selection_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic a,
|
||||
input logic b,
|
||||
output logic q
|
||||
);
|
||||
always_comb q = a;
|
||||
always_comb q = b;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "always_comb q = a;");
|
||||
assert!(message.contains("`q` is driven on both sides of the selection."), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_or_function_the_selection_calls_from_outside_it_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
function automatic logic [7:0] twice(input logic [7:0] x);
|
||||
return x + x;
|
||||
endfunction
|
||||
assign q = twice(a);
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign q = twice(a);");
|
||||
assert!(message.contains("`twice`"), "{message}");
|
||||
assert!(message.contains("a function"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_passed_to_a_routine_inside_the_selection_refuses_rather_than_guesses() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic clk,
|
||||
output logic [7:0] q
|
||||
);
|
||||
always_ff @(posedge clk) begin
|
||||
$cast(q, 8'h01);
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "always_ff @(posedge clk) begin\n $cast(q, 8'h01);\n end");
|
||||
assert!(message.contains("passes `q` to a task or function"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_reference_out_of_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i\n);\n logic probe;\nendmodule\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
sub u_sub (.i(i));
|
||||
assign o = u_sub.probe;
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "assign o = u_sub.probe;");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
let message = edit.expect_err("a refusal");
|
||||
assert!(message.contains("through the design hierarchy"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crossing_name_with_an_unpacked_dimension_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] mem [0:3];
|
||||
assign q = mem[0] ^ a;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign q = mem[0] ^ a;");
|
||||
assert!(message.contains("unpacked dimension"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_already_declares_is_refused() {
|
||||
let sub = "module taken;\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/lib/taken.sv", sub), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "taken", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("already declares `taken`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused() {
|
||||
let twin = "module m;\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/twin.sv", twin), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("declared in more than one indexed file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timescale_a_new_file_would_not_inherit_is_refused_and_the_same_file_is_not() {
|
||||
let text = format!("`timescale 1ns/1ps\n{COMB}");
|
||||
let (start, end) = at(&text, "assign s = a + b; // the sum");
|
||||
let sources = vec![(PathBuf::from(M), text.clone())];
|
||||
let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
let message = refused.expect_err("a refusal");
|
||||
assert!(message.contains("`timescale"), "{message}");
|
||||
// The same directive is no obstacle when the module stays in the file.
|
||||
extract_module(&sources, Path::new(M), start, end, "sum", Home::SameFile)
|
||||
.expect("the same file inherits it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_nettype_is_refused_the_same_way() {
|
||||
let text = format!("`default_nettype none\n{COMB}");
|
||||
let (start, end) = at(&text, "assign s = a + b; // the sum");
|
||||
let sources = vec![(PathBuf::from(M), text.clone())];
|
||||
let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(refused.expect_err("a refusal").contains("`default_nettype"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_an_identifier_is_refused_before_anything_else() {
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
for name in ["", "2fast", "\\odd-name", "with space"] {
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, end, name, Home::NewFile);
|
||||
assert!(
|
||||
edit.expect_err("a refusal").contains("not a plain SystemVerilog identifier"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_instantiation_inside_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top =
|
||||
"module m (\n input logic i,\n output logic o\n);\n sub u_sub (i, o);\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (i, o);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("by position"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_instantiation_inside_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top = "module m (\n input logic i,\n output logic o\n);\n sub u_sub (.*);\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (.*);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("`.*`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_of_a_module_the_index_does_not_know_is_refused() {
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
stranger u_s (.i(i), .o(o));
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(top, "stranger u_s (.i(i), .o(o));");
|
||||
assert!(message.contains("no single indexed declaration"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_outside_the_module_in_the_same_file_is_refused_for_a_new_file() {
|
||||
let text = "\
|
||||
typedef logic [7:0] byte_t;
|
||||
|
||||
module m (
|
||||
input byte_t a,
|
||||
output byte_t q
|
||||
);
|
||||
byte_t t;
|
||||
assign t = a;
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign t = a;");
|
||||
assert!(message.contains("declared outside `m` in the same file"), "{message}");
|
||||
// The same selection is fine when the module stays in that file.
|
||||
let (start, end) = at(text, "assign t = a;");
|
||||
extract_module(&files(text), Path::new(M), start, end, "n", Home::SameFile)
|
||||
.expect("the same file sees it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_covers_nothing_is_refused() {
|
||||
let (start, _) = at(COMB, "module m");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, start, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("no module item"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused() {
|
||||
let text = "module m;\n assign = ;\nendmodule\n";
|
||||
let edit = extract_module(&files(text), Path::new(M), 0, text.len() as u32, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("does not parse"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_occupied_file_name_is_refused() {
|
||||
let sources = workspace(&[("/rtl/sum.sv", "// notes\n"), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("already a `sum.sv`"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the cheap gate
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_gate_names_the_module_and_everything_the_engine_will_read() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
import p::*;
|
||||
sub u_sub (.i(i), .o(o));
|
||||
endmodule
|
||||
";
|
||||
let (start, end) = at(text, "sub u_sub (.i(i), .o(o));");
|
||||
let site = extract_site(text, start, end).expect("a site");
|
||||
assert_eq!(site.module, "m");
|
||||
assert_eq!(site.default_name, "m_extracted");
|
||||
assert_eq!(site.units, vec!["m".to_string(), "sub".to_string(), "p".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_is_empty_where_the_engine_would_refuse_for_want_of_an_item() {
|
||||
assert!(extract_site(COMB, 0, 3).is_none(), "outside every module");
|
||||
assert!(extract_site("not verilog at all", 0, 4).is_none(), "an unparsed buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_with_no_selection_extracts_the_item_it_is_on() {
|
||||
let at_assign = COMB.find("assign s").expect("assign") as u32 + 3;
|
||||
let edit =
|
||||
extract_module(&files(COMB), Path::new(M), at_assign, at_assign, "sum", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(COMB, &edit, "/rtl/sum.sv");
|
||||
assert!(new.contains("assign s = a + b;"), "{new}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the census: the design still names what it named
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_two_files_together_name_every_signal_the_one_file_named() {
|
||||
// The reference census the corpus trials run, in miniature: the names the
|
||||
// design writes down are the same before and after, because an extraction
|
||||
// moves items and adds a header, and adds no name that was not there.
|
||||
let start = SEQ.find("always_ff").expect("always") as u32;
|
||||
let end = SEQ.find(" end\n").expect("end") as u32 + 5;
|
||||
let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let old = applied(SEQ, &edit, M);
|
||||
let new = applied(SEQ, &edit, "/rtl/reg_stage.sv");
|
||||
let before = words(SEQ);
|
||||
let after: Vec<String> = words(&old).into_iter().chain(words(&new)).collect();
|
||||
for name in ["clk", "rst_n", "d", "q", "r"] {
|
||||
let was = before.iter().filter(|w| *w == name).count();
|
||||
let now = after.iter().filter(|w| *w == name).count();
|
||||
assert!(now >= was, "`{name}` was named {was} times and is now named {now}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier-shaped word of a text.
|
||||
fn words(text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in text.chars() {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else if !word.is_empty() {
|
||||
out.push(std::mem::take(&mut word));
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
out.push(word);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crossing_member_access_names_the_head_and_the_field_second() {
|
||||
// QA's LOW: `b.data` and `s.f` cross the boundary as `b` and `s` — the
|
||||
// port and the variable — and a sentence leading with the field reads as
|
||||
// if the field were a signal of `m`'s own.
|
||||
let iface = "interface bus_if;\n logic data;\n modport mp (output data);\nendinterface\nmodule m (bus_if.mp b, input logic a);\n logic q;\n assign b.data = a;\n assign q = a;\nendmodule\n";
|
||||
let said = refusal(iface, "assign b.data = a;");
|
||||
assert!(said.contains("uses `b.data`"), "{said}");
|
||||
assert!(said.contains("`b` is declared with a type written outside `m`"), "{said}");
|
||||
|
||||
let packed = "typedef struct packed {\n logic f;\n logic g;\n} s_t;\nmodule m (input logic a, output s_t s);\n logic q;\n assign s.f = a;\n assign q = a;\nendmodule\n";
|
||||
let said = refusal(packed, "assign s.f = a;");
|
||||
assert!(said.contains("uses `s.f`"), "{said}");
|
||||
assert!(said.contains("`s` is declared with a type written outside `m`"), "{said}");
|
||||
}
|
||||
@@ -97,7 +97,7 @@ request.
|
||||
| L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. |
|
||||
| L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. |
|
||||
| ~~L8~~ | ~~Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19).~~ — **delivered 2026-09-02 by TODO §26**: `lucisv.instantiate [uri, position, module]`, planned through the ghost's own `nearest_definition`/`plan_for`, rendered plainly and pushed as a `workspace/applyEdit`. Documented with a keymap in `editors/nvim/README.md`. | inline-instantiation README. |
|
||||
| L9 | `codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved. | TODO §10 deferred. |
|
||||
| ~~L9~~ | ~~`codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved.~~ — **delivered 2026-09-04/05 by TODO §37** (lazy resolve, 11.8× on the cursor path; the inlay zero ruled correct — `pins_if` is outside the default scope) and **ruled** (a widen stays one bar per session). | TODO §10 closed. |
|
||||
| L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. |
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_fc49ef3316","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_63f86fa784","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
Binary file not shown.
Binary file not shown.
+6
-1
@@ -297,6 +297,11 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
<td>Removes the <code dir="auto">import pkg::*;</code> lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — <code dir="auto">lucisv.organizeImports</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Extract module</td>
|
||||
<td>code action (<code dir="auto">refactor.extract</code>) / command</td>
|
||||
<td>Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, <code dir="auto">import</code>s carried across, the items moved byte for byte, the replacing instantiation rendered from the new module’s own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — <code dir="auto">lucisv.extractModule</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Instantiate module</td>
|
||||
<td>inline completion / <code dir="auto">lucisv.instantiate</code></td>
|
||||
<td>Builds an instance from an indexed module interface, including in clients without ghost text</td>
|
||||
@@ -347,4 +352,4 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
</table>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-lifecycle">Workspace lifecycle</h2><a class="sl-anchor-link" href="#workspace-lifecycle"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace lifecycle”</span></a></div>
|
||||
<p>The server handles <code dir="auto">didOpen</code>, incremental <code dir="auto">didChange</code>, <code dir="auto">didSave</code>, <code dir="auto">didClose</code>, watched-file changes, configuration changes, cancellation, shutdown, and exit. It dynamically registers file watchers, emits work-done progress while building large indexes, coalesces code-lens refreshes, and promotes open-buffer overlays into the workspace without waiting for disk writes.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T23:03:54.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T01:00:31.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+1
-1
@@ -757,4 +757,4 @@
|
||||
<p>Reports a <code dir="auto">;</code> written after a <code dir="auto">`uvm_*</code> macro invocation. The macros expand to a <code dir="auto">begin … end</code>, so the <code dir="auto">;</code> is a null statement — usually inert, and not after <code dir="auto">if (x) </code>uvm_info(…); else …<code dir="auto">, where the </code>else<code dir="auto">then belongs to nothing. Off by default in both, because the semicolon is written everywhere in existing UVM code. No fix: deleting it is exactly the edit that is unsafe in the shape the rule exists for. Verible's</code>uvm-macro-semicolon`, same default.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="v2001-generate-begin">v2001-generate-begin</h2><a class="sl-anchor-link" href="#v2001-generate-begin"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “v2001-generate-begin”</span></a></div>
|
||||
<p>Reports a bare <code dir="auto">begin … end</code> written directly inside a <code dir="auto">generate … endgenerate</code> with no <code dir="auto">if</code>, <code dir="auto">for</code> or <code dir="auto">case</code> around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block <code dir="auto">module-begin-block</code> reads, one scope in. Verible’s <code dir="auto">v2001-generate-begin</code>, same default.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T01:00:31.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
@@ -70,6 +70,7 @@ index scope when the defining module lives outside the default folder scope.
|
||||
| Rename | `textDocument/rename` | Renames local or workspace-resolved symbols |
|
||||
| Port actions | code actions / commands | Adds, removes, and propagates module ports; expands a `.*` wildcard into the named connections it stands for (a port with no same-named signal in scope becomes `.p()` and is named in a warning) — `lucisv.expandWildcard`; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — `lucisv.convertToAnsi` |
|
||||
| Organize imports | code action (`source.organizeImports`) / command | Removes the `import pkg::*;` lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — `lucisv.organizeImports` |
|
||||
| Extract module | code action (`refactor.extract`) / command | Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, `import`s carried across, the items moved byte for byte, the replacing instantiation rendered from the new module's own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — `lucisv.extractModule` |
|
||||
| Instantiate module | inline completion / `lucisv.instantiate` | Builds an instance from an indexed module interface, including in clients without ghost text |
|
||||
| Apply workspace edit | `workspace/applyEdit` | Delivers multi-file refactor changes to the client |
|
||||
| Show definition | `window/showDocument` | Opens a generated or resolved target after an action |
|
||||
|
||||
@@ -125,6 +125,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `vlog_refactor ──▶ vlog_semantic` (organize-imports) | depends | `imports::{import_usage, import_scopes, unused_imports, PackageExports, Exports}` — the one "is this import used" judgement, shared with the linter (§52, 2026-09-05). |
|
||||
| `vlog_linter ──▶ vlog_semantic` (organize-imports) | depends | the same `imports::*` judgement behind the `unused-import` rule; `MentionOracle::package_exports` is a new default method, so no implementor broke (§52). |
|
||||
| `lucisv_server ──▶ vlog_semantic` (organize-imports) | depends | `WorkspaceIndex::reexported_packages`, read by `lucisv_server::imports` to close the file set over re-exports (§52). |
|
||||
| `lucisv_server ◀── vlog_refactor` (extract-module) | depends | `RefactorEdit::created` — the files an edit creates, read by `lucisv_server::extract` to emit `CreateFile` document changes when `ClientAbilities::create_files` (read at `initialize`: `workspace.workspaceEdit.documentChanges` + `resourceOperations: create`) allows, else the same-file fallback (§53.1, 2026-09-06). |
|
||||
| `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. |
|
||||
| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). |
|
||||
| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache), `atomic::write_atomic` (formatter and lint-fix replacement). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) |
|
||||
@@ -666,6 +667,7 @@ update the filing README(s) and this file.
|
||||
| ~~29~~ | ~~An unknown rule name in the **editor's** `lucisv.lint.select`/`ignore` is still dropped silently, while §42 logs the same mistake in a project file (and `lucisv.lint.options` logs its bad entries). Wants the same once-only log through `notification.rs`.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.1):** `settings::rules` records every dropped name in `ClientSettings::lint_name_warnings` as `lucisv.lint.<select|ignore>: unknown rule: <name>`; `apply_settings` logs what the previous settings value did not already say — once per (setting, name), re-armed by a changed list. | lint-config-contract (QA) | lucisv_server |
|
||||
| ~~30~~ | ~~**An unreadable directory aborts the whole walk.** `Walk::dir` propagates `read_dir`'s error with `?`, so one permission-denied directory anywhere under the start — reachable now that a symlink to an outside directory is followed once (§2.9-8's ruling) — drops every file already found and fails the run. Found by walk-cycles' QA on a link to `/`. Wanted: skip the directory and say so through a warning channel the walk does not have today (the filelist-missing-file precedent), which is also where a dangling source link's warning belongs.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.2):** `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink; an unreadable directory, an unreadable `.gitignore` and a dangling source link are warned about (`warning: <path>: <message>` on the CLI's stderr before the report, exit code unchanged; logged once per scan by the server through `report_scope`) and the walk continues. | walk-cycles (QA) | lucisv_core / lucisv / lucisv_server |
|
||||
| 31 | **DPI-export name binding remains open.** Package re-export resolution closed §2.9-16, but the name in a DPI export is still not a semantic reference. Keep this separate from the delivered package-member traversal. | dpi-export request (b); package-reexports | vlog_semantic |
|
||||
| 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ const path = require('path');
|
||||
const vscode = require('vscode');
|
||||
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
|
||||
const { createRestarter } = require('./restart');
|
||||
const { executeCommand } = require('./extract');
|
||||
const { HierarchyView } = require('./hierarchyView');
|
||||
|
||||
/** The single client, kept only so `deactivate` can stop it. */
|
||||
@@ -187,6 +188,24 @@ function activate(context) {
|
||||
// still request a snapshot, but receive no unsolicited lucisv traffic.
|
||||
hierarchyView: true,
|
||||
},
|
||||
// The one place this extension steps between a server command and the
|
||||
// server. `lucisv.extractModule` needs a name for the new module and LSP
|
||||
// has no prompt, so the server's code action carries the command with a
|
||||
// default name and this asks the user for a better one before it goes out
|
||||
// (docs/features/extract-inline-module/README.md). Every other command
|
||||
// passes through untouched. It has to be middleware rather than a command
|
||||
// of our own: the language client registers every command the server
|
||||
// advertises, so a second registration of the same id would collide with
|
||||
// it at activation.
|
||||
middleware: {
|
||||
executeCommand: (command, args, next) =>
|
||||
executeCommand(
|
||||
{ showInputBox: (options) => vscode.window.showInputBox(options) },
|
||||
command,
|
||||
args,
|
||||
next,
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// The one thing "extract into module" needs that LSP has no request for:
|
||||
// asking the user what to call the new module.
|
||||
//
|
||||
// The server offers the code action with a `Command` rather than an edit —
|
||||
// `lucisv.extractModule [uri, range, defaultName]` — precisely so a client can
|
||||
// step in between the click and the edit. This file is that step.
|
||||
//
|
||||
// **Through the language client's middleware, not through a second command.**
|
||||
// `vscode-languageclient` registers every command the server advertises in
|
||||
// `executeCommandProvider` with `vscode.commands.registerCommand`, so an
|
||||
// extension that registered `lucisv.extractModule` itself would collide with
|
||||
// it at activation. `middleware.executeCommand` is the seam the client provides
|
||||
// for exactly this: it sees the command on its way out, may change the
|
||||
// arguments, and hands them to `next`. One command id, one server contract,
|
||||
// and every other client — Vim, a CLI — runs the same command with the default
|
||||
// name and gets the same edit.
|
||||
//
|
||||
// Nothing here knows about `vscode`: the dependencies come in as an object, so
|
||||
// `extract_test.js` drives the whole flow headlessly.
|
||||
// See docs/features/extract-inline-module/README.md.
|
||||
|
||||
/** The command the server's code action carries. */
|
||||
const EXTRACT_MODULE = 'lucisv.extractModule';
|
||||
|
||||
/**
|
||||
* A plain SystemVerilog identifier, which is the only thing the engine will
|
||||
* name a module — and a file — with. Checked here as well as in the engine so
|
||||
* the user is told while the box is open rather than by an error afterwards.
|
||||
*/
|
||||
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
||||
|
||||
/**
|
||||
* What the input box says about what has been typed so far, or `undefined`
|
||||
* when it is a name lucisv would accept.
|
||||
*
|
||||
* The message is the one the engine would refuse with, in the present tense:
|
||||
* an editor's validation is read while typing, not after.
|
||||
*/
|
||||
function validateModuleName(value) {
|
||||
const name = (value || '').trim();
|
||||
if (name === '') return 'The new module needs a name.';
|
||||
if (!IDENTIFIER.test(name)) {
|
||||
return 'A module name is a plain SystemVerilog identifier: a letter or `_`, then letters, digits, `_` or `$`.';
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The language client's `executeCommand` middleware.
|
||||
*
|
||||
* - `deps.showInputBox` — `vscode.window.showInputBox`, which resolves to the
|
||||
* typed string or to `undefined` when the user pressed Escape.
|
||||
* - `command`, `args`, `next` — what the client hands every middleware.
|
||||
*
|
||||
* Every command but this one goes straight through. This one asks for a name,
|
||||
* and a cancelled box resolves to `undefined` without ever reaching the
|
||||
* server: an extraction nobody named is one nobody asked for.
|
||||
*/
|
||||
async function executeCommand(deps, command, args, next) {
|
||||
if (command !== EXTRACT_MODULE) return next(command, args);
|
||||
const [uri, range, suggested] = args || [];
|
||||
const name = await deps.showInputBox({
|
||||
title: 'Extract into module',
|
||||
prompt: 'Name for the new module',
|
||||
value: typeof suggested === 'string' ? suggested : '',
|
||||
validateInput: validateModuleName,
|
||||
});
|
||||
if (name === undefined) return undefined;
|
||||
const trimmed = name.trim();
|
||||
if (validateModuleName(trimmed) !== undefined) return undefined;
|
||||
return next(command, [uri, range, trimmed]);
|
||||
}
|
||||
|
||||
module.exports = { EXTRACT_MODULE, executeCommand, validateModuleName };
|
||||
@@ -0,0 +1,137 @@
|
||||
// Checks for `extract.js`: the input box that names the module the server is
|
||||
// about to extract, and what it does when the user does not name one.
|
||||
//
|
||||
// node extract_test.js
|
||||
//
|
||||
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
|
||||
// test runner — the same style as `restart_test.js` next to it.
|
||||
//
|
||||
// The fakes below script only what `extract.js` is allowed to depend on: an
|
||||
// input box that resolves to a string or to `undefined`, and a `next` that
|
||||
// records what it was handed. Nothing here re-implements VS Code.
|
||||
// See docs/features/extract-inline-module/README.md.
|
||||
|
||||
const { EXTRACT_MODULE, executeCommand, validateModuleName } = require('./extract');
|
||||
|
||||
let checks = 0;
|
||||
|
||||
function ok(condition, what) {
|
||||
checks += 1;
|
||||
if (!condition) fail(what);
|
||||
}
|
||||
|
||||
function equal(got, want, what) {
|
||||
checks += 1;
|
||||
const a = JSON.stringify(got);
|
||||
const b = JSON.stringify(want);
|
||||
if (a !== b) fail(`${what}: got ${a}, want ${b}`);
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
console.error(`extract: FAIL — ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** A `next` that records every call and answers with a marker. */
|
||||
function recorder() {
|
||||
const calls = [];
|
||||
const next = (command, args) => {
|
||||
calls.push({ command, args });
|
||||
return Promise.resolve('applied');
|
||||
};
|
||||
return { calls, next };
|
||||
}
|
||||
|
||||
/** An input box that answers `answer` and records the options it was given. */
|
||||
function box(answer) {
|
||||
const seen = [];
|
||||
const showInputBox = (options) => {
|
||||
seen.push(options);
|
||||
return Promise.resolve(answer);
|
||||
};
|
||||
return { seen, showInputBox };
|
||||
}
|
||||
|
||||
const ARGS = ['file:///rtl/m.sv', { start: { line: 6 }, end: { line: 6 } }, 'm_extracted'];
|
||||
|
||||
async function aNameTypedIntoTheBoxReachesTheServer() {
|
||||
const { calls, next } = recorder();
|
||||
const { seen, showInputBox } = box('adder');
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, 'applied', 'the server’s answer comes back to the client');
|
||||
equal(calls.length, 1, 'the command is sent once');
|
||||
equal(calls[0].command, EXTRACT_MODULE, 'under its own name');
|
||||
equal(calls[0].args[0], ARGS[0], 'the uri is passed through');
|
||||
equal(calls[0].args[1], ARGS[1], 'and so is the range');
|
||||
equal(calls[0].args[2], 'adder', 'the typed name replaces the default');
|
||||
equal(seen.length, 1, 'one box is shown');
|
||||
equal(seen[0].value, 'm_extracted', 'prefilled with the default the server proposed');
|
||||
}
|
||||
|
||||
async function surroundingWhitespaceIsTrimmedOffTheName() {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(' adder\t');
|
||||
await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(calls[0].args[2], 'adder', 'a name is what is left after the spaces');
|
||||
}
|
||||
|
||||
async function anEscapedBoxSendsNothingAtAll() {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(undefined);
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, undefined, 'a cancelled extraction answers nothing');
|
||||
equal(calls.length, 0, 'and reaches the server not at all');
|
||||
}
|
||||
|
||||
async function aNameTheEngineWouldRefuseIsNotSentEither() {
|
||||
// The box's own validator should stop this, but a client that ignores
|
||||
// `validateInput` must not get a file called `2fast.sv` out of it.
|
||||
for (const typed of ['', ' ', '2fast', 'with space', '\\odd-name']) {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(typed);
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, undefined, `\`${typed}\` is not a module name`);
|
||||
equal(calls.length, 0, `\`${typed}\` never reaches the server`);
|
||||
}
|
||||
}
|
||||
|
||||
async function everyOtherCommandGoesStraightThrough() {
|
||||
const { calls, next } = recorder();
|
||||
let shown = 0;
|
||||
const showInputBox = () => {
|
||||
shown += 1;
|
||||
return Promise.resolve('never');
|
||||
};
|
||||
const args = ['file:///rtl/m.sv', { line: 3, character: 0 }];
|
||||
const result = await executeCommand({ showInputBox }, 'lucisv.organizeImports', args, next);
|
||||
equal(result, 'applied', 'the other commands answer as they always did');
|
||||
equal(shown, 0, 'and no box is shown for them');
|
||||
equal(calls, [{ command: 'lucisv.organizeImports', args }], 'passed through unchanged');
|
||||
}
|
||||
|
||||
function theValidatorSaysWhatTheEngineWouldSay() {
|
||||
equal(validateModuleName('adder'), undefined, 'a plain identifier is fine');
|
||||
equal(validateModuleName('_adder$2'), undefined, 'so are `_`, digits and `$` after the first');
|
||||
ok(validateModuleName('').includes('needs a name'), 'an empty box says so');
|
||||
ok(validateModuleName(' ').includes('needs a name'), 'and so does a blank one');
|
||||
ok(validateModuleName('2fast').includes('plain SystemVerilog identifier'), 'a leading digit');
|
||||
ok(validateModuleName('a b').includes('plain SystemVerilog identifier'), 'a space');
|
||||
ok(validateModuleName('\\odd-name').includes('plain SystemVerilog identifier'), 'an escaped name');
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const watchdog = setTimeout(
|
||||
() => fail('timed out after 5s — a promise this test waits on never settled'),
|
||||
5000,
|
||||
);
|
||||
theValidatorSaysWhatTheEngineWouldSay();
|
||||
await aNameTypedIntoTheBoxReachesTheServer();
|
||||
await surroundingWhitespaceIsTrimmedOffTheName();
|
||||
await anEscapedBoxSendsNothingAtAll();
|
||||
await aNameTheEngineWouldRefuseIsNotSentEither();
|
||||
await everyOtherCommandGoesStraightThrough();
|
||||
clearTimeout(watchdog);
|
||||
console.log(`extract: OK — ${checks} checks over the extract input box`);
|
||||
}
|
||||
|
||||
main().catch((error) => fail(error.stack || String(error)));
|
||||
Reference in new issue
Block a user