Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23e2e4bca5 | ||
|
|
a2a22adad8 | ||
|
|
9d1eb1671e | ||
|
|
5d70cb89cc | ||
|
|
da32237a0e | ||
|
|
c82978c3db | ||
|
|
1b8723ca1f | ||
|
|
2675131f8c | ||
|
|
409acae087 | ||
|
|
f5edac9197 | ||
|
|
7df86fe979 | ||
|
|
b4a0668b24 | ||
|
|
41945912a3 | ||
|
|
faf890d9f0 | ||
|
|
3ceba21bb2 | ||
|
|
b12e0cc2c4 | ||
|
|
01843eb75a | ||
|
|
5e02142a8f | ||
|
|
07ef771a35 | ||
|
|
eb54042032 | ||
|
|
a1c77c053f | ||
|
|
51cbfd27df | ||
|
|
e13ae4c89b | ||
|
|
b2bb912bbb | ||
|
|
126a6bcdac | ||
|
|
bc59336d91 | ||
|
|
b2a5f0a171 | ||
|
|
32204eba71 | ||
|
|
243472901d | ||
|
|
4621214a51 | ||
|
|
8e65da1ba8 | ||
|
|
5c9fdb2c62 | ||
|
|
e51a2c7f21 | ||
|
|
dafa4f0500 | ||
|
|
6c1f863417 | ||
|
|
501b36d8b8 | ||
|
|
9c75b7a4e5 | ||
|
|
be084f07b5 | ||
|
|
bbdbfe9045 |
No files matched your search
+194
@@ -4,6 +4,200 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.55.0 — 2026-09-17
|
||||
|
||||
### Loop 3, round 2 — find-references reaches a module's internals
|
||||
|
||||
- **References see every cross-file use of a module's nets, variables
|
||||
and instances.** With `module leaf` declaring `logic sig` and another
|
||||
file writing `assign w = u_leaf.sig;` (or a `bind` directive naming
|
||||
`sig` in a connection), Find All References from the declaration
|
||||
answered `leaf.sv` alone — while a rename already edited both files.
|
||||
The two index questions behind references asked the module's
|
||||
*connection* surface (ports and parameters), which cannot hold an
|
||||
internal net; they now ask the *hierarchical* surface, the one a path
|
||||
in another file actually reaches the declaration by. Every answer for
|
||||
a port, parameter, package member, class field or struct field is
|
||||
byte-for-byte what it was. Hover's declaration snippet uses the same
|
||||
lookup and now shows the live line for such a signal in an edited
|
||||
buffer. On the opentitan tree, references on `aes.sv`'s
|
||||
`entropy_masking_req` now list `aes_bind.sv`, and `state_q` in
|
||||
`entropy_src_main_sm.sv` lists its use in `entropy_src_core.sv`.
|
||||
(`docs/features/references-hierarchical-surface/README.md`.)
|
||||
- **A closed declaring file's own uses are in the answer.** The index
|
||||
deliberately posts no in-file references for a module's internal
|
||||
signals (a table sized by every RTL body, for a rarely asked
|
||||
question), so a request from another file into a declaring file
|
||||
nobody has open used to list the cross-file sites and silently omit
|
||||
that file's own `assign … = sig;` lines. That one file is now parsed
|
||||
once, on exactly that request shape — 0.4–1.5 ms on a real design
|
||||
file, the same trade a rename already makes.
|
||||
- **A stale index may omit a location; it can never point at a wrong
|
||||
line.** Three QA rounds found that a span recorded at index time, or
|
||||
computed against one read of a closed file, could be rendered against
|
||||
a different read of the same file after an external edit (another
|
||||
tool, `git checkout`, a build step) and land on a line that no longer
|
||||
holds the name. Each closed file is now read exactly once per
|
||||
request, and every index-time span — closed files and the
|
||||
open-buffer declaration fallback alike — must still spell the name
|
||||
exactly where it is rendered, or it is dropped. Escaped identifiers,
|
||||
UTF-8 boundaries, a deleted declaring file and a name that is both a
|
||||
port and a net are covered by tests; references and rename are
|
||||
asserted to agree with the whole-scope engine.
|
||||
- Cost, accepted and recorded in `docs/perf/README.md`: a references
|
||||
request on a heavily used local net in a 40 000-line buffer now
|
||||
walks the indexed path, 1.22 → 1.54 ms median; every other harness
|
||||
row unchanged.
|
||||
|
||||
## 0.54.0 — 2026-09-12
|
||||
|
||||
### Loop 3, round 1 — a rename correctness fix and a faster first edit
|
||||
|
||||
- **Rename edits a `bind` file's own occurrences.** Renaming a module's
|
||||
internal net that a `bind` directive's connection names bare
|
||||
(`bind aes chk u (.req(entropy_masking_req))`), or reaches by a
|
||||
hierarchical path (`u_aes_core.u_aes_prng_clearing.seed_en`), used to
|
||||
leave the bind file untouched and say nothing — the design no longer
|
||||
elaborated after the rename. The resolver had asked the bind target's
|
||||
connection surface (ports and parameters) for a bare name, and rooted a
|
||||
bind's hierarchical path in the scope the directive is written in,
|
||||
which declares nothing. A bind connection is now a reference on the
|
||||
target's hierarchical surface, a bind's path is rooted at the target
|
||||
(a multi-segment target such as `bind tb.u_aes …` included), and an
|
||||
occurrence the engine cannot resolve is warned about by file and line,
|
||||
never silent. Definition, hover and references answer over bind files
|
||||
the same way. The index store format is bumped (`FACTS_FORMAT` 20): a
|
||||
0.53.0 store is rebuilt once. (Found by the previous round's QA on the
|
||||
opentitan tree.)
|
||||
- **The first request after an edit is ~19 % faster.** On a 40 000-line
|
||||
generated register file the first code-action menu after a
|
||||
one-character change costs 88 ms instead of 109: the lexer's raw and
|
||||
comment-attachment phases are fused (no intermediate token vector), the
|
||||
parser no longer clones a token it is about to discard, and the
|
||||
operator table is filtered by first byte before the longest-match
|
||||
scan. Token stream, diagnostics, AST and symbols are byte-for-byte what
|
||||
they were over 4 807 files; every formatter and linter output is
|
||||
identical.
|
||||
- `--verbose` timing lines carry a third group, `rebuild{…}`, that splits
|
||||
the document rebuild after an edit into its stages.
|
||||
- Known remainder, filed: cross-file *references* from a module's
|
||||
internal net (bind or not) still stop at the connection surface; the
|
||||
rest of the rebuild (the token clone, analysis, external resolution).
|
||||
|
||||
## 0.53.0 — 2026-09-09
|
||||
|
||||
### The 0.52.0 review — one correctness fix
|
||||
|
||||
- **A symlink-aliased directory is indexed once at startup.** 0.52.0's
|
||||
startup scan walks the open file's folder before the rest of the
|
||||
workspace, and the two walks kept separate visited sets: a directory
|
||||
reachable by two spellings (`a_alias -> z_real`) was indexed twice, so
|
||||
go-to-definition offered two targets and a valid rename was refused as
|
||||
ambiguous until the next rescan (found by the independent review of
|
||||
0.52.0). The two walks now share one directory identity; when an alias
|
||||
sorts before the open folder the scan takes the single canonical walk;
|
||||
an alias only the remaining walk can see requests one ordinary rescan
|
||||
so the spellings converge; and a same-named symlink to an open buffer
|
||||
is never a second copy of it. Startup, rescan and restart agree on
|
||||
index paths, definitions, rename and diagnostics across nine alias
|
||||
shapes, and a genuine duplicate declaration is still refused.
|
||||
- The load probe in `tools/perf/` primes a warm store before timing and
|
||||
stamps scan completion from the scan's own end event.
|
||||
- No performance number moved; the CLI is unchanged.
|
||||
|
||||
## 0.52.0 — 2026-09-09
|
||||
|
||||
### Performance take 5 — the review round
|
||||
|
||||
An independent review of 0.51.0 (`docs/performance_take5_review.md`)
|
||||
named four remaining costs with gates; all four are implemented and
|
||||
measured (`docs/perf/README.md`, the 2026-09-08 review-round entry).
|
||||
Behaviour is unchanged everywhere the suites and byte-identity gates can
|
||||
see; two pre-existing gaps the round found are filed, not hidden.
|
||||
|
||||
- **A rename refuses cheaply.** A cursor with no symbol used to read,
|
||||
parse and index every file in the workspace before refusing (2 s on
|
||||
opentitan); an engine-owned preflight now refuses from the request
|
||||
buffer alone in 0.3 ms with the same sentence and precedence. Refusals
|
||||
the workspace index would have to answer stay on the slow road, because
|
||||
a wrong rename refusal is terminal.
|
||||
- **One lint pass per buffer revision.** The diagnostics publish and the
|
||||
quick-fix discovery share one result, keyed by value on every input
|
||||
(rule set, options, width, tab width, waiver *contents*) and cleared by
|
||||
every index change; a cursor move on a 42 000-line file costs 1 ms
|
||||
instead of 23, and the navigation queued behind it likewise.
|
||||
- **The first answer after opening a file.** A workspace start now
|
||||
walks, indexes and publishes the open file's own folders before it
|
||||
discovers the rest of the workspace, one scan, every file once: the
|
||||
first go-to-definition answers in about 80 ms cold and 115 ms warm,
|
||||
correct every session, and a warm start settles under one second.
|
||||
- **Scans under load.** A scan publishes at most once per 512 files
|
||||
instead of once per burst of requests (a publish costs the size of the
|
||||
index): at the same offered load the median request wait falls from
|
||||
112 ms to 2 ms and the scan finishes about twice as fast. An empty
|
||||
navigation answer computed while the index is still growing is no
|
||||
longer an answer — it is asked again at the next publish or at the
|
||||
scan's end — and a cancel for such a request is honoured where it
|
||||
lands.
|
||||
- **Rename reuses the index's own records.** For the files a rename
|
||||
selects but never analyses, the engine now takes the index cache's
|
||||
record instead of parsing, and only when the file's bytes hash to what
|
||||
that record was written for. The hierarchical-tail rename falls from
|
||||
380 to 314 ms, the duplicate-module refusal from 2 s to 0.7 s; every
|
||||
edit and every warning byte-identical.
|
||||
- The CLI is unchanged in this release.
|
||||
|
||||
## 0.51.0 — 2026-09-08
|
||||
|
||||
### Performance take 5 — the implementation round
|
||||
|
||||
The owner's take-5 plan (`docs/performance_take5.md`) implemented end to
|
||||
end, each stage measured against the 0.50.0 reference on opentitan
|
||||
(`docs/perf/README.md`, 2026-09-08). Behaviour is unchanged everywhere the
|
||||
suites and the byte-identity gates can see; what changed is how much work
|
||||
the same answers cost.
|
||||
|
||||
- **Code actions stop repeating work.** A code-action request runs the
|
||||
lint pass and reads the project configuration only when the client asks
|
||||
for quick fixes or fix-all (`only: []` answers at once); the formatter's
|
||||
fence answer is computed only when a finding carries a fix and once per
|
||||
document revision; the four refactoring selectors read the document's
|
||||
own parse instead of re-parsing the buffer; the ports and
|
||||
organize-imports lightbulbs are answered from the plan-time checks with
|
||||
the same titles and counts, the click still recomputing and verifying.
|
||||
On opentitan's 42 192-line generated file a no-offer cursor move fell
|
||||
from 310 ms to 24 ms, and the navigation queued behind it with it; an
|
||||
offering cursor from 22 ms to 5.5 ms.
|
||||
- **Rename reuses its analysis; the verifier is untouched.** A rename
|
||||
parses and analyses each selected file once and builds its after-index
|
||||
from the edited files' fresh records; every check the verifier makes is
|
||||
the same code, re-attacked. The hierarchical-tail rename fell from 780
|
||||
to 388 ms (2.01×), an ordinary rename 141 → 92 ms, the extract command
|
||||
246 → 149 ms. A `--verbose` session now logs a per-stage rename trace.
|
||||
Topology handshake 33 is closed: inline-module's hierarchical-use
|
||||
refusal now sees every file whose tokens write the dissolved instance's
|
||||
name, including a `bind` in a file that instantiates nothing in the
|
||||
chain.
|
||||
- **The CLI's package census parses once.** With `unused-import` on,
|
||||
`check --select error,warning,style` no longer builds a one-file index
|
||||
for every file: the census reads package exports off its one parse and
|
||||
skips the nine files in ten that declare no package. The rule's cost on
|
||||
`hw/ip` fell from 142 ms to 5 ms; every output is byte-identical.
|
||||
- **Startup.** The server asks for the client's settings before its first
|
||||
scan (2 s bound for a client that never answers) and runs one scan at
|
||||
the answered scope — the empty default-scope scan is gone; the index
|
||||
store is not rewritten when nothing changed and is opened at the first
|
||||
step that needs it; the corpus is read a file at a time in its own step
|
||||
rather than all up front; the open buffers' folders are indexed first
|
||||
and the first navigation after opening a file is answered once that
|
||||
folder is published — correct in every session, at ~250–275 ms, where
|
||||
it used to be 84–208 ms or over a second depending on a race. Warm
|
||||
start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, the store
|
||||
byte-identical across sessions. `--verbose` logs a per-stage scan trace.
|
||||
- **The harness** (`tools/perf/`) records units, status, result counts and
|
||||
edit fingerprints on every row, measures the extract/inline commands for
|
||||
real, and is what every number above was taken with.
|
||||
|
||||
## 0.50.0 — 2026-09-07
|
||||
|
||||
### The format cache key; performance take 4
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,11 +265,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -278,7 +278,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.50.0"
|
||||
version = "0.55.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
+46
-32
@@ -78,6 +78,44 @@ pub struct Census {
|
||||
packages: HashMap<String, Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
/// What one file contributes to a [`Census`]: its words, the units it
|
||||
/// declares, and the packages it exports from.
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
|
||||
/// One file's three contributions, off **one** parse.
|
||||
///
|
||||
/// The word census wants the tokens, the interface table wants the tree and
|
||||
/// the package table wants both — so a run that asks for either table lexes
|
||||
/// and parses the file exactly once and all three read that. A run that asks
|
||||
/// for neither never parses at all: `harvest_text` lexes and stops, which is
|
||||
/// what the word census alone needs.
|
||||
///
|
||||
/// A file that cannot be read contributes nothing, and so does one that does
|
||||
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
|
||||
/// The file's own check is what reports the error.
|
||||
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
if !interfaces && !packages {
|
||||
return (words::harvest_text(&src), Vec::new(), Vec::new());
|
||||
}
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
let declared = match interfaces {
|
||||
true => vlog_linter::module_interfaces(parsed.file()),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let exports = match packages {
|
||||
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
|
||||
false => Vec::new(),
|
||||
};
|
||||
(words::harvest(parsed.tokens()), declared, exports)
|
||||
}
|
||||
|
||||
impl Census {
|
||||
/// The census of every file in the run, harvested in parallel.
|
||||
///
|
||||
@@ -86,39 +124,15 @@ impl Census {
|
||||
/// file's own check reports the error.
|
||||
///
|
||||
/// `interfaces` says whether the run also needs each unit's ports and
|
||||
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
|
||||
/// of every file on top of the lex the word census already pays for, so
|
||||
/// it is built only when some enabled rule asks — measured on opentitan
|
||||
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
|
||||
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
|
||||
/// whether it needs each package's exported names (`unused-import`).
|
||||
/// Either costs a **parse** of every file on top of the lex the word
|
||||
/// census already pays for, so each is built only when some enabled rule
|
||||
/// asks — measured on opentitan `hw/` in
|
||||
/// `docs/features/linter-expansion-1/README.md`.
|
||||
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
let per_file: Vec<PerFile> = jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
let exports = match packages {
|
||||
true => vlog_linter::package_exports(&job.path, &src),
|
||||
false => Vec::new(),
|
||||
};
|
||||
if !interfaces {
|
||||
return (words::harvest_text(&src), Vec::new(), exports);
|
||||
}
|
||||
// One lex for both halves: the parse is what the interface
|
||||
// table needs, and its tokens are the word census's.
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
(
|
||||
words::harvest(parsed.tokens()),
|
||||
vlog_linter::module_interfaces(parsed.file()),
|
||||
exports,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let per_file: Vec<PerFile> =
|
||||
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).collect();
|
||||
|
||||
let mut files: HashMap<String, u32> = HashMap::new();
|
||||
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
||||
|
||||
@@ -2294,3 +2294,132 @@ fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A package with two exported names, and the two importers the rule has to
|
||||
/// tell apart.
|
||||
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
|
||||
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
|
||||
const IGNORES_PKG: &str =
|
||||
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
|
||||
|
||||
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
|
||||
/// and so is off in a default `check`.
|
||||
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
|
||||
|
||||
/// The headline: over a project, an import nothing in its file uses is
|
||||
/// reported, and one the file does use is not — and it is the *package
|
||||
/// census* that makes the difference, because the rule can only judge an
|
||||
/// import whose package the run can answer for.
|
||||
#[test]
|
||||
fn an_unused_package_import_is_reported_over_a_project() {
|
||||
let dir = TempDir::new("pkg-census");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("unused-import"), "{text}");
|
||||
assert!(text.contains("ignores_pkg.sv"), "{text}");
|
||||
assert!(
|
||||
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
|
||||
"the file that reads `A` keeps its import: {text}"
|
||||
);
|
||||
assert_eq!(code(&out), 1);
|
||||
}
|
||||
|
||||
/// `unused-import` is a style rule, so a default `check` neither reports it
|
||||
/// nor is changed by the presence of a package in the run.
|
||||
#[test]
|
||||
fn a_default_check_says_nothing_about_imports() {
|
||||
let dir = TempDir::new("pkg-default");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A package the run does not contain is a package the run cannot answer
|
||||
/// for, and the rule is silent about every import of it. This is the
|
||||
/// conservative direction the whole feature is built around: an accusation
|
||||
/// needs a known export list.
|
||||
#[test]
|
||||
fn an_import_of_a_package_outside_the_run_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-unknown");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("uses_pkg.sv", USES_PKG);
|
||||
dir.write(
|
||||
"stranger.sv",
|
||||
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// A package that re-exports from another one answers `None`: only a whole
|
||||
/// project index settles what a re-export chain lets through, and the CLI's
|
||||
/// one-file census will not guess. Every import of it goes quiet.
|
||||
#[test]
|
||||
fn an_import_of_a_re_exporting_package_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-reexport");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write(
|
||||
"r_pkg.sv",
|
||||
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
|
||||
endpackage\n",
|
||||
);
|
||||
dir.write(
|
||||
"ignores_r.sv",
|
||||
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
|
||||
);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// Two files declaring one package name is a name the run cannot answer for,
|
||||
/// whatever the two say — `Census::of`'s merge turns the second contribution
|
||||
/// into `None`, and the rule goes quiet about it.
|
||||
#[test]
|
||||
fn an_import_of_a_package_two_files_declare_is_not_reported() {
|
||||
let dir = TempDir::new("pkg-duplicate");
|
||||
dir.write("p_pkg.sv", PKG);
|
||||
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
|
||||
dir.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
|
||||
}
|
||||
|
||||
/// The gate is a claim about *cost*, not about answers, so the answers get
|
||||
/// their own end-to-end pin: a run whose only package file is surrounded by
|
||||
/// files holding the word `package` in strings and comments reports exactly
|
||||
/// what a run without those files reports.
|
||||
#[test]
|
||||
fn text_that_merely_says_package_changes_no_finding() {
|
||||
let bare = TempDir::new("pkg-bare");
|
||||
bare.write("p_pkg.sv", PKG);
|
||||
bare.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
|
||||
let noisy = TempDir::new("pkg-noisy");
|
||||
noisy.write("p_pkg.sv", PKG);
|
||||
noisy.write("ignores_pkg.sv", IGNORES_PKG);
|
||||
noisy.write(
|
||||
"talker.sv",
|
||||
"// package q_pkg; endpackage\n\
|
||||
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
|
||||
);
|
||||
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
|
||||
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
|
||||
let tail = finding.rsplit('/').next().unwrap_or(finding);
|
||||
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
|
||||
}
|
||||
assert_eq!(
|
||||
plain.matches("unused-import").count(),
|
||||
with_noise.matches("unused-import").count(),
|
||||
"{plain}\n---\n{with_noise}"
|
||||
);
|
||||
}
|
||||
+393
-19
@@ -2,7 +2,7 @@
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions lucisv formats when walking a directory.
|
||||
@@ -48,27 +48,134 @@ pub fn collect_files(
|
||||
gitignore: bool,
|
||||
files: &mut Vec<PathBuf>,
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
collect_files_with(input, exclude, gitignore, &mut |path, _| files.push(path), warn)
|
||||
}
|
||||
|
||||
/// [`collect_files`] with the size the walk already read handed on beside each
|
||||
/// path.
|
||||
///
|
||||
/// The same walk, the same order, the same warnings — the only difference is
|
||||
/// where a file goes when it is found. A directory walk already calls
|
||||
/// `metadata` on every entry to answer "directory?", so the length is a field
|
||||
/// of a struct it holds anyway; a caller that has to know how big a file is —
|
||||
/// the server's `lucisv.index.maxFileSize` cap — would otherwise ask the
|
||||
/// filesystem the same question a second time, once per file.
|
||||
/// `docs/features/perf5r-first-answer/README.md` measured that second `stat`
|
||||
/// at 6.9 ms of a 165 ms discovery over 3 976 files — small, because the walk
|
||||
/// has just warmed every one of those inodes, and 3 976 system calls that buy
|
||||
/// a number already in hand all the same.
|
||||
///
|
||||
/// **`None` means the walk did not look.** `input` naming a file rather than a
|
||||
/// directory is handed straight over, exactly as [`collect_files`] hands it
|
||||
/// over, with no `metadata` call added to a path that never needed one — so a
|
||||
/// caller that wants a size there asks for it itself. Every path a *directory
|
||||
/// walk* yields carries `Some`.
|
||||
pub fn collect_files_with(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
collect_files_tracked(input, exclude, gitignore, &mut tracker, found, warn)
|
||||
}
|
||||
|
||||
/// [`collect_files_with`] using an existing [`DirectoryTracker`].
|
||||
pub fn collect_files_tracked(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
tracker: &mut DirectoryTracker,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
let mut walk = Walk {
|
||||
exclude,
|
||||
gitignore,
|
||||
ignores: Vec::new(),
|
||||
rel: Vec::new(),
|
||||
visited: HashSet::new(),
|
||||
files,
|
||||
warn,
|
||||
};
|
||||
let mut walk =
|
||||
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
|
||||
walk.dir(path);
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
found(path.to_path_buf(), None);
|
||||
} else {
|
||||
return Err(format!("{input}: no such file or directory"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`collect_files_with`] over `input`, which lies **under** `root`, finding
|
||||
/// exactly what a walk of `root` would have found there.
|
||||
///
|
||||
/// The difference from walking `input` directly is the `.gitignore` files
|
||||
/// between the two. A walk reads ignore rules from its own starting directory
|
||||
/// downwards, so `collect_files_with("<root>/hw/ip/aes")` never sees the rule
|
||||
/// `<root>/.gitignore` writes about `hw/ip/aes/gen/` — and a caller walking a
|
||||
/// subtree *of a scope whose rung is the root* would then index files that
|
||||
/// scope excludes. This one walks the ancestor chain first: it reads each
|
||||
/// ancestor's `.gitignore` onto the stack with the depth it belongs at, and it
|
||||
/// stops without yielding anything when one of those ancestors is itself
|
||||
/// ignored or excluded — because a walk of `root` would never have descended
|
||||
/// into it.
|
||||
///
|
||||
/// `input` not being under `root` is the caller's mistake and is answered the
|
||||
/// way a walk of an unknown path is: nothing found, and no error, since there
|
||||
/// is no ancestor chain to apply.
|
||||
///
|
||||
/// Everything else is [`collect_files_with`]: the same order, the same cycle
|
||||
/// guard, the same warnings, the same lengths.
|
||||
pub fn collect_files_below(
|
||||
root: &Path,
|
||||
input: &Path,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
collect_files_below_tracked(root, input, exclude, gitignore, &mut tracker, found, warn)
|
||||
}
|
||||
|
||||
/// [`collect_files_below`] using an existing [`DirectoryTracker`].
|
||||
pub fn collect_files_below_tracked(
|
||||
root: &Path,
|
||||
input: &Path,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
tracker: &mut DirectoryTracker,
|
||||
found: &mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let Ok(below) = input.strip_prefix(root) else { return Ok(()) };
|
||||
if !input.is_dir() {
|
||||
return Err(format!("{}: no such file or directory", input.display()));
|
||||
}
|
||||
let mut walk =
|
||||
Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn };
|
||||
// The root's own `.gitignore` sits at depth 0, exactly where a walk of the
|
||||
// root would have put it.
|
||||
walk.push_ignore(root);
|
||||
let mut here = root.to_path_buf();
|
||||
let names: Vec<String> = below.iter().map(|name| name.to_string_lossy().into_owned()).collect();
|
||||
for (at, name) in names.iter().enumerate() {
|
||||
here.push(name);
|
||||
if is_excluded(&here, exclude) {
|
||||
return Ok(());
|
||||
}
|
||||
walk.rel.push(name.clone());
|
||||
if is_ignored(&walk.ignores, &walk.rel, true) {
|
||||
return Ok(());
|
||||
}
|
||||
// Not `input`'s own — `Walk::dir` pushes that one itself, and pushing
|
||||
// it twice would apply its rules at two different depths.
|
||||
if at + 1 < names.len() {
|
||||
walk.push_ignore(&here);
|
||||
}
|
||||
}
|
||||
walk.dir(input);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How a directory is recognised as one the walk has already entered. Two
|
||||
/// names for the same directory — a symlink and its target, or two symlinks
|
||||
/// pointing at one place — must map to the same identity, or a cycle has no
|
||||
@@ -76,24 +183,78 @@ pub fn collect_files(
|
||||
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
||||
/// at the cost of a real path lookup.
|
||||
#[cfg(unix)]
|
||||
type DirId = (u64, u64);
|
||||
pub type DirId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
type DirId = PathBuf;
|
||||
pub type DirId = PathBuf;
|
||||
|
||||
/// The identity of the directory at `path`, or `None` when it cannot be
|
||||
/// read — a dangling symlink, or a directory that vanished mid-walk.
|
||||
#[cfg(unix)]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
pub fn dir_id(path: &Path) -> Option<DirId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
Some((meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
pub fn dir_id(path: &Path) -> Option<DirId> {
|
||||
std::fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// What happened when attempting to enter a directory with [`DirectoryTracker`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DirStatus {
|
||||
/// Entered for the first time.
|
||||
EnteredFirstTime,
|
||||
/// Already visited under the same or an earlier path.
|
||||
AlreadyVisited,
|
||||
/// Previously entered under `recorded`, but `dir < recorded` indicating
|
||||
/// out-of-order traversal relative to a canonical root walk.
|
||||
PrecedenceConflict { recorded: PathBuf },
|
||||
}
|
||||
|
||||
/// Tracks visited directories across one or more walks to ensure cycle termination
|
||||
/// and detect order divergence.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DirectoryTracker {
|
||||
visited: HashMap<DirId, PathBuf>,
|
||||
has_conflict: bool,
|
||||
}
|
||||
|
||||
impl DirectoryTracker {
|
||||
/// Creates an empty directory tracker.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records `dir` as entered and returns its [`DirStatus`].
|
||||
pub fn enter(&mut self, dir: &Path) -> DirStatus {
|
||||
let Some(id) = dir_id(dir) else {
|
||||
return DirStatus::AlreadyVisited;
|
||||
};
|
||||
match self.visited.entry(id) {
|
||||
std::collections::hash_map::Entry::Vacant(v) => {
|
||||
v.insert(dir.to_path_buf());
|
||||
DirStatus::EnteredFirstTime
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(o) => {
|
||||
let recorded = o.get();
|
||||
if dir < recorded.as_path() {
|
||||
self.has_conflict = true;
|
||||
DirStatus::PrecedenceConflict { recorded: recorded.clone() }
|
||||
} else {
|
||||
DirStatus::AlreadyVisited
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any precedence conflict was observed across walks.
|
||||
pub fn has_conflict(&self) -> bool {
|
||||
self.has_conflict
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `path` names one of the source files lucisv formats.
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
|
||||
@@ -109,8 +270,10 @@ struct Walk<'a> {
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
visited: HashSet<DirId>,
|
||||
files: &'a mut Vec<PathBuf>,
|
||||
tracker: &'a mut DirectoryTracker,
|
||||
/// Where a source file goes when the walk finds one, with the length the
|
||||
/// walk's own `metadata` call already read.
|
||||
found: &'a mut dyn FnMut(PathBuf, Option<u64>),
|
||||
warn: &'a mut dyn FnMut(Warning),
|
||||
}
|
||||
|
||||
@@ -169,7 +332,10 @@ impl Walk<'_> {
|
||||
if meta.is_dir() {
|
||||
self.dir(&path);
|
||||
} else if meta.is_file() && is_source(&path) {
|
||||
self.files.push(path);
|
||||
// The length comes off the `metadata` above — the same
|
||||
// call that answered "directory?" — so a caller wanting it
|
||||
// costs the walk nothing at all.
|
||||
(self.found)(path, Some(meta.len()));
|
||||
}
|
||||
}
|
||||
self.rel.pop();
|
||||
@@ -192,7 +358,7 @@ impl Walk<'_> {
|
||||
///
|
||||
/// A directory whose identity cannot be read is not entered.
|
||||
fn enter(&mut self, dir: &Path) -> bool {
|
||||
dir_id(dir).is_some_and(|id| self.visited.insert(id))
|
||||
matches!(self.tracker.enter(dir), DirStatus::EnteredFirstTime)
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
@@ -680,6 +846,181 @@ mod tests {
|
||||
assert_eq!(tree.walk(""), ["keep.sv"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The metadata hand-off — `docs/features/perf5r-first-answer/README.md`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every path `collect_files_with` yields under `rel`, with its length.
|
||||
#[cfg(unix)]
|
||||
fn walked_with(tree: &TempTree, rel: &str) -> Vec<(String, Option<u64>)> {
|
||||
let start = if rel.is_empty() { tree.path.clone() } else { tree.path.join(rel) };
|
||||
let mut out = Vec::new();
|
||||
collect_files_with(
|
||||
start.to_str().expect("utf-8 temp path"),
|
||||
&[],
|
||||
true,
|
||||
&mut |path, len| out.push((tree.rel_of(&path), len)),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_metadata_entry_yields_exactly_the_paths_the_plain_one_does() {
|
||||
// The claim the server's cap rests on: `collect_files` is
|
||||
// `collect_files_with` with the length thrown away, so the two cannot
|
||||
// disagree about which files exist — not about order, not about
|
||||
// `.gitignore`, not about a symlink cycle, not about a broken link.
|
||||
let tree = TempTree::new("handoffsame");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("a.sv");
|
||||
tree.source("rtl/b.sv");
|
||||
tree.source("rtl/deep/c.svh");
|
||||
tree.source("build/hidden.sv");
|
||||
tree.write("rtl/notsource.txt", "x");
|
||||
tree.link("rtl/loop", "..");
|
||||
tree.link("rtl/dangling.sv", "nowhere.sv");
|
||||
|
||||
let mut plain = Vec::new();
|
||||
collect_files(tree.path.to_str().expect("utf-8"), &[], true, &mut plain, &mut |_| {})
|
||||
.expect("the walk finishes");
|
||||
let plain: Vec<String> = plain.iter().map(|p| tree.rel_of(p)).collect();
|
||||
let handed: Vec<String> =
|
||||
walked_with(&tree, "").into_iter().map(|(path, _)| path).collect();
|
||||
assert_eq!(plain, handed, "the same paths in the same order, byte for byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_walked_file_carries_the_length_the_walk_already_read() {
|
||||
let tree = TempTree::new("handofflen");
|
||||
tree.write("small.sv", "module m;\nendmodule\n");
|
||||
tree.write("big.sv", &"// pad\n".repeat(500));
|
||||
let found = walked_with(&tree, "");
|
||||
let sizes: Vec<(String, Option<u64>)> = found;
|
||||
assert_eq!(
|
||||
sizes,
|
||||
[("big.sv".to_string(), Some(3_500)), ("small.sv".to_string(), Some(20))],
|
||||
"the length is the file's own, not a guess"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_path_named_directly_is_handed_over_without_a_stat() {
|
||||
// `None` is the walk saying it did not look — the file was named, not
|
||||
// walked to, and adding a `metadata` call for it would be a cost
|
||||
// `collect_files` never paid.
|
||||
let tree = TempTree::new("handoffnamed");
|
||||
tree.source("one.sv");
|
||||
let found = walked_with(&tree, "one.sv");
|
||||
assert_eq!(found, [("one.sv".to_string(), None)]);
|
||||
}
|
||||
|
||||
/// What `collect_files_below(root, root/rel)` finds, relative to the tree.
|
||||
#[cfg(unix)]
|
||||
fn below(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
|
||||
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
|
||||
let mut out = Vec::new();
|
||||
collect_files_below(
|
||||
&tree.path,
|
||||
&tree.path.join(rel),
|
||||
&patterns,
|
||||
true,
|
||||
&mut |path, _| out.push(tree.rel_of(&path)),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// What a walk of the whole tree finds under `rel` — the answer `below`
|
||||
/// has to reproduce.
|
||||
#[cfg(unix)]
|
||||
fn whole_under(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
|
||||
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
|
||||
let mut out = Vec::new();
|
||||
collect_files(tree.path.to_str().expect("utf-8"), &patterns, true, &mut out, &mut |_| {})
|
||||
.expect("the walk finishes");
|
||||
let prefix = format!("{rel}/");
|
||||
let mut under: Vec<String> =
|
||||
out.iter().map(|p| tree.rel_of(p)).filter(|p| p.starts_with(&prefix)).collect();
|
||||
under.sort();
|
||||
under
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_walk_that_starts_below_a_root_still_obeys_that_roots_gitignore() {
|
||||
// The whole reason `collect_files_below` exists. Starting the walk at
|
||||
// `hw/ip/aes` loses every rule written above it, and a scope whose
|
||||
// rung *is* the root would then index files that scope excludes.
|
||||
let tree = TempTree::new("belowignore");
|
||||
tree.write(".gitignore", "gen/\n*_generated.sv\n");
|
||||
tree.write("hw/.gitignore", "vendor/\n");
|
||||
tree.source("hw/ip/aes/rtl/aes.sv");
|
||||
tree.source("hw/ip/aes/rtl/aes_generated.sv");
|
||||
tree.source("hw/ip/aes/gen/made.sv");
|
||||
tree.source("hw/ip/aes/vendor/third.sv");
|
||||
tree.source("hw/ip/aes/dv/tb.sv");
|
||||
|
||||
let seen = below(&tree, "hw/ip/aes", &[]);
|
||||
assert_eq!(seen, ["hw/ip/aes/dv/tb.sv", "hw/ip/aes/rtl/aes.sv"]);
|
||||
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_the_root_walk_never_entered_yields_nothing_below_it() {
|
||||
// An ancestor the root's own rules ignore is an ancestor the root walk
|
||||
// never descended into, so nothing under it is in scope however
|
||||
// directly it is named.
|
||||
let tree = TempTree::new("belowblocked");
|
||||
tree.write(".gitignore", "hw/vendor/\n");
|
||||
tree.source("hw/vendor/ip/aes/aes.sv");
|
||||
tree.source("hw/ip/aes/aes.sv");
|
||||
assert!(below(&tree, "hw/vendor/ip/aes", &[]).is_empty());
|
||||
assert_eq!(below(&tree, "hw/ip/aes", &[]), ["hw/ip/aes/aes.sv"]);
|
||||
// An excluded ancestor is the same answer by the other filter.
|
||||
assert!(below(&tree, "hw/ip/aes", &["ip"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_negation_below_the_root_still_wins_over_the_root_rule() {
|
||||
// The precedence a root walk gives — deeper file last, so its `!` line
|
||||
// re-includes — must survive the ancestor chain being pre-loaded.
|
||||
let tree = TempTree::new("belownegate");
|
||||
tree.write(".gitignore", "*.sv\n");
|
||||
tree.write("hw/ip/aes/.gitignore", "!keep.sv\n");
|
||||
tree.source("hw/ip/aes/keep.sv");
|
||||
tree.source("hw/ip/aes/drop.sv");
|
||||
let seen = below(&tree, "hw/ip/aes", &[]);
|
||||
assert_eq!(seen, ["hw/ip/aes/keep.sv"]);
|
||||
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_start_that_is_not_under_the_root_finds_nothing() {
|
||||
let tree = TempTree::new("belowoutside");
|
||||
tree.source("a/x.sv");
|
||||
let mut out = Vec::new();
|
||||
collect_files_below(
|
||||
&tree.path.join("a"),
|
||||
&tree.path,
|
||||
&[],
|
||||
true,
|
||||
&mut |path, _| out.push(path),
|
||||
&mut |_| {},
|
||||
)
|
||||
.expect("no error, nothing found");
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_syntax_degrades_to_plain_globbing() {
|
||||
// `**` is just two stars inside one component; documented.
|
||||
@@ -689,4 +1030,37 @@ mod tests {
|
||||
assert!(ignored("x?.sv", "x?.sv"));
|
||||
assert!(!ignored("x?.sv", "xa.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn tracker_detects_precedence_conflict_when_alias_sorts_before() {
|
||||
let tree = TempTree::new("trackconflict");
|
||||
tree.source("z_real/child.sv");
|
||||
tree.link("a_alias", "z_real");
|
||||
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
assert_eq!(tracker.enter(&tree.path.join("z_real")), DirStatus::EnteredFirstTime);
|
||||
assert!(!tracker.has_conflict());
|
||||
|
||||
// Entering a_alias afterwards detects that a_alias sorts before z_real
|
||||
let status = tracker.enter(&tree.path.join("a_alias"));
|
||||
assert!(matches!(status, DirStatus::PrecedenceConflict { .. }));
|
||||
assert!(tracker.has_conflict());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn tracker_allows_alias_sorting_after_without_conflict() {
|
||||
let tree = TempTree::new("trackorder");
|
||||
tree.source("a_real/child.sv");
|
||||
tree.link("z_alias", "a_real");
|
||||
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
assert_eq!(tracker.enter(&tree.path.join("a_real")), DirStatus::EnteredFirstTime);
|
||||
assert!(!tracker.has_conflict());
|
||||
|
||||
// Entering z_alias afterwards: already visited, no precedence conflict
|
||||
assert_eq!(tracker.enter(&tree.path.join("z_alias")), DirStatus::AlreadyVisited);
|
||||
assert!(!tracker.has_conflict());
|
||||
}
|
||||
}
|
||||
@@ -108,23 +108,49 @@ impl Candidates {
|
||||
/// here, exactly as every file used to be. The two produce the same words
|
||||
/// because they are the same function over the same tokens
|
||||
/// ([`words_of_tokens`]).
|
||||
///
|
||||
/// Test-only since 2026-09-08: a scan holds every file's words and no
|
||||
/// file's text, so it calls [`Candidates::from_words`]. This is that call
|
||||
/// with the lex in front of it, which is what a test building tables from
|
||||
/// a fixture's text wants and what makes the two one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(
|
||||
index: &WorkspaceIndex,
|
||||
sources: &[(PathBuf, String)],
|
||||
mut known: HashMap<PathBuf, Vec<String>>,
|
||||
) -> Candidates {
|
||||
let words = sources
|
||||
.iter()
|
||||
.map(|(path, text)| {
|
||||
let words = known.remove(path).unwrap_or_else(|| words_in(text));
|
||||
(path.clone(), words)
|
||||
})
|
||||
.collect();
|
||||
Candidates::from_words(index, words)
|
||||
}
|
||||
|
||||
/// [`Candidates::build`] for a caller that already holds **every** file's
|
||||
/// words — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so there is no text left to lex when the tables are
|
||||
/// built at the end. There never was any lexing to do: since `FACTS_FORMAT`
|
||||
/// 13 a file's identifier census is one of its facts, so a scan already has
|
||||
/// the words of every file it stepped, cached or parsed, and `build`'s
|
||||
/// `known` covered the whole list. This is that call without the text it
|
||||
/// no longer reads (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
///
|
||||
/// Order-independent: the word counts are a sum and `words` is sorted at
|
||||
/// the end, so a map is as good as a list here.
|
||||
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
|
||||
let mut out = Candidates::default();
|
||||
out.take_index_tables(index);
|
||||
for (path, text) in sources {
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for (path, words) in words {
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
if !words.is_empty() {
|
||||
out.per_file.insert(path.clone(), words);
|
||||
out.per_file.insert(path, words);
|
||||
}
|
||||
}
|
||||
out.words = out.word_files.keys().cloned().collect();
|
||||
@@ -293,6 +319,17 @@ impl Candidates {
|
||||
self.remask_words();
|
||||
}
|
||||
|
||||
/// How many entries each completion table holds, and what the word table
|
||||
/// weighs — the startup memory question, asked of the one table that
|
||||
/// grows with the corpus rather than with its declarations.
|
||||
///
|
||||
/// A walk, so it is asked once at the end of a traced scan and never on a
|
||||
/// request path (`docs/features/perf5-p4/README.md`).
|
||||
pub fn sizes(&self) -> (usize, usize, usize, usize) {
|
||||
let word_bytes: usize = self.words.iter().map(String::len).sum();
|
||||
(self.units.len(), self.macros.len(), self.words.len(), word_bytes)
|
||||
}
|
||||
|
||||
/// Index names starting with `prefix`, case-insensitively.
|
||||
pub fn units(&self, prefix: &str) -> &[Candidate] {
|
||||
matching(&self.units, prefix, |c| &c.name)
|
||||
|
||||
@@ -33,19 +33,36 @@ pub fn code_actions(
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
only: Option<&[CodeActionKind]>,
|
||||
tab_width: usize,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let violations = crate::lint::fixable(run, doc);
|
||||
// Timed apart from the lint pass that found them: a menu that is slow
|
||||
// because it *renders* a thousand fixes is a different problem from one
|
||||
// that is slow because it found them (review round §R1b).
|
||||
let actions = crate::lint_trace::stage(crate::lint_trace::Stage::Serialize, || {
|
||||
offered(uri, doc, range, only, &violations)
|
||||
});
|
||||
crate::lint_trace::saw_actions(actions.len());
|
||||
actions
|
||||
}
|
||||
|
||||
/// The quick fixes and the fix-all action `only` asks for, built from
|
||||
/// violations already found.
|
||||
fn offered(
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
only: Option<&[CodeActionKind]>,
|
||||
violations: &[Violation],
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let positions = doc.positions();
|
||||
let violations = crate::lint::fixable(run, doc, tab_width);
|
||||
let mut actions = Vec::new();
|
||||
if wanted(only, &CodeActionKind::QUICKFIX) {
|
||||
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
|
||||
actions.extend(quick.map(CodeActionOrCommand::CodeAction));
|
||||
}
|
||||
if wanted(only, &CodeActionKind::new(FIX_ALL)) {
|
||||
actions.extend(
|
||||
fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction),
|
||||
);
|
||||
actions
|
||||
.extend(fix_all(uri, doc, &positions, violations).map(CodeActionOrCommand::CodeAction));
|
||||
}
|
||||
actions
|
||||
}
|
||||
@@ -133,6 +150,18 @@ fn title(violation: &Violation) -> String {
|
||||
format!("lucisv: {what} [{}]", violation.rule)
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants anything [`code_actions`] can
|
||||
/// offer — a quick fix or the fix-all action.
|
||||
///
|
||||
/// The two kinds this module answers for are the only two the **lint pass**
|
||||
/// answers for, so this is the question the dispatcher asks before reading the
|
||||
/// buffer's configuration and running the rules. A client asking for
|
||||
/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays
|
||||
/// for neither (take 5 §P1a).
|
||||
pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool {
|
||||
wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL))
|
||||
}
|
||||
|
||||
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
|
||||
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
|
||||
/// at all selects everything.
|
||||
@@ -172,7 +201,7 @@ mod tests {
|
||||
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None, 2)
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => action,
|
||||
@@ -256,7 +285,6 @@ mod tests {
|
||||
doc,
|
||||
line1,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
|
||||
}
|
||||
@@ -329,14 +357,8 @@ mod tests {
|
||||
start: Position { line: fenced_line, character: 0 },
|
||||
end: Position { line: fenced_line, character: 0 },
|
||||
};
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
let actions =
|
||||
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]));
|
||||
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
|
||||
// The unfenced tab one line further down still has one.
|
||||
let at = Range {
|
||||
@@ -344,15 +366,8 @@ mod tests {
|
||||
end: Position { line: 4, character: 0 },
|
||||
};
|
||||
assert_eq!(
|
||||
code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2
|
||||
)
|
||||
.len(),
|
||||
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),)
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
@@ -397,19 +412,14 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
|
||||
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only));
|
||||
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
|
||||
// `source` is a prefix filter for `source.fixAll.lucisv`.
|
||||
let source = [CodeActionKind::SOURCE];
|
||||
assert_eq!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source), 2).len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source)).len(), 1);
|
||||
// And an unrelated filter selects nothing.
|
||||
let refactor = [CodeActionKind::REFACTOR];
|
||||
assert!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty()
|
||||
);
|
||||
assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -419,12 +429,11 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&LintRun::default().with_tab_width(4),
|
||||
&uri(),
|
||||
doc,
|
||||
whole,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
4,
|
||||
);
|
||||
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
|
||||
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
|
||||
@@ -455,18 +464,14 @@ mod tests {
|
||||
let ws = workspace(src);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let (external, problems) = vlog_linter::ExternalWaivers::parse(
|
||||
std::path::Path::new("team.waiver"),
|
||||
"waive --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let waived = LintRun::default().with_external(external);
|
||||
let waived = LintRun::default()
|
||||
.with_waivers(std::path::Path::new("team.waiver"), "waive --rule=no-tabs\n");
|
||||
assert!(
|
||||
code_actions(&waived, &uri(), doc, whole, None, 2).is_empty(),
|
||||
code_actions(&waived, &uri(), doc, whole, None).is_empty(),
|
||||
"no quick fix and no fix-all for a waived finding"
|
||||
);
|
||||
assert!(
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None, 2).is_empty(),
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(),
|
||||
"the same buffer without the waiver is fixable"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{Home, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Extract a selection into a module: `[uri, range, name]`.
|
||||
@@ -63,6 +63,19 @@ pub fn kind() -> CodeActionKind {
|
||||
/// "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.
|
||||
/// Whether `[start, end)` is a selection lucisv could extract, asked of the
|
||||
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes rather than of the empty analysis that path installs — see
|
||||
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
|
||||
fn site_at(doc: &Document, start: u32, end: u32) -> Option<vlog_refactor::ExtractSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::extract_site(&doc.text, start, end),
|
||||
false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end),
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -73,7 +86,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOr
|
||||
}
|
||||
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 Some(site) = site_at(doc, 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),
|
||||
@@ -110,7 +123,7 @@ pub fn execute(
|
||||
.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 {
|
||||
let Some(site) = site_at(doc, start, end) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine looks up every module the selection instantiates and every
|
||||
@@ -124,6 +137,16 @@ pub fn execute(
|
||||
true => Home::NewFile,
|
||||
false => Home::SameFile,
|
||||
};
|
||||
// No preflight here, and the take 5 review round (§61.1) is why: every
|
||||
// refusal one could take is already taken before a scope is built. The
|
||||
// `site_at` gate above **is** `extract_site_in`, which returns `None` on a
|
||||
// parse diagnostic and on every `Region::read` refusal, so neither can
|
||||
// reach the engine; and `extract_module` checks the new name and the
|
||||
// occupied target as its own first two statements, ahead of
|
||||
// `Extraction::plan`. The 805 ms at `aes_wrap.sv` is none of those — it is
|
||||
// `boundary::Crossing::read`, which needs the instantiated modules' port
|
||||
// directions and so needs the scope. See
|
||||
// `docs/features/perf5r-preflight/README.md`.
|
||||
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
@@ -368,4 +391,76 @@ endmodule
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Where the extract refusals are actually taken (take 5 review §3 item 5,
|
||||
// TODO §61.1). No preflight was added — every refusal below is already
|
||||
// reached before a scope exists, and these pin that it stays so.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn run(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
range: Range,
|
||||
name: &str,
|
||||
create: bool,
|
||||
) -> Result<(), String> {
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).expect("uri"),
|
||||
serde_json::to_value(range).expect("range"),
|
||||
Value::String(name.to_string()),
|
||||
];
|
||||
execute(ws, &arguments, create).map(|_| ())
|
||||
}
|
||||
|
||||
/// A bad new name is refused by `extract_module`'s own first statement,
|
||||
/// and a selection covering no whole item is refused by the `site_at` gate
|
||||
/// — neither reaches `Extraction::plan`, so neither builds a scope.
|
||||
#[test]
|
||||
fn the_cheap_refusals_reach_the_wire_in_the_engines_words() {
|
||||
let tree = Tree::new("preflightrefusals");
|
||||
let (ws, uri) = opened(&tree);
|
||||
|
||||
let bad = run(&ws, &uri, selection(), "1bad", true).expect_err("a bad name");
|
||||
assert!(bad.contains("plain SystemVerilog identifier"), "{bad}");
|
||||
|
||||
// Half of `assign s = a + b;`, which covers no whole item.
|
||||
let partial = Range {
|
||||
start: Position { line: 6, character: 6 },
|
||||
end: Position { line: 6, character: 19 },
|
||||
};
|
||||
assert_eq!(
|
||||
run(&ws, &uri, partial, "sum", true),
|
||||
Err(NOTHING.to_string()),
|
||||
"the `site_at` gate answers a partial selection before the engine is asked"
|
||||
);
|
||||
}
|
||||
|
||||
/// A file already sitting where the new module would go is refused before
|
||||
/// `Extraction::plan`, and the question is asked of the source set the
|
||||
/// engine was handed rather than of the disk behind its back.
|
||||
#[test]
|
||||
fn an_occupied_target_is_refused_with_the_engines_sentence() {
|
||||
let tree = Tree::new("preflightoccupied");
|
||||
tree.write("sum.sv", "module sum;\nendmodule\n");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let refusal = run(&ws, &uri, selection(), "sum", true).expect_err("occupied");
|
||||
assert!(refusal.contains("there is already a"), "{refusal}");
|
||||
assert!(refusal.contains("sum.sv"), "and it names the file: {refusal}");
|
||||
|
||||
// Into the same file nothing is occupied, so the early check passes
|
||||
// and the engine refuses for its own, later reason: the workspace
|
||||
// already declares that name — an index question, answered by the
|
||||
// stage that owns the index.
|
||||
let deferred = run(&ws, &uri, selection(), "sum", false).expect_err("already declared");
|
||||
assert!(deferred.contains("the workspace already declares"), "{deferred}");
|
||||
}
|
||||
|
||||
/// The control: a whole, movable item still extracts.
|
||||
#[test]
|
||||
fn a_whole_movable_selection_still_extracts() {
|
||||
let tree = Tree::new("preflightok");
|
||||
let (ws, uri) = opened(&tree);
|
||||
assert!(run(&ws, &uri, selection(), "sum", true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The fenced regions of an open buffer, asked once per document revision.
|
||||
//!
|
||||
//! `vlog_formatter::fence::protected_regions` takes **text** and parses it
|
||||
//! itself, on purpose: one fence answer for every front end, and none of them
|
||||
//! able to feed it a stale tree. That contract
|
||||
//! (`docs/features/shared-fence-filter/README.md`) is not amended here, and
|
||||
//! `fence.rs` is not touched — the call is still
|
||||
//! `protected_regions(&doc.text)`, byte for byte the same question.
|
||||
//!
|
||||
//! What this module adds is that the answer is computed **once** for a given
|
||||
//! buffer instead of once per `textDocument/codeAction`. That is safe for one
|
||||
//! structural reason: a `Document` is built whole by
|
||||
//! `Workspace::set_document` and thrown away by it, so the text a `Document`
|
||||
//! holds cannot change without a new `Document` — and `answer_request`
|
||||
//! flushes every pending change before a handler runs. There is no revision
|
||||
//! number to compare because there is no way to be looking at the wrong one.
|
||||
//!
|
||||
//! A 42 192-line generated buffer is where this is worth having: the fence
|
||||
//! parse alone measured ~59 ms of that file's code-action cost (take 5 §P1,
|
||||
//! `docs/features/perf5-p1/README.md`).
|
||||
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// The regions of `doc` no tool may edit automatically.
|
||||
///
|
||||
/// Computed on first use and kept for the life of this `Document`. The
|
||||
/// caller borrows the answer rather than a copy of it, so asking twice costs
|
||||
/// a pointer.
|
||||
pub fn of(doc: &Document) -> &[Region] {
|
||||
doc.fences.get_or_init(|| fence::protected_regions(&doc.text))
|
||||
}
|
||||
|
||||
/// Whether the answer is already in hand — asked *before* [`of`], so a
|
||||
/// `--verbose` trace can say whether this request paid the parse or read the
|
||||
/// memo (review round §R1b, `crate::lint_trace`). Decides nothing.
|
||||
pub fn held(doc: &Document) -> bool {
|
||||
doc.fences.get().is_some()
|
||||
}
|
||||
@@ -455,7 +455,7 @@ fn span_text(text: &str, span: TextRange) -> Option<&str> {
|
||||
/// to not continue an identifier turns that prefix/suffix match back into a
|
||||
/// miss, without needing anything more than the same "is this still a name
|
||||
/// character" question a lexer already answers for `$`, `_` and alnum.
|
||||
fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool {
|
||||
pub(crate) fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool {
|
||||
if span_text(text, span) != Some(name) {
|
||||
return false;
|
||||
}
|
||||
@@ -1313,6 +1313,45 @@ endmodule
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// TODO §64.1. The same live-span read for a declaration only a
|
||||
/// **hierarchical** path can reach — a module's internal net, named from
|
||||
/// another file as `u_leaf.sig`.
|
||||
///
|
||||
/// `declaration_snippet` reaches it through `live_symbol` →
|
||||
/// `nav::indexed_def_for_symbol`, which asked `WorkspaceIndex::member`
|
||||
/// (the *connection* surface) until §64.1 and so mapped no live symbol
|
||||
/// back to this `Def` at all: the card came out with its heading and no
|
||||
/// fence, on a file that was open and perfectly readable. It now shows the
|
||||
/// live line, which is the same guarantee the port above gets — and the
|
||||
/// guard is untouched, so a buffer whose live text no longer declares the
|
||||
/// name still prints nothing (asserted below).
|
||||
#[test]
|
||||
fn a_hierarchical_only_declaration_is_read_at_its_live_span_too() {
|
||||
let top =
|
||||
"module top;\n leaf u_leaf ();\n wire w;\n assign w = u_leaf.sig;\nendmodule\n";
|
||||
let saved = "module leaf;\n logic [7:0] sig;\nendmodule\n";
|
||||
let (dir, mut ws, uri) = included("livehier", &[("leaf.sv", saved), ("top.sv", top)]);
|
||||
let leaf_uri = path_to_uri(&dir.join("leaf.sv")).expect("uri");
|
||||
let edited =
|
||||
"// two lines\n// pushed it down\nmodule leaf;\n logic [15:0] sig;\nendmodule\n";
|
||||
ws.set_document(leaf_uri.clone(), edited.to_string());
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover"));
|
||||
assert!(
|
||||
body.contains("```systemverilog\n logic [15:0] sig;\n```"),
|
||||
"the live line, width and all: got {body}"
|
||||
);
|
||||
assert!(!body.contains("[7:0]"), "not the saved one: got {body}");
|
||||
|
||||
// The guard half, on the same shape: the net renamed away in the
|
||||
// buffer leaves the heading and no fence.
|
||||
ws.set_document(leaf_uri, "module leaf;\n logic [15:0] renamed;\nendmodule\n".to_string());
|
||||
let guarded = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover"));
|
||||
assert!(guarded.contains("— declared in"), "today's card, intact: got {guarded}");
|
||||
assert!(!guarded.contains("```"), "and no snippet at all: got {guarded}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() {
|
||||
// The file changed on disk under a live index — a rescan the server has
|
||||
|
||||
@@ -30,7 +30,7 @@ use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri,
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Organize the imports at a position: `[uri, position]`.
|
||||
pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports";
|
||||
@@ -74,8 +74,9 @@ pub fn offers(
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
|
||||
let Ok((_, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else {
|
||||
let Ok((removed, sorted)) = counts_at(doc, &files, &path, offset) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let title = vlog_refactor::organize_title(removed, sorted);
|
||||
@@ -88,6 +89,37 @@ pub fn offers(
|
||||
})]
|
||||
}
|
||||
|
||||
/// The two counts the offered title promises, asked of the buffer's own parse,
|
||||
/// analysis and token stream, and **without** verifying the splice.
|
||||
///
|
||||
/// `organize_counts` computes the whole edit and runs `check::verify_splice`,
|
||||
/// which rebuilds the index over every in-scope file and re-analyzes them —
|
||||
/// about two thirds of the offer's cost for an answer the offer discards (take
|
||||
/// 5 §P1c, `docs/features/perf5-p1/README.md`). [`resolve`] and [`execute`]
|
||||
/// still compute and verify the real edit when the user picks the action.
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, exactly as
|
||||
/// [`packages_at`] does.
|
||||
fn counts_at(
|
||||
doc: &Document,
|
||||
files: &[(PathBuf, String)],
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::organize_offer(files, path, offset),
|
||||
false => vlog_refactor::organize_offer_in(
|
||||
files,
|
||||
path,
|
||||
&doc.tree,
|
||||
&doc.diagnostics,
|
||||
&doc.semantics,
|
||||
&doc.tokens,
|
||||
offset,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit for an offered action, computed now that the user has picked it.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
@@ -144,10 +176,23 @@ pub fn execute(
|
||||
/// The cheap gate first: `imported_packages` is one parse of one buffer and
|
||||
/// answers "nothing here" for almost every cursor, which is what keeps a
|
||||
/// `textDocument/codeAction` on every keystroke off the index.
|
||||
/// Every package the scope at `offset` imports, asked of the buffer's own
|
||||
/// parse and its own diagnostics rather than of its text (take 5 §P1b). A
|
||||
/// buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes — see `ports::modules_at` for the whole reason.
|
||||
fn packages_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::imported_packages(&doc.text, offset),
|
||||
false => {
|
||||
vlog_refactor::imported_packages_in(&doc.tree, &doc.diagnostics, &doc.text, offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> {
|
||||
let doc = ws.document(uri)?;
|
||||
let path = doc.path.clone()?;
|
||||
let packages = vlog_refactor::imported_packages(&doc.text, offset);
|
||||
let packages = packages_at(doc, offset);
|
||||
if packages.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -116,14 +116,39 @@ pub struct IncludeGraph {
|
||||
|
||||
impl IncludeGraph {
|
||||
/// Scan every in-scope file for its `` `include``s and resolve them.
|
||||
///
|
||||
/// Test-only since 2026-09-08: the scan that used to hold every file's
|
||||
/// text no longer does, and calls [`IncludeGraph::from_includes`] with the
|
||||
/// lines it read at each file's own step. This is that call with the scan
|
||||
/// in front of it — which is what makes it the right thing for a test to
|
||||
/// build a graph from a fixture with, and the two provably one function.
|
||||
#[cfg(test)]
|
||||
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let scanned: Vec<(PathBuf, Vec<Include>)> =
|
||||
sources.iter().map(|(path, text)| (path.clone(), scan(text))).collect();
|
||||
let borrowed: Vec<(&Path, &[Include])> =
|
||||
scanned.iter().map(|(path, found)| (path.as_path(), found.as_slice())).collect();
|
||||
IncludeGraph::from_includes(&borrowed, incdirs)
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::build`] for a caller that has already read each file's
|
||||
/// `` `include`` lines off its text — the form a scan uses.
|
||||
///
|
||||
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
|
||||
/// and drops it again, so the text is not there to be scanned when the
|
||||
/// graph is built at the end; [`scan`] runs once per file, at that step,
|
||||
/// and the lines it found are what arrives here
|
||||
/// (`docs/features/perf5-p4/README.md` §P4b3). The two entries are the
|
||||
/// same function over the same lines — `build` is this one with the scan
|
||||
/// in front of it — so a graph built either way is the same graph.
|
||||
pub fn from_includes(sources: &[(&Path, &[Include])], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
|
||||
// Learned before the edges: `resolve` consults both tables, and an edge
|
||||
// resolved against a half-filled one would be keyed inconsistently.
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.to_path_buf()).collect();
|
||||
graph.relearn(&paths);
|
||||
for (path, text) in sources {
|
||||
graph.rescan_edges(path, text);
|
||||
for (path, found) in sources {
|
||||
graph.rescan_found(path, found);
|
||||
}
|
||||
graph.respell();
|
||||
graph
|
||||
@@ -151,9 +176,11 @@ impl IncludeGraph {
|
||||
self.respell();
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
|
||||
/// the scope resolves to right now — the form a scan publishing what it
|
||||
/// has indexed so far uses.
|
||||
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
|
||||
/// lines have already been read, with the `+incdir+`s the scope resolves
|
||||
/// to right now — the form a scan publishing what it has indexed so far
|
||||
/// uses. The lines come from the step that indexed each file, for the
|
||||
/// reason [`IncludeGraph::from_includes`] gives.
|
||||
///
|
||||
/// `known` is the scan's whole work list rather than the files it has
|
||||
/// reached, so the known-file and folded-spelling tables are complete from
|
||||
@@ -162,11 +189,16 @@ impl IncludeGraph {
|
||||
/// `relearn` for the batch, for the same reason
|
||||
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
|
||||
/// its index tables once.
|
||||
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
|
||||
pub fn absorb_includes(
|
||||
&mut self,
|
||||
incdirs: &[PathBuf],
|
||||
known: &[PathBuf],
|
||||
batch: &[(&Path, &[Include])],
|
||||
) {
|
||||
self.incdirs = incdirs.to_vec();
|
||||
self.relearn(known);
|
||||
for (path, text) in batch {
|
||||
self.rescan_edges(path, text);
|
||||
for (path, found) in batch {
|
||||
self.rescan_found(path, found);
|
||||
}
|
||||
self.respell();
|
||||
}
|
||||
@@ -183,8 +215,14 @@ impl IncludeGraph {
|
||||
/// each one lands. A file that includes nothing holds no entry at all,
|
||||
/// which is what keeps `raw` a set of edges rather than a set of files.
|
||||
fn rescan_edges(&mut self, path: &Path, text: &str) {
|
||||
self.rescan_found(path, &scan(text));
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::rescan_edges`] with the file's `` `include`` lines
|
||||
/// already in hand: where the disk says each one lands, held.
|
||||
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
|
||||
let targets: Vec<PathBuf> =
|
||||
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
|
||||
match targets.is_empty() {
|
||||
true => self.raw.remove(path),
|
||||
false => self.raw.insert(path.to_path_buf(), targets),
|
||||
@@ -230,6 +268,12 @@ impl IncludeGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many resolved edges the graph holds and how many files it knows —
|
||||
/// the two numbers that say what a rebuilt graph weighs.
|
||||
pub fn sizes(&self) -> (usize, usize) {
|
||||
(self.edges.values().map(Vec::len).sum(), self.known.len())
|
||||
}
|
||||
|
||||
/// The `+incdir+` directories an include is looked for in, in filelist
|
||||
/// order — the search rungs past the including file's own directory.
|
||||
pub fn incdirs(&self) -> &[PathBuf] {
|
||||
|
||||
@@ -24,14 +24,17 @@
|
||||
//! `docs/features/index-persistence/README.md` and is the same one
|
||||
//! `lucisv_core::cache` accepts.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
|
||||
|
||||
use crate::scan_trace::CacheWork;
|
||||
use crate::settings::ClientSettings;
|
||||
|
||||
/// The store inside the cache directory.
|
||||
@@ -51,6 +54,45 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
/// The subdirectory of the OS cache directory this server's stores live in.
|
||||
const OS_DIR: [&str; 2] = ["lucisv", "index"];
|
||||
|
||||
/// What one load of the store found — the numbers that decide whether the file
|
||||
/// on disk is *already* the file a compaction would write.
|
||||
///
|
||||
/// [`IndexCache::render`] writes this build's header and then one line per
|
||||
/// path in path order, so a store this build compacted and nothing has
|
||||
/// appended to since comes back with every line kept, no line dropped, no path
|
||||
/// named twice and the paths ascending. Anything else — another version's
|
||||
/// header, a torn line, a record the checksum rejects, two lines for one path,
|
||||
/// a session's appends still unvacuumed — means the file and the render differ,
|
||||
/// and compaction is what makes them the same.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Load {
|
||||
/// Whether the first line was this build's own header.
|
||||
header: bool,
|
||||
/// Record lines the store held below the header.
|
||||
read: usize,
|
||||
/// Of those, the ones that became an entry of their own.
|
||||
kept: usize,
|
||||
/// Lines that were not a record this build can use.
|
||||
dropped: usize,
|
||||
/// Lines naming a path an earlier line had already named.
|
||||
duplicates: usize,
|
||||
/// Whether the paths arrived strictly ascending, the order `render` writes
|
||||
/// them in.
|
||||
ordered: bool,
|
||||
}
|
||||
|
||||
impl Load {
|
||||
/// Whether these lines are exactly the lines [`IndexCache::render`] would
|
||||
/// write from the entries they produced.
|
||||
fn canonical(&self) -> bool {
|
||||
self.header
|
||||
&& self.ordered
|
||||
&& self.dropped == 0
|
||||
&& self.duplicates == 0
|
||||
&& self.kept == self.read
|
||||
}
|
||||
}
|
||||
|
||||
/// What one entry asserts: a file with exactly this content contributed
|
||||
/// exactly these facts.
|
||||
struct Entry {
|
||||
@@ -75,6 +117,18 @@ pub struct IndexCache {
|
||||
/// False for a missing store — which the first write claims — and for one
|
||||
/// from another version, which the first write replaces wholesale.
|
||||
header_ok: bool,
|
||||
/// What [`IndexCache::open`] read out of the store, which is what
|
||||
/// [`IndexCache::already_compact`] asks whether a rewrite would reproduce.
|
||||
load: Load,
|
||||
/// What this cache's own work has cost since it was opened, for the
|
||||
/// startup breakdown (`docs/features/perf5-p4/README.md`).
|
||||
///
|
||||
/// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the
|
||||
/// hash/decode split is exactly the number §P4a needed. Counted whether
|
||||
/// anything is going to read it or not: four clock reads per file are
|
||||
/// noise beside the decode they bracket, and a flag threaded down here to
|
||||
/// save them would cost more code than time.
|
||||
work: Cell<CacheWork>,
|
||||
}
|
||||
|
||||
impl IndexCache {
|
||||
@@ -96,24 +150,62 @@ impl IndexCache {
|
||||
/// whose tail was cut inside a multi-byte character costs the record that
|
||||
/// was torn and no other. Reading the whole buffer as text would have
|
||||
/// rejected all of it for one bad byte at the end.
|
||||
///
|
||||
/// The load is *counted* as well as performed — lines read, kept, dropped
|
||||
/// and duplicated, and whether the paths arrived in order — because those
|
||||
/// five numbers are what say whether the file already is what
|
||||
/// [`IndexCache::compact`] would write over it.
|
||||
pub fn open(dir: Option<PathBuf>) -> IndexCache {
|
||||
let Some(dir) = dir else { return IndexCache::disabled() };
|
||||
let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default();
|
||||
let mut lines = store_lines(&bytes).into_iter();
|
||||
let header_ok = lines.next() == Some(header().as_bytes());
|
||||
let mut entries = HashMap::new();
|
||||
let mut load = Load { header: header_ok, ordered: true, ..Load::default() };
|
||||
if header_ok {
|
||||
let mut previous: Option<PathBuf> = None;
|
||||
for line in lines {
|
||||
let Ok(line) = std::str::from_utf8(line) else { continue };
|
||||
if let Some((path, entry)) = parse_entry(line) {
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
entries.insert(path, entry);
|
||||
load.read += 1;
|
||||
let Ok(line) = std::str::from_utf8(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
let Some((path, entry)) = parse_entry(line) else {
|
||||
load.dropped += 1;
|
||||
continue;
|
||||
};
|
||||
if let Some(previous) = &previous {
|
||||
load.ordered &= *previous < path;
|
||||
}
|
||||
previous = Some(path.clone());
|
||||
// A later record for a path wins: the log is appended to
|
||||
// as a rescan goes, so the last one written is the one
|
||||
// that describes the file as the server last saw it.
|
||||
match entries.insert(path, entry) {
|
||||
Some(_) => load.duplicates += 1,
|
||||
None => load.kept += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok }
|
||||
let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() });
|
||||
IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work }
|
||||
}
|
||||
|
||||
/// What this cache has spent and moved since it was opened.
|
||||
pub fn work(&self) -> CacheWork {
|
||||
self.work.get()
|
||||
}
|
||||
|
||||
/// How many records this cache is holding.
|
||||
pub fn entry_count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The encoded bytes those records weigh — the retention §P4's memory
|
||||
/// hypothesis is about, since every one of them sits beside a decoded
|
||||
/// copy in the workspace index.
|
||||
pub fn encoded_bytes(&self) -> usize {
|
||||
self.entries.values().map(|entry| entry.facts.len()).sum()
|
||||
}
|
||||
|
||||
/// Where this cache writes. Test-only: production opens a cache from a
|
||||
@@ -123,6 +215,28 @@ impl IndexCache {
|
||||
self.dir.as_deref()
|
||||
}
|
||||
|
||||
/// The entry that asserts *exactly these bytes*, if there is one.
|
||||
///
|
||||
/// The one place the record and the key it is filed under are read
|
||||
/// together: an entry holds the FNV-1a of the bytes its facts were read
|
||||
/// off, and this is the only comparison anything in the server makes
|
||||
/// against it. Both readers below go through here, so "the store answers
|
||||
/// for this text" means one thing in a scan and in a refactoring alike.
|
||||
fn entry_for(&self, path: &Path, text: &str) -> Option<&Entry> {
|
||||
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()))
|
||||
}
|
||||
|
||||
/// [`IndexCache::facts_for`] asked by something that is **not** a scan.
|
||||
///
|
||||
/// The same question, the same entry, the same answer — but the work is
|
||||
/// not counted into [`IndexCache::work`], because that counter is what a
|
||||
/// scan's own trace subtracts to say what *it* did. A refactoring reading
|
||||
/// records between two scans would otherwise show up as decodes the next
|
||||
/// scan never made (review round §R3b, `crate::state::Workspace::known_facts`).
|
||||
pub fn facts_now(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
FileFacts::decode(&self.entry_for(path, text)?.facts)
|
||||
}
|
||||
|
||||
/// The facts a previous session read off this exact text, if it did.
|
||||
///
|
||||
/// The hash is of the text the server is about to index — an open buffer's
|
||||
@@ -133,11 +247,27 @@ impl IndexCache {
|
||||
/// they were written with, which [`IndexCache::open`] drops before it ever
|
||||
/// gets here.
|
||||
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
let entry = self.entries.get(path)?;
|
||||
if entry.content != content_hash(text.as_bytes()) {
|
||||
let looking = Instant::now();
|
||||
let found = self.entry_for(path, text);
|
||||
let mut work = self.work.get();
|
||||
work.lookup_ns += elapsed_ns(looking);
|
||||
let Some(entry) = found else {
|
||||
work.misses += 1;
|
||||
self.work.set(work);
|
||||
return None;
|
||||
};
|
||||
let decoding = Instant::now();
|
||||
let facts = FileFacts::decode(&entry.facts);
|
||||
work.decode_ns += elapsed_ns(decoding);
|
||||
work.decoded_bytes += entry.facts.len();
|
||||
// A record that no longer decodes costs a parse, so it is a miss —
|
||||
// the counters say what the scan actually did, not what it looked up.
|
||||
match facts.is_some() {
|
||||
true => work.hits += 1,
|
||||
false => work.misses += 1,
|
||||
}
|
||||
FileFacts::decode(&entry.facts)
|
||||
self.work.set(work);
|
||||
facts
|
||||
}
|
||||
|
||||
/// Record what parsing `text` found, and write it through immediately.
|
||||
@@ -149,13 +279,36 @@ impl IndexCache {
|
||||
/// the checksum of the facts it was written with) for the same reasons it
|
||||
/// rejects any other malformed record. That is the whole crash-safety
|
||||
/// argument, and it is why records are one line each.
|
||||
///
|
||||
/// **A record the store already holds is not written again.** An open
|
||||
/// buffer is indexed from its own analysis on every scan and its record is
|
||||
/// written through with it, so a warm session appends a line for every
|
||||
/// open buffer that is byte-identical to the line already in the store —
|
||||
/// a duplicate the next load collapses, at the price of making the store
|
||||
/// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The
|
||||
/// test is the exact one: same path, same content hash, same encoded
|
||||
/// facts. Anything that differs by a byte is a new record and is appended
|
||||
/// as it always was.
|
||||
pub fn record(&mut self, facts: &FileFacts, text: &str) {
|
||||
if self.dir.is_none() {
|
||||
return;
|
||||
}
|
||||
let encoding = Instant::now();
|
||||
let Some(encoded) = facts.encode() else { return };
|
||||
let content = content_hash(text.as_bytes());
|
||||
let mut work = self.work.get();
|
||||
work.encode_ns += elapsed_ns(encoding);
|
||||
if self.holds(facts.path(), content, &encoded) {
|
||||
work.repeats += 1;
|
||||
self.work.set(work);
|
||||
return;
|
||||
}
|
||||
let writing = Instant::now();
|
||||
self.append(&line(content, &encoded));
|
||||
work.write_ns += elapsed_ns(writing);
|
||||
work.records += 1;
|
||||
work.written_bytes += encoded.len();
|
||||
self.work.set(work);
|
||||
self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded });
|
||||
}
|
||||
|
||||
@@ -171,7 +324,76 @@ impl IndexCache {
|
||||
/// Atomic and silent: written to a temporary file and renamed, and a
|
||||
/// failure anywhere leaves the previous store standing. A cache that could
|
||||
/// fail a rescan would be worse than no cache.
|
||||
///
|
||||
/// **Skipped when the rewrite would reproduce the file byte for byte**
|
||||
/// ([`IndexCache::already_compact`]). A warm session whose every file hit
|
||||
/// the store appends nothing, so the store it loaded is the store it would
|
||||
/// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a
|
||||
/// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
pub fn compact(&mut self) {
|
||||
let before = self.store_bytes();
|
||||
let compacting = Instant::now();
|
||||
let rewriting = !self.already_compact();
|
||||
if rewriting {
|
||||
self.compact_now();
|
||||
}
|
||||
let mut work = self.work.get();
|
||||
work.compact_ns += elapsed_ns(compacting);
|
||||
work.compactions += usize::from(rewriting);
|
||||
work.store_before = before;
|
||||
work.store_after = self.store_bytes();
|
||||
self.work.set(work);
|
||||
}
|
||||
|
||||
/// Whether the store on disk is already exactly what [`IndexCache::render`]
|
||||
/// would write over it.
|
||||
///
|
||||
/// Four things have to hold, and any one of them failing compacts as
|
||||
/// before:
|
||||
///
|
||||
/// * the store was **loaded canonical** — this build's header, every line
|
||||
/// a record this build can read, no path named twice, the paths
|
||||
/// ascending ([`Load::canonical`]);
|
||||
/// * **nothing has been appended since**, so no line is out of order and
|
||||
/// no path has a second one;
|
||||
/// * **no entry's file is gone**, because `render` drops those;
|
||||
/// * there is a directory to write in at all.
|
||||
///
|
||||
/// **Crash safety is untouched.** A session that appended nothing left the
|
||||
/// store exactly as it found it, so what is on disk is already the
|
||||
/// compacted file and there is no half-written state a rewrite would
|
||||
/// resolve; skipping it only means the append log — which has no appends —
|
||||
/// stays as it is. The existence sweep is the one part that costs
|
||||
/// anything, one `stat` per entry, against the whole-store render and
|
||||
/// write it stands in for.
|
||||
fn already_compact(&self) -> bool {
|
||||
self.dir.is_some()
|
||||
&& self.load.canonical()
|
||||
&& self.work.get().records == 0
|
||||
&& self.entries.keys().all(|path| path.exists())
|
||||
}
|
||||
|
||||
/// Whether the store already holds exactly this record — the same path,
|
||||
/// the same content hash and the same encoded facts, byte for byte.
|
||||
///
|
||||
/// Only exactly that counts. A record whose facts differ by a byte under
|
||||
/// the same hash is still written, because the line on disk and the facts
|
||||
/// in hand would then disagree and the store must say what this session
|
||||
/// last saw.
|
||||
fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool {
|
||||
self.entries
|
||||
.get(path)
|
||||
.is_some_and(|entry| entry.content == content && entry.facts == encoded)
|
||||
}
|
||||
|
||||
/// The store file's size on disk, or 0 when there is no store.
|
||||
fn store_bytes(&self) -> u64 {
|
||||
let Some(dir) = self.dir.as_ref() else { return 0 };
|
||||
std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`IndexCache::compact`] without the accounting around it.
|
||||
fn compact_now(&mut self) {
|
||||
let Some(dir) = self.dir.clone() else { return };
|
||||
// The append handle must go before the rename, or a later append would
|
||||
// write into the file the rename replaced.
|
||||
@@ -342,6 +564,11 @@ fn line(content: u64, facts: &str) -> String {
|
||||
/// `None` for anything that is not a whole record whose facts still match
|
||||
/// their checksum, which includes the torn last line of a store whose writer
|
||||
/// was killed.
|
||||
/// Nanoseconds since `from`, saturated into the counters' `u64`.
|
||||
fn elapsed_ns(from: Instant) -> u64 {
|
||||
from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
|
||||
}
|
||||
|
||||
fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> {
|
||||
let (hash, rest) = line.split_once('\t')?;
|
||||
// Exactly as wide as `line` writes it: a hash that reads as a number but
|
||||
@@ -507,6 +734,42 @@ mod tests {
|
||||
assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none());
|
||||
}
|
||||
|
||||
/// **The R3b tie, both ways.** `facts_now` is the same content key
|
||||
/// `facts_for` is — a record answers for the bytes it was read off and for
|
||||
/// no others — and it leaves the scan's own work counters alone.
|
||||
///
|
||||
/// The stale case is the one that matters: a record written from one text
|
||||
/// must never be handed to a refactoring reading a different text, because
|
||||
/// the refactoring would index it as that file's facts and edit against an
|
||||
/// index describing bytes nobody has.
|
||||
#[test]
|
||||
fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() {
|
||||
let dir = TempDir::new("factsnow");
|
||||
let file = dir.file("m.sv", M);
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&file, M), M);
|
||||
cache.compact();
|
||||
|
||||
let reopened = IndexCache::open(Some(dir.path.clone()));
|
||||
let before = reopened.work();
|
||||
assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes");
|
||||
// Every way the bytes can differ, and the wrong path too.
|
||||
const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n";
|
||||
assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served");
|
||||
assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's");
|
||||
assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short");
|
||||
assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's");
|
||||
let after = reopened.work();
|
||||
assert_eq!(
|
||||
(after.hits, after.misses, after.decode_ns, after.lookup_ns),
|
||||
(before.hits, before.misses, before.decode_ns, before.lookup_ns),
|
||||
"a refactoring's reads are not a scan's work"
|
||||
);
|
||||
// The counted reader, asked the same questions, answers the same way.
|
||||
assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M));
|
||||
assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_survives_a_session_that_never_compacted() {
|
||||
// The crash case: records are written through as they are made, so a
|
||||
@@ -720,6 +983,221 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A store two files were recorded into and then compacted — this build's
|
||||
/// header and one line per path in path order, which is what every
|
||||
/// session after a whole rescan finds on disk.
|
||||
fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) {
|
||||
let one = dir.file("a.sv", M);
|
||||
let two = dir.file("b.sv", M);
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&one, M), M);
|
||||
cache.record(&facts(&two, M), M);
|
||||
cache.compact();
|
||||
assert_eq!(cache.work().compactions, 1, "premise: the store was written");
|
||||
(one, two)
|
||||
}
|
||||
|
||||
/// The store's bytes and its modification time — "not rewritten" as
|
||||
/// something a test can see rather than infer.
|
||||
fn store_stamp(dir: &TempDir) -> (Vec<u8>, std::time::SystemTime) {
|
||||
let path = dir.path.join(FILE);
|
||||
let bytes = std::fs::read(&path).expect("read store");
|
||||
let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime");
|
||||
(bytes, stamp)
|
||||
}
|
||||
|
||||
/// Rewrite the store's record lines, keeping this build's header.
|
||||
fn rewrite_records(dir: &TempDir, records: &[String]) {
|
||||
let mut text = header();
|
||||
for record in records {
|
||||
text.push('\n');
|
||||
text.push_str(record);
|
||||
}
|
||||
text.push('\n');
|
||||
std::fs::write(dir.path.join(FILE), text).expect("write store");
|
||||
}
|
||||
|
||||
/// The store's record lines, header excluded.
|
||||
fn records_of(dir: &TempDir) -> Vec<String> {
|
||||
dir.store_text().lines().skip(1).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canonical_store_nothing_appended_to_is_not_rewritten() {
|
||||
// §P4b (a): a warm session hits the store for every file, appends
|
||||
// nothing, and would rewrite 44 MiB to produce the same 44 MiB —
|
||||
// 182 ms of a 1.33 s start. What is on disk is already what `render`
|
||||
// writes, so the rewrite is skipped and the file is not touched at
|
||||
// all: not its bytes, not even its modification time.
|
||||
let dir = TempDir::new("alreadycompact");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads");
|
||||
warm.compact();
|
||||
|
||||
assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store was not touched");
|
||||
// And what is on disk is still a store: the next session reads it.
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_the_store_already_holds_is_not_appended_again() {
|
||||
// An open buffer is indexed from its own analysis on *every* scan and
|
||||
// its record is written through with it, so a warm session would
|
||||
// append a byte-identical duplicate for each open buffer — which
|
||||
// costs the store its canonical shape and so owes the next scan a
|
||||
// whole 44 MiB rewrite. The same record is a no-op; a changed one is
|
||||
// not (`docs/features/perf5-p4/README.md`, §P4b (a)).
|
||||
let dir = TempDir::new("repeatrecord");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let before = store_stamp(&dir);
|
||||
|
||||
let mut warm = IndexCache::open(Some(dir.path.clone()));
|
||||
warm.record(&facts(&one, M), M);
|
||||
assert_eq!(warm.work().records, 0, "nothing was appended");
|
||||
assert_eq!(warm.work().repeats, 1, "and the store was already holding it");
|
||||
assert_eq!(store_stamp(&dir), before, "so the store on disk did not move");
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 0, "which leaves it canonical");
|
||||
assert_eq!(store_stamp(&dir), before);
|
||||
|
||||
// One byte of difference and the record is written exactly as before.
|
||||
let edited = "module m;\n sub u ();\n wire w;\nendmodule\n";
|
||||
warm.record(&facts(&one, edited), edited);
|
||||
assert_eq!(warm.work().records, 1, "different bytes are a new record");
|
||||
assert_eq!(warm.work().repeats, 1);
|
||||
warm.compact();
|
||||
assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again");
|
||||
assert_eq!(
|
||||
IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited),
|
||||
Some(facts(&one, edited)),
|
||||
"the newer record is what the next session reads"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_two_lines_for_one_path_is_compacted() {
|
||||
// The growth bound the skip must not cost: a session that saved a
|
||||
// file appended a second line for its path, and only a rewrite folds
|
||||
// the two back into one.
|
||||
let dir = TempDir::new("dupline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
let repeat = records[0].clone();
|
||||
records.push(repeat);
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "one line per path again");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_with_a_line_this_build_cannot_read_is_compacted() {
|
||||
// A record dropped at load — a torn append, bit rot, a checksum that
|
||||
// no longer matches — means the file on disk holds a line `render`
|
||||
// would not write, so the store is not canonical and the rewrite is
|
||||
// what removes it.
|
||||
let dir = TempDir::new("droppedline");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0));
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical");
|
||||
assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_whose_records_are_out_of_path_order_is_compacted() {
|
||||
// `render` writes paths sorted, so a store that arrives unsorted was
|
||||
// not written by a compaction of this shape and rewriting it is not a
|
||||
// no-op — even though every line in it is a good record.
|
||||
let dir = TempDir::new("unsorted");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let mut records = records_of(&dir);
|
||||
records.reverse();
|
||||
rewrite_records(&dir, &records);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical");
|
||||
let sorted: Vec<String> = records_of(&dir);
|
||||
assert_eq!(sorted.len(), 2);
|
||||
assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_recorded_one_file_compacts() {
|
||||
// The moment an append happens the store on disk is no longer the
|
||||
// store `render` would write — the appended line is out of order at
|
||||
// best and a second line for its path at worst — so the rewrite is
|
||||
// owed exactly as it always was.
|
||||
let dir = TempDir::new("appended");
|
||||
let (one, _) = compacted_store(&dir);
|
||||
let third = dir.file("c.sv", M);
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(cache.facts_for(&one, M).is_some(), "the other two still hit");
|
||||
cache.record(&facts(&third, M), M);
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite");
|
||||
assert_eq!(records_of(&dir).len(), 3);
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_holding_a_file_that_is_gone_is_compacted() {
|
||||
// `render` drops an entry whose file no longer exists, so a store
|
||||
// holding one is not what a rewrite would produce — and the rewrite
|
||||
// is what prunes it, exactly as before.
|
||||
let dir = TempDir::new("goneentry");
|
||||
let (one, two) = compacted_store(&dir);
|
||||
std::fs::remove_file(&two).expect("remove");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned");
|
||||
assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone");
|
||||
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() {
|
||||
// The header is the one line the skip may never leave standing: its
|
||||
// records were dropped at load, so a session that keeps it leaves a
|
||||
// store nobody can read on disk for ever.
|
||||
let dir = TempDir::new("foreignheader");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
let foreign = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), foreign).expect("write");
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.compact();
|
||||
|
||||
assert_eq!(cache.work().compactions, 1, "another version's header is not canonical");
|
||||
let text = dir.store_text();
|
||||
assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() {
|
||||
// The line is well-formed as far as the store is concerned — hash,
|
||||
|
||||
@@ -23,7 +23,8 @@ use lsp_types::{
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::module_select::Reach;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// Inline the module instantiated at a position: `[uri, position]`.
|
||||
pub const INLINE_MODULE: &str = "lucisv.inlineModule";
|
||||
@@ -40,6 +41,19 @@ pub fn kind() -> CodeActionKind {
|
||||
}
|
||||
|
||||
/// The action for the cursor, carrying the command that does the work.
|
||||
/// Whether the cursor is on an instantiation lucisv could inline, asked of the
|
||||
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes rather than of the empty analysis that path installs — see
|
||||
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
|
||||
fn site_at(doc: &Document, offset: u32) -> Option<vlog_refactor::InlineSite> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::inline_site(&doc.text, offset),
|
||||
false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset),
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -48,7 +62,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOr
|
||||
return Vec::new();
|
||||
}
|
||||
let offset = doc.positions().offset(range.start);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { return Vec::new() };
|
||||
let Some(site) = site_at(doc, offset) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range.start).unwrap_or(Value::Null),
|
||||
@@ -80,14 +94,21 @@ pub fn execute(
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
|
||||
let offset = doc.positions().offset(position);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else {
|
||||
let Some(site) = site_at(doc, offset) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine reads the instantiated module's declaration and refuses over
|
||||
// any hierarchical path into the instance, so the file set is the two
|
||||
// units' own fan-out: the declaring file, and every file the index says
|
||||
// mentions either name.
|
||||
let files = ws.module_sources(&path, &site.units);
|
||||
// units' own fan-out — the declaring file, and every file the index says
|
||||
// mentions either name — **plus the fifth rung**: every file whose tokens
|
||||
// write the instance's own name down. A file naming
|
||||
// `u_wrapper.u_top.u_sub.s` reaches this instance through modules it does
|
||||
// not itself instantiate, and the first four rungs have nothing that asks
|
||||
// for it (topology handshake 33). The rung is the exact census
|
||||
// `no_hierarchy` can refuse from, so this set answers that refusal the way
|
||||
// the whole workspace would.
|
||||
let scopes = [site.instance.clone()];
|
||||
let files = ws.module_sources_reaching(&path, &site.units, Reach { scopes: &scopes });
|
||||
let refactoring = vlog_refactor::inline_module(&files, &path, offset)?;
|
||||
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ pub use project::{ConfigProblems, ProblemLog, ProjectLint};
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use lucisv_core::config::FileConfig;
|
||||
@@ -35,6 +36,8 @@ use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::diagnostics::SOURCE;
|
||||
use crate::lint_snapshot::{Key, Slot};
|
||||
use crate::lint_trace::{self, Fences, Reuse, Stage};
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
@@ -53,10 +56,29 @@ pub struct LintRun<'a> {
|
||||
/// The width `line-length` holds this buffer to — the width the formatter
|
||||
/// would wrap it to, so the two halves of lucisv cannot disagree.
|
||||
line_length: usize,
|
||||
/// The width a `no-tabs` fix writes where a tab was — the same ladder
|
||||
/// `format::indent_width` walks, read off the `FileConfig` this pass
|
||||
/// already discovered.
|
||||
///
|
||||
/// On the run rather than passed to [`fixable`] since the review round's
|
||||
/// §R1a: the diagnostics pass and the quick-fix pass must build the *same*
|
||||
/// `LintContext` to share one snapshot. Nothing published moves — the
|
||||
/// width reaches only `no-tabs`' fix *text*, and the diagnostics path
|
||||
/// never reads a fix.
|
||||
tab_width: usize,
|
||||
/// The external waiver files in force for this buffer, from its
|
||||
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
|
||||
/// configured, and then costing the pass nothing.
|
||||
external: ExternalWaivers,
|
||||
/// Those files' paths and contents, in the order they were read — the
|
||||
/// snapshot key's row 7. Empty when no waiver file is configured.
|
||||
///
|
||||
/// **Written in the same step as `external`**, by `waiver_files` and by
|
||||
/// `with_waivers` and by nothing else, so a run can never carry a waiver
|
||||
/// its key cannot see. A run whose key missed a waiver would offer a fix
|
||||
/// for a finding the waiver had silenced, which is the stale-fix failure
|
||||
/// this whole key exists to prevent.
|
||||
waiver_texts: Vec<(PathBuf, String)>,
|
||||
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
|
||||
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
|
||||
/// (config file, message) — and never fatal here: §42.2.
|
||||
@@ -70,7 +92,9 @@ impl Default for LintRun<'_> {
|
||||
oracle: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
tab_width: DEFAULT_TAB_WIDTH,
|
||||
external: ExternalWaivers::default(),
|
||||
waiver_texts: Vec::new(),
|
||||
problems: ConfigProblems::default(),
|
||||
}
|
||||
}
|
||||
@@ -80,6 +104,11 @@ impl Default for LintRun<'_> {
|
||||
/// editor says otherwise — `vlog_formatter::Config`'s own default.
|
||||
const DEFAULT_LINE_LENGTH: usize = 100;
|
||||
|
||||
/// The indent width a buffer's fixes are written at when neither its
|
||||
/// `lucisv.toml` nor the editor says otherwise — `vlog_formatter::Config`'s
|
||||
/// own default, which is what `format::indent_width` falls back to.
|
||||
const DEFAULT_TAB_WIDTH: usize = 2;
|
||||
|
||||
impl<'a> LintRun<'a> {
|
||||
/// The pass this workspace's settings and index describe for one buffer.
|
||||
///
|
||||
@@ -90,25 +119,12 @@ impl<'a> LintRun<'a> {
|
||||
/// cross-file evidence behind them, which is the false-positive mode this
|
||||
/// whole round exists to close.
|
||||
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
// One discovery for the whole pass: the selection, the options, the
|
||||
// width and the waiver paths all read the same `FileConfig`, so
|
||||
// reading the project's rules costs no extra stat and no extra open.
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (from_file, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
|
||||
let (mut external, bad_waivers) = external_waivers(&project_waivers(&file));
|
||||
messages.extend(bad_waivers);
|
||||
// The editor's own waiver files are read separately and their
|
||||
// problems dropped: `notification::apply_settings` already said them
|
||||
// once, where the setting arrived.
|
||||
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
|
||||
let problems = ConfigProblems::new(&file, messages);
|
||||
LintRun { rules, oracle, options, line_length, external, problems }
|
||||
// Two stages, so `--verbose` can say which of them the request spent
|
||||
// its milliseconds in: everything read from disk, then everything
|
||||
// decided from what was read (review round §R1b, `crate::lint_trace`).
|
||||
let found = lint_trace::stage(Stage::Config, || Discovered::read(ws, doc));
|
||||
lint_trace::saw_config(found.file.source.is_some(), found.texts.len());
|
||||
lint_trace::stage(Stage::Build, || found.into_run(ws, doc))
|
||||
}
|
||||
|
||||
/// What this buffer's `lucisv.toml` asked for and did not get, for a
|
||||
@@ -117,17 +133,53 @@ impl<'a> LintRun<'a> {
|
||||
&self.problems
|
||||
}
|
||||
|
||||
/// A run carrying these external waivers — for the tests that pin what a
|
||||
/// waiver keeps out of the code actions.
|
||||
/// A run carrying this waiver file — for the tests that pin what a waiver
|
||||
/// keeps out of the code actions.
|
||||
///
|
||||
/// Takes the file's **text**, not a parsed `ExternalWaivers`, for the same
|
||||
/// reason `waiver_files` returns both: the waivers a run lints with and
|
||||
/// the texts its snapshot key holds must be written in one step, or a run
|
||||
/// could carry waivers its key cannot see. The bad-line messages are
|
||||
/// dropped here; the caller asserts about them itself where it cares.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_external(mut self, external: ExternalWaivers) -> Self {
|
||||
self.external = external;
|
||||
pub(crate) fn with_waivers(mut self, path: &Path, text: &str) -> Self {
|
||||
self.external.absorb(ExternalWaivers::parse(path, text).0);
|
||||
self.waiver_texts.push((path.to_path_buf(), text.to_string()));
|
||||
self
|
||||
}
|
||||
|
||||
/// A run whose fixes are written at this indent width — for the tests
|
||||
/// that pin what a `no-tabs` fix writes. The server itself reads the
|
||||
/// width off the buffer's own configuration in [`Discovered::read`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_tab_width(mut self, tab_width: usize) -> Self {
|
||||
self.tab_width = tab_width;
|
||||
self
|
||||
}
|
||||
|
||||
/// What this run would lint with, as the snapshot compares it.
|
||||
///
|
||||
/// Every field is an argument of the `lint_with` call it guards; the
|
||||
/// buffer itself and the workspace index are settled by identity and by
|
||||
/// `Document::refresh_overlay` instead. The feature README's table is the
|
||||
/// whole argument.
|
||||
fn key(&self) -> Key {
|
||||
Key {
|
||||
rules: self.rules.iter().map(|rule| rule.name()).collect(),
|
||||
options: self.options.clone(),
|
||||
line_length: self.line_length,
|
||||
tab_width: self.tab_width,
|
||||
has_oracle: self.oracle.is_some(),
|
||||
waivers: self.waiver_texts.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
|
||||
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
|
||||
let ctx = context(doc)
|
||||
.with_options(&self.options)
|
||||
.with_line_length(self.line_length)
|
||||
.with_tab_width(self.tab_width);
|
||||
match &self.oracle {
|
||||
Some(oracle) => ctx.with_oracle(oracle),
|
||||
None => ctx,
|
||||
@@ -135,6 +187,76 @@ impl<'a> LintRun<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything one lint pass reads **from disk**: the `lucisv.toml` governing
|
||||
/// the buffer, what its `[lint]` table said, and the external waiver files in
|
||||
/// force.
|
||||
///
|
||||
/// Split out of [`LintRun::for_document`] so the I/O has a name and a stage of
|
||||
/// its own on the `--verbose` channel — "config read plus lint" was as far as
|
||||
/// take 5 §P1 could attribute the pinmux menu's 23 ms, and that is two
|
||||
/// answers. Nothing about *what* is read changed: the calls below are
|
||||
/// `for_document`'s own, in its own order, so the messages a config problem
|
||||
/// produces arrive in the order §42.2 fixed.
|
||||
struct Discovered {
|
||||
options: RuleOptions,
|
||||
line_length: usize,
|
||||
tab_width: usize,
|
||||
file: FileConfig,
|
||||
project: ProjectLint,
|
||||
external: ExternalWaivers,
|
||||
/// Each waiver file's path and the text it was parsed from — the
|
||||
/// snapshot key's only I/O-derived field.
|
||||
texts: Vec<(PathBuf, String)>,
|
||||
messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Discovered {
|
||||
/// One discovery for the whole pass: the selection, the options, the
|
||||
/// width, the indent and the waiver paths all read the same `FileConfig`,
|
||||
/// so reading the project's rules costs no extra stat and no extra open.
|
||||
fn read(ws: &Workspace, doc: &Document) -> Discovered {
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (project, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file));
|
||||
messages.extend(bad_waivers);
|
||||
// The editor's own waiver files are read separately and their
|
||||
// problems dropped: `notification::apply_settings` already said them
|
||||
// once, where the setting arrived.
|
||||
let editor = waiver_files(&editor_waivers(ws.client_settings(), ws.roots()));
|
||||
external.absorb(editor.0);
|
||||
texts.extend(editor.2);
|
||||
// `format::indent_width` stays the one authority on the indent ladder
|
||||
// (`lucisv.toml` > `lucisv.indent` > the formatter's default): reading
|
||||
// it here rather than spelling the ladder a second time costs a second
|
||||
// `Discovery` walk, which the R1b trace measures at hundredths of a
|
||||
// millisecond against a 21 ms pass.
|
||||
let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings());
|
||||
Discovered { options, line_length, tab_width, file, project, external, texts, messages }
|
||||
}
|
||||
|
||||
/// What this buffer's index and settings make of it: the census oracle and
|
||||
/// the rule ladder, neither of which touches the filesystem.
|
||||
fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let rules = enabled_rules(ws.client_settings(), &self.project, workspace);
|
||||
let problems = ConfigProblems::new(&self.file, self.messages);
|
||||
LintRun {
|
||||
rules,
|
||||
oracle,
|
||||
options: self.options,
|
||||
line_length: self.line_length,
|
||||
tab_width: self.tab_width,
|
||||
external: self.external,
|
||||
waiver_texts: self.texts,
|
||||
problems,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-rule options and the line width governing one buffer.
|
||||
///
|
||||
/// **Precedence for an option, highest first: the editor, then the buffer's
|
||||
@@ -237,18 +359,37 @@ fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
|
||||
/// pass, which runs on every keystroke, drops them silently rather than
|
||||
/// logging the same line a hundred times.
|
||||
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
|
||||
let (waivers, problems, _) = waiver_files(paths);
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// [`external_waivers`], keeping each file's **text** as well.
|
||||
///
|
||||
/// The text is what the lint snapshot's key holds (review round §R1a): a
|
||||
/// waiver file is not watched — `watch::SOURCE_GLOB` covers sources and the
|
||||
/// filelist alone — so comparing its contents is the only thing that ever
|
||||
/// notices one being rewritten under a running server.
|
||||
///
|
||||
/// One read, not two. `ExternalWaivers::read` is `read_to_string` followed by
|
||||
/// `ExternalWaivers::parse`, and both halves are public, so the bytes are
|
||||
/// taken once and handed to the parser; the sentence an unreadable file
|
||||
/// produces is `read`'s own, byte for byte.
|
||||
fn waiver_files(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>, Vec<(PathBuf, String)>) {
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
let mut problems = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
for path in paths {
|
||||
match ExternalWaivers::read(path) {
|
||||
Ok((file, bad)) => {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => {
|
||||
let (file, bad) = ExternalWaivers::parse(path, &text);
|
||||
problems.extend(bad);
|
||||
waivers.absorb(file);
|
||||
texts.push((path.clone(), text));
|
||||
}
|
||||
Err(problem) => problems.push(problem),
|
||||
Err(problem) => problems.push(format!("{}: {problem}", path.display())),
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
(waivers, problems, texts)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings and
|
||||
@@ -419,16 +560,43 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
/// waiver was dead, and a server never has one — it lints the buffers a user
|
||||
/// happens to have open. `lucisv check` is what reports an unused external
|
||||
/// waiver; see `docs/features/waiver-files/README.md`.
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
lint_with(&run.context(doc), &run.rules, &run.external).0
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
|
||||
found(doc, run)
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for, with their fixes built for
|
||||
/// `tab_width`.
|
||||
/// The one place `vlog_linter::lint_with` is called for an open buffer.
|
||||
///
|
||||
/// The code-action path passes the indent width of the `lucisv.toml` governing
|
||||
/// the buffer, so a quick fix that replaces a tab writes exactly what `lucisv`
|
||||
/// would have written there.
|
||||
/// One place, so there is one snapshot to read (review round §R1a) and one
|
||||
/// site that says on the `--verbose` channel what a pass ran, what it found,
|
||||
/// and whether it ran at all. Both doors — the diagnostics publish and
|
||||
/// quick-fix discovery — arrive here with the *same* context, which is why the
|
||||
/// tab width lives on the [`LintRun`] rather than being handed to [`fixable`].
|
||||
fn found(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
|
||||
let key = run.key();
|
||||
let (violations, hit) = lint_trace::stage(Stage::Lint, || {
|
||||
snapshot(doc).read_or(&key, || lint_with(&run.context(doc), &run.rules, &run.external).0)
|
||||
});
|
||||
let reuse = if hit { Reuse::Hit } else { Reuse::Miss };
|
||||
lint_trace::saw_lint(run.rules.len(), violations.len(), reuse);
|
||||
violations
|
||||
}
|
||||
|
||||
/// The slot this buffer's findings are kept in.
|
||||
///
|
||||
/// A field on the `Document`, so it is dropped with the buffer and cannot
|
||||
/// outlive the text it was computed from: `Workspace::set_document` builds a
|
||||
/// new `Document` for every flushed change. One per open document and nothing
|
||||
/// else — no map, no eviction, no second analysis cache.
|
||||
fn snapshot(doc: &Document) -> &Slot {
|
||||
&doc.lint
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for.
|
||||
///
|
||||
/// The fixes are written at the run's own indent width — the `lucisv.toml`
|
||||
/// governing the buffer, else `lucisv.indent`, else the formatter's default —
|
||||
/// so a quick fix that replaces a tab writes exactly what `lucisv` would have
|
||||
/// written there.
|
||||
///
|
||||
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
|
||||
/// region is dropped here, so the editor keeps the same promise `lucisv check
|
||||
@@ -437,21 +605,39 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
/// just has no lightbulb. Which bytes count as fenced is
|
||||
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
|
||||
/// `docs/features/shared-fence-filter/README.md`.
|
||||
pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
pub fn fixable(run: &LintRun, doc: &Document) -> Arc<[Violation]> {
|
||||
// The buffer's own run: its enabled rules and its external waiver files,
|
||||
// so a fix is never offered — nor applied by fix-on-save — for a finding
|
||||
// the diagnostics pass would not have shown. Found by §39's QA: with
|
||||
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
|
||||
// line a checked-in waiver file had waived.
|
||||
let ctx = run.context(doc).with_tab_width(tab_width);
|
||||
let found = lint_with(&ctx, &run.rules, &run.external).0;
|
||||
// One tolerant parse per code-action request: `protected_regions` takes
|
||||
// text and parses internally, on purpose — one fence answer for every
|
||||
// front end, none of which can feed it a stale tree (see
|
||||
// `docs/features/shared-fence-filter/README.md`). The per-keystroke
|
||||
// diagnostics path pays nothing, because it never reads a fix.
|
||||
let regions = fence::protected_regions(&doc.text);
|
||||
found.into_iter().filter(|violation| !fix_touches_fence(violation, ®ions)).collect()
|
||||
let violations = found(doc, run);
|
||||
// The fence answer is a whole second tolerant parse of the buffer:
|
||||
// `protected_regions` takes text and parses internally, on purpose — one
|
||||
// fence answer for every front end, none of which can feed it a stale tree
|
||||
// (see `docs/features/shared-fence-filter/README.md`). It protects
|
||||
// *fixes*, so a pass whose findings carry no fix has nothing to protect
|
||||
// and nothing to ask: the filter below would be the identity. Skipping it
|
||||
// there is take 5 §P1a. The per-keystroke diagnostics path pays nothing
|
||||
// either, because it never reads a fix.
|
||||
if !violations.iter().any(|violation| violation.fix.is_some()) {
|
||||
lint_trace::saw_fences(Fences::Skipped);
|
||||
return violations;
|
||||
}
|
||||
// Asked once per document revision rather than once per request: the text
|
||||
// a `Document` holds cannot change without a new `Document` (§P1b,
|
||||
// `crate::fences`). The question itself is unchanged — still
|
||||
// `protected_regions` over this buffer's text.
|
||||
let held = crate::fences::held(doc);
|
||||
let regions = lint_trace::stage(Stage::Fence, || crate::fences::of(doc));
|
||||
lint_trace::saw_fences(if held { Fences::Memo } else { Fences::Computed });
|
||||
// The snapshot's own findings when the fence drops nothing, which is every
|
||||
// buffer with no `// lucisv: off` region in it: the filter would be the
|
||||
// identity, and copying the findings to prove it would undo the reuse.
|
||||
if !violations.iter().any(|violation| fix_touches_fence(violation, regions)) {
|
||||
return violations;
|
||||
}
|
||||
violations.iter().filter(|v| !fix_touches_fence(v, regions)).cloned().collect()
|
||||
}
|
||||
|
||||
/// True when a violation carries a fix any edit of which lands in a fenced
|
||||
@@ -635,7 +821,7 @@ mod tests {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
|
||||
let offered = fixable(&LintRun::default(), doc, 2);
|
||||
let offered = fixable(&LintRun::default(), doc);
|
||||
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
|
||||
let free = text.find("\twire b").expect("the unfenced tab") as u32;
|
||||
assert_eq!(offered[0].span.start, free);
|
||||
@@ -655,7 +841,7 @@ mod tests {
|
||||
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
|
||||
"still reported"
|
||||
);
|
||||
assert!(fixable(&LintRun::default(), doc, 2).is_empty(), "and still not fixable");
|
||||
assert!(fixable(&LintRun::default(), doc).is_empty(), "and still not fixable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -903,7 +1089,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_unfenced_file_offers_every_fix() {
|
||||
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -911,7 +1097,7 @@ mod tests {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for width in [2usize, 4] {
|
||||
let found = fixable(&LintRun::default(), doc, width);
|
||||
let found = fixable(&LintRun::default().with_tab_width(width), doc);
|
||||
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
|
||||
assert_eq!(fix.edits[0].1, " ".repeat(width));
|
||||
}
|
||||
@@ -948,6 +1134,79 @@ mod tests {
|
||||
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
|
||||
}
|
||||
|
||||
/// The run's indent width is the formatter's own ladder, read through
|
||||
/// `format::indent_width` rather than spelled a second time — pinned at
|
||||
/// each rung, because the width is a fix's bytes and this lane moved
|
||||
/// where it is read (review round §R1a).
|
||||
#[test]
|
||||
fn the_runs_tab_width_is_the_formatters_own_ladder() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_indent", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("m.sv"), "module m;\n\twire a;\nendmodule\n").expect("write");
|
||||
let path = dir.join("m.sv");
|
||||
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
|
||||
|
||||
// Rung by rung: the built-in default, the editor's setting, and a
|
||||
// `lucisv.toml` that outranks it.
|
||||
let rungs: Vec<(Option<&str>, Option<usize>, usize)> = vec![
|
||||
(None, None, 2),
|
||||
(None, Some(8), 8),
|
||||
(Some("indent = 4\n"), Some(8), 4),
|
||||
(Some("indent = 3\n"), None, 3),
|
||||
];
|
||||
for (toml, editor, want) in rungs {
|
||||
match toml {
|
||||
Some(text) => std::fs::write(dir.join("lucisv.toml"), text).expect("write"),
|
||||
None => {
|
||||
let _ = std::fs::remove_file(dir.join("lucisv.toml"));
|
||||
}
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { indent: editor, ..Default::default() });
|
||||
ws.set_document(uri.clone(), "module m;\n\twire a;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::for_document(&ws, doc);
|
||||
assert_eq!(run.tab_width, want, "toml={toml:?} editor={editor:?}");
|
||||
assert_eq!(
|
||||
run.tab_width,
|
||||
crate::format::indent_width(Some(&path), ws.client_settings()),
|
||||
"the two readings of the ladder agree"
|
||||
);
|
||||
assert_eq!(
|
||||
fixable(&run, doc)[0].fix.as_ref().expect("a fix").edits[0].1,
|
||||
" ".repeat(want)
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The snapshot is a memo and not a second implementation: what it hands
|
||||
/// back is what a pass computed from scratch would have, violation for
|
||||
/// violation, and both doors get the same object.
|
||||
#[test]
|
||||
fn a_reused_snapshot_is_what_a_fresh_pass_would_have_found() {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a; \nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let run = LintRun::default();
|
||||
let fresh: Vec<Violation> = lint_with(&run.context(doc), &run.rules, &run.external).0;
|
||||
let first = violations_in(doc, &run);
|
||||
let second = fixable(&run, doc);
|
||||
assert!(Arc::ptr_eq(&first, &second), "the diagnostics and the fixes are one pass");
|
||||
assert_eq!(first.len(), fresh.len(), "{fresh:#?}");
|
||||
for (held, made) in first.iter().zip(&fresh) {
|
||||
assert_eq!(
|
||||
(held.rule, held.span, &held.message),
|
||||
(made.rule, made.span, &made.message)
|
||||
);
|
||||
assert_eq!(
|
||||
held.fix.as_ref().map(|fix| &fix.edits),
|
||||
made.fix.as_ref().map(|fix| &fix.edits),
|
||||
"the fix bytes are the fresh pass's too"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A waiver file that is missing, and one with a bad line, are both
|
||||
/// described rather than fatal — and the good directives of the second
|
||||
/// still apply. TODO §39.
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! One lint pass's findings, kept for as long as they are still the answer.
|
||||
//!
|
||||
//! Take 5 **review** round §R1a (`docs/features/perf5r-lint-snapshot/README.md`,
|
||||
//! `docs/performance_take5_review.md` §1). A `textDocument/codeAction` on
|
||||
//! `pinmux_reg_top.sv` spends **21 of its 22 ms in `lint_with`**, and the first
|
||||
//! request after an edit runs that pass **twice** on one revision — once to
|
||||
//! publish diagnostics, once to discover quick fixes. This module is what lets
|
||||
//! the second one read the first one's answer.
|
||||
//!
|
||||
//! **The whole design is in [`Key`].** A snapshot is legitimate only while
|
||||
//! every input of `lint_with(ctx, rules, external)` is what it was, and the
|
||||
//! key is those inputs *by value* — no hash, no mtime, no generation number,
|
||||
//! so "could this offer a stale fix?" is a question about `PartialEq` and not
|
||||
//! about collision probability. What the key deliberately does **not** carry
|
||||
//! is the two things identity already settles:
|
||||
//!
|
||||
//! * the **buffer** — a [`Slot`] is a field on the `Document`, and
|
||||
//! `Workspace::set_document` builds a new `Document` for every flushed
|
||||
//! change, so a slot cannot outlive the text it was computed from (the
|
||||
//! argument `crate::fences` already rests on);
|
||||
//! * the **workspace index** the census oracle reads — every index mutation in
|
||||
//! `state/mod.rs` ends by calling `Document::refresh_overlay` on every open
|
||||
//! buffer, and that is where the slot is cleared.
|
||||
//!
|
||||
//! The invalidation table in the feature README has one row per input, the
|
||||
//! mechanism for each, and the test that flips it.
|
||||
//!
|
||||
//! **Bounded by construction:** one slot per open document, holding that
|
||||
//! document's own violations, dropped with the `Document` on `didClose`. There
|
||||
//! is no map, no eviction policy and no second unbounded analysis cache.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use vlog_linter::{RuleOptions, Violation};
|
||||
|
||||
/// Everything a lint result depends on that is **not** settled by the
|
||||
/// `Document`'s own identity.
|
||||
///
|
||||
/// Compared by value, field by field. Every field is an argument of the
|
||||
/// `lint_with` call it guards, which is what makes the list complete: see the
|
||||
/// feature README's table, which derives it from that call's signature.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Key {
|
||||
/// The enabled rules' names, in registry order — the whole of what the
|
||||
/// `lucisv.lint.*` ladder and the project's `[lint]` table decided.
|
||||
pub rules: Vec<&'static str>,
|
||||
/// The merged per-rule options: the buffer's `lucisv.toml` overlaid with
|
||||
/// the editor's `lucisv.lint.options`.
|
||||
pub options: RuleOptions,
|
||||
/// The width `line-length` holds this buffer to.
|
||||
pub line_length: usize,
|
||||
/// The width a `no-tabs` fix writes. It changes a fix's *text* and
|
||||
/// nothing else, but a fix's text is what a user applies.
|
||||
pub tab_width: usize,
|
||||
/// Whether the pass had a census to ask. The oracle's *answers* are
|
||||
/// covered by `refresh_overlay`; whether there is one at all is decided
|
||||
/// from the index's file count, which can move without any one file's
|
||||
/// facts moving.
|
||||
pub has_oracle: bool,
|
||||
/// Every external waiver file in force, path and **contents**, in the
|
||||
/// order they were read.
|
||||
///
|
||||
/// The contents, not a digest and not an mtime: a waiver file is not
|
||||
/// watched (`watch::SOURCE_GLOB` covers sources and the filelist alone),
|
||||
/// so the only thing that ever notices a rewritten one is this
|
||||
/// comparison. The text is already in hand — the pass read it to parse
|
||||
/// it — so keeping it costs a copy per open document and no I/O.
|
||||
pub waivers: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// One document's lint snapshot: the key it was computed under, and what it
|
||||
/// found.
|
||||
struct Held {
|
||||
key: Key,
|
||||
violations: Arc<[Violation]>,
|
||||
}
|
||||
|
||||
/// The snapshot slot a `Document` carries.
|
||||
///
|
||||
/// A `Mutex` rather than a `RefCell` so a `Document` stays `Sync` exactly as
|
||||
/// its `OnceLock` fence memo leaves it; the lock is uncontended (one message
|
||||
/// loop) and is never held across the pass itself.
|
||||
#[derive(Default)]
|
||||
pub struct Slot(Mutex<Option<Held>>);
|
||||
|
||||
impl Slot {
|
||||
/// An empty slot — what every `Document` is built with.
|
||||
pub fn new() -> Slot {
|
||||
Slot(Mutex::new(None))
|
||||
}
|
||||
|
||||
/// Forget whatever is held.
|
||||
///
|
||||
/// Called from `Document::refresh_overlay`, which is the one place a
|
||||
/// `Document` is told the workspace index moved. Dropping here rather
|
||||
/// than keying on an index generation is deliberate: the four call sites
|
||||
/// that mutate the index all end in that loop, so there is no way for the
|
||||
/// index to move without this running, and no counter to keep in step.
|
||||
pub fn clear(&mut self) {
|
||||
if let Ok(mut held) = self.0.lock() {
|
||||
*held = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The violations for `key`, computing them when what is held is for
|
||||
/// anything else.
|
||||
///
|
||||
/// Returns `(violations, answered_from_the_snapshot)`. A poisoned lock —
|
||||
/// which this server has no way to produce, having one message loop and no
|
||||
/// panicking library code — degrades to computing every time rather than
|
||||
/// to an error a user would see.
|
||||
pub fn read_or(
|
||||
&self,
|
||||
key: &Key,
|
||||
compute: impl FnOnce() -> Vec<Violation>,
|
||||
) -> (Arc<[Violation]>, bool) {
|
||||
if let Ok(held) = self.0.lock() {
|
||||
if let Some(held) = held.as_ref().filter(|held| held.key == *key) {
|
||||
return (Arc::clone(&held.violations), true);
|
||||
}
|
||||
}
|
||||
// Computed with the lock released: `lint_with` is the expensive part
|
||||
// and it reads nothing this slot owns.
|
||||
let violations: Arc<[Violation]> = compute().into();
|
||||
if let Ok(mut held) = self.0.lock() {
|
||||
*held = Some(Held { key: key.clone(), violations: Arc::clone(&violations) });
|
||||
}
|
||||
(violations, false)
|
||||
}
|
||||
|
||||
/// Whether anything is held at all — for the tests that assert a slot was
|
||||
/// filled, or was not.
|
||||
#[cfg(test)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.lock().map_or(true, |held| held.is_none())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Slot {
|
||||
/// Says whether a snapshot is held and nothing about it: a `Document`'s
|
||||
/// `Debug` must not print a thousand violations.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let held = self.0.lock().map(|held| held.is_some()).unwrap_or(false);
|
||||
f.debug_tuple("Slot").field(&held).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
fn key() -> Key {
|
||||
Key {
|
||||
rules: vec!["no-tabs"],
|
||||
options: RuleOptions::new(),
|
||||
line_length: 100,
|
||||
tab_width: 2,
|
||||
has_oracle: false,
|
||||
waivers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn violation(message: &str) -> Violation {
|
||||
Violation::new("no-tabs", message, TextRange::new(0, 1))
|
||||
}
|
||||
|
||||
/// The second ask for the same key does not compute, and answers with the
|
||||
/// same findings.
|
||||
#[test]
|
||||
fn a_matching_key_answers_without_computing() {
|
||||
let slot = Slot::new();
|
||||
let (first, hit) = slot.read_or(&key(), || vec![violation("one")]);
|
||||
assert!(!hit, "an empty slot cannot hit");
|
||||
let (again, hit) = slot.read_or(&key(), || panic!("must not recompute"));
|
||||
assert!(hit);
|
||||
assert_eq!(again.len(), 1);
|
||||
assert_eq!(again[0].message, first[0].message);
|
||||
}
|
||||
|
||||
/// Every field of the key is load-bearing: change any one and the pass
|
||||
/// runs again. This is the table's row set in miniature — the per-input
|
||||
/// server tests assert the same thing through the real doors.
|
||||
#[test]
|
||||
fn every_field_of_the_key_forces_a_recompute() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw("line-length", "length", "80").expect("a real option");
|
||||
let changes: Vec<(&str, Key)> = vec![
|
||||
("rules", Key { rules: vec!["no-tabs", "posix-eof"], ..key() }),
|
||||
("options", Key { options, ..key() }),
|
||||
("line_length", Key { line_length: 120, ..key() }),
|
||||
("tab_width", Key { tab_width: 4, ..key() }),
|
||||
("has_oracle", Key { has_oracle: true, ..key() }),
|
||||
(
|
||||
"waivers",
|
||||
Key {
|
||||
waivers: vec![(PathBuf::from("/w.waiver"), "waive --rule=no-tabs\n".into())],
|
||||
..key()
|
||||
},
|
||||
),
|
||||
];
|
||||
for (what, moved) in changes {
|
||||
let slot = Slot::new();
|
||||
slot.read_or(&key(), || vec![violation("old")]);
|
||||
let (found, hit) = slot.read_or(&moved, || vec![violation("new")]);
|
||||
assert!(!hit, "{what} did not invalidate the snapshot");
|
||||
assert_eq!(found[0].message, "new", "{what} answered stale");
|
||||
// ... and the new answer is what is held afterwards, so the stale
|
||||
// one cannot come back on the next request.
|
||||
let (again, hit) = slot.read_or(&moved, || panic!("must not recompute"));
|
||||
assert!(hit);
|
||||
assert_eq!(again[0].message, "new", "{what} left the old answer held");
|
||||
}
|
||||
}
|
||||
|
||||
/// A waiver file rewritten to the same length with different bytes is a
|
||||
/// different key: the contents are compared, not a size or a time.
|
||||
#[test]
|
||||
fn a_waiver_rewritten_in_place_is_a_different_key() {
|
||||
let one = |text: &str| Key {
|
||||
waivers: vec![(PathBuf::from("/w.waiver"), text.to_string())],
|
||||
..key()
|
||||
};
|
||||
let slot = Slot::new();
|
||||
slot.read_or(&one("waive --rule=no-tabs\n"), || vec![violation("old")]);
|
||||
let (found, hit) =
|
||||
slot.read_or(&one("waive --rule=posix-eof\n"), || vec![violation("new")]);
|
||||
assert!(!hit, "same length, different bytes");
|
||||
assert_eq!(found[0].message, "new");
|
||||
}
|
||||
|
||||
/// Clearing is what `refresh_overlay` does when the index moves.
|
||||
#[test]
|
||||
fn clearing_forces_the_next_pass_to_compute() {
|
||||
let mut slot = Slot::new();
|
||||
slot.read_or(&key(), || vec![violation("old")]);
|
||||
assert!(!slot.is_empty());
|
||||
slot.clear();
|
||||
assert!(slot.is_empty());
|
||||
let (found, hit) = slot.read_or(&key(), || vec![violation("new")]);
|
||||
assert!(!hit, "a cleared slot cannot hit");
|
||||
assert_eq!(found[0].message, "new");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! Where a lint-answering request's milliseconds went.
|
||||
//!
|
||||
//! Take 5 **review** round §R1b (`docs/performance_take5_review.md` §1,
|
||||
//! `docs/features/perf5r-lint-snapshot/README.md`). The review's own note is
|
||||
//! that the pinmux code-action menu costs **25 ms of which 23 is quickfix**,
|
||||
//! and that the first request after a one-character edit costs **136 ms** —
|
||||
//! but "config read plus lint" was as far as the previous lane could
|
||||
//! attribute it, and *config read plus lint* is two answers, not one. This
|
||||
//! module splits the request into the five stages a reader can act on:
|
||||
//!
|
||||
//! | stage | what it is |
|
||||
//! |---|---|
|
||||
//! | `config` | `Discovery::for_file`, `ProjectLint::read` and every waiver file read |
|
||||
//! | `build` | the rest of [`crate::lint::LintRun::for_document`] — the oracle, the rule ladder |
|
||||
//! | `lint` | `vlog_linter::lint_with`, and how many times it ran |
|
||||
//! | `fence` | `crate::fences::of` — computed, taken from the memo, or skipped |
|
||||
//! | `serialize` | turning violations into `CodeAction`s |
|
||||
//!
|
||||
//! and reports the **flush** — the debounced `Document` rebuild `answer_request`
|
||||
//! performs before any handler runs — as its own group, with the diagnostics
|
||||
//! pass that publishes inside it split the same five ways. That separation is
|
||||
//! the review's item 4: if the dirty-buffer stage dominates the 136 ms, a lint
|
||||
//! cache alone cannot fix it, and only a number can say.
|
||||
//!
|
||||
//! **Nothing here decides anything.** A trace is armed by
|
||||
//! [`crate::server`]'s request wrapper when `--verbose` asked for one, written
|
||||
//! as the request runs, logged once and dropped.
|
||||
//!
|
||||
//! Off is the shipped state and costs **one thread-local `Cell<bool>` read**
|
||||
//! per traced site — no clock read, no allocation, no line — which is the same
|
||||
//! bargain `Server::timer` makes for the rest of `docs/features/verbose-timing/`.
|
||||
//!
|
||||
//! Per thread, deliberately, for `vlog_parser::stats`' reason: a request is
|
||||
//! answered on one thread, so a thread-local accumulator is that request's
|
||||
//! number exactly, and `cargo test`'s parallel binaries cannot add to each
|
||||
//! other's.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// One stage of a lint-answering request.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
/// Reading the project's configuration: the `lucisv.toml` discovery walk,
|
||||
/// its `[lint]` table, and the external waiver files.
|
||||
Config,
|
||||
/// The rest of the `LintRun`: the census oracle and the rule ladder.
|
||||
Build,
|
||||
/// `vlog_linter::lint_with` itself.
|
||||
Lint,
|
||||
/// The formatter's fenced-region answer.
|
||||
Fence,
|
||||
/// Turning violations into what goes on the wire.
|
||||
Serialize,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
/// The name this stage is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Stage::Config => "config",
|
||||
Stage::Build => "build",
|
||||
Stage::Lint => "lint",
|
||||
Stage::Fence => "fence",
|
||||
Stage::Serialize => "serialize",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stage, in the order a request passes through them — so a line
|
||||
/// always carries the same fields whether or not a stage ran.
|
||||
const ALL: [Stage; 5] =
|
||||
[Stage::Config, Stage::Build, Stage::Lint, Stage::Fence, Stage::Serialize];
|
||||
}
|
||||
|
||||
/// One stage of the debounced `Document` rebuild the flush performs, plus the
|
||||
/// diagnostics publish that follows it.
|
||||
///
|
||||
/// TODO §63.2: `flush{wall=…}` said the rebuild cost 100 ms and nothing about
|
||||
/// *which* of the six derivations that was, so the first thing this round does
|
||||
/// is name them. The six are [`crate::state::Document::new`]'s own steps in
|
||||
/// the order it runs them; `Publish` is what `flush_dirty` does with the
|
||||
/// rebuilt buffer, and the flush group's `config`/`build`/`lint`/`fence`
|
||||
/// stages are inside it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Rebuild {
|
||||
/// `tokenize` over the buffer's text.
|
||||
Lex,
|
||||
/// `parse_tolerant` over those tokens (or `parse_source_tolerant` when the
|
||||
/// buffer does not lex).
|
||||
Parse,
|
||||
/// `collect_defines` over the tokens.
|
||||
Defines,
|
||||
/// `analyze` over the tree.
|
||||
Analyze,
|
||||
/// `resolve_external` against the workspace index.
|
||||
External,
|
||||
/// `LineIndex::new` over the text.
|
||||
Lines,
|
||||
/// The diagnostics publish for the rebuilt buffer.
|
||||
Publish,
|
||||
}
|
||||
|
||||
impl Rebuild {
|
||||
/// The name this stage is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Rebuild::Lex => "lex",
|
||||
Rebuild::Parse => "parse",
|
||||
Rebuild::Defines => "defines",
|
||||
Rebuild::Analyze => "analyze",
|
||||
Rebuild::External => "external",
|
||||
Rebuild::Lines => "lines",
|
||||
Rebuild::Publish => "publish",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stage, in the order the flush passes through them.
|
||||
const ALL: [Rebuild; 7] = [
|
||||
Rebuild::Lex,
|
||||
Rebuild::Parse,
|
||||
Rebuild::Defines,
|
||||
Rebuild::Analyze,
|
||||
Rebuild::External,
|
||||
Rebuild::Lines,
|
||||
Rebuild::Publish,
|
||||
];
|
||||
}
|
||||
|
||||
/// The flush's inner stages: what rebuilding the dirty buffers cost, split.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Rebuilt {
|
||||
ms: [f64; Rebuild::ALL.len()],
|
||||
/// How many `Document`s were built from scratch.
|
||||
documents: usize,
|
||||
}
|
||||
|
||||
impl Rebuilt {
|
||||
/// The `const` form `thread_local!`'s initializer needs.
|
||||
const EMPTY: Rebuilt = Rebuilt { ms: [0.0; Rebuild::ALL.len()], documents: 0 };
|
||||
|
||||
fn add(&mut self, stage: Rebuild, took: Duration) {
|
||||
self.ms[stage as usize] += took.as_secs_f64() * 1_000.0;
|
||||
}
|
||||
|
||||
/// This group's fields, in the `key=value` shape `tools/perf` parses.
|
||||
fn fields(&self) -> String {
|
||||
let stages: Vec<String> = Rebuild::ALL
|
||||
.iter()
|
||||
.map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize]))
|
||||
.collect();
|
||||
format!("{} documents={}", stages.join(" "), self.documents)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the fence filter did, when a pass reached it at all.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Fences {
|
||||
/// No finding carried a fix, so the filter would have been the identity
|
||||
/// and was not asked (take 5 §P1a).
|
||||
#[default]
|
||||
Skipped,
|
||||
/// `protected_regions` parsed the buffer for this `Document`.
|
||||
Computed,
|
||||
/// The `Document`'s memo answered (take 5 §P1b).
|
||||
Memo,
|
||||
}
|
||||
|
||||
impl Fences {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Fences::Skipped => "skipped",
|
||||
Fences::Computed => "computed",
|
||||
Fences::Memo => "memo",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a lint pass was answered from the snapshot (review round §R1a).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Reuse {
|
||||
/// No pass ran.
|
||||
#[default]
|
||||
None,
|
||||
/// The `Document` held no snapshot, or held one for other inputs.
|
||||
Miss,
|
||||
/// The snapshot matched and `lint_with` did not run.
|
||||
Hit,
|
||||
}
|
||||
|
||||
impl Reuse {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Reuse::None => "none",
|
||||
Reuse::Miss => "miss",
|
||||
Reuse::Hit => "hit",
|
||||
}
|
||||
}
|
||||
|
||||
/// A hit only survives while every pass hit: one recompute in a request
|
||||
/// is a miss for that request, which is what a reader wants to know.
|
||||
fn saw(self, other: Reuse) -> Reuse {
|
||||
match (self, other) {
|
||||
(Reuse::Miss, _) | (_, Reuse::Miss) => Reuse::Miss,
|
||||
(Reuse::Hit, _) | (_, Reuse::Hit) => Reuse::Hit,
|
||||
_ => Reuse::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One group of stages: the flush's, or the handler's own.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Group {
|
||||
ms: [f64; Stage::ALL.len()],
|
||||
/// How many times `lint_with` ran in this group.
|
||||
passes: u32,
|
||||
/// How many violations the last pass found.
|
||||
violations: usize,
|
||||
/// How many rules that pass ran.
|
||||
rules: usize,
|
||||
/// How many actions were serialized.
|
||||
actions: usize,
|
||||
/// How many waiver files were read from disk.
|
||||
waivers: usize,
|
||||
/// Whether a `lucisv.toml` was found and read.
|
||||
toml: bool,
|
||||
fences: Fences,
|
||||
reuse: Reuse,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// The `const` form `thread_local!`'s initializer needs; `Default` is not
|
||||
/// callable there.
|
||||
const EMPTY: Group = Group {
|
||||
ms: [0.0; Stage::ALL.len()],
|
||||
passes: 0,
|
||||
violations: 0,
|
||||
rules: 0,
|
||||
actions: 0,
|
||||
waivers: 0,
|
||||
toml: false,
|
||||
fences: Fences::Skipped,
|
||||
reuse: Reuse::None,
|
||||
};
|
||||
|
||||
fn add(&mut self, stage: Stage, took: Duration) {
|
||||
self.ms[stage as usize] += took.as_secs_f64() * 1_000.0;
|
||||
}
|
||||
|
||||
/// This group's fields, in the `key=value` shape `tools/perf` parses.
|
||||
fn fields(&self) -> String {
|
||||
let stages: Vec<String> = Stage::ALL
|
||||
.iter()
|
||||
.map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize]))
|
||||
.collect();
|
||||
format!(
|
||||
"{} passes={} rules={} violations={} actions={} waivers={} toml={} fences={} \
|
||||
snapshot={}",
|
||||
stages.join(" "),
|
||||
self.passes,
|
||||
self.rules,
|
||||
self.violations,
|
||||
self.actions,
|
||||
self.waivers,
|
||||
self.toml,
|
||||
self.fences.label(),
|
||||
self.reuse.label(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One request's trace: what the flush cost, and what the handler cost.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Trace {
|
||||
/// The stages the debounced `Document` rebuild and its diagnostics
|
||||
/// publish passed through, closed by [`close_flush`].
|
||||
pub flush: Group,
|
||||
/// How long the whole flush took, publish included.
|
||||
pub flush_ms: f64,
|
||||
/// Buffers the flush rebuilt.
|
||||
pub flush_buffers: usize,
|
||||
/// Whole-file parses the flush performed (`vlog_parser::stats`).
|
||||
pub flush_parses: u64,
|
||||
/// What the flush's `Document` rebuild and publish cost, stage by stage.
|
||||
pub rebuild: Rebuilt,
|
||||
/// The handler's own stages.
|
||||
pub action: Group,
|
||||
}
|
||||
|
||||
impl Trace {
|
||||
/// Whether this request touched the lint path at all. A trace that did
|
||||
/// not is not worth a line.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.flush == Group::default()
|
||||
&& self.action == Group::default()
|
||||
&& self.flush_buffers == 0
|
||||
&& self.rebuild == Rebuilt::default()
|
||||
}
|
||||
|
||||
/// The whole trace as one `timing:`-style fragment.
|
||||
///
|
||||
/// The three groups are siblings, never nested: `tools/perf`'s group
|
||||
/// regex flattens `name{…}` one level and would not survive a brace
|
||||
/// inside a brace.
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"flush{{wall={:.2}ms buffers={} parses={} {}}} rebuild{{{}}} action{{{}}}",
|
||||
self.flush_ms,
|
||||
self.flush_buffers,
|
||||
self.flush_parses,
|
||||
self.flush.fields(),
|
||||
self.rebuild.fields(),
|
||||
self.action.fields(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// One branch is the whole of what verbose-off costs at a traced site.
|
||||
static ARMED: Cell<bool> = const { Cell::new(false) };
|
||||
static TRACE: RefCell<Trace> = const { RefCell::new(Trace {
|
||||
flush: Group::EMPTY,
|
||||
flush_ms: 0.0,
|
||||
flush_buffers: 0,
|
||||
flush_parses: 0,
|
||||
rebuild: Rebuilt::EMPTY,
|
||||
action: Group::EMPTY,
|
||||
}) };
|
||||
/// Which group the stages recorded right now belong to.
|
||||
static IN_FLUSH: Cell<bool> = const { Cell::new(true) };
|
||||
}
|
||||
|
||||
/// Start a fresh trace for one request. Called by the request wrapper when
|
||||
/// `--verbose` asked for timing, and by nothing else.
|
||||
pub fn arm() {
|
||||
ARMED.set(true);
|
||||
IN_FLUSH.set(true);
|
||||
TRACE.with_borrow_mut(|trace| *trace = Trace::default());
|
||||
}
|
||||
|
||||
/// Whether a trace is being written — the one branch a caller checks before
|
||||
/// reading a clock of its own.
|
||||
pub fn armed() -> bool {
|
||||
ARMED.get()
|
||||
}
|
||||
|
||||
/// Stop tracing and return what was written, or `None` when nothing armed it.
|
||||
pub fn disarm() -> Option<Trace> {
|
||||
if !ARMED.replace(false) {
|
||||
return None;
|
||||
}
|
||||
Some(TRACE.with_borrow(Clone::clone))
|
||||
}
|
||||
|
||||
/// Close the flush group: everything recorded from here on is the handler's.
|
||||
///
|
||||
/// `parses` is the `vlog_parser::stats::parses()` delta across the flush and
|
||||
/// `buffers` is how many dirty buffers it rebuilt, so the `Document` rebuild
|
||||
/// is readable beside the diagnostics pass that follows it.
|
||||
pub fn close_flush(took: Duration, buffers: usize, parses: u64) {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
TRACE.with_borrow_mut(|trace| {
|
||||
trace.flush_ms = took.as_secs_f64() * 1_000.0;
|
||||
trace.flush_buffers = buffers;
|
||||
trace.flush_parses = parses;
|
||||
});
|
||||
IN_FLUSH.set(false);
|
||||
}
|
||||
|
||||
/// Run `work`, counting what it took against `stage`.
|
||||
///
|
||||
/// Untimed and unallocated when nothing armed a trace, which is every session
|
||||
/// but a `--verbose` one.
|
||||
pub fn stage<T>(stage: Stage, work: impl FnOnce() -> T) -> T {
|
||||
if !ARMED.get() {
|
||||
return work();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let out = work();
|
||||
let took = started.elapsed();
|
||||
group(|held| held.add(stage, took));
|
||||
out
|
||||
}
|
||||
|
||||
/// Run `work`, counting what it took against one of the flush's inner stages.
|
||||
///
|
||||
/// Off costs the same one thread-local read [`stage`] costs. The flush group
|
||||
/// is not consulted: a rebuild belongs to the rebuild it is part of whichever
|
||||
/// half of the request it happens in, and outside a flush there is none.
|
||||
pub fn rebuild<T>(stage: Rebuild, work: impl FnOnce() -> T) -> T {
|
||||
if !ARMED.get() {
|
||||
return work();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let out = work();
|
||||
let took = started.elapsed();
|
||||
TRACE.with_borrow_mut(|trace| trace.rebuild.add(stage, took));
|
||||
out
|
||||
}
|
||||
|
||||
/// Record that one `Document` was built from scratch.
|
||||
pub fn saw_document() {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
TRACE.with_borrow_mut(|trace| trace.rebuild.documents += 1);
|
||||
}
|
||||
|
||||
/// Record what a lint pass ran and found.
|
||||
pub fn saw_lint(rules: usize, violations: usize, reuse: Reuse) {
|
||||
group(|held| {
|
||||
held.passes += 1;
|
||||
held.rules = rules;
|
||||
held.violations = violations;
|
||||
held.reuse = held.reuse.saw(reuse);
|
||||
});
|
||||
}
|
||||
|
||||
/// Record what the configuration read found: a `lucisv.toml`, and how many
|
||||
/// waiver files it and the editor's settings between them named.
|
||||
pub fn saw_config(toml: bool, waivers: usize) {
|
||||
group(|held| {
|
||||
held.toml |= toml;
|
||||
held.waivers += waivers;
|
||||
});
|
||||
}
|
||||
|
||||
/// Record what the fence filter did.
|
||||
pub fn saw_fences(fences: Fences) {
|
||||
group(|held| held.fences = fences);
|
||||
}
|
||||
|
||||
/// Record how many actions were put on the wire.
|
||||
pub fn saw_actions(actions: usize) {
|
||||
group(|held| held.actions += actions);
|
||||
}
|
||||
|
||||
/// Apply `write` to whichever group is being filled, or to nothing at all.
|
||||
fn group(write: impl FnOnce(&mut Group)) {
|
||||
if !ARMED.get() {
|
||||
return;
|
||||
}
|
||||
let flushing = IN_FLUSH.get();
|
||||
TRACE.with_borrow_mut(|trace| {
|
||||
write(if flushing { &mut trace.flush } else { &mut trace.action })
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Nothing is written when nothing armed a trace — the shipped state.
|
||||
#[test]
|
||||
fn an_unarmed_trace_records_nothing_and_returns_the_work() {
|
||||
assert_eq!(disarm(), None);
|
||||
assert_eq!(stage(Stage::Lint, || 7), 7);
|
||||
saw_lint(3, 4, Reuse::Miss);
|
||||
assert_eq!(disarm(), None, "still nothing to say");
|
||||
}
|
||||
|
||||
/// The two groups are kept apart, and `close_flush` is what separates
|
||||
/// them: a stage before it is the flush's, one after it the handler's.
|
||||
#[test]
|
||||
fn close_flush_divides_the_request_into_its_two_halves() {
|
||||
arm();
|
||||
saw_lint(9, 100, Reuse::Miss);
|
||||
close_flush(Duration::from_millis(110), 1, 1);
|
||||
saw_lint(9, 100, Reuse::Hit);
|
||||
saw_actions(2);
|
||||
saw_fences(Fences::Memo);
|
||||
let trace = disarm().expect("armed");
|
||||
assert_eq!(trace.flush.passes, 1);
|
||||
assert_eq!(trace.flush.violations, 100);
|
||||
assert_eq!(trace.flush.actions, 0, "the flush serializes nothing");
|
||||
assert_eq!(trace.flush_buffers, 1);
|
||||
assert_eq!(trace.flush_parses, 1);
|
||||
assert!((trace.flush_ms - 110.0).abs() < 5.0, "{}", trace.flush_ms);
|
||||
assert_eq!(trace.action.passes, 1);
|
||||
assert_eq!(trace.action.actions, 2);
|
||||
assert_eq!(trace.action.fences, Fences::Memo);
|
||||
assert_eq!(trace.action.reuse, Reuse::Hit);
|
||||
assert_eq!(disarm(), None, "disarming twice says nothing twice");
|
||||
}
|
||||
|
||||
/// One recompute in a request is a miss for that request: a reader asking
|
||||
/// "did this menu re-lint?" must not be told "hit" because the second
|
||||
/// pass reused what the first one had just computed.
|
||||
#[test]
|
||||
fn a_single_recompute_makes_the_whole_request_a_miss() {
|
||||
arm();
|
||||
close_flush(Duration::ZERO, 0, 0);
|
||||
saw_lint(9, 100, Reuse::Hit);
|
||||
saw_lint(9, 100, Reuse::Miss);
|
||||
assert_eq!(disarm().expect("armed").action.reuse, Reuse::Miss);
|
||||
}
|
||||
|
||||
/// Every stage is named in the line whether or not it ran, so a reader
|
||||
/// (and `tools/perf/phases_r1.py`) always parses the same fields.
|
||||
#[test]
|
||||
fn the_line_names_every_stage_in_both_groups() {
|
||||
arm();
|
||||
stage(Stage::Config, || {});
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
stage(Stage::Lint, || {});
|
||||
let line = disarm().expect("armed").line();
|
||||
for stage in Stage::ALL {
|
||||
assert_eq!(line.matches(&format!("{}=", stage.label())).count(), 2, "{line}");
|
||||
}
|
||||
assert!(line.contains("buffers=1"), "{line}");
|
||||
assert!(line.contains("snapshot=none"), "{line}");
|
||||
assert!(!line.contains(" "), "no empty field: {line}");
|
||||
}
|
||||
|
||||
/// The flush's inner stages are their own sibling group, named whether or
|
||||
/// not they ran, and never nested inside `flush{…}` — `tools/perf`'s
|
||||
/// group regex flattens one level only (TODO §63.2).
|
||||
#[test]
|
||||
fn the_rebuild_group_names_every_stage_beside_the_other_two() {
|
||||
arm();
|
||||
rebuild(Rebuild::Lex, || {});
|
||||
saw_document();
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
let line = disarm().expect("armed").line();
|
||||
let rebuilt = line.split("rebuild{").nth(1).expect("a rebuild group").split('}').next();
|
||||
let rebuilt = rebuilt.expect("a closed rebuild group");
|
||||
for stage in Rebuild::ALL {
|
||||
assert!(rebuilt.contains(&format!("{}=", stage.label())), "{line}");
|
||||
}
|
||||
assert!(rebuilt.contains("documents=1"), "{line}");
|
||||
assert!(!rebuilt.contains('{'), "no nested group: {line}");
|
||||
}
|
||||
|
||||
/// TODO §63.2 QA: the sibling-group contract, attacked directly against
|
||||
/// the parser it is a contract *with*.
|
||||
///
|
||||
/// `tools/perf/phases_p2.py`'s `GROUP` regex is `([a-z_]+)\{([^{}]*)\}` —
|
||||
/// a group's body may not contain another `{`. Sabotaging `line()` to
|
||||
/// nest `rebuild{…}` inside `flush{…}` (tried by hand while attacking
|
||||
/// this pin) does **not** fail the test above: splitting on `"rebuild{"`
|
||||
/// still finds a clean `rebuild` body, because the extra brace the
|
||||
/// nesting adds sits *outside* the slice that test inspects. Run through
|
||||
/// the actual regex, though, nesting is fatal: `[^{}]*` cannot cross the
|
||||
/// inner `{`, so the whole `flush{...}` match fails and `flush_wall`,
|
||||
/// `flush_buffers`, `flush_parses` and every `flush.fields()` entry
|
||||
/// silently vanish from every `tools/perf` row — confirmed with
|
||||
/// `GROUP.findall` in a scratch interpreter against the sabotaged line,
|
||||
/// which matched only `rebuild` and `action`, never `flush`. This test
|
||||
/// reads the line the way the regex does (each group's body must reach
|
||||
/// its own `}` before another `{` opens) so a future nesting regression
|
||||
/// fails here instead of only downstream in Python.
|
||||
#[test]
|
||||
fn the_three_top_level_groups_are_flat_never_nested() {
|
||||
arm();
|
||||
rebuild(Rebuild::Lex, || {});
|
||||
saw_document();
|
||||
close_flush(Duration::from_millis(1), 1, 1);
|
||||
let line = disarm().expect("armed").line();
|
||||
for name in ["flush", "rebuild", "action"] {
|
||||
let open =
|
||||
line.find(&format!("{name}{{")).unwrap_or_else(|| panic!("no {name}{{ in {line}"));
|
||||
let body = &line[open + name.len() + 1..];
|
||||
let close =
|
||||
body.find('}').unwrap_or_else(|| panic!("no closing brace for {name}: {line}"));
|
||||
let next_open = body.find('{');
|
||||
assert!(
|
||||
next_open.is_none_or(|o| o > close),
|
||||
"{name}{{...}} is not flat — a nested group vanishes from every \
|
||||
tools/perf row parsed by phases_p2.GROUP instead of failing loudly: {line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rebuild is recorded in either half of the request, and an unarmed
|
||||
/// one records nothing at all.
|
||||
#[test]
|
||||
fn a_rebuild_is_counted_whichever_half_of_the_request_runs_it() {
|
||||
assert_eq!(rebuild(Rebuild::Parse, || 4), 4);
|
||||
assert_eq!(disarm(), None);
|
||||
arm();
|
||||
rebuild(Rebuild::Parse, || {});
|
||||
close_flush(Duration::ZERO, 1, 1);
|
||||
rebuild(Rebuild::Parse, || {});
|
||||
saw_document();
|
||||
saw_document();
|
||||
let trace = disarm().expect("armed");
|
||||
assert_eq!(trace.rebuild.documents, 2);
|
||||
assert_eq!(trace.flush.passes, 0, "a rebuild is not a lint pass");
|
||||
assert_eq!(trace.action.passes, 0);
|
||||
}
|
||||
|
||||
/// A request that only rebuilt a buffer still has something to say: the
|
||||
/// trace must not be discarded as empty before the line is logged.
|
||||
///
|
||||
/// The rebuilt *count*, not a stage's milliseconds, is what says a
|
||||
/// rebuild happened — a stage whose work takes less than the clock's
|
||||
/// resolution adds 0.00 ms, which is why `Document::new` reports itself
|
||||
/// with [`saw_document`] rather than leaving the evidence to a duration.
|
||||
#[test]
|
||||
fn a_trace_holding_only_a_rebuild_is_not_empty() {
|
||||
arm();
|
||||
rebuild(Rebuild::Analyze, || {});
|
||||
saw_document();
|
||||
assert!(!disarm().expect("armed").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod extract;
|
||||
mod fences;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
@@ -30,7 +31,10 @@ mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod lint_snapshot;
|
||||
mod lint_trace;
|
||||
mod locate;
|
||||
mod module_select;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
@@ -38,6 +42,9 @@ mod pairs;
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod rename_trace;
|
||||
mod scan_order;
|
||||
mod scan_trace;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Which files can name a scope *inside* the module a refactoring rewrites.
|
||||
//!
|
||||
//! [`Workspace::module_sources`](crate::state::Workspace::module_sources)'s
|
||||
//! four rungs answer "who declares, instantiates or refers to these **names**".
|
||||
//! That is enough for the port refactorings and for extract, whose refusals
|
||||
//! are about the names themselves. It is not enough for inline-module, whose
|
||||
//! `no_hierarchy` refusal is about a *path through the design hierarchy*:
|
||||
//! `tb.sv` writing `u_wrapper.u_top.u_sub.s` names the instance `u_sub` that
|
||||
//! inlining dissolves, and `tb.sv` instantiates `wrapper` — not `top`, not
|
||||
//! `sub`. No rung asks for it, `no_hierarchy` only sees what it is handed, and
|
||||
//! the inline was **silently accepted**, dissolving a scope a testbench walks
|
||||
//! through. §53.2's QA reproduced exactly that; it is topology handshake 33.
|
||||
//!
|
||||
//! **The rung is the instance's own word census.** `no_hierarchy` refuses when
|
||||
//! some handed file's token stream holds an `Ident` spelling the instance with
|
||||
//! a `.` (or a `bind`) beside it. [`WorkspaceIndex::files_mentioning`] is the
|
||||
//! census of every file whose token stream writes a word down at all — read
|
||||
//! off `FileFacts::words`, which `vlog_semantic::words::harvest` fills from
|
||||
//! every `Ident` token *and* from the raw text of macro invocations,
|
||||
//! directives and attributes. So a file that could raise that refusal is
|
||||
//! always in this answer, and [`hierarchical_users`] hands inline exactly the
|
||||
//! files that could change its mind.
|
||||
//!
|
||||
//! That is a stronger claim than the transitive-instantiator walk the topology
|
||||
//! row asks for, and it is why this module does not do that walk. Climbing the
|
||||
//! instantiation edges upward from the host module finds the wrapper levels,
|
||||
//! but it misses `bind tb.u_wrapper.u_top.u_sub …` written in an SVA file that
|
||||
//! instantiates nothing in the chain, and `$root`-anchored and macro-built
|
||||
//! paths with it — all shapes `no_hierarchy` refuses over and all shapes the
|
||||
//! word census holds. It also selects files that instantiate up the chain and
|
||||
//! never spell the instance, which no refusal can turn on. The census is both
|
||||
//! the tighter and the more complete answer. Written out in the feature
|
||||
//! README's handshake note, with the failing `bind` fixture that settled it.
|
||||
//!
|
||||
//! The rung can only **add** files, so an edit stays the edit it was and a
|
||||
//! refusal it makes possible is one the whole-workspace engine also makes.
|
||||
//! Nothing here reads a file or parses anything: it is a walk over the records
|
||||
//! the index already holds, binary-searching each file's sorted word list.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// The extra reach one refactoring asks for.
|
||||
///
|
||||
/// A caller that needs none passes [`Reach::none`] — which is what
|
||||
/// `module_sources` itself does, so the port and extract paths are unchanged
|
||||
/// by this module in answer and in cost.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Reach<'a> {
|
||||
/// The scope names whose *inside* the refactoring dissolves: for
|
||||
/// inline-module, the instance it removes. Every file whose tokens write
|
||||
/// one of these words is wanted, because every file that could refuse
|
||||
/// over a hierarchical path through it does.
|
||||
pub scopes: &'a [String],
|
||||
}
|
||||
|
||||
impl Reach<'_> {
|
||||
/// No extra reach — the four rungs alone.
|
||||
pub fn none() -> Reach<'static> {
|
||||
Reach { scopes: &[] }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file whose token stream writes one of `reach`'s scope names.
|
||||
///
|
||||
/// The caller unions this into the set its own rungs filled, so a path this
|
||||
/// rung is the first to ask for is still just a path.
|
||||
pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<PathBuf> {
|
||||
let mut out = BTreeSet::new();
|
||||
for scope in reach.scopes {
|
||||
out.extend(
|
||||
index
|
||||
.files_mentioning(scope)
|
||||
.filter_map(|file| index.path(file))
|
||||
.map(Path::to_path_buf),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `tb` → `wrapper` → `top` → `sub`, the shape §53.2's QA reported: `tb`
|
||||
/// names `u_sub` through two levels it does not itself instantiate, and
|
||||
/// `sva.sv` names it through a `bind` while instantiating nothing at all.
|
||||
fn ladder() -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(vec![
|
||||
(PathBuf::from("/w/sub.sv"), "module sub; logic s; endmodule\n"),
|
||||
(PathBuf::from("/w/top.sv"), "module top; sub u_sub (); endmodule\n"),
|
||||
(PathBuf::from("/w/wrapper.sv"), "module wrapper; top u_top (); endmodule\n"),
|
||||
(
|
||||
PathBuf::from("/w/tb.sv"),
|
||||
"module tb; wrapper u_wrapper (); assign x = u_wrapper.u_top.u_sub.s; endmodule\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("/w/sva.sv"),
|
||||
"module chk (input logic a); endmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n",
|
||||
),
|
||||
(PathBuf::from("/w/stranger.sv"), "module stranger; logic q; endmodule\n"),
|
||||
])
|
||||
}
|
||||
|
||||
fn names(paths: &BTreeSet<PathBuf>) -> Vec<String> {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_that_writes_the_instance_down_is_wanted() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let found = hierarchical_users(&index, Reach { scopes: &scopes });
|
||||
assert_eq!(
|
||||
names(&found),
|
||||
vec!["sva.sv".to_string(), "tb.sv".to_string(), "top.sv".to_string()],
|
||||
"the declaring file, the bench two levels up, and the bind that instantiates nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_never_writes_it_is_not() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_sub".to_string()];
|
||||
assert!(!names(&hierarchical_users(&index, Reach { scopes: &scopes }))
|
||||
.contains(&"stranger.sv".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_nothing_writes_wants_nothing() {
|
||||
let index = ladder();
|
||||
let scopes = ["u_no_such_instance".to_string()];
|
||||
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_reach_asked_for_is_no_work_done() {
|
||||
let index = ladder();
|
||||
assert!(hierarchical_users(&index, Reach::none()).is_empty());
|
||||
}
|
||||
}
|
||||
+1756
-54
File diff suppressed because it is too large.
Load diff
@@ -401,7 +401,7 @@ fn what_a_scan_does_before_its_first_file() {
|
||||
});
|
||||
workspace.adopt_roots(vec![dir.clone()]);
|
||||
let started = Instant::now();
|
||||
let mut scan = workspace.begin_scan(&mut |_| {});
|
||||
let mut scan = workspace.begin_scan(&mut |_| {}, false);
|
||||
let head = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.scan_step(&mut scan, &mut |_| {});
|
||||
@@ -556,7 +556,7 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() {
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||||
let started = Instant::now();
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {});
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||||
while incremental.scan_step(&mut scan, &mut |_| {}) {}
|
||||
black_box(incremental.finish_scan(scan));
|
||||
let widen = started.elapsed();
|
||||
@@ -646,7 +646,7 @@ fn what_a_widen_that_subsumes_the_old_scope_costs() {
|
||||
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
|
||||
let mut read = 0usize;
|
||||
let started = Instant::now();
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {});
|
||||
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
|
||||
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
|
||||
// Split out because it is where the 2026-08-29 round's fix landed: folding
|
||||
// a widen's words into the completion table used to move the table's tail
|
||||
@@ -1120,9 +1120,15 @@ fn a_rename_before_and_after() {
|
||||
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
|
||||
});
|
||||
let rename_after = mean(20, || {
|
||||
let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed"));
|
||||
let _ = black_box(crate::rename::rename_traced(
|
||||
&ws,
|
||||
&uri,
|
||||
black_box(offset),
|
||||
"renamed",
|
||||
&mut None,
|
||||
));
|
||||
});
|
||||
let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len();
|
||||
let fan_out = ws.rename_sources_traced(&path, "sub", Some("renamed")).0.len();
|
||||
// Building the file set at all, and the one rung of it that is a linear
|
||||
// walk over every file's records rather than a keyed lookup
|
||||
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
|
||||
@@ -1130,7 +1136,7 @@ fn a_rename_before_and_after() {
|
||||
// it is the only part of the set builder whose cost grows with the
|
||||
// workspace rather than with the symbol.
|
||||
let file_set = mean(2_000, || {
|
||||
black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed")));
|
||||
black_box(ws.rename_sources_traced(black_box(&path), "sub", Some("renamed")));
|
||||
});
|
||||
let spelling_rung = mean(2_000, || {
|
||||
black_box(ws.index().files_spelling(black_box("renamed")).count());
|
||||
@@ -1138,7 +1144,8 @@ fn a_rename_before_and_after() {
|
||||
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
|
||||
let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames");
|
||||
let (edit, _) =
|
||||
crate::rename::rename_traced(&ws, &uri, offset, "renamed", &mut None).expect("renames");
|
||||
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
|
||||
|
||||
eprintln!(
|
||||
|
||||
@@ -36,7 +36,7 @@ use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{ModuleRef, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// The kind every port refactoring is filed under, so a client can ask for
|
||||
@@ -73,6 +73,24 @@ pub fn commands() -> Vec<String> {
|
||||
/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file:
|
||||
/// fine once, when the user has clicked, and not fine on every cursor move,
|
||||
/// which is why [`offers`] exists.
|
||||
/// Every module name a port refactoring at `offset` could act on, asked of
|
||||
/// the buffer's **own parse** rather than of its text.
|
||||
///
|
||||
/// `doc.tree` is the tolerant parse of `doc.text`, which is exactly what the
|
||||
/// text form would build (`docs/features/one-parse/README.md`), so the answer
|
||||
/// is the same and the parse is not paid for twice (take 5 §P1b).
|
||||
///
|
||||
/// A buffer on the large-file fast path is the exception, and deliberately so:
|
||||
/// its `tree` is the analysis of the *empty* file, while the text form parses
|
||||
/// the real bytes and may offer. That is today's behaviour and this reuse does
|
||||
/// not change it — see `docs/features/perf5-p1/README.md`.
|
||||
fn modules_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::port_action_modules(&doc.text, offset),
|
||||
false => vlog_refactor::port_action_modules_in(&doc.tree, offset),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
@@ -82,7 +100,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
// find something, it says which module, so the files handed to the engine
|
||||
// are that module's own fan-out rather than every file in scope
|
||||
// (`Workspace::module_sources`).
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
let modules = modules_at(doc, offset);
|
||||
if modules.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -146,7 +164,7 @@ pub fn offers(
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
let modules = modules_at(doc, offset);
|
||||
// A name the workspace declares twice is a refusal the engine makes over
|
||||
// the fan-out, where it can see both declarations. The offer cannot, so it
|
||||
// asks the index the same question rather than offering an action that
|
||||
@@ -155,10 +173,10 @@ pub fn offers(
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = offer_sources(ws, &path, &doc.text, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
offered(doc, &sources, &path, offset)
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
let title = counted(ws, action.title, &modules);
|
||||
.map(|offer| {
|
||||
let title = counted(ws, offer.title, &modules);
|
||||
let data =
|
||||
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
|
||||
.ok();
|
||||
@@ -172,6 +190,40 @@ pub fn offers(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Which refactorings the cursor would be offered, and what each title says —
|
||||
/// asked of the buffer's **own** parse and analysis rather than recomputed.
|
||||
///
|
||||
/// `vlog_refactor::port_offers_in` runs each of the four planners' plan-time
|
||||
/// half over `doc`'s existing tree, diagnostics and semantics plus, at most,
|
||||
/// one parse of the instantiated module's declaring file. It builds no index
|
||||
/// and verifies nothing, which is the whole of take 5 §P1c: the offer used to
|
||||
/// compute four verified plans over one or two files and throw all four edits
|
||||
/// away (`docs/features/perf5-p1/README.md`). [`resolve`] still recomputes and
|
||||
/// verifies the real refactoring over the module's whole fan-out when the user
|
||||
/// clicks.
|
||||
///
|
||||
/// A buffer on the large-file fast path keeps the text form, whose parse is of
|
||||
/// the real bytes — [`modules_at`] draws the same line, and for the same
|
||||
/// reason.
|
||||
fn offered(
|
||||
doc: &Document,
|
||||
sources: &[(PathBuf, String)],
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
) -> Vec<vlog_refactor::PortOffer> {
|
||||
match doc.large {
|
||||
true => vlog_refactor::port_offers(sources, path, offset),
|
||||
false => vlog_refactor::port_offers_in(
|
||||
sources,
|
||||
path,
|
||||
&doc.tree,
|
||||
&doc.diagnostics,
|
||||
&doc.semantics,
|
||||
offset,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The files an [`offers`] call reads: the buffer the request names, and the
|
||||
/// declaration of every module an instantiation under the cursor names.
|
||||
///
|
||||
|
||||
@@ -17,9 +17,11 @@ use std::path::PathBuf;
|
||||
|
||||
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::locate::display_name;
|
||||
use crate::rename_trace::SelectionTrace;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -48,25 +50,62 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameRe
|
||||
|
||||
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
|
||||
/// user told. An `Err` is the engine's own sentence, returned verbatim.
|
||||
pub fn rename(
|
||||
/// `trace` is filled whenever the request got as far as asking the engine,
|
||||
/// refusals included, because a rename that refuses after 800 ms is exactly
|
||||
/// the kind this exists to explain (take 5 §P2a). Its two halves are the
|
||||
/// server's ([`SelectionTrace`]: which rung wanted which file) and the
|
||||
/// engine's ([`vlog_refactor::RenameTrace`]: where the time and the parses
|
||||
/// went); it reaches a user only through `--verbose`'s `timing:` channel, and
|
||||
/// a caller that wants none passes `&mut None`.
|
||||
pub fn rename_traced(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut Option<String>,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
// The engine's own first look at the request, over the buffer it is about
|
||||
// to be handed anyway. It refuses only what `vlog_refactor::rename` is
|
||||
// certain to refuse in the same words — so this is still one voice
|
||||
// deciding, just asked before the workspace is materialized for it. A
|
||||
// cursor on nothing used to read, parse and index all 3 976 files before
|
||||
// saying so (take 5 review §3 item 6); now it reads none.
|
||||
//
|
||||
// Sound because both selectors below hand the engine this very buffer, so
|
||||
// the out-of-scope refusal that outranks a cursor refusal cannot fire.
|
||||
//
|
||||
// A refusal here still writes a trace, because "where did the time go" is
|
||||
// a question about the fast refusals too — and the answer, nowhere, is
|
||||
// only believable if the line says `selected=0` and `parses=0` in the same
|
||||
// fields the slow road fills.
|
||||
if let Err(refusal) = vlog_refactor::rename_preflight(&doc.semantics, offset, new_name) {
|
||||
let (selection, engine) =
|
||||
(SelectionTrace::default(), vlog_refactor::RenameTrace::default());
|
||||
*trace = Some(format!("{} {} preflight=true", selection.line(), engine.line()));
|
||||
return Err(refusal);
|
||||
}
|
||||
// The name the cursor sits on, read off the buffer, is what the index is
|
||||
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
|
||||
// is the one voice that decides, and it decides over the files below. A
|
||||
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
|
||||
// the engine will say so, and saying it is cheap either way.
|
||||
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
|
||||
let sources = match &old_name {
|
||||
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
let (sources, selection) = match &old_name {
|
||||
Some(name) => ws.rename_sources_traced(&path, name, Some(new_name)),
|
||||
None => {
|
||||
let all = ws.sources();
|
||||
let selection = SelectionTrace::whole_scope(all.len(), 0.0);
|
||||
(all, selection)
|
||||
}
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
let mut engine = vlog_refactor::RenameTrace::default();
|
||||
let known = Known(ws);
|
||||
let outcome =
|
||||
vlog_refactor::rename_traced_with(&sources, &path, offset, new_name, &known, &mut engine);
|
||||
*trace = Some(format!("{} {}", selection.line(), engine.line()));
|
||||
let refactoring = outcome?;
|
||||
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
for (path, edits) in &refactoring.edits {
|
||||
@@ -100,6 +139,23 @@ pub fn rename(
|
||||
Ok((WorkspaceEdit::new(changes), warnings))
|
||||
}
|
||||
|
||||
/// The workspace answering the engine's `KnownFacts` question, and nothing
|
||||
/// else: one call, to the one query that ties a record to the bytes it was
|
||||
/// read off ([`Workspace::known_facts`]).
|
||||
///
|
||||
/// A newtype rather than an `impl` on `Workspace` so that the promise this
|
||||
/// makes to `vlog_refactor` is written where a reader of the rename can see
|
||||
/// it, and so that no other handler can acquire it by accident — the facts a
|
||||
/// refactoring may reuse are the facts of the very texts it was handed, which
|
||||
/// is a property of *this* call site.
|
||||
struct Known<'a>(&'a Workspace);
|
||||
|
||||
impl vlog_refactor::KnownFacts for Known<'_> {
|
||||
fn facts_for(&self, path: &std::path::Path, text: &str) -> Option<FileFacts> {
|
||||
self.0.known_facts(path, text)
|
||||
}
|
||||
}
|
||||
|
||||
/// One sentence per file that writes the old name inside a macro invocation,
|
||||
/// a directive line or an attribute and was **not** among the files the engine
|
||||
/// was handed.
|
||||
@@ -116,7 +172,7 @@ pub fn rename(
|
||||
/// about the one shape it cannot see.
|
||||
///
|
||||
/// Subtracting the handed set leaves out every open buffer too, because
|
||||
/// [`Workspace::rename_sources`] puts every open buffer in it.
|
||||
/// [`Workspace::rename_sources_traced`] puts every open buffer in it.
|
||||
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
|
||||
let index = ws.index();
|
||||
index
|
||||
@@ -141,6 +197,17 @@ mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// [`rename_traced`] with the trace thrown away — what a test that is not
|
||||
/// about the trace asks.
|
||||
fn rename(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
rename_traced(ws, uri, offset, new_name, &mut None)
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
@@ -186,6 +253,118 @@ mod tests {
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// A third file that spells nothing this rename is about, kept open so
|
||||
/// the open-buffer rung selects it: the "container" class in miniature —
|
||||
/// a file the engine must index and never analyses.
|
||||
const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n";
|
||||
|
||||
/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a
|
||||
/// persistent index store behind the workspace — so a rename is handed
|
||||
/// records keyed on the very bytes it reads.
|
||||
fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let quiet = tree.write("bystander.sv", BYSTANDER);
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()),
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
ws.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// Every edit and every warning one rename produced, with the workspace's
|
||||
/// own scratch path taken out — the fingerprint the parity proof compares.
|
||||
fn print(result: &(WorkspaceEdit, Vec<String>), root: &Path) -> String {
|
||||
let (edit, warnings) = result;
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for (uri, edits) in edit.changes.iter().flatten() {
|
||||
for one in edits {
|
||||
lines.push(format!(
|
||||
"{} {:?}..{:?} -> {}",
|
||||
uri.as_str(),
|
||||
one.range.start,
|
||||
one.range.end,
|
||||
one.new_text
|
||||
));
|
||||
}
|
||||
}
|
||||
lines.sort();
|
||||
lines.extend(warnings.iter().map(|w| format!("warn {w}")));
|
||||
lines.join("\n").replace(root.to_str().expect("utf-8"), "")
|
||||
}
|
||||
|
||||
/// **§R3b's server-side proof.** The same rename over the same files, once
|
||||
/// with a warm index store behind it — where the engine is handed every
|
||||
/// file's record and stops parsing the ones nothing analyses — and once
|
||||
/// with no store at all, where it parses them all: byte-identical edits,
|
||||
/// byte-identical warnings.
|
||||
///
|
||||
/// The reuse is asserted to have happened *and* to have removed a parse,
|
||||
/// so a store that silently stopped answering would fail this rather than
|
||||
/// pass it for the wrong reason.
|
||||
#[test]
|
||||
fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() {
|
||||
let tree = Tree::new("reuse_store");
|
||||
let store = Tree::new("reuse_store_cache");
|
||||
let (warm, uri) = three_with_store(&tree, Some(&store));
|
||||
let mut line = None;
|
||||
let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line)
|
||||
.expect("the rename succeeds");
|
||||
let trace = line.expect("a trace is always written");
|
||||
assert!(trace.contains("selected=3"), "all three files are selected: {trace}");
|
||||
assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}");
|
||||
assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}");
|
||||
assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}");
|
||||
|
||||
let bare = Tree::new("reuse_none");
|
||||
let (plain, plain_uri) = three_with_store(&bare, None);
|
||||
let mut plain_line = None;
|
||||
let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line)
|
||||
.expect("the rename succeeds");
|
||||
let plain_trace = plain_line.expect("a trace is always written");
|
||||
assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse");
|
||||
assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed");
|
||||
|
||||
assert_eq!(
|
||||
print(&with_store, &tree.path),
|
||||
print(&no_store, &bare.path),
|
||||
"the reuse changed an edit or a warning"
|
||||
);
|
||||
}
|
||||
|
||||
/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees
|
||||
/// with the file on disk is not the bytes any record was written from, so
|
||||
/// the store answers nothing for it and it is parsed — and the rename acts
|
||||
/// on the buffer's text, which is the precedence it always had.
|
||||
///
|
||||
/// Nothing in the reuse arranges this: the key is the content, so unsaved
|
||||
/// text misses the same way changed text does.
|
||||
#[test]
|
||||
fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() {
|
||||
let tree = Tree::new("reuse_unsaved");
|
||||
let store = Tree::new("reuse_unsaved_cache");
|
||||
let (mut ws, uri) = three_with_store(&tree, Some(&store));
|
||||
// A signal that exists only in the buffer. Its record cannot be in a
|
||||
// store keyed on what is on disk.
|
||||
let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n";
|
||||
ws.set_document(uri.clone(), edited.to_string());
|
||||
|
||||
let mut line = None;
|
||||
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
|
||||
.expect("the buffer's own declaration renames");
|
||||
let trace = line.expect("a trace is always written");
|
||||
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
|
||||
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
|
||||
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
|
||||
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_offers_the_identifier_and_its_placeholder() {
|
||||
let tree = Tree::new("prepare");
|
||||
@@ -281,7 +460,7 @@ mod tests {
|
||||
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => ws.sources(),
|
||||
}
|
||||
.into_iter()
|
||||
@@ -301,7 +480,7 @@ mod tests {
|
||||
let everything = ws.sources();
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => everything.clone(),
|
||||
};
|
||||
for (path, text) in &subset {
|
||||
@@ -955,7 +1134,7 @@ mod tests {
|
||||
|
||||
// The premise: `far.svh` is in no rung of the fan-out, so the engine
|
||||
// never sees it. Asked of the same function `rename` asks.
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: the engine is not handed far.svh — {handed:?}"
|
||||
@@ -989,7 +1168,7 @@ mod tests {
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
|
||||
let (ws, uri) = macro_workspace(&tree, &far);
|
||||
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: instantiating `sub` puts far.svh in the source set"
|
||||
@@ -1003,4 +1182,106 @@ mod tests {
|
||||
"and it is the engine's sentence, not the census's: {warning}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The engine-owned preflight (take 5 review §3 item 6, TODO §61.1)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A cursor on nothing used to select every in-scope file, parse all of
|
||||
/// them and index them before the engine's 0.1 ms refusal. The preflight
|
||||
/// is only worth having if that is now literally no parses at all — not
|
||||
/// fewer, none — so the gate is asserted, not measured.
|
||||
#[test]
|
||||
fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() {
|
||||
let tree = Tree::new("nosymbolparses");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule`
|
||||
|
||||
let before = vlog_parser::stats::parses();
|
||||
let mut trace = None;
|
||||
let refusal =
|
||||
rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there");
|
||||
let parses = vlog_parser::stats::parses() - before;
|
||||
|
||||
assert_eq!(parses, 0, "the refusal parsed {parses} whole files");
|
||||
assert_eq!(refusal, "there is no symbol to rename at this position.");
|
||||
|
||||
// And the `--verbose` channel says so in its own fields, so the phase
|
||||
// that measures this row reads the parse count instead of trusting it.
|
||||
let trace = trace.expect("a refusal traces too");
|
||||
assert!(trace.contains("selected=0"), "{trace}");
|
||||
assert!(trace.contains("parses=0"), "{trace}");
|
||||
assert!(trace.contains("preflight=true"), "{trace}");
|
||||
}
|
||||
|
||||
/// …and it is the same sentence the whole workspace produced, taken from
|
||||
/// the engine over every in-scope file rather than from this module.
|
||||
#[test]
|
||||
fn the_preflights_refusal_is_the_whole_workspaces_refusal() {
|
||||
let tree = Tree::new("preflightparity");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let path = tree.path.join("top.sv");
|
||||
for (case, offset) in [
|
||||
("past the last item", TOP.len() as u32 - 1),
|
||||
("on the `module` keyword", at(TOP, "module")),
|
||||
("on a literal", at(TOP, "1'b0")),
|
||||
] {
|
||||
let fast = rename(&ws, &uri, offset, "probe").expect_err(case);
|
||||
let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe")
|
||||
.expect_err("the whole workspace refuses too");
|
||||
assert_eq!(fast, slow, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Precedence, in the two places the preflight could have disturbed it: an
|
||||
/// unusable buffer is refused by this module before the engine is asked
|
||||
/// anything, and an invalid new name outranks whatever the cursor is on.
|
||||
#[test]
|
||||
fn the_preflight_does_not_disturb_the_refusal_order() {
|
||||
let tree = Tree::new("preflightorder");
|
||||
let (ws, uri) = opened(&tree);
|
||||
|
||||
let untitled = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||
let mut with_untitled = Workspace::default();
|
||||
with_untitled.set_document(untitled.clone(), TOP.to_string());
|
||||
assert_eq!(
|
||||
rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"),
|
||||
UNSAVED,
|
||||
"an untitled buffer is refused before the engine sees the cursor"
|
||||
);
|
||||
|
||||
// A cursor on nothing *and* a keyword for a new name: the name's
|
||||
// sentence, which is the one `renaming` reaches first.
|
||||
let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword");
|
||||
assert_eq!(refusal, "`module` is a Verilog keyword.");
|
||||
}
|
||||
|
||||
/// The one buffer the preflight must never judge: on the large-file fast
|
||||
/// path every field but the text is the analysis of the *empty* file, so a
|
||||
/// preflight over it would refuse every cursor as symbolless. The
|
||||
/// large-buffer gate refuses the whole request first, and this pins that
|
||||
/// it still does.
|
||||
#[test]
|
||||
fn a_large_buffer_is_refused_before_the_preflight_could_see_it() {
|
||||
let tree = Tree::new("preflightlarge");
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
large_file_threshold: 1,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert!(doc.large, "premise: the buffer took the fast path");
|
||||
assert!(
|
||||
vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(),
|
||||
"premise: the empty analysis would refuse a real cursor, which is why \
|
||||
`server/large_file.rs` must answer this method before we are reached"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Which rung of the rename fan-out put each file in the engine's input.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`). `Workspace::rename_sources_traced`
|
||||
//! climbs six rungs and has one escape hatch, and the tracker's own note says
|
||||
//! it plainly: *two output files is not an input count*. A rename of `state_q`
|
||||
//! may hand the engine hundreds of files and nobody could say which rung asked
|
||||
//! for them. This module is the answer — a set of paths that also remembers
|
||||
//! **why** each one was added.
|
||||
//!
|
||||
//! [`Wanted`] is a `BTreeMap<PathBuf, Rung>` with a current [`Rung`]: the
|
||||
//! selector sets the rung it is on and inserts exactly as it did before, so
|
||||
//! the selection logic is not changed by being watched. The first rung to ask
|
||||
//! for a path is the one recorded, which is what makes the counts add up to
|
||||
//! the selected set rather than over-counting a file three rungs want.
|
||||
//!
|
||||
//! Take 5 §P2d added the second question on top of the first: of the files a
|
||||
//! rung asked for, how many **write neither name down** and are therefore in
|
||||
//! the request only to shape how the others resolve ([`indirect_census`]).
|
||||
//! That census is what says which rung a narrower selector would have to
|
||||
//! argue about, and the argument it needs.
|
||||
//!
|
||||
//! Nothing here decides anything. A [`SelectionTrace`] is written, logged once
|
||||
//! behind `--verbose`, and dropped.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// Why one file is in a rename's input.
|
||||
///
|
||||
/// One variant per rung of [`crate::state::Workspace::rename_sources_traced`]'s
|
||||
/// ladder, in the order the ladder climbs them.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Rung {
|
||||
/// The file the request was made in.
|
||||
#[default]
|
||||
Request,
|
||||
/// A file declaring one of the two names — its own file, from
|
||||
/// `workspace_symbols` or `hierarchical_declarations`.
|
||||
Declaration,
|
||||
/// A file the index recorded a use of such a declaration in.
|
||||
Reference,
|
||||
/// A file instantiating the name, or one of its containers.
|
||||
Instantiation,
|
||||
/// A file whose `` `define`` table names it or spells it in a macro body.
|
||||
MacroText,
|
||||
/// A file spelling the **new** name in a use this workspace had to look
|
||||
/// outside that file to answer.
|
||||
Speller,
|
||||
/// An open buffer, added whatever else it is.
|
||||
OpenBuffer,
|
||||
}
|
||||
|
||||
impl Rung {
|
||||
/// The name this rung is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Rung::Request => "request",
|
||||
Rung::Declaration => "declaration",
|
||||
Rung::Reference => "reference",
|
||||
Rung::Instantiation => "instantiation",
|
||||
Rung::MacroText => "macro",
|
||||
Rung::Speller => "speller",
|
||||
Rung::OpenBuffer => "open",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rung, in ladder order — so a trace line always has the same
|
||||
/// fields whether or not a rung contributed.
|
||||
const ALL: [Rung; 7] = [
|
||||
Rung::Request,
|
||||
Rung::Declaration,
|
||||
Rung::Reference,
|
||||
Rung::Instantiation,
|
||||
Rung::MacroText,
|
||||
Rung::Speller,
|
||||
Rung::OpenBuffer,
|
||||
];
|
||||
}
|
||||
|
||||
/// How many files each rung was the first to ask for, and whether the
|
||||
/// ambiguity escape hatch fired.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct SelectionTrace {
|
||||
counts: Vec<(Rung, usize)>,
|
||||
/// The index could not bound the fan-out, so every in-scope file went.
|
||||
pub fallback: bool,
|
||||
/// How many files went in the end.
|
||||
pub selected: usize,
|
||||
/// Milliseconds the selection itself took, reading and all.
|
||||
pub ms: f64,
|
||||
/// Per rung, how many of its files write **neither** name down —
|
||||
/// [`indirect_census`]. Empty on the fallback path, which climbs no rung.
|
||||
pub indirect: Vec<(Rung, usize)>,
|
||||
}
|
||||
|
||||
impl SelectionTrace {
|
||||
/// The trace of a selection that gave up and handed over the whole scope
|
||||
/// — the ambiguity escape hatch, and a cursor with no name to fan out
|
||||
/// from. No rung ran, so none is counted.
|
||||
pub fn whole_scope(selected: usize, ms: f64) -> SelectionTrace {
|
||||
SelectionTrace { counts: Vec::new(), fallback: true, selected, ms, indirect: Vec::new() }
|
||||
}
|
||||
|
||||
/// One file added by `rung`, if no earlier rung had it.
|
||||
fn add(&mut self, rung: Rung) {
|
||||
match self.counts.iter_mut().find(|(held, _)| *held == rung) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => self.counts.push((rung, 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files this rung was the first to ask for.
|
||||
pub fn count(&self, rung: Rung) -> usize {
|
||||
self.counts.iter().find(|(held, _)| *held == rung).map_or(0, |(_, count)| *count)
|
||||
}
|
||||
|
||||
/// The trace as one `timing:`-style fragment.
|
||||
pub fn line(&self) -> String {
|
||||
let rungs: Vec<String> = Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| format!("{}={}", rung.label(), self.count(*rung)))
|
||||
.collect();
|
||||
format!(
|
||||
"select={:.1}ms selected={} fallback={} rungs{{{}}} {}",
|
||||
self.ms,
|
||||
self.selected,
|
||||
self.fallback,
|
||||
rungs.join(" "),
|
||||
census_line(&self.indirect)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path set a fan-out fills, plus the rung it is currently climbing.
|
||||
///
|
||||
/// `paths` is exactly the `BTreeSet<PathBuf>` the selector built before; the
|
||||
/// only difference is that an insertion also tells the trace which rung made
|
||||
/// it. A path already held is not re-attributed, so the counts partition the
|
||||
/// selected set.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Wanted {
|
||||
paths: BTreeMap<PathBuf, Rung>,
|
||||
trace: SelectionTrace,
|
||||
rung: Rung,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
/// An empty set, on the rung a request's own file is added by.
|
||||
pub fn new() -> Wanted {
|
||||
Wanted::default()
|
||||
}
|
||||
|
||||
/// Climb to `rung`: every insertion until the next call is attributed to
|
||||
/// it.
|
||||
pub fn on(&mut self, rung: Rung) {
|
||||
self.rung = rung;
|
||||
}
|
||||
|
||||
/// Add one path, attributed to the current rung if it is new.
|
||||
///
|
||||
/// `entry(…).or_insert(…)`, not `insert(…)`: the map keeps the **first**
|
||||
/// rung to ask for a path, which is what makes the counts partition the
|
||||
/// selected set. A plain `insert` would overwrite with the last.
|
||||
pub fn insert(&mut self, path: PathBuf) {
|
||||
let rung = self.rung;
|
||||
let before = self.paths.len();
|
||||
self.paths.entry(path).or_insert(rung);
|
||||
if self.paths.len() != before {
|
||||
self.trace.add(rung);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Wanted::insert`] over an iterator — the shape the selector's
|
||||
/// `wanted.extend(...)` calls had.
|
||||
pub fn extend(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
|
||||
for path in paths {
|
||||
self.insert(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths, in path order and each with the rung that asked for it, and
|
||||
/// the trace of how they got there.
|
||||
pub fn finish(self) -> (BTreeMap<PathBuf, Rung>, SelectionTrace) {
|
||||
let Wanted { paths, mut trace, .. } = self;
|
||||
trace.selected = paths.len();
|
||||
(paths, trace)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files each rung asked for that **write neither name down**.
|
||||
///
|
||||
/// The census §P2d turns on. Every direct input of the four verifier checks is
|
||||
/// a file that spells one of the two names: an occurrence is a use of the old
|
||||
/// name, `check::watched_files` watches exactly the files whose text holds
|
||||
/// either as a whole word, `Scope::warnings` speaks only about the two names,
|
||||
/// and an edited file is a subset of the watched ones. A selected file that
|
||||
/// writes neither is therefore in the request for one reason only — **it
|
||||
/// shapes how the others resolve**, by declaring a unit some path hops
|
||||
/// through or a base class a member lookup climbs to.
|
||||
///
|
||||
/// So this is not "files that could be dropped". It is the exact set whose
|
||||
/// contribution is *indirect*, which is the set a narrower selector has to
|
||||
/// argue about one shape at a time. Counting it by rung says which rung the
|
||||
/// argument would have to be made for.
|
||||
///
|
||||
/// The word census is `FileFacts::words`, so this reads no file and parses
|
||||
/// nothing. It is asked of the **selected** files only — one `facts_for` and
|
||||
/// two binary searches each — rather than through
|
||||
/// [`WorkspaceIndex::files_mentioning`], which would walk every record in the
|
||||
/// workspace to answer about a couple of hundred of them. On the tail rename
|
||||
/// that is the difference between ~1.7 ms and ~0.05 ms, and a diagnostic that
|
||||
/// costs a measurable slice of the request it is measuring is a bad
|
||||
/// instrument.
|
||||
///
|
||||
/// A path the index has no record for — an open buffer the scan has not
|
||||
/// reached — counts as spelling the name: the census may not claim a file is
|
||||
/// idle when it does not know.
|
||||
pub fn indirect_census(
|
||||
index: &WorkspaceIndex,
|
||||
paths: &BTreeMap<PathBuf, Rung>,
|
||||
names: [&str; 2],
|
||||
) -> Vec<(Rung, usize)> {
|
||||
let idle = |path: &Path| match index.facts_for(path) {
|
||||
Some(facts) => !names
|
||||
.iter()
|
||||
.any(|name| facts.words().binary_search_by(|w| w.as_str().cmp(name)).is_ok()),
|
||||
None => false,
|
||||
};
|
||||
Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| {
|
||||
let count = paths.iter().filter(|(path, held)| *held == rung && idle(path)).count();
|
||||
(*rung, count)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`indirect_census`] as one `timing:`-style fragment — every rung named,
|
||||
/// whether or not it contributed, so the line's shape never moves.
|
||||
pub fn census_line(census: &[(Rung, usize)]) -> String {
|
||||
let fields: Vec<String> = Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| {
|
||||
let count = census.iter().find(|(held, _)| held == rung).map_or(0, |(_, n)| *n);
|
||||
format!("{}={}", rung.label(), count)
|
||||
})
|
||||
.collect();
|
||||
format!("indirect{{{}}}", fields.join(" "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_first_rung_to_ask_for_a_path_is_the_one_counted() {
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.on(Rung::Reference);
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.insert(PathBuf::from("/rtl/b.sv"));
|
||||
let (paths, trace) = wanted.finish();
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert_eq!(trace.count(Rung::Request), 1);
|
||||
assert_eq!(trace.count(Rung::Reference), 1);
|
||||
assert_eq!(trace.selected, 2);
|
||||
// And the map agrees with the counts: a re-insertion does not
|
||||
// re-attribute, which is what makes the census partition the set.
|
||||
assert_eq!(paths[&PathBuf::from("/rtl/a.sv")], Rung::Request);
|
||||
assert_eq!(paths[&PathBuf::from("/rtl/b.sv")], Rung::Reference);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_census_counts_only_the_files_that_write_neither_name() {
|
||||
let index = WorkspaceIndex::build(vec![
|
||||
(PathBuf::from("/w/decl.sv"), "module decl; logic state_q; endmodule\n"),
|
||||
(PathBuf::from("/w/user.sv"), "module user; decl u_d (); endmodule\n"),
|
||||
(PathBuf::from("/w/reads.sv"), "module reads; assign x = u_d.state_q; endmodule\n"),
|
||||
]);
|
||||
let mut paths = BTreeMap::new();
|
||||
paths.insert(PathBuf::from("/w/decl.sv"), Rung::Declaration);
|
||||
paths.insert(PathBuf::from("/w/reads.sv"), Rung::Reference);
|
||||
paths.insert(PathBuf::from("/w/user.sv"), Rung::Instantiation);
|
||||
let census = indirect_census(&index, &paths, ["state_q", "state_q_x"]);
|
||||
let count = |rung: Rung| census.iter().find(|(r, _)| *r == rung).map_or(0, |(_, n)| *n);
|
||||
assert_eq!(count(Rung::Declaration), 0, "it declares the name");
|
||||
assert_eq!(count(Rung::Reference), 0, "it spells the name");
|
||||
assert_eq!(count(Rung::Instantiation), 1, "it only instantiates the container");
|
||||
assert!(census_line(&census).contains("instantiation=1"), "{}", census_line(&census));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rung_appears_in_the_line_even_at_zero() {
|
||||
let trace = SelectionTrace::default();
|
||||
let line = trace.line();
|
||||
for rung in Rung::ALL {
|
||||
assert!(line.contains(&format!("{}=0", rung.label())), "{line} lacks {rung:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! What order a scan walks its work list in, and how much of that order a
|
||||
//! request answered mid-scan is owed.
|
||||
//!
|
||||
//! A scan indexes every in-scope file, and [`vlog_semantic::IndexBuilder`]
|
||||
//! sorts its records by path inside `finish`, so **no insertion order can
|
||||
//! reach the finished index**. What the order decides is what the *prefix* of
|
||||
//! a scan holds — which file the progress bar names first, and what a request
|
||||
//! answered between two files can see (`docs/features/scan-interleave`).
|
||||
//!
|
||||
//! Three groups, in this order:
|
||||
//!
|
||||
//! 1. the **open buffers' own files** — the ones the user is looking at;
|
||||
//! 2. every other file under those buffers' **raised scope directories** —
|
||||
//! the neighbourhood `docs/features/index-scope/README.md`'s folder rung
|
||||
//! would have indexed for them;
|
||||
//! 3. everything else, in path order.
|
||||
//!
|
||||
//! Group 1 was the whole of `Workspace::open_first` until 2026-09-08, and on
|
||||
//! its own it made the first useful answer of a workspace-scoped session
|
||||
//! *empty*: a definition sent with the opening `didOpen` was answered off a
|
||||
//! prefix holding that one buffer and the alphabet after it, and the module it
|
||||
//! named lives in the folder next door. Group 2 is that folder
|
||||
//! (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::index_order;
|
||||
|
||||
/// A scan's work list, ordered, with the length of its head segment.
|
||||
pub struct WorkList {
|
||||
/// Every file the scan will index, in the order it will index them.
|
||||
pub files: Vec<PathBuf>,
|
||||
/// How many files at the front of `files` are the user's own
|
||||
/// neighbourhood — groups 1 and 2 above.
|
||||
///
|
||||
/// **0 means there is no neighbourhood worth waiting for**: no buffer is
|
||||
/// open, none of them has a folder in scope, or the folders cover so much
|
||||
/// of the work list that "the user's own folder" and "the workspace" are
|
||||
/// the same wait. See [`work_list`].
|
||||
pub head: usize,
|
||||
}
|
||||
|
||||
/// The user's own file.
|
||||
const OWN: u8 = 0;
|
||||
/// A file under one of the folders the user's own files raise to.
|
||||
const FOLDER: u8 = 1;
|
||||
/// Everything else.
|
||||
const TAIL: u8 = 2;
|
||||
|
||||
/// Order `files` open-buffers-first, then their folders, then the rest.
|
||||
///
|
||||
/// `open` is every open buffer's own path and `folders` the directories those
|
||||
/// buffers raise to (`Workspace::raised`). Both may be empty, and an empty
|
||||
/// `folders` is the ordering this function had before 2026-09-08.
|
||||
///
|
||||
/// The head is reported raw; [`worth_waiting`] is what bounds it, because the
|
||||
/// bound is against the **whole** scan and this function may be ordering only
|
||||
/// what is left of one.
|
||||
pub fn work_list(files: Vec<PathBuf>, open: &[PathBuf], folders: &[PathBuf]) -> WorkList {
|
||||
// Asked of `vlog_semantic` rather than re-derived here, so the count a
|
||||
// scan reports is the count the index will hold: sorted by path, one entry
|
||||
// per path.
|
||||
let ordered = index_order(files.into_iter().map(|path| (path, ())));
|
||||
let own: HashSet<&Path> = open.iter().map(PathBuf::as_path).collect();
|
||||
let mut ranked: Vec<(u8, PathBuf)> =
|
||||
ordered.into_iter().map(|(path, ())| (rank(&path, &own, folders), path)).collect();
|
||||
// Stable, so each group keeps the path order `index_order` sorted it into.
|
||||
ranked.sort_by_key(|(rank, _)| *rank);
|
||||
let head = ranked.iter().take_while(|(rank, _)| *rank < TAIL).count();
|
||||
WorkList { files: ranked.into_iter().map(|(_, path)| path).collect(), head }
|
||||
}
|
||||
|
||||
/// `pending` — the files a held request would wait for — or **0** when that is
|
||||
/// too many to wait for in a scan of `total` files.
|
||||
///
|
||||
/// A request held for the startup scan waits for the whole neighbourhood
|
||||
/// before it is answered ([`WorkList::head`]), which is a good trade only
|
||||
/// while the neighbourhood is a small part of the scan: a buffer opened from a
|
||||
/// workspace *root* raises to that root, and waiting for "its folder" would be
|
||||
/// waiting for the entire scan and answering nothing at all until it ended. So
|
||||
/// a neighbourhood that is not a minority of the workspace is no
|
||||
/// neighbourhood — the ordering still applies, and the drain falls back to the
|
||||
/// first interleave point exactly as it did before.
|
||||
///
|
||||
/// **`pending` is what is left to wait for, not where the segment ends.** A
|
||||
/// `didOpen` can arrive at any point of a scan, and re-ordering puts its
|
||||
/// folder next: 124 files is 124 files of waiting whether the scan has done
|
||||
/// none of the workspace or nine tenths of it.
|
||||
pub fn worth_waiting(pending: usize, total: usize) -> usize {
|
||||
match pending * 2 > total {
|
||||
true => 0,
|
||||
false => pending,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the three groups `path` belongs to.
|
||||
fn rank(path: &Path, own: &HashSet<&Path>, folders: &[PathBuf]) -> u8 {
|
||||
if own.contains(path) {
|
||||
return OWN;
|
||||
}
|
||||
match folders.iter().any(|folder| path.starts_with(folder)) {
|
||||
true => FOLDER,
|
||||
false => TAIL,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn paths(names: &[&str]) -> Vec<PathBuf> {
|
||||
names.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
fn names(list: &WorkList) -> Vec<String> {
|
||||
list.files.iter().map(|p| p.display().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_open_the_list_is_path_order_and_there_is_no_head() {
|
||||
let list = work_list(paths(&["/w/z.sv", "/w/a.sv", "/w/m.sv"]), &[], &[]);
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/m.sv", "/w/z.sv"]);
|
||||
assert_eq!(list.head, 0, "nothing is waited for when nothing is open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_buffer_leads_then_its_folder_then_the_rest() {
|
||||
let list = work_list(
|
||||
paths(&[
|
||||
"/w/other/far.sv",
|
||||
"/w/ip/aes/rtl/aes.sv",
|
||||
"/w/ip/aes/dv/tb.sv",
|
||||
"/w/other/near.sv",
|
||||
]),
|
||||
&paths(&["/w/ip/aes/dv/tb.sv"]),
|
||||
&paths(&["/w/ip/aes"]),
|
||||
);
|
||||
assert_eq!(
|
||||
names(&list),
|
||||
["/w/ip/aes/dv/tb.sv", "/w/ip/aes/rtl/aes.sv", "/w/other/far.sv", "/w/other/near.sv"],
|
||||
"the buffer, then its folder, then the rest in path order"
|
||||
);
|
||||
assert_eq!(list.head, 2, "the buffer and its folder are what a held request waits for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_is_most_of_the_workspace_is_not_a_head_to_wait_for() {
|
||||
// A buffer opened from the workspace root raises to the root, so
|
||||
// "its folder" is the whole scan. The order is unchanged; the drain
|
||||
// falls back to the first interleave point.
|
||||
let files = paths(&["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
|
||||
let list = work_list(files, &paths(&["/w/a.sv"]), &paths(&["/w"]));
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
|
||||
assert_eq!(list.head, 3, "the ranking itself says the whole list is the folder");
|
||||
assert_eq!(worth_waiting(list.head, 3), 0, "and that is no head at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_half_is_still_a_head_and_one_more_is_not() {
|
||||
assert_eq!(worth_waiting(2, 4), 2, "two of four is a minority");
|
||||
assert_eq!(worth_waiting(3, 4), 0, "three of four is not");
|
||||
assert_eq!(worth_waiting(0, 4), 0, "and nothing is nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bound_is_against_the_whole_scan_and_not_against_what_is_left() {
|
||||
// The `didOpen` that names a folder can arrive at any point of a scan.
|
||||
// Measured against the tail alone, a 124-file folder would stop being
|
||||
// worth waiting for once 3 700 of a 3 976-file workspace were done —
|
||||
// which is exactly when it costs least.
|
||||
assert_eq!(worth_waiting(124, 3_976), 124, "124 files of 3 976, at any point of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_handed_over_twice_is_one_file() {
|
||||
let list = work_list(paths(&["/w/a.sv", "/w/a.sv", "/w/b.sv"]), &[], &[]);
|
||||
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_outside_the_scope_still_lends_its_folder() {
|
||||
// The buffer's own file is not in the work list — it is over the size
|
||||
// cap, say — but the folder it raised is still the neighbourhood.
|
||||
let list = work_list(
|
||||
paths(&["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]),
|
||||
&paths(&["/w/ip/aes/dv/huge.sv"]),
|
||||
&paths(&["/w/ip/aes"]),
|
||||
);
|
||||
assert_eq!(names(&list), ["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]);
|
||||
assert_eq!(list.head, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
//! What one workspace scan spent its time on, and what the tables it left
|
||||
//! behind weigh — the startup breakdown take 5 §P4a exists to measure.
|
||||
//!
|
||||
//! A [`ScanTrace`] rides on the [`crate::state::Scan`] it describes. It is a
|
||||
//! bag of sums and counters and nothing else: no per-file allocation, no
|
||||
//! per-file string, no `Vec` that grows with the work list, so a traced scan
|
||||
//! costs a handful of clock reads per file and two `format!`s at the end. It
|
||||
//! is off unless `--verbose` asked for it ([`ScanTrace::new`]), and off means
|
||||
//! [`ScanTrace::now`] hands back `None` and every `add` below is a branch.
|
||||
//!
|
||||
//! The three lines it renders go out on the `timing:` channel
|
||||
//! (`docs/features/verbose-timing/README.md`) when the scan ends. They are
|
||||
//! `key=value` after a human prefix because both readers matter: a person
|
||||
//! grepping an output channel, and `tools/perf/phases_p4.py`, which turns
|
||||
//! them into schema-2 rows.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
thread_local! {
|
||||
static READS: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many source files this thread has read off disk for a scan.
|
||||
///
|
||||
/// A work counter, not a timer, and modelled on `vlog_parser::stats::parses`
|
||||
/// for the same reason: the claim a scan makes since 2026-09-08 is that it
|
||||
/// reads each file's bytes **exactly once** — the content hash, the parse and
|
||||
/// the `` `include`` scan all come out of that one read — and the honest way
|
||||
/// to prove that is to count the reads. A stopwatch would be a flake; a count
|
||||
/// is not.
|
||||
///
|
||||
/// Per thread, because `cargo test` runs tests in parallel and a process-wide
|
||||
/// counter would be adding up every other test's scans. Monotone and never
|
||||
/// reset, so a caller measures a delta.
|
||||
///
|
||||
/// Only a test asks — this is a bin crate, so nothing outside it can — while
|
||||
/// [`count_read`] is **unconditional**: one non-atomic add per file is noise
|
||||
/// beside the read it counts, and gating the increment as well would mean the
|
||||
/// path under test and the shipped path were not the same code.
|
||||
#[cfg(test)]
|
||||
pub fn source_reads() -> u64 {
|
||||
READS.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Count one file read off disk — see [`source_reads`].
|
||||
pub fn count_read() {
|
||||
READS.with(|reads| reads.set(reads.get() + 1));
|
||||
}
|
||||
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::IncludeGraph;
|
||||
use crate::index_cache::IndexCache;
|
||||
|
||||
/// What the persistent store's own work cost, counted inside
|
||||
/// [`crate::index_cache::IndexCache`] because that is where it happens.
|
||||
///
|
||||
/// Always counted, trace or no trace: the four clock reads a file costs here
|
||||
/// are noise beside the read and the decode they bracket, and a flag threaded
|
||||
/// through the cache to save them would be more code than it saves time.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct CacheWork {
|
||||
/// Hashing the text and finding the entry — what every lookup pays,
|
||||
/// whether it hits or misses.
|
||||
pub lookup_ns: u64,
|
||||
/// Decoding the record of a lookup that hit.
|
||||
pub decode_ns: u64,
|
||||
/// Encoding a record on the way out.
|
||||
pub encode_ns: u64,
|
||||
/// Appending an encoded record to the log.
|
||||
pub write_ns: u64,
|
||||
/// Rewriting the whole store at the end of a whole scan.
|
||||
pub compact_ns: u64,
|
||||
/// Lookups that found a record for exactly these bytes.
|
||||
pub hits: usize,
|
||||
/// Lookups that did not, and so cost a parse.
|
||||
pub misses: usize,
|
||||
/// Records written through.
|
||||
pub records: usize,
|
||||
/// Write-throughs the store already held, byte for byte, and so did not
|
||||
/// append again — one per open buffer on a warm scan (§P4b (a)).
|
||||
pub repeats: usize,
|
||||
/// Encoded bytes handed to `FileFacts::decode`.
|
||||
pub decoded_bytes: usize,
|
||||
/// Encoded bytes appended to the log.
|
||||
pub written_bytes: usize,
|
||||
/// Times the store was read off disk. One per whole rescan that reached a
|
||||
/// file — a scan whose work list is empty opens nothing (§P4b (b1)).
|
||||
pub opens: usize,
|
||||
/// Times the store was actually rewritten. Zero when the rewrite would
|
||||
/// have reproduced the file byte for byte (§P4b (a)).
|
||||
pub compactions: usize,
|
||||
/// The store file's size before and after a compaction, in bytes.
|
||||
pub store_before: u64,
|
||||
pub store_after: u64,
|
||||
}
|
||||
|
||||
impl CacheWork {
|
||||
/// This session's counters minus the ones a scan started with, so a scan
|
||||
/// reports its own work rather than the process's.
|
||||
pub fn since(self, before: CacheWork) -> CacheWork {
|
||||
CacheWork {
|
||||
lookup_ns: self.lookup_ns.saturating_sub(before.lookup_ns),
|
||||
decode_ns: self.decode_ns.saturating_sub(before.decode_ns),
|
||||
encode_ns: self.encode_ns.saturating_sub(before.encode_ns),
|
||||
write_ns: self.write_ns.saturating_sub(before.write_ns),
|
||||
compact_ns: self.compact_ns.saturating_sub(before.compact_ns),
|
||||
hits: self.hits.saturating_sub(before.hits),
|
||||
misses: self.misses.saturating_sub(before.misses),
|
||||
records: self.records.saturating_sub(before.records),
|
||||
repeats: self.repeats.saturating_sub(before.repeats),
|
||||
decoded_bytes: self.decoded_bytes.saturating_sub(before.decoded_bytes),
|
||||
written_bytes: self.written_bytes.saturating_sub(before.written_bytes),
|
||||
opens: self.opens.saturating_sub(before.opens),
|
||||
compactions: self.compactions.saturating_sub(before.compactions),
|
||||
store_before: self.store_before,
|
||||
store_after: self.store_after,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How big the tables a finished scan leaves behind are — the memory half of
|
||||
/// §P4a, in counts and bytes rather than in a resident-set reading.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct TableSizes {
|
||||
pub index_files: usize,
|
||||
pub unit_names: usize,
|
||||
pub unit_defs: usize,
|
||||
pub members: usize,
|
||||
pub hier_members: usize,
|
||||
pub reference_keys: usize,
|
||||
pub reference_sites: usize,
|
||||
pub defines: usize,
|
||||
pub instantiations: usize,
|
||||
pub fact_words: usize,
|
||||
pub fact_word_bytes: usize,
|
||||
pub candidate_units: usize,
|
||||
pub candidate_macros: usize,
|
||||
pub candidate_words: usize,
|
||||
pub candidate_word_bytes: usize,
|
||||
pub include_edges: usize,
|
||||
pub include_known: usize,
|
||||
}
|
||||
|
||||
/// One scan's stage times, counts and end-state sizes.
|
||||
///
|
||||
/// Every `*_ms` is a sum over however many times that stage ran: `parse_ms`
|
||||
/// is every parse of the scan added up, `absorb_ms` is the one final absorb,
|
||||
/// `publish_absorb_ms` is the mid-scan ones.
|
||||
#[derive(Default)]
|
||||
pub struct ScanTrace {
|
||||
on: bool,
|
||||
/// When the scan began — the first thing [`crate::state::Workspace::begin_scan`] does.
|
||||
started: Option<Instant>,
|
||||
/// How long the server had been alive when this scan began.
|
||||
pub since_start_ms: f64,
|
||||
/// Whether this scan rebuilds the whole index or folds a widen in.
|
||||
pub kind: &'static str,
|
||||
/// Which scan of the session this is, counting from 1.
|
||||
pub number: u32,
|
||||
|
||||
// -- discovery ------------------------------------------------------
|
||||
/// Resolving the scope, walking it, asking the size cap about each file
|
||||
/// and taking every open buffer's text. **Not** reading the files: since
|
||||
/// 2026-09-08 that happens at the step that indexes each one, and is
|
||||
/// `read_ms` below (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
pub discovery_ms: f64,
|
||||
|
||||
// -- discovery, split (TODO §61.3) ----------------------------------
|
||||
//
|
||||
// Five disjoint parts of `discovery_ms` and one counter. They are a split
|
||||
// *of* that stage, not stages beside it, so nothing that adds the scan up
|
||||
// may add these as well
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
/// Reading each walk root's `lucisv.toml` for its `exclude` patterns —
|
||||
/// `Discovery::for_dir`, cached per instance, so a second root under the
|
||||
/// same config costs a map lookup.
|
||||
pub config_ms: f64,
|
||||
/// The directory walks themselves: `read_dir`, `.gitignore` parsing, the
|
||||
/// cycle guard, and the one `metadata` per entry the walk has always made.
|
||||
pub walk_ms: f64,
|
||||
/// How many roots were walked — one per scope directory, so a folder scope
|
||||
/// over three open buffers' folders is three.
|
||||
pub walk_dirs: usize,
|
||||
/// Reading a filelist, when rung 1 is the one in force.
|
||||
pub filelist_ms: f64,
|
||||
/// Sorting the walk's output into path order and dropping the paths two
|
||||
/// overlapping walks both found.
|
||||
pub sort_ms: f64,
|
||||
/// Applying `lucisv.index.maxFileSize` to every walked file.
|
||||
pub cap_ms: f64,
|
||||
/// `metadata` calls the cap made *itself* — the ones the walk's hand-off
|
||||
/// did not already answer. Zero for a walked scope since 2026-09-08;
|
||||
/// a filelist's entries are not walked and still cost one each.
|
||||
pub stats: usize,
|
||||
/// Taking every open buffer's text and its finished analysis, and letting
|
||||
/// it override the disk copy of its own path.
|
||||
pub buffers_ms: f64,
|
||||
/// Directories the remaining walk met under a spelling the root walk
|
||||
/// would have preferred — a directory alias outside the open folder's own
|
||||
/// chain ([`crate::state::Scan::wants_rescan`]). 0 in every ordinary
|
||||
/// session; 1 says this scan's paths are the head's spelling.
|
||||
pub conflict: usize,
|
||||
/// Whole rescans this scan asked for on its way out. One per `conflict`,
|
||||
/// and nothing else sets it.
|
||||
pub rescan_requested: usize,
|
||||
|
||||
/// Sorting into index order and putting the user's own neighbourhood at
|
||||
/// the front ([`crate::scan_order`]).
|
||||
pub order_ms: f64,
|
||||
/// Reading the persistent store off disk.
|
||||
pub cache_open_ms: f64,
|
||||
/// Reading one file's text off disk, at the step that indexes it, summed
|
||||
/// over the scan. An open buffer's text is not read and not timed here:
|
||||
/// the scan took it when the work list was.
|
||||
pub read_ms: f64,
|
||||
/// Files the scan will read, known when the work list is taken — and the
|
||||
/// bytes it has read so far, which only equals the whole list once the
|
||||
/// scan has finished.
|
||||
pub read: usize,
|
||||
pub read_bytes: usize,
|
||||
/// The bytes the scan **holds** for its whole life: the open buffers'
|
||||
/// texts, taken with the work list because their facts were. Every other
|
||||
/// file's text lives from its own step to the end of it, which is what
|
||||
/// `work_kib` on the memory line reports.
|
||||
pub work_bytes: usize,
|
||||
/// Files the size cap kept out.
|
||||
pub skipped: usize,
|
||||
/// Entries the store held when it was opened, and their encoded bytes.
|
||||
pub cache_entries: usize,
|
||||
pub cache_bytes: usize,
|
||||
|
||||
// -- per file -------------------------------------------------------
|
||||
/// Parsing a file the store could not answer for, and its bytes.
|
||||
pub parse_ms: f64,
|
||||
pub parse_bytes: usize,
|
||||
/// Files indexed from an open buffer's own finished analysis. Untimed:
|
||||
/// there is nothing to time — the facts are already in hand, and what
|
||||
/// that file then costs is the record the store writes through, which is
|
||||
/// counted with every other record below.
|
||||
pub buffers: usize,
|
||||
/// The store's own work over this scan.
|
||||
pub cache: CacheWork,
|
||||
|
||||
// -- mid-scan publishes ---------------------------------------------
|
||||
pub publishes: usize,
|
||||
pub published: usize,
|
||||
pub publish_absorb_ms: f64,
|
||||
pub publish_candidates_ms: f64,
|
||||
pub publish_includes_ms: f64,
|
||||
pub publish_overlay_ms: f64,
|
||||
/// When the first publish landed, measured from the start of the scan —
|
||||
/// the earliest moment a request answered mid-scan can see any of it.
|
||||
pub first_publish_ms: f64,
|
||||
|
||||
// -- the end --------------------------------------------------------
|
||||
/// Working out which files left the scope.
|
||||
pub gone_ms: f64,
|
||||
pub absorb_ms: f64,
|
||||
pub candidates_ms: f64,
|
||||
pub includes_ms: f64,
|
||||
/// Re-resolving every open buffer against the finished index.
|
||||
pub overlay_ms: f64,
|
||||
pub overlays: usize,
|
||||
/// The whole scan, `begin_scan` to the end of `finish_scan`.
|
||||
pub total_ms: f64,
|
||||
pub sizes: TableSizes,
|
||||
}
|
||||
|
||||
impl ScanTrace {
|
||||
/// A trace that records, or one that does nothing at all.
|
||||
pub fn new(on: bool) -> ScanTrace {
|
||||
ScanTrace { on, started: on.then(Instant::now), ..ScanTrace::default() }
|
||||
}
|
||||
|
||||
/// A trace for a scan that is starting, numbered so a session's lines can
|
||||
/// be told apart — or an inert one when nobody asked for a trace.
|
||||
///
|
||||
/// `scans` is the session's own count of scans so far and is advanced
|
||||
/// here, so a line's number is the number of the scan that prints it.
|
||||
/// `since_start_ms` is left for the server to stamp: how long the process
|
||||
/// had been alive is the server's own knowledge, not the workspace's.
|
||||
pub fn opened(scans: &mut u32, on: bool, kind: &'static str) -> ScanTrace {
|
||||
*scans = scans.saturating_add(1);
|
||||
ScanTrace { kind, number: *scans, ..ScanTrace::new(on) }
|
||||
}
|
||||
|
||||
/// Whether anything below will be recorded.
|
||||
pub fn on(&self) -> bool {
|
||||
self.on
|
||||
}
|
||||
|
||||
/// The work list's size, the bytes the scan will hold for as long as it
|
||||
/// runs, and the store counters this scan is measured from.
|
||||
///
|
||||
/// `held` is what the scan is carrying — the open buffers' texts — and not
|
||||
/// the work list's own bytes, which are read a file at a time and let go
|
||||
/// again ([`ScanTrace::saw_read`]).
|
||||
///
|
||||
/// `cache` is the baseline [`ScanTrace::landed`] subtracts: a widen
|
||||
/// inherits the store the previous scan opened, so the counters on it are
|
||||
/// the session's and not this scan's. A whole scan that opens one of its
|
||||
/// own resets the baseline when it does.
|
||||
pub fn measure_work(&mut self, files: usize, held: usize, skipped: usize, cache: CacheWork) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
self.read = files;
|
||||
self.work_bytes = held;
|
||||
self.skipped = skipped;
|
||||
self.cache = cache;
|
||||
}
|
||||
|
||||
/// One file's text, read at the step that indexes it.
|
||||
pub fn saw_read(&mut self, bytes: usize, from: Option<Instant>) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
ScanTrace::add(&mut self.read_ms, from);
|
||||
self.read_bytes += bytes;
|
||||
}
|
||||
|
||||
/// Close this trace: the tables the finished scan left behind, measured.
|
||||
///
|
||||
/// Every size below is a walk, so all of them are behind [`ScanTrace::on`]
|
||||
/// and none of them happens in a session that did not ask for a trace.
|
||||
pub fn landed(
|
||||
&mut self,
|
||||
overlays: usize,
|
||||
cache: &IndexCache,
|
||||
index: &WorkspaceIndex,
|
||||
candidates: &Candidates,
|
||||
includes: &IncludeGraph,
|
||||
) {
|
||||
if !self.on {
|
||||
return;
|
||||
}
|
||||
// Read first, before a single size below is walked: describing a scan
|
||||
// is not part of the scan, and charging the walks to `total_ms` would
|
||||
// make the trace inflate the very number it exists to explain.
|
||||
self.total_ms = self.elapsed_ms();
|
||||
self.overlays = overlays;
|
||||
self.cache = cache.work().since(self.cache);
|
||||
// At the *end*, so the store's retention is what the finished scan
|
||||
// leaves resident rather than what it started from — the two differ
|
||||
// by every record a cold scan wrote.
|
||||
self.cache_entries = cache.entry_count();
|
||||
self.cache_bytes = cache.encoded_bytes();
|
||||
let tables = index.table_sizes();
|
||||
let counts = index.counts();
|
||||
let (units, macros, words, word_bytes) = candidates.sizes();
|
||||
let (include_edges, include_known) = includes.sizes();
|
||||
self.sizes = TableSizes {
|
||||
index_files: counts.files,
|
||||
unit_names: tables.unit_names,
|
||||
unit_defs: tables.unit_defs,
|
||||
members: tables.members,
|
||||
hier_members: tables.hier_members,
|
||||
reference_keys: tables.reference_keys,
|
||||
reference_sites: tables.reference_sites,
|
||||
defines: counts.defines,
|
||||
instantiations: counts.instantiations,
|
||||
fact_words: tables.words,
|
||||
fact_word_bytes: tables.word_bytes,
|
||||
candidate_units: units,
|
||||
candidate_macros: macros,
|
||||
candidate_words: words,
|
||||
candidate_word_bytes: word_bytes,
|
||||
include_edges,
|
||||
include_known,
|
||||
};
|
||||
}
|
||||
|
||||
/// The clock a stage is timed from — `None`, and so free, when off.
|
||||
pub fn now(&self) -> Option<Instant> {
|
||||
self.on.then(Instant::now)
|
||||
}
|
||||
|
||||
/// Add the time since `from` to `slot`. Nothing at all when off, because
|
||||
/// `now` handed out no clock to be since.
|
||||
pub fn add(slot: &mut f64, from: Option<Instant>) {
|
||||
if let Some(from) = from {
|
||||
*slot += millis(from);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long this scan has been running, or 0 when it is not being traced.
|
||||
pub fn elapsed_ms(&self) -> f64 {
|
||||
self.started.map(millis).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Stamp the first publish, if this is the first one.
|
||||
pub fn saw_publish(&mut self, files: usize) {
|
||||
self.publishes += 1;
|
||||
self.published += files;
|
||||
if self.publishes == 1 {
|
||||
self.first_publish_ms = self.elapsed_ms();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stage line: every `*_ms` this scan collected, in the order the
|
||||
/// scan spends them.
|
||||
pub fn stage_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} stages ({}, {} files): discovery={:.2} config={:.2} walk={:.2} \
|
||||
filelist={:.2} sort={:.2} cap={:.2} buffers={:.2} order={:.2} cache_open={:.2} \
|
||||
read={:.2} lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \
|
||||
publish_absorb={:.2} publish_candidates={:.2} publish_includes={:.2} \
|
||||
publish_overlay={:.2} gone={:.2} absorb={:.2} compact={:.2} candidates={:.2} \
|
||||
includes={:.2} overlay={:.2} total={:.2} since_start={:.2} ms",
|
||||
self.number,
|
||||
self.kind,
|
||||
self.read,
|
||||
self.discovery_ms,
|
||||
self.config_ms,
|
||||
self.walk_ms,
|
||||
self.filelist_ms,
|
||||
self.sort_ms,
|
||||
self.cap_ms,
|
||||
self.buffers_ms,
|
||||
self.order_ms,
|
||||
self.cache_open_ms,
|
||||
self.read_ms,
|
||||
nanos(c.lookup_ns),
|
||||
nanos(c.decode_ns),
|
||||
self.parse_ms,
|
||||
nanos(c.encode_ns),
|
||||
nanos(c.write_ns),
|
||||
self.publish_absorb_ms,
|
||||
self.publish_candidates_ms,
|
||||
self.publish_includes_ms,
|
||||
self.publish_overlay_ms,
|
||||
self.gone_ms,
|
||||
self.absorb_ms,
|
||||
nanos(c.compact_ns),
|
||||
self.candidates_ms,
|
||||
self.includes_ms,
|
||||
self.overlay_ms,
|
||||
self.total_ms,
|
||||
self.since_start_ms,
|
||||
)
|
||||
}
|
||||
|
||||
/// The count line: how much work of each kind there was to spend that
|
||||
/// time on.
|
||||
pub fn count_line(&self) -> String {
|
||||
let c = &self.cache;
|
||||
format!(
|
||||
"scan {} counts ({}): read={} read_kib={} walk_dirs={} stats={} skipped={} \
|
||||
hits={} misses={} buffers={} \
|
||||
records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \
|
||||
publishes={} published={} first_publish={:.2} overlays={} \
|
||||
conflict={} rescan_requested={}",
|
||||
self.number,
|
||||
self.kind,
|
||||
self.read,
|
||||
kib(self.read_bytes),
|
||||
self.walk_dirs,
|
||||
self.stats,
|
||||
self.skipped,
|
||||
c.hits,
|
||||
c.misses,
|
||||
self.buffers,
|
||||
c.records,
|
||||
c.repeats,
|
||||
kib(c.decoded_bytes),
|
||||
kib(c.written_bytes),
|
||||
c.opens,
|
||||
c.compactions,
|
||||
self.publishes,
|
||||
self.published,
|
||||
self.first_publish_ms,
|
||||
self.overlays,
|
||||
self.conflict,
|
||||
self.rescan_requested,
|
||||
)
|
||||
}
|
||||
|
||||
/// The memory line: what the scan left resident, table by table.
|
||||
pub fn memory_line(&self) -> String {
|
||||
let s = &self.sizes;
|
||||
format!(
|
||||
"scan {} memory ({}): store_before_kib={} store_after_kib={} cache_entries={} \
|
||||
cache_encoded_kib={} index_files={} unit_names={} unit_defs={} members={} \
|
||||
hier_members={} reference_keys={} reference_sites={} defines={} instantiations={} \
|
||||
fact_words={} fact_word_kib={} candidate_units={} candidate_macros={} \
|
||||
candidate_words={} candidate_word_kib={} include_edges={} include_known={} \
|
||||
work_kib={}",
|
||||
self.number,
|
||||
self.kind,
|
||||
kib(self.cache.store_before as usize),
|
||||
kib(self.cache.store_after as usize),
|
||||
self.cache_entries,
|
||||
kib(self.cache_bytes),
|
||||
s.index_files,
|
||||
s.unit_names,
|
||||
s.unit_defs,
|
||||
s.members,
|
||||
s.hier_members,
|
||||
s.reference_keys,
|
||||
s.reference_sites,
|
||||
s.defines,
|
||||
s.instantiations,
|
||||
s.fact_words,
|
||||
kib(s.fact_word_bytes),
|
||||
s.candidate_units,
|
||||
s.candidate_macros,
|
||||
s.candidate_words,
|
||||
kib(s.candidate_word_bytes),
|
||||
s.include_edges,
|
||||
s.include_known,
|
||||
kib(self.work_bytes),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Milliseconds since `from`.
|
||||
fn millis(from: Instant) -> f64 {
|
||||
from.elapsed().as_secs_f64() * 1_000.0
|
||||
}
|
||||
|
||||
/// Nanoseconds as milliseconds, the unit every line is written in.
|
||||
fn nanos(ns: u64) -> f64 {
|
||||
ns as f64 / 1_000_000.0
|
||||
}
|
||||
|
||||
/// Bytes as whole KiB, rounded down — the unit every size field carries.
|
||||
fn kib(bytes: usize) -> usize {
|
||||
bytes / 1024
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_trace_that_is_off_hands_out_no_clock_and_stays_zero() {
|
||||
let trace = ScanTrace::new(false);
|
||||
assert!(!trace.on());
|
||||
assert!(trace.now().is_none());
|
||||
assert_eq!(trace.elapsed_ms(), 0.0);
|
||||
let mut slot = 0.0;
|
||||
ScanTrace::add(&mut slot, trace.now());
|
||||
assert_eq!(slot, 0.0, "an off trace cannot accumulate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trace_that_is_on_accumulates_into_the_slot_it_is_given() {
|
||||
let trace = ScanTrace::new(true);
|
||||
let started = trace.now();
|
||||
assert!(started.is_some());
|
||||
let mut slot = 0.0;
|
||||
ScanTrace::add(&mut slot, started);
|
||||
ScanTrace::add(&mut slot, started);
|
||||
assert!(slot >= 0.0, "two adds are two summands, never a replacement");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_publish_is_the_one_that_is_stamped() {
|
||||
let mut trace = ScanTrace::new(true);
|
||||
trace.saw_publish(10);
|
||||
let first = trace.first_publish_ms;
|
||||
trace.saw_publish(5);
|
||||
assert_eq!(trace.publishes, 2);
|
||||
assert_eq!(trace.published, 15);
|
||||
assert_eq!(trace.first_publish_ms, first, "a later publish never moves the stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_work_reports_a_scans_own_share_and_never_goes_negative() {
|
||||
let before = CacheWork { hits: 10, lookup_ns: 500, ..CacheWork::default() };
|
||||
let after = CacheWork { hits: 25, lookup_ns: 900, ..CacheWork::default() };
|
||||
let mine = after.since(before);
|
||||
assert_eq!(mine.hits, 15);
|
||||
assert_eq!(mine.lookup_ns, 400);
|
||||
// A counter that somehow went backwards saturates rather than wrapping
|
||||
// into a nonsense number the tracker would then quote.
|
||||
assert_eq!(before.since(after).hits, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_line_names_its_scan_and_is_one_line() {
|
||||
let mut trace = ScanTrace::new(true);
|
||||
trace.kind = "whole";
|
||||
trace.number = 2;
|
||||
trace.read = 124;
|
||||
for line in [trace.stage_line(), trace.count_line(), trace.memory_line()] {
|
||||
assert!(line.starts_with("scan 2 "), "{line}");
|
||||
assert!(!line.contains('\n'), "a timing line is one line: {line}");
|
||||
assert!(line.contains("(whole, 124 files)") || line.contains("(whole)"), "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,7 +94,7 @@ pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
|
||||
/// The request id a `$/cancelRequest` names, or `None` for any other message.
|
||||
/// Both id forms the protocol allows are read; a cancel whose params do not
|
||||
/// parse is dropped, because there is no id to act on.
|
||||
fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
pub(super) fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
let Message::Notification(notification) = message else { return None };
|
||||
if notification.method != Cancel::METHOD {
|
||||
return None;
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Server {
|
||||
}],
|
||||
};
|
||||
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
||||
self.pending.insert(id, Pending::Configuration);
|
||||
self.pending.insert(id, Pending::Configuration(std::time::Instant::now()));
|
||||
}
|
||||
|
||||
/// Ask the client to watch the source files and the filelist for us,
|
||||
@@ -174,7 +174,7 @@ impl Server {
|
||||
pub(super) fn response(&mut self, response: Response) {
|
||||
match self.pending.remove(&response.id) {
|
||||
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
||||
Some(Pending::Configuration) => self.configured(response),
|
||||
Some(Pending::Configuration(asked)) => self.configured(asked, response),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,8 @@ impl Server {
|
||||
/// string) means the same thing: the client has no settings for us, which
|
||||
/// is the defaults. Nothing here is worth a popup — the user did not ask
|
||||
/// for this request and cannot act on its failure.
|
||||
fn configured(&mut self, response: Response) {
|
||||
fn configured(&mut self, asked: std::time::Instant, response: Response) {
|
||||
self.timed(self.timer().map(|_| asked), |took| format!("configuration answered in {took}"));
|
||||
let answered = response.response_result.unwrap_or(Value::Null);
|
||||
let section = answered.get(0).cloned().unwrap_or(Value::Null);
|
||||
self.apply_settings(settings::from_section(§ion));
|
||||
@@ -271,6 +272,12 @@ impl Server {
|
||||
self.verbose.then(std::time::Instant::now)
|
||||
}
|
||||
|
||||
/// How long this server has been alive, in milliseconds — the clock every
|
||||
/// startup number is read against.
|
||||
pub(super) fn since_start(&self) -> f64 {
|
||||
self.born.elapsed().as_secs_f64() * 1_000.0
|
||||
}
|
||||
|
||||
/// One timing line for work that was being timed — and nothing at all,
|
||||
/// closure included, for work that was not.
|
||||
pub(super) fn timed(
|
||||
@@ -297,7 +304,7 @@ impl Server {
|
||||
}
|
||||
|
||||
/// One line for a request the order contract makes wait, naming which of
|
||||
/// [`Server::must_wait`]'s three clauses held it.
|
||||
/// [`Server::must_wait`]'s four clauses held it.
|
||||
///
|
||||
/// The question this answers is the one a slow-looking editor raises:
|
||||
/// "was that request slow, or was it never started?". Silent for anything
|
||||
@@ -308,11 +315,12 @@ impl Server {
|
||||
}
|
||||
let Message::Request(request) = message else { return };
|
||||
self.timing(format!(
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={}, staging={})",
|
||||
request.method,
|
||||
self.answering_a_rescan,
|
||||
self.rescan_wanted,
|
||||
self.held.len()
|
||||
self.held.len(),
|
||||
self.staging
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Server {
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
||||
|
||||
@@ -26,17 +26,17 @@ use lsp_types::request::{
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams,
|
||||
DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams,
|
||||
DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams,
|
||||
FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams,
|
||||
TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri,
|
||||
WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse,
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeLensParams,
|
||||
CompletionParams, DocumentDiagnosticParams, DocumentDiagnosticReportResult,
|
||||
DocumentHighlightParams, DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse,
|
||||
ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse,
|
||||
HoverParams, InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Position,
|
||||
ReferenceParams, RenameFilesParams, RenameParams, SelectionRangeParams, SemanticTokens,
|
||||
SemanticTokensDeltaParams, SemanticTokensParams, SemanticTokensRangeParams,
|
||||
SemanticTokensRangeResult, SemanticTokensResult, SignatureHelpParams,
|
||||
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
|
||||
TypeHierarchySupertypesParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult,
|
||||
WorkspaceSymbolParams, WorkspaceSymbolResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
@@ -45,10 +45,29 @@ use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
|
||||
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, nav, pairs, ports,
|
||||
rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav,
|
||||
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
/// The requests whose empty answer may mean "this scan has not reached the
|
||||
/// file yet" rather than "there is nowhere to go".
|
||||
///
|
||||
/// All three answer with a **list of places** and with an empty list when they
|
||||
/// find none, so `[]` is exactly the shape that carries no information. Every
|
||||
/// other request is left alone: a hover's `null`, a completion's empty list and
|
||||
/// a code-action menu with no offers all mean what they say whatever the scan
|
||||
/// has reached, and deferring one would be withholding an answer rather than
|
||||
/// waiting for a better one. `textDocument/implementation` would belong here;
|
||||
/// this server does not answer it, so it is not written down as if it did.
|
||||
const NAVIGATION: [&str; 3] =
|
||||
[GotoDefinition::METHOD, GotoTypeDefinition::METHOD, References::METHOD];
|
||||
|
||||
/// Whether a response says **nowhere**: an answer, not a failure, and an empty
|
||||
/// list of places. See [`NAVIGATION`].
|
||||
pub(super) fn names_nowhere(response: &Response) -> bool {
|
||||
matches!(&response.response_result, Ok(Value::Array(found)) if found.is_empty())
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Answer one request, timing it when `--verbose` asked.
|
||||
///
|
||||
@@ -61,18 +80,92 @@ impl Server {
|
||||
pub(super) fn request(&mut self, request: Request) -> Response {
|
||||
let Some(started) = self.timer() else { return self.answer_request(request) };
|
||||
let method = request.method.clone();
|
||||
// One trace per request, armed here so the flush this request triggers
|
||||
// is inside it: the diagnostics pass that publishes during the flush is
|
||||
// the *other* consumer of a lint result, and the two are only readable
|
||||
// against each other when one line carries both (review round §R1b).
|
||||
lint_trace::arm();
|
||||
let response = self.answer_request(request);
|
||||
self.timing(format!("{method} answered in {}", ms(started)));
|
||||
// Silent for every request that never linted anything, which is all of
|
||||
// them but the code actions and the flushes that publish diagnostics.
|
||||
if let Some(trace) = lint_trace::disarm().filter(|trace| !trace.is_empty()) {
|
||||
self.timing(format!(
|
||||
"codeaction method={method} total={} {}",
|
||||
ms(started),
|
||||
trace.line()
|
||||
));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// A copy of `request` to ask again at the scan's next publish, when an
|
||||
/// empty answer to it right now would mean "not scanned yet" rather than
|
||||
/// "nowhere".
|
||||
///
|
||||
/// **The lead's ruling from §61.3, as a rule in the drain.** A held
|
||||
/// startup request is answered the moment the user's own folder is
|
||||
/// published, and a definition whose target lives in another folder was
|
||||
/// answered `[]` there — coherent, and wrong by the time the scan ended.
|
||||
/// Rather than teach the drain to work out whether the published prefix
|
||||
/// resolves *this* request's target, the answer is computed through the
|
||||
/// ordinary handler and, when it names nowhere and the index is still
|
||||
/// growing, put back ([`Server::deferred`]).
|
||||
///
|
||||
/// **Only while a scan is running**, so a settled server answers empty
|
||||
/// exactly as it always did — including the last try, after the scan ends.
|
||||
/// **Only the three navigation methods that answer with a list of places**
|
||||
/// ([`NAVIGATION`]): a hover, a completion, a code action or a rename is
|
||||
/// unaffected, and so is every request whose empty answer means something
|
||||
/// else. `textDocument/implementation` is not on the list because this
|
||||
/// server does not answer it.
|
||||
pub(super) fn ask_again_if_empty(&self, request: &Request) -> Option<Request> {
|
||||
if !self.scanning || !NAVIGATION.contains(&request.method.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(Request::new(request.id.clone(), request.method.clone(), request.params.clone()))
|
||||
}
|
||||
|
||||
/// `--verbose`: that a navigation answer was set aside for the next
|
||||
/// publish rather than sent, and how many are waiting with it.
|
||||
pub(super) fn say_deferred(&self, request: &Request) {
|
||||
if !self.verbose {
|
||||
return;
|
||||
}
|
||||
self.timing(format!(
|
||||
"{} DEFERRED to the next publish (empty mid-scan, already deferred={})",
|
||||
request.method,
|
||||
self.deferred.len()
|
||||
));
|
||||
}
|
||||
|
||||
/// [`Server::flush_dirty`], with the dirty-buffer stage measured apart
|
||||
/// from the handler that follows it.
|
||||
///
|
||||
/// The review's item 4: *if the dirty-buffer stage dominates the 136 ms, a
|
||||
/// lint cache alone cannot fix it*. The flush rebuilds each dirty
|
||||
/// `Document` (parse and analysis, counted as whole-file parses) and then
|
||||
/// publishes its diagnostics, which lints; the handler lints again. One
|
||||
/// line carrying both is what makes the two comparable.
|
||||
fn flush_dirty_traced(&mut self) {
|
||||
if !lint_trace::armed() {
|
||||
return self.flush_dirty();
|
||||
}
|
||||
let buffers = self.dirty.len();
|
||||
let before = vlog_parser::stats::parses();
|
||||
let started = std::time::Instant::now();
|
||||
self.flush_dirty();
|
||||
let parses = vlog_parser::stats::parses().saturating_sub(before);
|
||||
lint_trace::close_flush(started.elapsed(), buffers, parses);
|
||||
}
|
||||
|
||||
fn answer_request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
self.flush_dirty_traced();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
@@ -246,14 +339,34 @@ impl Server {
|
||||
let uri = p.text_document.uri;
|
||||
let only = p.context.only;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
let mut actions =
|
||||
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// A filter naming no kind at all selects nothing: every
|
||||
// `wanted` below is false, so the answer is empty however much
|
||||
// work is done to reach it. Answering here is what keeps a
|
||||
// client that asks for nothing from paying for config
|
||||
// discovery, a lint pass and four selectors (take 5 §P1a).
|
||||
if only.as_deref().is_some_and(<[CodeActionKind]>::is_empty) {
|
||||
return to_value(Vec::<CodeActionOrCommand>::new());
|
||||
}
|
||||
let mut actions: Vec<CodeActionOrCommand> = Vec::new();
|
||||
// Quick fixes and `source.fixAll.lucisv` are the only two
|
||||
// families the lint pass answers for, so a request for neither
|
||||
// — an organize-on-save, a refactor-only menu — does not read
|
||||
// the project's configuration and does not lint.
|
||||
if code_action::wants_fixes(only.as_deref()) {
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default — read by the run itself, off
|
||||
// the `FileConfig` it discovers anyway, so this path no longer
|
||||
// walks for a config file twice (review round §R1a).
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
actions.extend(code_action::code_actions(
|
||||
&run,
|
||||
&uri,
|
||||
doc,
|
||||
p.range,
|
||||
only.as_deref(),
|
||||
));
|
||||
}
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
@@ -347,7 +460,16 @@ impl Server {
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
||||
// One `timing: rename trace …` line behind `--verbose`, and
|
||||
// nothing at all otherwise: where a rename's selection, its
|
||||
// stages and its whole-file parses went (take 5 §P2a).
|
||||
let mut trace = None;
|
||||
let outcome =
|
||||
rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace);
|
||||
if let (true, Some(line)) = (self.verbose, trace) {
|
||||
self.timing(format!("rename trace {line}"));
|
||||
}
|
||||
match outcome {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
to_value(edit)
|
||||
|
||||
@@ -28,8 +28,10 @@ impl Server {
|
||||
/// or a file the client renamed or deleted.
|
||||
pub(super) fn reindex(&mut self) {
|
||||
// A rescan asked for by a message this scan answered is *this* scan's
|
||||
// successor, not a scan inside it. See `scan_until_settled`.
|
||||
if self.scanning {
|
||||
// successor, not a scan inside it — and one asked for before the
|
||||
// startup scan has begun is that scan itself. See
|
||||
// `scan_until_settled` and [`Server::scan_owed`].
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
@@ -84,8 +86,9 @@ impl Server {
|
||||
// bytes a moment later. One more scan when this one ends is the whole
|
||||
// answer, and it is the same flag every other mid-scan trigger sets.
|
||||
// `true` because the caller's fallback — a whole rebuild, right now —
|
||||
// is exactly what must not happen.
|
||||
if self.scanning {
|
||||
// is exactly what must not happen. Same for the startup's
|
||||
// configuration wait, whose scan reads this file from disk anyway.
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return true;
|
||||
}
|
||||
@@ -122,11 +125,17 @@ impl Server {
|
||||
/// sets, and it is what keeps the coalescing rule one rule
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(super) fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
|
||||
if self.scanning {
|
||||
// Before the startup scan has begun there is nothing to widen *into*:
|
||||
// that scan resolves the scope afresh, the buffer this `didOpen` just
|
||||
// installed is already in it, and `open_first` puts the buffer at the
|
||||
// head of its work list. So the widen is folded into the one scan
|
||||
// rather than run as a second one (`server/startup.rs`).
|
||||
if self.scan_owed() {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
let since_start = self.since_start();
|
||||
if started.is_some() {
|
||||
// The folders by name: which folder a jump widened into is the one
|
||||
// thing the file log below it does not say in one line.
|
||||
@@ -138,9 +147,10 @@ impl Server {
|
||||
paths.join(", ")
|
||||
));
|
||||
}
|
||||
let verbose = started.is_some();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan =
|
||||
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
|
||||
self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose));
|
||||
let total = scan.total();
|
||||
// No drain between the files: a widen is a rescan a message asked for,
|
||||
// and `must_wait` would hold every request queued behind it anyway. It
|
||||
@@ -163,6 +173,7 @@ impl Server {
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.say_scan_trace(since_start);
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
@@ -208,9 +219,31 @@ impl Server {
|
||||
};
|
||||
self.answering_a_rescan = false;
|
||||
self.scanning = false;
|
||||
// A neighbourhood can only be owed by a scan, and there is none now.
|
||||
self.head_owed = false;
|
||||
self.answer_what_was_deferred();
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Answer whatever the empty-answer rule set aside, now that the index has
|
||||
/// stopped growing.
|
||||
///
|
||||
/// **The other half of that rule, and the reason it can never strand a
|
||||
/// request.** A navigation answer was deferred because `[]` might have
|
||||
/// meant "not scanned yet"; here it cannot mean that any more, so an empty
|
||||
/// answer is the honest one and goes out. The scan is over, so
|
||||
/// [`Server::ask_again_if_empty`] defers nothing this time round — and a
|
||||
/// request the order contract still holds, one behind something already
|
||||
/// `held`, is put back by `process_batch`'s own rule exactly as any other
|
||||
/// message would be.
|
||||
pub(super) fn answer_what_was_deferred(&mut self) {
|
||||
let deferred = std::mem::take(&mut self.deferred);
|
||||
if deferred.is_empty() || self.stopped {
|
||||
return;
|
||||
}
|
||||
self.stopped = !matches!(self.process_batch(deferred), Ok(false));
|
||||
}
|
||||
|
||||
/// One whole scan: the bar up, every file indexed with the client's
|
||||
/// messages answered between two of them, the bar down.
|
||||
///
|
||||
@@ -224,26 +257,58 @@ impl Server {
|
||||
// scope and walking it is part of what a scan costs, and a number that
|
||||
// left it out would be the wrong answer to "why was that slow?".
|
||||
let started = self.timer();
|
||||
let since_start = self.since_start();
|
||||
let verbose = started.is_some();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
||||
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
|
||||
// A scan that has walked the user's own folders and owes itself the
|
||||
// rest of the workspace **always** interleaves, whatever its work list
|
||||
// says today: the whole point of leading with that neighbourhood is
|
||||
// that the request waiting for it is answered the moment it is in
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE || scan.discovery_pending();
|
||||
let total = scan.total();
|
||||
if started.is_some() {
|
||||
// Whether it interleaves is said here because it is decided here,
|
||||
// and because it is the answer to "why did my hover wait?" — a
|
||||
// scan that does not interleave answers nothing until it is done.
|
||||
let interleaving = if interleave { ", interleaved" } else { "" };
|
||||
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
|
||||
let staged = if scan.discovery_pending() { " (the folder first)" } else { "" };
|
||||
self.timing(format!(
|
||||
"scan started: {total} file{}{staged}{interleaving}",
|
||||
plural(total)
|
||||
));
|
||||
}
|
||||
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
|
||||
{
|
||||
loop {
|
||||
// **No bar while the denominator can still grow.** The work list
|
||||
// is the neighbourhood so far, and a percentage against it would
|
||||
// fall to a twentieth of itself the moment the rest of the
|
||||
// workspace lands. The per-file log still runs — it names files,
|
||||
// not fractions — and the first percentage the client sees is the
|
||||
// first measured one (`docs/features/indexing-ux/README.md`).
|
||||
let showing = if scan.discovery_pending() { None } else { bar.as_ref() };
|
||||
let stepped =
|
||||
self.watching(showing, |workspace, watch| workspace.scan_step(&mut scan, watch));
|
||||
if !stepped {
|
||||
break;
|
||||
}
|
||||
if interleave && self.answer_what_is_waiting(&mut scan) {
|
||||
// Nothing after this may speak to a client that has gone, the
|
||||
// timing line included.
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let total = scan.total();
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
// A split discovery whose two halves reached one directory by two
|
||||
// spellings: nothing was indexed twice, and every answer this scan
|
||||
// gives is the right one, but the paths are the head's and a plain
|
||||
// walk of the same tree spells them the other way
|
||||
// ([`Scan::wants_rescan`]). One ordinary rescan *is* that plain walk,
|
||||
// so it converges them — asked for with the same flag a save or a
|
||||
// settings change sets, and therefore run when this scan ends, with
|
||||
// every request held for the whole of it.
|
||||
self.rescan_wanted |= scan.wants_rescan();
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
@@ -252,9 +317,27 @@ impl Server {
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.say_scan_trace(since_start);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// The three `timing: scan …` lines the startup breakdown is read from —
|
||||
/// stages, counts and the sizes the scan left resident.
|
||||
///
|
||||
/// Silent without `--verbose`, because a scan that was not traced left a
|
||||
/// trace of zeroes and three lines of them would be a lie
|
||||
/// (`docs/features/perf5-p4/README.md` holds the field list).
|
||||
fn say_scan_trace(&mut self, since_start: f64) {
|
||||
let mut trace = self.workspace.take_scan_trace();
|
||||
if !trace.on() {
|
||||
return;
|
||||
}
|
||||
trace.since_start_ms = since_start;
|
||||
self.timing(trace.stage_line());
|
||||
self.timing(trace.count_line());
|
||||
self.timing(trace.memory_line());
|
||||
}
|
||||
|
||||
/// Do one piece of a scan with the progress bar and the per-file log
|
||||
/// watching it.
|
||||
///
|
||||
@@ -280,36 +363,110 @@ impl Server {
|
||||
/// **This is the round's whole point, and its whole cost.** Polling costs
|
||||
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
|
||||
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
|
||||
/// on pays one merge per burst to make the records it has taken since the
|
||||
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// on pays a merge to make the records it has taken since the last one
|
||||
/// answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// through the same `process_batch` the loop uses, so a `didChange` queued
|
||||
/// ahead of a hover is applied before that hover is answered and a cancel
|
||||
/// beside its request still answers it `RequestCancelled` — the order
|
||||
/// contract is the loop's, unchanged, because it is the loop's code.
|
||||
///
|
||||
/// **A merge per burst was the cost; a merge per 512 files is what it is
|
||||
/// now.** [`Scan::publish_is_due`] is the cadence, and the one drain
|
||||
/// exempt from it is the one with something *waiting* — the startup's held
|
||||
/// requests, drained the moment the neighbourhood is in, which is the
|
||||
/// session's first useful answer and must not be a file later than it was
|
||||
/// (`docs/features/perf5r-first-answer/README.md`). Everything else reads
|
||||
/// a coherent prefix that is at most a cadence older, which is the trade
|
||||
/// `docs/features/perf5r-publication/README.md` measures.
|
||||
///
|
||||
/// An error here is a client that has gone: there is nobody to report it
|
||||
/// to and no reason to go on scanning, so it stops the scan the same way a
|
||||
/// `shutdown` does.
|
||||
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
|
||||
let mut batch = Vec::new();
|
||||
// Nothing may be answered off a prefix that does not yet hold the
|
||||
// folder the user is working in: a definition into the file next door
|
||||
// would be `[]` (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
let mut batch = self.waiting_for_this_scan();
|
||||
let owed = !batch.is_empty();
|
||||
let mut arrived = Vec::new();
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
batch.push(message);
|
||||
arrived.push(message);
|
||||
}
|
||||
// A quiet scan pays nothing at all, and that is a promise: the cadence
|
||||
// is asked only when there is something for a publish to be *for*.
|
||||
if !owed && arrived.is_empty() && self.deferred.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if owed || scan.publish_is_due() {
|
||||
self.workspace.publish_scan(scan);
|
||||
// A navigation answer this scan could not give yet is asked again
|
||||
// off the prefix that has just grown — behind whatever was already
|
||||
// waiting, ahead of everything newer ([`Server::deferred`]).
|
||||
batch.append(&mut self.deferred);
|
||||
}
|
||||
batch.append(&mut arrived);
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let opened = opened_in(&batch);
|
||||
self.workspace.publish_scan(scan);
|
||||
// A `didOpen` in this burst names a folder the work list has not been
|
||||
// ordered around yet, so the requests behind it in the burst are owed
|
||||
// that ordering before they are answered — which is exactly what the
|
||||
// widen this `didOpen` used to trigger made them wait for. The flag is
|
||||
// set *before* the batch is applied, so `must_wait` holds them; it is
|
||||
// recomputed below once the new head segment is known.
|
||||
let opened = !opened_in(&batch).is_empty();
|
||||
self.head_owed |= opened;
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
// The file the user has just opened is the one they are looking at, so
|
||||
// it is indexed next rather than when the alphabet reaches it — the
|
||||
// open-first rule, for a file opened after the work list was taken.
|
||||
for path in opened {
|
||||
scan.index_next(&path);
|
||||
// The files the user has just opened, and the folders around them, are
|
||||
// what they are looking at, so they are indexed next rather than when
|
||||
// the alphabet reaches them — the open-first rule, for buffers opened
|
||||
// after the work list was taken.
|
||||
if opened {
|
||||
self.watching(None, |workspace, watch| workspace.open_next(scan, watch));
|
||||
self.head_owed = !scan.neighbourhood_indexed();
|
||||
}
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// What the startup's configuration wait set aside, when this scan is the
|
||||
/// one those messages were waiting for.
|
||||
///
|
||||
/// **Not an exemption from the order contract — the other side of it.** A
|
||||
/// request that arrives before the startup scan has begun is held for the
|
||||
/// same reason one arriving *during* it is answered: there is no index at
|
||||
/// all to answer it from, and the scan it is waiting for is the server's
|
||||
/// own startup, with nothing queued ahead of it and — being the session's
|
||||
/// first — an empty `gone` set. So the startup scan answers it exactly as
|
||||
/// it answers a message that turns up while it runs, off the same
|
||||
/// published prefix.
|
||||
///
|
||||
/// A scan a **message** asked for takes nothing: its held messages are
|
||||
/// queued behind the message that asked for it, and answering them off a
|
||||
/// half-updated index is precisely the trade
|
||||
/// `docs/features/scan-interleave/README.md`'s decision 2 refuses. Same
|
||||
/// for a scan with a further rescan already wanted — the requests behind
|
||||
/// that ask are owed its effect.
|
||||
///
|
||||
/// **And not at the very first file.** A prefix holding the user's own
|
||||
/// buffer and nothing else answers a definition in the file next door with
|
||||
/// `[]` — coherent, and useless, which is what §P4b2 measured
|
||||
/// (`docs/features/perf5-p4/README.md`). So the startup scan takes what it
|
||||
/// was handed once it has stepped the user's whole neighbourhood
|
||||
/// ([`Server::head_owed`], from [`Scan::neighbourhood_indexed`]); the
|
||||
/// `publish_scan` in [`Server::answer_what_is_waiting`] is what then makes
|
||||
/// that neighbourhood answerable, in the same call. A scan with no
|
||||
/// neighbourhood — nothing open, or a folder covering the workspace — says
|
||||
/// so with `head` 0 and drains at the first file exactly as before.
|
||||
/// Requests arriving *after* that are answered at every interleave point,
|
||||
/// as they always were.
|
||||
fn waiting_for_this_scan(&mut self) -> Vec<lsp_server::Message> {
|
||||
if self.answering_a_rescan || self.rescan_wanted || self.head_owed {
|
||||
return Vec::new();
|
||||
}
|
||||
std::mem::take(&mut self.held)
|
||||
}
|
||||
|
||||
/// Publish a new completed hierarchy revision after any index mutation.
|
||||
pub(super) fn hierarchy_index_changed(&mut self) {
|
||||
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
|
||||
|
||||
@@ -44,10 +44,10 @@ use lsp_server::{Connection, Message, RequestId};
|
||||
use lsp_types::notification::{Cancel, Notification as _};
|
||||
use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_in, cancelled_response, forward};
|
||||
use batch::{burst, cancelled_id, cancelled_in, cancelled_response};
|
||||
use dispatch::names_nowhere;
|
||||
|
||||
mod batch;
|
||||
mod client;
|
||||
@@ -59,6 +59,7 @@ mod large_file;
|
||||
mod notification;
|
||||
mod progress;
|
||||
mod semantic_tokens;
|
||||
mod startup;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -192,6 +193,24 @@ pub struct Server {
|
||||
/// another one, and this is what turns that into the flag below rather
|
||||
/// than a scan inside a scan.
|
||||
scanning: bool,
|
||||
/// Whether the startup scan is still *owed* — the window between the
|
||||
/// `workspace/configuration` request that opens a session and the answer
|
||||
/// that decides the scope its one scan runs at
|
||||
/// (`server/startup.rs`). Nothing has been indexed yet, so a rescan
|
||||
/// trigger in this window is folded into the scan that is about to run
|
||||
/// rather than run as a scan of its own, and every request waits for it —
|
||||
/// there is nothing to answer one from. Never true again after
|
||||
/// construction.
|
||||
staging: bool,
|
||||
/// Whether the scan now running still owes the user's own neighbourhood —
|
||||
/// their open buffers and the folders those raise to, which
|
||||
/// [`crate::scan_order`] puts at the head of its work list. Until it has
|
||||
/// been indexed there is nothing worth answering a request off: the prefix
|
||||
/// holds the alphabet rather than what the user is looking at, and §P4b2
|
||||
/// measured what that answers, which is `[]`
|
||||
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
|
||||
/// running, and false during a scan with no neighbourhood to wait for.
|
||||
head_owed: bool,
|
||||
/// A rescan asked for while a scan was running. Coalesced: any number of
|
||||
/// requests is one more scan when this one ends, whatever asked for them.
|
||||
rescan_wanted: bool,
|
||||
@@ -209,11 +228,33 @@ pub struct Server {
|
||||
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
||||
/// own.
|
||||
held: Vec<Message>,
|
||||
/// Navigation requests a scan answered **empty** while it was still
|
||||
/// growing the index, to be asked again at its next publish.
|
||||
///
|
||||
/// **Not a second `held`, and deliberately not part of
|
||||
/// [`Server::must_wait`].** A held request is one the order contract says
|
||||
/// nothing newer may overtake; this is one whose answer was computed,
|
||||
/// found to name nowhere, and set aside because the reason it named
|
||||
/// nowhere may be that the file it wants has not been scanned yet
|
||||
/// (`docs/features/perf5r-publication/README.md`). Nothing else is owed
|
||||
/// anything by it — a hover, a completion or a code action behind one is
|
||||
/// answered exactly as before — and it is asked again at most once per
|
||||
/// publish, so the re-computation is bounded by the cadence and not by the
|
||||
/// scan's file count. A scan ending runs whatever is left through the
|
||||
/// dispatch one last time, with itself already over — so nothing is
|
||||
/// deferred that time round and an empty answer, which is now the honest
|
||||
/// one, goes out ([`Server::answer_what_was_deferred`]).
|
||||
deferred: Vec<Message>,
|
||||
/// `--verbose`: whether every operation says how long it took, in the
|
||||
/// client's log channel. Off is the shipped state and the whole of what it
|
||||
/// costs is the branch that reads this field — see
|
||||
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
|
||||
verbose: bool,
|
||||
/// When this server was built — the moment after `initialize`/`initialized`
|
||||
/// that `main` hands control over. Every startup number is measured from
|
||||
/// here, so a scan's line can say how much of the wait came before it
|
||||
/// (`docs/features/perf5-p4/README.md`).
|
||||
born: std::time::Instant,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
@@ -252,8 +293,9 @@ enum Pending {
|
||||
/// A `workspace/applyEdit`, remembering the command that asked for it so
|
||||
/// a refusal can be named to the user.
|
||||
ApplyEdit(String),
|
||||
/// A `workspace/configuration` asking for the `lucisv` section.
|
||||
Configuration,
|
||||
/// A `workspace/configuration` asking for the `lucisv` section, and when
|
||||
/// it was asked — the config round trip is part of what a startup costs.
|
||||
Configuration(std::time::Instant),
|
||||
}
|
||||
|
||||
/// One semantic-token answer, kept so the next delta request can be answered
|
||||
@@ -264,136 +306,6 @@ struct TokenAnswer {
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the **default** settings — including the
|
||||
/// folder scope — because neither settings door can deliver anything
|
||||
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
|
||||
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
|
||||
/// has always cost one.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
Server::started(
|
||||
connection,
|
||||
roots,
|
||||
abilities,
|
||||
ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Server::new`] with a client's settings already in hand — the seam the
|
||||
/// tests start a session from. Only a test has any settings this early:
|
||||
/// one whose subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
///
|
||||
/// `queued` is what the client had already sent when the server was built
|
||||
/// — the opening burst, put straight onto the queue the startup scan
|
||||
/// drains. Empty for [`Server::new`]; a test fills it because racing the
|
||||
/// forwarder thread for it would make the test a coin toss rather than a
|
||||
/// check.
|
||||
fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
client: ClientSettings,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
// Started before the first scan, not in `run`: the scan below answers
|
||||
// whatever the client has already sent, and it can only do that off a
|
||||
// queue that is already being filled.
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
let mut server = Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
verbose,
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead. The
|
||||
// first index build is the slowest one of the session, so it gets the
|
||||
// same bar every later rescan gets.
|
||||
//
|
||||
// And it answers messages while it runs, which is what stops the first
|
||||
// request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
server.workspace.adopt_roots(roots);
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can now be *opened* during the startup scan, and what was
|
||||
// published for it then was computed against a half-built index. This
|
||||
// is the same debt a rescan pays at the end of `reindex`, owed here
|
||||
// for the first time because before this round no buffer could exist
|
||||
// at this point. Nothing at all is sent when nothing is open, which is
|
||||
// every session whose client did not get a `didOpen` in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
// The pull half of the settings model. Asked here because this is the
|
||||
// same moment the watchers are registered — the earliest legal one —
|
||||
// and answered later, in the loop: the settings therefore arrive
|
||||
// *after* the first index build, exactly as a pushed
|
||||
// `didChangeConfiguration` always has (it cannot arrive before
|
||||
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
|
||||
// costs one extra rescan when it lands; nothing is stale in between,
|
||||
// it is simply the default scope until the client answers.
|
||||
server.request_configuration();
|
||||
server
|
||||
}
|
||||
|
||||
/// Receive until the client shuts us down or the channel closes.
|
||||
///
|
||||
/// One blocking receive, then everything already queued behind it, then
|
||||
@@ -499,7 +411,20 @@ impl Server {
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
self.request(request)
|
||||
// A navigation request whose answer would be `[]` only
|
||||
// because the scan has not reached its target yet is
|
||||
// asked again at the next publish rather than answered
|
||||
// with nowhere ([`Server::deferred`]).
|
||||
let again = self.ask_again_if_empty(&request);
|
||||
let response = self.request(request);
|
||||
match again.filter(|_| names_nowhere(&response)) {
|
||||
Some(request) => {
|
||||
self.say_deferred(&request);
|
||||
self.deferred.push(Message::Request(request));
|
||||
continue;
|
||||
}
|
||||
None => response,
|
||||
}
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
}
|
||||
@@ -508,7 +433,14 @@ impl Server {
|
||||
// already been done above. Kept only so that a request behind
|
||||
// one that has to wait takes its cancel with it.
|
||||
Message::Notification(notification) if notification.method == Cancel::METHOD => {
|
||||
consumed_cancels.push(Message::Notification(notification));
|
||||
let cancel = Message::Notification(notification);
|
||||
// A request the empty-answer rule set aside is not in this
|
||||
// burst, so `cancelled_in` cannot see it — but it is still
|
||||
// a request the client is waiting on, and a cancel for it
|
||||
// is honoured where it lands: answered `RequestCancelled`
|
||||
// now, and never asked again (QA, perf5r-publication).
|
||||
self.cancel_deferred(&cancel)?;
|
||||
consumed_cancels.push(cancel);
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
Message::Response(response) => self.response(response),
|
||||
@@ -517,6 +449,22 @@ impl Server {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
|
||||
/// take it out and answer it cancelled. A cancel naming anything else is
|
||||
/// left to the batch's own rule.
|
||||
fn cancel_deferred(&mut self, cancel: &Message) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let Some(id) = cancelled_id(cancel) else { return Ok(()) };
|
||||
let found = self
|
||||
.deferred
|
||||
.iter()
|
||||
.position(|message| matches!(message, Message::Request(request) if request.id == id));
|
||||
if let Some(at) = found {
|
||||
self.deferred.remove(at);
|
||||
self.connection.sender.send(Message::Response(cancelled_response(id)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a request reaching the dispatch right now must wait instead of
|
||||
/// being answered.
|
||||
///
|
||||
@@ -528,7 +476,7 @@ impl Server {
|
||||
/// setting or an added workspace folder before a go-to-definition. Those
|
||||
/// four ask for a rescan, and "applied" for them means the rescan has
|
||||
/// **run**: one message at a time, the server would have finished it
|
||||
/// before ever taking the request. Three clauses, one rule:
|
||||
/// before ever taking the request. Four clauses, one rule:
|
||||
///
|
||||
/// * `answering_a_rescan` — this scan is one a message asked for, so
|
||||
/// every request that arrives while it runs arrived *after* that
|
||||
@@ -536,7 +484,19 @@ impl Server {
|
||||
/// * `rescan_wanted` — a message in this very burst has just asked for
|
||||
/// one, and the requests behind it in the burst are owed the same;
|
||||
/// * `held` — a request is already waiting, and answering a newer one
|
||||
/// ahead of it would reorder them just as badly.
|
||||
/// ahead of it would reorder them just as badly;
|
||||
/// * `staging` — the startup scan has not begun, because the settings
|
||||
/// that decide its scope are still in flight. There is no index at all
|
||||
/// to answer from, so a request waits for that scan — and is answered
|
||||
/// *inside* it, mid-way, exactly as one arriving while it runs is
|
||||
/// ([`Server::waiting_for_this_scan`]);
|
||||
/// * `head_owed` — the scan running has not yet reached the end of the
|
||||
/// user's own folder. There *is* an index, but the part of it a request
|
||||
/// is asking about is the part not built yet, and answering off the
|
||||
/// alphabet's prefix returns `[]` rather than an answer. A request
|
||||
/// behind a `didOpen` is owed that `didOpen`'s effect on the scan
|
||||
/// order, which is the same rule the other four state
|
||||
/// ([`Server::head_owed`]).
|
||||
///
|
||||
/// What is left answered mid-scan is exactly what is queued behind
|
||||
/// *nothing*: the opening burst of a session, whose scan is the server's
|
||||
@@ -544,7 +504,23 @@ impl Server {
|
||||
/// the round is about, and it is the one a user feels
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
fn must_wait(&self) -> bool {
|
||||
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
|
||||
self.answering_a_rescan
|
||||
|| self.rescan_wanted
|
||||
|| !self.held.is_empty()
|
||||
|| self.staging
|
||||
|| self.head_owed
|
||||
}
|
||||
|
||||
/// Whether a scan is running or already owed — the two states in which a
|
||||
/// rescan trigger records that one more scan is wanted instead of running
|
||||
/// one itself.
|
||||
///
|
||||
/// The second is the startup's configuration wait (`server/startup.rs`):
|
||||
/// the scan it is waiting for has not begun, and when it does it will
|
||||
/// resolve the scope afresh and read every file in it, so anything asked
|
||||
/// for now is satisfied by it.
|
||||
fn scan_owed(&self) -> bool {
|
||||
self.scanning || self.staging
|
||||
}
|
||||
|
||||
/// Whether the installed index covers the whole scope with no indexing
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
//! What a session does before its message loop: ask the client for its
|
||||
//! settings, wait a bounded moment for the answer, and run **one** startup
|
||||
//! scan at the scope that answer decided.
|
||||
//!
|
||||
//! Before 2026-09-08 the order was the other way round — scan at the
|
||||
//! defaults, then ask — and a client whose `lucisv.index.scope` differs from
|
||||
//! the default folder scope (which is every VS Code session that sets one)
|
||||
//! paid a whole second scan when the answer landed. With no buffer open the
|
||||
//! first of those scans indexes **zero files**, so what it bought was the
|
||||
//! round-trip wait and nothing else; §P4b then made it cost 0.15 ms instead
|
||||
//! of 181 ms, which turned the head start it had accidentally been giving the
|
||||
//! opening `didOpen` into a genuine race and made the first useful answer of
|
||||
//! a warm session bimodal. Staging removes the scan rather than the race:
|
||||
//! there is one scan, it runs at the settings the client actually wants, and
|
||||
//! the opening burst is answered *inside* it exactly as
|
||||
//! `docs/features/scan-interleave/README.md` has always answered the startup
|
||||
//! scan's own arrivals.
|
||||
//!
|
||||
//! The bound below is what a client that advertised
|
||||
//! `workspace/configuration` and then never answers costs: after it, the scan
|
||||
//! runs at the defaults exactly as it used to, and an answer that turns up
|
||||
//! afterwards is an ordinary settings change with an ordinary rescan behind
|
||||
//! it. See `docs/features/perf5-p4/README.md` §P4b2 and
|
||||
//! `docs/features/folders-and-config/README.md`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lsp_server::{Connection, Message};
|
||||
|
||||
use super::batch::{burst, forward};
|
||||
use super::{ClientAbilities, Pending, Server};
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// How long a startup waits for the client's `workspace/configuration`
|
||||
/// answer before scanning at the defaults.
|
||||
///
|
||||
/// **Not a budget — a bound on a client that never answers.** The round trip
|
||||
/// itself is single-digit milliseconds: §P4a measured the whole of it,
|
||||
/// including the empty scan that used to run in front of it, at 27–85 ms, and
|
||||
/// with that scan gone what is left is the client's own reply. Two seconds is
|
||||
/// therefore two orders of magnitude of slack for a slow client, and still
|
||||
/// short enough that a client which advertised the capability and then says
|
||||
/// nothing does not leave a workspace unindexed.
|
||||
pub(super) const CONFIGURATION_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How long a startup waits, *after* the settings answer, for the editor to
|
||||
/// say which file it has open.
|
||||
///
|
||||
/// **Only when that name changes what the scan does.** A workspace-scoped scan
|
||||
/// with a buffer open walks that buffer's folder first, indexes it, and
|
||||
/// answers the request waiting for it in ~115 ms; without the name it walks
|
||||
/// all 3 976 files first and answers in ~290
|
||||
/// (`docs/features/perf5r-first-answer/README.md`). The two messages are
|
||||
/// written by the client at the same moment — the settings answer by whatever
|
||||
/// handles server-initiated requests, the `didOpen` by the editor — so which
|
||||
/// arrives first is a coin toss, and losing it costs 175 ms of the thing this
|
||||
/// round is about. This is that coin toss removed.
|
||||
///
|
||||
/// It is spent **only** by a session that is going to walk a whole workspace
|
||||
/// and has no buffer at all yet: a folder-scoped session has nothing to lead
|
||||
/// with, and a session whose buffer is already in hand stops waiting the
|
||||
/// moment it applies one. So the session that pays the full bound is the one
|
||||
/// with an empty editor, where nothing is waiting on the scan.
|
||||
pub(super) const OPENING_FILE_WAIT: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Everything a session starts with that is not the connection or the roots.
|
||||
///
|
||||
/// One struct rather than six more parameters: `started` is the seam every
|
||||
/// test starts a session from, and the two fields only a test ever sets
|
||||
/// ([`Startup::queued`] and [`Startup::wait`]) would otherwise be positional
|
||||
/// arguments nobody can read at the call site.
|
||||
pub(super) struct Startup {
|
||||
/// What the client said it can do, read once at `initialize`.
|
||||
pub(super) abilities: ClientAbilities,
|
||||
/// Settings already in hand. Only a test has any this early: one whose
|
||||
/// subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
pub(super) client: ClientSettings,
|
||||
/// `initializationOptions.storagePath` — where the persistent index cache
|
||||
/// goes.
|
||||
pub(super) storage: Option<std::path::PathBuf>,
|
||||
/// `--verbose`: whether every operation says how long it took.
|
||||
pub(super) verbose: bool,
|
||||
/// What the client had already sent when the server was built — the
|
||||
/// opening burst, put straight onto the queue the wait and the startup
|
||||
/// scan drain. Empty for [`Server::new`]; a test fills it because racing
|
||||
/// the forwarder thread for it would make the test a coin toss rather
|
||||
/// than a check.
|
||||
pub(super) queued: Vec<Message>,
|
||||
/// How long to wait for the settings answer before scanning at the
|
||||
/// defaults. [`CONFIGURATION_WAIT`] in a real session; a test says what
|
||||
/// it means to test, and `Duration::ZERO` is the client that never
|
||||
/// answers.
|
||||
pub(super) wait: Duration,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the settings the client answered a
|
||||
/// `workspace/configuration` with — asked first thing and waited for, up
|
||||
/// to [`CONFIGURATION_WAIT`]. A client that cannot be asked, or that does
|
||||
/// not answer inside the bound, gets the scan at the **defaults**
|
||||
/// (including the folder scope) exactly as every client did before
|
||||
/// 2026-09-08, and pays one extra rescan if its settings land later.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
queued: Vec::new(),
|
||||
wait: CONFIGURATION_WAIT,
|
||||
};
|
||||
Server::started(connection, roots, startup)
|
||||
}
|
||||
|
||||
/// A server that owns nothing yet: no index, no settings, no roots — only
|
||||
/// its connection, what the client can do, and the queue its messages are
|
||||
/// already arriving on.
|
||||
///
|
||||
/// The forwarder starts here rather than in `run` because both the
|
||||
/// settings wait and the startup scan answer whatever the client has
|
||||
/// already sent, and they can only do that off a queue that is already
|
||||
/// being filled. `queued` is what a test says the client had sent by then.
|
||||
fn empty(
|
||||
connection: Connection,
|
||||
abilities: ClientAbilities,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
head_owed: false,
|
||||
staging: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
verbose,
|
||||
born: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Server::new`] with everything spelled out — the seam the tests start
|
||||
/// a session from.
|
||||
pub(super) fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
startup: Startup,
|
||||
) -> Server {
|
||||
let Startup { abilities, client, storage, verbose, queued, wait } = startup;
|
||||
let mut server = Server::empty(connection, abilities, verbose, queued);
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
server.workspace.adopt_roots(roots);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead.
|
||||
server.stage_for_configuration(wait);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
// The first index build is the slowest one of the session, so it gets
|
||||
// the same bar every later rescan gets. And it answers messages while
|
||||
// it runs — the ones the wait above set aside included — which is what
|
||||
// stops the first request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can be *opened* before or during the startup scan, and what
|
||||
// was published for it then was computed against a half-built index.
|
||||
// This is the same debt a rescan pays at the end of `reindex`, owed
|
||||
// here for the first time because before scan-interleave no buffer
|
||||
// could exist at this point. Nothing at all is sent when nothing is
|
||||
// open, which is every session whose client did not get a `didOpen`
|
||||
// in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
server
|
||||
}
|
||||
|
||||
/// Ask the client for its settings and hold everything until they arrive,
|
||||
/// so the one startup scan runs at the scope the client actually wants.
|
||||
///
|
||||
/// Silent for a client that never advertised `workspace/configuration`:
|
||||
/// that one is only ever *pushed* settings, so there is nothing to wait
|
||||
/// for and the scan runs at the defaults immediately, byte for byte as it
|
||||
/// always has.
|
||||
///
|
||||
/// [`Server::staging`] is what makes the window safe. While it is set,
|
||||
/// every rescan trigger a message pulls — a `didOpen` that widened the
|
||||
/// scope, a pushed setting, a save — records that one more scan is wanted
|
||||
/// instead of running one, and [`Server::must_wait`] holds every request.
|
||||
/// Clearing `rescan_wanted` afterwards is not dropping those asks: the
|
||||
/// scan about to run is the session's **first**, it resolves the scope
|
||||
/// afresh and reads every file in it from disk, and it runs at the
|
||||
/// settings that have just landed — so it is what every one of them was
|
||||
/// asking for.
|
||||
fn stage_for_configuration(&mut self, wait: Duration) {
|
||||
if !self.abilities.configuration {
|
||||
return;
|
||||
}
|
||||
self.staging = true;
|
||||
self.request_configuration();
|
||||
self.await_configuration(wait);
|
||||
// Inside the staging window, because it is the same window: every
|
||||
// request is still held, and the scan has still not begun.
|
||||
if !wait.is_zero() && !self.stopped {
|
||||
self.await_opening_file(OPENING_FILE_WAIT);
|
||||
}
|
||||
self.staging = false;
|
||||
self.rescan_wanted = false;
|
||||
}
|
||||
|
||||
/// Wait a bounded moment for the editor's first `didOpen`, when knowing
|
||||
/// which folder the user is in is what decides the shape of the scan
|
||||
/// about to run ([`OPENING_FILE_WAIT`]).
|
||||
///
|
||||
/// Silent for every session that would not spend the knowledge: only a
|
||||
/// workspace-scoped scan leads with a folder, and only one with nothing
|
||||
/// open has a folder still to learn. The loop stops on the first buffer
|
||||
/// rather than draining the bound, so the ordinary session pays what the
|
||||
/// message took to arrive and nothing more.
|
||||
///
|
||||
/// **Not a scope decision.** Which files the scan indexes is settled by
|
||||
/// the settings that have just landed; this decides only which of them it
|
||||
/// indexes *first*, which `vlog_semantic::IndexBuilder` cannot see
|
||||
/// (`crate::scan_order`).
|
||||
fn await_opening_file(&mut self, wait: Duration) {
|
||||
if !self.workspace.leads_with_a_folder() {
|
||||
return;
|
||||
}
|
||||
let asked = Instant::now();
|
||||
while self.workspace.open_uris().is_empty() {
|
||||
let Some(left) = wait.checked_sub(asked.elapsed()) else { return };
|
||||
let Ok(message) = self.queue.recv_timeout(left) else { return };
|
||||
let batch = burst(&self.queue, message);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the client's messages until it answers the settings pull, the
|
||||
/// bound runs out, or it goes away.
|
||||
///
|
||||
/// **The bound is observed on the receive itself.** `recv_timeout` with
|
||||
/// whatever is left of it blocks in the transport, wakes on the next
|
||||
/// message, and returns `Timeout` at the deadline — so there is no poll,
|
||||
/// no busy-wait and no clock the loop has to be woken to read. A client
|
||||
/// that answers late is not stranded: its answer arrives in `run` as an
|
||||
/// ordinary `Message::Response`, goes through the same `configured` →
|
||||
/// `apply_settings` it always did, and costs the one rescan a settings
|
||||
/// change has always cost — under the order contract, held requests and
|
||||
/// all.
|
||||
fn await_configuration(&mut self, wait: Duration) {
|
||||
if wait.is_zero() {
|
||||
return;
|
||||
}
|
||||
let asked = Instant::now();
|
||||
while self.pending.values().any(|p| matches!(p, Pending::Configuration(_))) {
|
||||
let Some(left) = wait.checked_sub(asked.elapsed()) else { return };
|
||||
let Ok(message) = self.queue.recv_timeout(left) else { return };
|
||||
let batch = burst(&self.queue, message);
|
||||
// A `shutdown` in the burst has already been through
|
||||
// `handle_shutdown` by the time this returns `Ok(true)`;
|
||||
// `started` then returns without scanning at all.
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
self.take_the_answer_out_of_held();
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a settings answer that a held request took down with it.
|
||||
///
|
||||
/// **Measured, not theorised** (2026-09-08): without this, one warm
|
||||
/// session in three waited the whole two-second bound and then rescanned,
|
||||
/// because `process_batch` moves *everything behind* a request that must
|
||||
/// wait into `held` — the rule that keeps a burst's arrival order intact
|
||||
/// across the wait — and the client's answer to the pull can be in that
|
||||
/// burst behind the editor's opening `textDocument/definition`. Left
|
||||
/// there, the loop above sees the pull still outstanding and blocks until
|
||||
/// the bound, which is the opposite of what staging is for.
|
||||
///
|
||||
/// Reordering it is sound because that rule is about the **client's**
|
||||
/// message stream. The answer to a request the *server* sent is not part
|
||||
/// of it: the client replies to a pull from wherever it handles
|
||||
/// server-initiated requests, and no ordering promise ties that reply to a
|
||||
/// request the editor happened to send at the same moment. Only a
|
||||
/// `Pending::Configuration` answer is taken — everything else in `held`,
|
||||
/// requests included, keeps its place and its order.
|
||||
fn take_the_answer_out_of_held(&mut self) {
|
||||
let waiting = std::mem::take(&mut self.held);
|
||||
let mut answers = Vec::new();
|
||||
for message in waiting {
|
||||
match message {
|
||||
Message::Response(response)
|
||||
if matches!(
|
||||
self.pending.get(&response.id),
|
||||
Some(Pending::Configuration(_))
|
||||
) =>
|
||||
{
|
||||
answers.push(response);
|
||||
}
|
||||
kept => self.held.push(kept),
|
||||
}
|
||||
}
|
||||
for answer in answers {
|
||||
self.response(answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -386,3 +386,35 @@ fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
|
||||
// cancel did not intercept it.
|
||||
session.answer(server_id, Value::Null);
|
||||
}
|
||||
|
||||
/// A request the empty-answer rule set aside (`Server::deferred`,
|
||||
/// perf5r-publication) is not in any burst, so the burst's own cancel rule
|
||||
/// cannot see it. A cancel for it must still be honoured where it lands:
|
||||
/// answered `RequestCancelled` at once, taken out of the deferred set, and
|
||||
/// never asked again when the scan ends. Found by QA on §61.4; the request is
|
||||
/// planted directly because a real deferral lives only inside a running scan.
|
||||
#[test]
|
||||
fn a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancel-deferred", ONE_MODULE);
|
||||
let parked = Request::new(
|
||||
RequestId::from(41),
|
||||
GotoDefinition::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 7 }
|
||||
}),
|
||||
);
|
||||
session.server.deferred.push(Message::Request(parked));
|
||||
|
||||
session.server.process_batch(vec![cancel(serde_json::json!(41))]).expect("a burst");
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(41), Some(CANCELLED))]);
|
||||
assert!(session.server.deferred.is_empty(), "the cancelled request is not asked again");
|
||||
|
||||
// And the scan's end finds nothing left to answer: exactly one response.
|
||||
session.server.answer_what_was_deferred();
|
||||
assert!(outcomes(&session).is_empty(), "a cancelled request is answered once");
|
||||
|
||||
// A cancel naming a request that is *not* deferred changes nothing.
|
||||
session.server.process_batch(vec![cancel(serde_json::json!(42))]).expect("a burst");
|
||||
assert!(outcomes(&session).is_empty());
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
//! What a `textDocument/codeAction` request does, and — just as much — what
|
||||
//! it no longer does.
|
||||
//!
|
||||
//! Take 5 §P1 (`docs/features/perf5-p1/README.md`) removed work from this
|
||||
//! path: an empty `context.only` answers before the configuration is read, the
|
||||
//! lint pass runs only when a fix family is asked for, the fence answer is
|
||||
//! computed only when a fix exists and only once per document revision, and
|
||||
//! the four refactoring selectors read the buffer's own parse instead of
|
||||
//! parsing its text again. Every one of those is asserted here **by counting
|
||||
//! parses**, not by timing them: `vlog_parser::stats::parses()` is a
|
||||
//! thread-local count and a request is answered on this thread.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A module with a tab in it — one `no-tabs` finding, carrying a Safe fix —
|
||||
/// an instantiation of `sub`, so the port and inline families have something
|
||||
/// to look at, and a comment line where nothing at all is offered.
|
||||
///
|
||||
/// Line 1 is the tab, line 2 the instantiation, line 3 the comment.
|
||||
const FIXABLE: &str = "module m;\n\twire a;\n sub u_sub (.a(a));\n // nothing here\nendmodule\n";
|
||||
|
||||
/// The declaration `FIXABLE` instantiates.
|
||||
const SUB: &str = "module sub (\n input logic a,\n input logic b\n);\nendmodule\n";
|
||||
|
||||
/// A finding with **no** fix: `module-filename` does not offer to rename a
|
||||
/// file. So a lint pass over this buffer produces a violation, and nothing
|
||||
/// that a fence could protect.
|
||||
const UNFIXABLE: &str = "module other;\nendmodule\n";
|
||||
|
||||
/// A zero-width range at a position — the shape an editor sends on a cursor
|
||||
/// move.
|
||||
fn cursor(uri: &Uri, line: u32, character: u32) -> Value {
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": line, "character": character },
|
||||
"end": { "line": line, "character": character },
|
||||
},
|
||||
"context": { "diagnostics": [] },
|
||||
})
|
||||
}
|
||||
|
||||
/// `cursor`, with a `context.only` filter.
|
||||
fn filtered(uri: &Uri, line: u32, character: u32, only: &[&str]) -> Value {
|
||||
let mut params = cursor(uri, line, character);
|
||||
params["context"]["only"] = serde_json::json!(only);
|
||||
params
|
||||
}
|
||||
|
||||
/// The whole-file parses one request performed.
|
||||
fn parses_during(session: &mut Session, params: Value) -> (u64, Value) {
|
||||
let before = vlog_parser::stats::parses();
|
||||
let result = session.result(CodeActionRequest::METHOD, params);
|
||||
(vlog_parser::stats::parses() - before, result)
|
||||
}
|
||||
|
||||
/// The titles an answer carries, in the order it carries them.
|
||||
fn titles(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an action list")
|
||||
.iter()
|
||||
.map(|action| action["title"].as_str().unwrap_or_default().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The kinds an answer carries, in order.
|
||||
fn kinds(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an action list")
|
||||
.iter()
|
||||
.map(|action| action["kind"].as_str().unwrap_or_default().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session over a tree holding `m.sv` and `sub.sv`, with `m.sv` open.
|
||||
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// [`opened`] against a client that can `codeAction/resolve` — the shape that
|
||||
/// is *offered* actions without their edits, which is the path §P1c changed.
|
||||
fn opened_lazily(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// §P1a — the work a filtered request no longer does
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_empty_only_filter_answers_empty_and_does_no_work_at_all() {
|
||||
let tree = Tree::new("caempty");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &[]));
|
||||
assert_eq!(result, serde_json::json!([]), "no kind is selected, so no action is");
|
||||
assert_eq!(
|
||||
parses, 0,
|
||||
"an empty filter reads no configuration, lints nothing and parses nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refactor_only_request_never_runs_the_lint_pass() {
|
||||
let tree = Tree::new("carefactor");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The buffer has a fixable finding, so a lint pass here would ask for the
|
||||
// fence regions — a whole-file parse of its own. One parse means exactly
|
||||
// one selector ran and the lint pass did not.
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["refactor.extract"]));
|
||||
assert_eq!(parses, 0, "the selector reads the buffer's own parse (§P1b): {result:#?}");
|
||||
assert!(
|
||||
!titles(&result).iter().any(|title| title.contains("no-tabs")),
|
||||
"and no quick fix is offered: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quickfix_only_request_never_runs_the_selectors() {
|
||||
let tree = Tree::new("caquickfix");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(parses, 1, "the fence parse alone — no selector ran: {result:#?}");
|
||||
assert_eq!(
|
||||
titles(&result),
|
||||
vec!["lucisv: use spaces, not tabs [no-tabs]".to_string()],
|
||||
"{result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_whose_findings_carry_no_fix_never_asks_about_fences() {
|
||||
let tree = Tree::new("canofix");
|
||||
let (mut session, uri) = opened(&tree, UNFIXABLE);
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 0, 0, &["quickfix"]));
|
||||
assert_eq!(result, serde_json::json!([]), "the finding has no fix to offer");
|
||||
assert_eq!(parses, 0, "and nothing to protect, so no fence parse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_filter_is_a_prefix_and_still_selects_the_whole_family() {
|
||||
let tree = Tree::new("caprefix");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// `source` selects `source.fixAll.lucisv`, which is a fix family: the
|
||||
// lint pass must run for it.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["source"]));
|
||||
assert_eq!(kinds(&result), vec!["source.fixAll.lucisv".to_string()], "{result:#?}");
|
||||
// `refactor` selects every refactoring family and no fix family.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
|
||||
assert!(
|
||||
kinds(&result).iter().all(|kind| kind.starts_with("refactor")),
|
||||
"no fix family under a refactor filter: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfiltered_request_keeps_the_order_quick_fixes_fix_all_then_refactorings() {
|
||||
let tree = Tree::new("caorder");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The cursor is on the tabbed line, so the quick fix is offered, and the
|
||||
// buffer's one instantiation puts a refactoring family behind it.
|
||||
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 1, 1));
|
||||
let kinds = kinds(&result);
|
||||
assert_eq!(kinds.first().map(String::as_str), Some("quickfix"), "{result:#?}");
|
||||
assert_eq!(kinds.get(1).map(String::as_str), Some("source.fixAll.lucisv"), "{result:#?}");
|
||||
// Everything after the two fix families is a refactoring, and there is at
|
||||
// least one — an answer of two actions would prove nothing about order.
|
||||
assert!(kinds.len() > 2, "a refactoring is offered here too: {result:#?}");
|
||||
assert!(
|
||||
kinds[2..].iter().all(|kind| kind.starts_with("refactor")),
|
||||
"the refactoring families come last: {kinds:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_spanning_the_cursor_is_still_offered() {
|
||||
let tree = Tree::new("caspan");
|
||||
// A trailing-whitespace finding whose span starts before the cursor and
|
||||
// ends after it: the cursor is *inside* the fix, not at its start.
|
||||
let (mut session, uri) = opened(&tree, "module m;\n wire a; \nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 10, &["quickfix"]));
|
||||
assert!(
|
||||
titles(&result).iter().any(|title| title.contains("no-trailing-whitespace")),
|
||||
"{result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_with_no_selection_is_still_offered_the_extraction() {
|
||||
let tree = Tree::new("cacursor");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// A zero-width range on a whole item: extraction takes the item the
|
||||
// cursor is in, so an empty selection must not disable it.
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
|
||||
assert!(
|
||||
kinds(&result).iter().any(|kind| kind == "refactor.extract"),
|
||||
"an empty range still extracts: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// §P1b — the work a repeated request no longer does
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_repeated_offer_where_nothing_is_offered_parses_nothing_at_all() {
|
||||
let tree = Tree::new("carepeat");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// The comment line: every family is asked, and every family answers
|
||||
// nothing, so the four gates are the whole of the work. This is the
|
||||
// pinmux-comment cursor of take 5's headline row, in miniature.
|
||||
let (first, expected) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert!(first <= 1, "the first request pays for the fence answer at most: {first}");
|
||||
// Every request after it, on the same revision, parses nothing: the four
|
||||
// selectors read `doc.tree` and the fence answer is the one already made.
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert_eq!(parses, 0, "round {round} re-parsed the buffer");
|
||||
assert_eq!(again, expected, "round {round} answered differently");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_only_families_parse_nothing_even_where_they_do_offer() {
|
||||
let tree = Tree::new("carepeatgate");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
// Extraction and inlining are answered by their gate alone — the offer
|
||||
// carries a command, not an edit, so no engine runs. On the
|
||||
// instantiation both of them offer, and neither parses.
|
||||
let only = &["refactor.extract", "refactor.inline"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(kinds(&first).len(), 2, "both families offer here: {first:#?}");
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(parses, 0, "round {round}");
|
||||
assert_eq!(again, first, "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_port_offer_reads_the_declaring_file_once_and_nothing_else() {
|
||||
let tree = Tree::new("carepeatports");
|
||||
let (mut session, uri) = opened_lazily(&tree, FIXABLE);
|
||||
// §P1b gave the port family its *gate* for free, but a gate that said yes
|
||||
// still handed the engine one or two files and paid for four verified
|
||||
// plans whose edits were thrown away — 21.15 ms of a 21.83 ms request on
|
||||
// opentitan. §P1c replaced that with a predicate that reads the buffer's
|
||||
// own parse and, at most, one parse of the instantiated module's
|
||||
// declaring file. This assertion is what would notice a second one
|
||||
// reappearing.
|
||||
let only = &["refactor.rewrite.lucisv.ports"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert!(!kinds(&first).is_empty(), "the port family offers here: {first:#?}");
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
|
||||
assert_eq!(parses, 1, "round {round}: `sub.sv`'s parse, and no other (§P1c)");
|
||||
assert_eq!(again, first, "round {round}: and the same menu every time");
|
||||
}
|
||||
// The buffer's *own* parse is not among them: the gate was answered from
|
||||
// `doc.tree`, and so is everything the predicate asks of the buffer.
|
||||
let (gate_only, _) = parses_during(&mut session, filtered(&uri, 3, 2, only));
|
||||
assert_eq!(gate_only, 0, "at a cursor the gate refuses, nothing is parsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_organize_imports_offer_never_parses_the_buffer_it_is_offered_on() {
|
||||
let tree = Tree::new("caimports");
|
||||
tree.write("a_pkg.sv", "package a_pkg;\n localparam int A = 1;\nendpackage\n");
|
||||
tree.write("b_pkg.sv", "package b_pkg;\n localparam int B = 2;\nendpackage\n");
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(
|
||||
&tree.path.join("user.sv"),
|
||||
"module user;\n import b_pkg::*;\n import a_pkg::*;\n logic q;\n assign q = A;\nendmodule\n",
|
||||
);
|
||||
session.drain();
|
||||
let only = &["source.organizeImports"];
|
||||
let (_, first) = parses_during(&mut session, filtered(&uri, 1, 2, only));
|
||||
assert_eq!(
|
||||
titles(&first),
|
||||
vec!["lucisv: organize imports (removes 1, sorts 1)".to_string()],
|
||||
"the unused import goes and the used one is written back: {first:#?}"
|
||||
);
|
||||
// The buffer's own parse, analysis and token stream are the `Document`'s,
|
||||
// and no splice is verified for a menu (§P1c). What is left is one
|
||||
// `Scope::build` — the index that decides which import supplies a used
|
||||
// name — over the buffer and the two packages it imports: **3** parses,
|
||||
// where verifying the splice used to build a second index over the same
|
||||
// three and re-analyze them. The buffer's own share of that index is the
|
||||
// residue §P1c names and does not remove.
|
||||
for round in 0..3 {
|
||||
let (parses, again) = parses_during(&mut session, filtered(&uri, 1, 2, only));
|
||||
assert_eq!(parses, 3, "round {round}: one index over the buffer and its two packages");
|
||||
assert_eq!(again, first, "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offer_the_fan_out_refuses_says_so_on_resolve_rather_than_crashing() {
|
||||
let tree = Tree::new("caresolvegone");
|
||||
tree.write("sub.sv", SUB);
|
||||
// `sub`'s one instantiation connects by position, which makes the removal
|
||||
// refuse whole — but it lives in a file the *offer* never reads, since an
|
||||
// offer reads the buffer and the module's declaration and nothing else
|
||||
// (`docs/features/lazy-code-action/README.md`). So the lightbulb appears
|
||||
// and the click declines: the contract §P1c inherited and did not widen.
|
||||
tree.write(
|
||||
"other.sv",
|
||||
"module other;\n logic x;\n logic y;\n sub u_pos (x, y);\nendmodule\n",
|
||||
);
|
||||
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), SUB);
|
||||
session.drain();
|
||||
|
||||
let only = &["refactor.rewrite.lucisv.ports"];
|
||||
let offered = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 14, only));
|
||||
let titles = titles(&offered);
|
||||
assert_eq!(
|
||||
titles,
|
||||
vec!["lucisv: remove port `b` (updates 1 instantiation)".to_string()],
|
||||
"the offer is made, counted from the index: {offered:#?}"
|
||||
);
|
||||
let action = offered.as_array().and_then(|list| list.first()).expect("the offer").clone();
|
||||
assert!(action.get("edit").is_none(), "a lazy offer carries no edit: {action:#?}");
|
||||
|
||||
let refused = session.request(CodeActionResolveRequest::METHOD, action);
|
||||
let error = refused.response_result.expect_err("the fan-out refuses this removal");
|
||||
assert_eq!(error.message, "lucisv: the action is no longer available.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_filter_parses_nothing_however_often_it_is_asked() {
|
||||
let tree = Tree::new("carepeatempty");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
for round in 0..4 {
|
||||
let (parses, result) = parses_during(&mut session, filtered(&uri, 2, 2, &[]));
|
||||
assert_eq!(parses, 0, "round {round}");
|
||||
assert_eq!(result, serde_json::json!([]), "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_offer_after_a_change_parses_the_buffer_once_and_no_more() {
|
||||
let tree = Tree::new("cachange");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let _ = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
// A `didChange` is flushed by the request behind it, so the parse
|
||||
// `Document::new` makes is counted inside this request — one parse, plus
|
||||
// the fence answer, and nothing from the four selectors.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": format!("{FIXABLE}// changed\n") }],
|
||||
}),
|
||||
);
|
||||
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert!(parses <= 2, "the document's own parse, plus at most the fence answer: {parses}");
|
||||
// And the request after that one is free again.
|
||||
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
|
||||
assert_eq!(parses, 0, "the new revision is reused like any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_typed_into_the_buffer_is_seen_by_the_next_request() {
|
||||
let tree = Tree::new("cafence");
|
||||
// A tab on line 1: a `no-tabs` finding with a Safe fix, offered as a
|
||||
// quick fix.
|
||||
let (mut session, uri) = opened(&tree, "module m;\n\twire a;\nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&result).len(), 1, "the fix is offered: {result:#?}");
|
||||
// Now fence that line. The memo is held on the `Document`, and a change
|
||||
// builds a new one — so the answer must be the new text's, not the old
|
||||
// text's.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{
|
||||
"text": "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n",
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 1, &["quickfix"]));
|
||||
assert!(result.as_array().expect("a list").is_empty(), "fenced: {result:#?}");
|
||||
// And back again: removing the fence restores the fix, which a memo that
|
||||
// outlived its revision could not do.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 3 },
|
||||
"contentChanges": [{ "text": "module m;\n\twire a;\nendmodule\n" }],
|
||||
}),
|
||||
);
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&result).len(), 1, "unfenced again: {result:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_external_waiver_still_keeps_its_fix_out_of_the_offer() {
|
||||
let tree = Tree::new("cawaiver");
|
||||
tree.write("waivers.txt", "no-tabs\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\twire a;\nendmodule\n");
|
||||
session.drain();
|
||||
// Without the waiver configured the fix is there.
|
||||
let before = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert_eq!(titles(&before).len(), 1, "{before:#?}");
|
||||
// A `lucisv.toml` written between requests changes the pass, and the
|
||||
// configuration is read per request — nothing about it is memoized.
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
|
||||
let after = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
|
||||
assert!(after.as_array().expect("a list").is_empty(), "the new config is read: {after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_is_offered_the_fix_families_and_no_refactoring() {
|
||||
let tree = Tree::new("cauntitled");
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||
session.notify(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": FIXABLE,
|
||||
}
|
||||
}),
|
||||
);
|
||||
session.drain();
|
||||
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert!(
|
||||
!kinds(&result).iter().any(|kind| kind == "refactor.extract"),
|
||||
"an untitled buffer has no directory to extract into: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_with_crlf_endings_and_an_astral_character_offers_the_same_actions() {
|
||||
let tree = Tree::new("cacrlf");
|
||||
let lf = "// \u{1F600}\nmodule m;\n sub u_sub (.a(1));\nendmodule\n";
|
||||
let (mut session, uri) = opened(&tree, lf);
|
||||
// Line 2, character 2 is inside the instantiation in both encodings; the
|
||||
// comment above it puts a non-BMP character in front of every offset, so
|
||||
// the UTF-16 conversion is doing real work.
|
||||
let plain = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": lf.replace('\n', "\r\n") }],
|
||||
}),
|
||||
);
|
||||
let windows = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert_eq!(titles(&plain), titles(&windows), "{plain:#?}\n{windows:#?}");
|
||||
assert_eq!(kinds(&plain), kinds(&windows));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_offers_what_it_always_offered() {
|
||||
let tree = Tree::new("cabroken");
|
||||
let (mut session, uri) =
|
||||
opened(&tree, "module m;\n sub u_sub (.a(1));\n logic ;;; w\nendmodule\n");
|
||||
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 6, &["refactor"]));
|
||||
// The three gates that refuse over parse diagnostics still refuse; the
|
||||
// port family, which never had that check, still answers.
|
||||
assert!(
|
||||
!kinds(&result).iter().any(|kind| kind == "refactor.extract" || kind == "refactor.inline"),
|
||||
"a broken parse offers no extraction and no inline: {result:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_refresh_does_not_change_what_the_cursor_offers() {
|
||||
let tree = Tree::new("careindex");
|
||||
let (mut session, uri) = opened(&tree, FIXABLE);
|
||||
let before = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
// A saved file elsewhere rebuilds the index; the buffer is untouched, so
|
||||
// its own parse — and its fence answer — stay exactly as they were.
|
||||
tree.write("other.sv", "module other_one;\nendmodule\n");
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.drain();
|
||||
let after = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
|
||||
assert_eq!(titles(&before), titles(&after), "{before:#?}\n{after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_still_answers_its_command_from_its_text() {
|
||||
// The large-file fast path installs the analysis of the *empty* file, so
|
||||
// a `doc.tree` reader would find nothing in a large buffer. The four
|
||||
// selectors therefore keep their text form there — which is exactly what
|
||||
// they did before §P1b, and this pins it.
|
||||
//
|
||||
// `textDocument/codeAction` cannot show it: the fast path answers that
|
||||
// method with an empty list before the dispatch is entered
|
||||
// (`server/large_file.rs`). `workspace/executeCommand` is not gated, and
|
||||
// is where a large buffer really does reach a selector.
|
||||
let tree = Tree::new("calarge");
|
||||
tree.write("sub.sv", SUB);
|
||||
let mut body = String::from("module big;\n logic a;\n sub u_sub (.a(a), .b(a));\n");
|
||||
for i in 0..20 {
|
||||
body.push_str(&format!(" logic pad{i};\n"));
|
||||
}
|
||||
body.push_str("endmodule\n");
|
||||
assert!(body.len() > 100, "the premise: over the test threshold");
|
||||
let settings = crate::settings::ClientSettings {
|
||||
large_file_threshold: 100,
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
let mut session =
|
||||
Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings);
|
||||
let path = tree.path.join("big.sv");
|
||||
std::fs::write(&path, &body).expect("write");
|
||||
let uri = session.open(&path, &body);
|
||||
session.drain();
|
||||
let response = session.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": crate::inline_module::INLINE_MODULE,
|
||||
"arguments": [uri, { "line": 2, "character": 2 }],
|
||||
}),
|
||||
);
|
||||
let refusal = match response.response_result {
|
||||
Ok(_) => None,
|
||||
Err(error) => Some(error.message),
|
||||
};
|
||||
assert_ne!(
|
||||
refusal.as_deref(),
|
||||
Some("there is no module instantiation at this position to inline."),
|
||||
"a large buffer's selector reads its text, so the instantiation is found"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Topology handshake 33: the file that reaches an instance through modules
|
||||
//! it does not itself instantiate.
|
||||
//!
|
||||
//! `tb.sv` writes `u_wrapper.u_top.u_sub.s`. It instantiates `wrapper`;
|
||||
//! `wrapper` instantiates `top`; `top` is where `sub u_sub (…)` is written and
|
||||
//! where the inline happens. None of `module_sources`' four rungs asks for
|
||||
//! `tb.sv` — it declares neither `sub` nor `top`, refers to neither, and
|
||||
//! instantiates neither — so `inline/mod.rs::no_hierarchy` never saw the path
|
||||
//! and the inline was **silently accepted**, dissolving a scope a testbench
|
||||
//! walks through. §53.2's QA reproduced exactly this.
|
||||
//!
|
||||
//! `module_select`'s fifth rung is the fix and this file is its pin: the
|
||||
//! ladder, the deeper ladder, the shapes the rung must **not** walk, and the
|
||||
//! callers whose answers must not move.
|
||||
|
||||
use super::*;
|
||||
use crate::module_select::Reach;
|
||||
use crate::state::Workspace;
|
||||
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
logic s;
|
||||
assign s = a;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (
|
||||
.a(x),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const WRAPPER: &str = "\
|
||||
module wrapper (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
top u_top (
|
||||
.x(x),
|
||||
.z(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The instantiation of `sub` in `top.sv`: line 4, on the module name.
|
||||
fn inline_cursor() -> Value {
|
||||
serde_json::json!({ "line": 4, "character": 2 })
|
||||
}
|
||||
|
||||
/// A tree holding the three-level ladder, with `tb.sv` written by the caller
|
||||
/// so each test can say what the bench does.
|
||||
fn ladder(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
tree.write("wrapper.sv", WRAPPER);
|
||||
tree
|
||||
}
|
||||
|
||||
/// A wide session with `top.sv` open, ready to be asked to inline.
|
||||
fn opened(tree: &Tree) -> (Session, Uri) {
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// Run `lucisv.inlineModule` at the `sub` instantiation; `Err` is the
|
||||
/// engine's own sentence.
|
||||
fn inline(session: &mut Session, uri: &Uri) -> Result<Value, String> {
|
||||
let response = session.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": crate::inline_module::INLINE_MODULE,
|
||||
"arguments": [uri, inline_cursor()],
|
||||
}),
|
||||
);
|
||||
response.response_result.map_err(|error| error.message)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bench_two_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33ladder");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("the bench names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("tb.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bench_three_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33deep");
|
||||
tree.write(
|
||||
"outer.sv",
|
||||
"module outer (\n input logic x,\n output logic z\n);\n\
|
||||
\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n outer u_outer (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_outer.u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("three levels up is still the same scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("tb.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_level_the_four_rungs_already_saw_still_refuses() {
|
||||
// `wrapper.sv` instantiates `top` directly, so it was always in the set.
|
||||
// The fifth rung must not change what the fourth already answered.
|
||||
let tree = ladder("h33direct");
|
||||
tree.write(
|
||||
"wrapper.sv",
|
||||
"module wrapper (\n input logic x,\n output logic z\n);\n\
|
||||
\n top u_top (.x(x), .z(z));\n logic peek;\n assign peek = u_top.u_sub.s;\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("the direct parent names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("wrapper.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ladder_nobody_reaches_into_still_inlines() {
|
||||
// The rung selects more files; selecting them must not invent a refusal.
|
||||
let tree = ladder("h33clean");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let edit = inline(&mut session, &uri).expect("nothing names the instance");
|
||||
assert!(edit.is_object() || edit.is_null(), "{edit:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_scope_two_levels_above_is_refused_and_stays_refused() {
|
||||
let tree = ladder("h33generate");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("a generated path walks the same scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_two_levels_above_the_instance_refuses_the_inline() {
|
||||
let tree = ladder("h33bind");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"sva.sv",
|
||||
"module checker_m (input logic a);\nendmodule\n\
|
||||
\nbind tb.u_wrapper.u_top.u_sub checker_m u_chk (.a(1'b0));\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("a bind names the instance as a scope");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
assert!(refusal.contains("sva.sv"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_bench_that_adds_the_path_refuses_the_inline() {
|
||||
// The bench on disk names nothing; the buffer does. Open buffers are a
|
||||
// rung of their own, and this pins that the fifth rung did not displace
|
||||
// it.
|
||||
let tree = ladder("h33unsaved");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
session.open(
|
||||
&tree.path.join("tb.sv"),
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
session.drain();
|
||||
let refusal = inline(&mut session, &uri).expect_err("the unsaved text names the instance");
|
||||
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_declaration_of_the_inlined_module_still_refuses_for_being_ambiguous() {
|
||||
let tree = ladder("h33duplicate");
|
||||
tree.write("sub_again.sv", SUB);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
|
||||
);
|
||||
let (mut session, uri) = opened(&tree);
|
||||
let refusal = inline(&mut session, &uri).expect_err("two `sub`s is ambiguous");
|
||||
assert!(refusal.contains("sub"), "{refusal}");
|
||||
assert!(
|
||||
!refusal.contains("named as a scope of the design hierarchy"),
|
||||
"the ambiguity refusal, not the hierarchy one: {refusal}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_hiding_the_path_selects_the_file_and_still_does_not_refuse() {
|
||||
// Today's behaviour, pinned rather than asserted to be right. The fifth
|
||||
// rung *does* hand `tb.sv` over — `words::harvest` splits raw text, so
|
||||
// `u_sub` written inside a `` `define`` body is in the file's census. But
|
||||
// `no_hierarchy` tokenizes, and a directive line is one opaque token, so
|
||||
// there is no `Ident` spelling `u_sub` for it to find. The selection is
|
||||
// not the limit here; the lexical refusal is. The whole-workspace engine
|
||||
// answers exactly the same way, which is the parity that matters.
|
||||
let tree = ladder("h33macro");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"`define PEEK u_wrapper.u_top.u_sub.s\n\
|
||||
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", `PEEK);\nendmodule\n",
|
||||
);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let selected = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
|
||||
assert!(selected.contains(&tree.path.join("tb.sv")), "the census sees raw text: {selected:?}");
|
||||
let (mut session, uri) = opened(&tree);
|
||||
inline(&mut session, &uri).expect("a macro-hidden path is not a token `no_hierarchy` can see");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rung_is_the_instances_word_census_and_nothing_wider() {
|
||||
// A package, an interface and a class are not scopes an inline dissolves,
|
||||
// and the rung is keyed by the instance's spelling alone — so a caller
|
||||
// that names one of them by mistake selects only the files that really
|
||||
// do write that word.
|
||||
let tree = Tree::new("h33units");
|
||||
tree.write("p.sv", "package p;\n localparam K = 1;\nendpackage\n");
|
||||
tree.write("user.sv", "module user;\n import p::*;\n logic a;\nendmodule\n");
|
||||
tree.write("stranger.sv", "module stranger;\n logic b;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let scopes = ["p".to_string()];
|
||||
let found = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
|
||||
assert_eq!(
|
||||
found,
|
||||
[tree.path.join("p.sv"), tree.path.join("user.sv")].into_iter().collect(),
|
||||
"{found:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selected_set_answers_the_inline_exactly_as_the_whole_workspace_does() {
|
||||
// The claim the fifth rung is worth having: `no_hierarchy` refuses from a
|
||||
// token census, and the rung *is* that census, so the narrowed set and
|
||||
// `sources()` cannot disagree. Six shapes, each run through the engine
|
||||
// twice — the one the four rungs missed, the one they saw, the bind, the
|
||||
// generated path, the macro-hidden path, and the clean ladder.
|
||||
let benches = [
|
||||
("h33p1", " initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\n", ""),
|
||||
("h33p2", "", ""),
|
||||
("h33p3", "", "module chk (input logic a);\nendmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n"),
|
||||
("h33p4", " initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\n", ""),
|
||||
("h33p5", " initial $display(\"%b\", `PEEK);\n", ""),
|
||||
("h33p6", " initial $display(\"%b\", u_wrapper.u_top.z);\n", ""),
|
||||
];
|
||||
for (name, extra, sva) in benches {
|
||||
let tree = ladder(name);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
&format!(
|
||||
"`define PEEK u_wrapper.u_top.u_sub.s\n\
|
||||
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n{extra}endmodule\n"
|
||||
),
|
||||
);
|
||||
if !sva.is_empty() {
|
||||
tree.write("sva.sv", sva);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("top.sv");
|
||||
let offset = TOP.find("sub u_sub").expect("the instantiation") as u32;
|
||||
let units = ["sub".to_string(), "top".to_string()];
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let narrowed = ws.module_sources_reaching(&path, &units, Reach { scopes: &scopes });
|
||||
let whole = ws.sources();
|
||||
assert_eq!(
|
||||
vlog_refactor::inline_module(&narrowed, &path, offset).map(|edit| edit.edits),
|
||||
vlog_refactor::inline_module(&whole, &path, offset).map(|edit| edit.edits),
|
||||
"{name}: the narrowed set and the whole workspace disagree"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_four_rung_selector_answers_exactly_what_it_did_before() {
|
||||
// Every other caller of `module_sources` — the port actions, extract —
|
||||
// asks with no reach, and the fifth rung must therefore be invisible to
|
||||
// them. Asserted as an equality against the rungs' own answer rather
|
||||
// than as a count, so a file appearing is a failure whatever its name.
|
||||
let tree = ladder("h33unchanged");
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
|
||||
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
|
||||
);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let units = ["sub".to_string(), "top".to_string()];
|
||||
let path = tree.path.join("top.sv");
|
||||
let four: Vec<PathBuf> =
|
||||
ws.module_sources(&path, &units).into_iter().map(|(path, _)| path).collect();
|
||||
assert_eq!(
|
||||
four,
|
||||
vec![tree.path.join("sub.sv"), tree.path.join("top.sv"), tree.path.join("wrapper.sv")],
|
||||
"the four rungs, unchanged — and `tb.sv` is exactly what they miss"
|
||||
);
|
||||
let scopes = ["u_sub".to_string()];
|
||||
let five: Vec<PathBuf> = ws
|
||||
.module_sources_reaching(&path, &units, Reach { scopes: &scopes })
|
||||
.into_iter()
|
||||
.map(|(path, _)| path)
|
||||
.collect();
|
||||
assert!(five.contains(&tree.path.join("tb.sv")), "{five:?}");
|
||||
for path in &four {
|
||||
assert!(five.contains(path), "the fifth rung only ever adds: {path:?} went missing");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! One test per row of the lint snapshot's invalidation table.
|
||||
//!
|
||||
//! Take 5 **review** round §R1a
|
||||
//! (`docs/features/perf5r-lint-snapshot/README.md`). A `Document` keeps the
|
||||
//! findings of one `lint_with` pass so that the diagnostics publish and
|
||||
//! quick-fix discovery do not run the same 21 ms twice on one revision. What
|
||||
//! makes that legitimate is that **every input which can change the answer
|
||||
//! either builds a new `Document`, or is in the key, or clears the slot** —
|
||||
//! and the README's table has one row per input.
|
||||
//!
|
||||
//! This file walks that table through the real doors: a `didChange`, a
|
||||
//! `didChangeConfiguration`, a `lucisv.toml` rewritten on disk, a waiver file
|
||||
//! rewritten in place, a watched file in **another** buffer, a close and
|
||||
//! reopen, a UTF-16 range, a large buffer — and one attack, a fix offered for
|
||||
//! a span the buffer no longer has.
|
||||
//!
|
||||
//! Reuse is observed by pointer, not by a stopwatch: two passes that share a
|
||||
//! snapshot answer with the same `Arc`, and one that recomputed cannot. A
|
||||
//! timing assertion on a lint pass would be a flake; `Arc::ptr_eq` is not.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vlog_linter::Violation;
|
||||
|
||||
use super::*;
|
||||
use crate::lint::{fixable, violations_in, LintRun};
|
||||
|
||||
/// A module with one tab in it: one `no-tabs` finding, carrying a Safe fix
|
||||
/// whose text is the indent width. Line 1 is the tab.
|
||||
const TABBED: &str = "module m;\n\twire a;\nendmodule\n";
|
||||
|
||||
/// A session over `tree` with `m.sv` open, its diagnostics already published.
|
||||
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
let _ = session.drain();
|
||||
(session, uri)
|
||||
}
|
||||
|
||||
/// The findings quick-fix discovery would offer for `uri` right now, taken
|
||||
/// through the same two calls the dispatcher makes.
|
||||
fn offered(session: &Session, uri: &Uri) -> Arc<[Violation]> {
|
||||
let doc = session.server.workspace.document(uri).expect("an open buffer");
|
||||
let run = LintRun::for_document(&session.server.workspace, doc);
|
||||
fixable(&run, doc)
|
||||
}
|
||||
|
||||
/// The rules that fired, by name, in the order they fired.
|
||||
fn rules(found: &[Violation]) -> Vec<&'static str> {
|
||||
found.iter().map(|violation| violation.rule).collect()
|
||||
}
|
||||
|
||||
/// The replacement text of the first fix, for the rows about fix bytes.
|
||||
fn fix_text(found: &[Violation]) -> String {
|
||||
let fix = found.first().and_then(|v| v.fix.as_ref()).expect("a fix");
|
||||
fix.edits.first().map(|(_, text)| text.clone()).expect("an edit")
|
||||
}
|
||||
|
||||
/// Push one `lucisv.lint.*` section and let the republish it triggers settle.
|
||||
fn push_lint_settings(session: &mut Session, lint: Value) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
|
||||
);
|
||||
let _ = session.drain();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the headline: one pass, two consumers
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The whole point of the round. A `didOpen` publishes diagnostics, which
|
||||
/// lints; the code action that follows reads **that** answer rather than
|
||||
/// running the rules again, and the two are the same object.
|
||||
#[test]
|
||||
fn the_diagnostics_publish_and_the_quick_fix_pass_share_one_lint() {
|
||||
let tree = Tree::new("lsshare");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(
|
||||
!doc.lint.is_empty(),
|
||||
"the publish that answered the didOpen left its findings on the document"
|
||||
);
|
||||
let run = LintRun::for_document(&session.server.workspace, doc);
|
||||
let published = violations_in(doc, &run);
|
||||
let fixes = fixable(&run, doc);
|
||||
assert!(Arc::ptr_eq(&published, &fixes), "one pass answers both doors");
|
||||
assert_eq!(rules(&published), vec!["no-tabs"]);
|
||||
// ... and asking twice more does not compute twice more.
|
||||
assert!(Arc::ptr_eq(&fixes, &fixable(&run, doc)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 1 — the buffer's own text
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_edited_buffer_is_relinted() {
|
||||
let tree = Tree::new("lsedit");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "module m;\n wire a;\nendmodule\n" }]),
|
||||
);
|
||||
assert!(
|
||||
offered(&session, &uri).is_empty(),
|
||||
"the tab is gone, so the finding and its fix are gone"
|
||||
);
|
||||
|
||||
change(&mut session, &uri, 3, serde_json::json!([{ "text": TABBED }]));
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and back again");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 2 — the large-file fast path
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_lints_nothing_and_stores_nothing() {
|
||||
let tree = Tree::new("lslarge");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 16 } } } }),
|
||||
);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TABBED);
|
||||
let _ = session.drain();
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(doc.large, "premise: over the threshold");
|
||||
assert!(doc.lint.is_empty(), "a large buffer's publish lints nothing to keep");
|
||||
let menu = session.result(
|
||||
CodeActionRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 1 },
|
||||
"end": { "line": 1, "character": 1 } },
|
||||
"context": { "diagnostics": [] },
|
||||
}),
|
||||
);
|
||||
assert_eq!(menu, serde_json::json!([]), "and offers nothing");
|
||||
let doc = session.server.workspace.document(&uri).expect("open");
|
||||
assert!(doc.lint.is_empty(), "the request left no snapshot behind either");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 3 and 11 — the rule selection, pushed by the editor
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_pushed_rule_selection_is_relinted() {
|
||||
let tree = Tree::new("lsselect");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
push_lint_settings(&mut session, serde_json::json!({ "ignore": ["no-tabs"] }));
|
||||
assert!(offered(&session, &uri).is_empty(), "the setting silenced the rule and its fix");
|
||||
|
||||
push_lint_settings(&mut session, serde_json::json!({ "ignore": [] }));
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and un-silenced it");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 4, 5, 8 and 12 — the `lucisv.toml`, rewritten under a running server
|
||||
// with no watcher event of any kind
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_rewritten_toml_is_relinted() {
|
||||
let tree = Tree::new("lstoml");
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert!(offered(&session, &uri).is_empty(), "premise: the project ignores the rule");
|
||||
|
||||
// Rewritten behind the server's back. `watch::SOURCE_GLOB` covers
|
||||
// `**/*.{v,vh,sv,svh}` and the filelist, so **no event is sent** — the
|
||||
// only thing that can notice is the per-request read and the key.
|
||||
tree.write("lucisv.toml", "[lint]\nignore = [\"posix-eof\"]\n");
|
||||
assert_eq!(
|
||||
rules(&offered(&session, &uri)),
|
||||
vec!["no-tabs"],
|
||||
"the next request read the new file"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 6 — the indent width, which is a fix's bytes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_tab_width_change_rewrites_the_fix() {
|
||||
let tree = Tree::new("lsindent");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(fix_text(&offered(&session, &uri)), " ", "premise: the default indent");
|
||||
|
||||
tree.write("lucisv.toml", "indent = 4\n");
|
||||
assert_eq!(
|
||||
fix_text(&offered(&session, &uri)),
|
||||
" ",
|
||||
"the same finding, a different fix — and the snapshot must not hand back the old one"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 7 — an external waiver file, rewritten in place
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_rewritten_waiver_file_is_relinted() {
|
||||
let tree = Tree::new("lswaiver");
|
||||
tree.write("lucisv.toml", "[lint]\nwaivers = [\"team.waiver\"]\n");
|
||||
tree.write("team.waiver", "waive --rule=no-tabs\n");
|
||||
let (session, uri) = opened(&tree, TABBED);
|
||||
assert!(offered(&session, &uri).is_empty(), "premise: the waiver silences it");
|
||||
|
||||
// Rewritten to name a different rule. The two texts are different
|
||||
// lengths, so this row alone would pass on a length check too — the
|
||||
// same-length case is `lint_snapshot::tests`'
|
||||
// `a_waiver_rewritten_in_place_is_a_different_key`.
|
||||
tree.write("team.waiver", "waive --rule=posix-eof\n");
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "the waiver moved");
|
||||
|
||||
tree.write("team.waiver", "waive --rule=no-tabs\n");
|
||||
assert!(offered(&session, &uri).is_empty(), "and moved back");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// rows 9 and 10 — the workspace index the census oracle reads
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A change in **another** file, which is the row a document-revision key
|
||||
/// could not have covered: this buffer's bytes never move, and what the
|
||||
/// semantic rules say about it does.
|
||||
#[test]
|
||||
fn a_change_in_another_file_relints_this_one() {
|
||||
let tree = Tree::new("lsoracle");
|
||||
let dut = "module dut;\n logic dbg_probe;\nendmodule\n";
|
||||
tree.write("dut.sv", dut);
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
|
||||
);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("dut.sv"), dut);
|
||||
let _ = session.drain();
|
||||
assert!(
|
||||
offered(&session, &uri).is_empty(),
|
||||
"premise: another file reads the signal, so it is not unused"
|
||||
);
|
||||
|
||||
// The other file stops mentioning it, and the watcher says so.
|
||||
tree.write("tb.sv", "module tb;\n dut d ();\nendmodule\n");
|
||||
session.watched(&[tree.path.join("tb.sv")]);
|
||||
let _ = session.drain();
|
||||
assert_eq!(
|
||||
rules(&offered(&session, &uri)),
|
||||
vec!["unused-signal"],
|
||||
"the index moved, so the snapshot had to go"
|
||||
);
|
||||
|
||||
tree.write(
|
||||
"tb.sv",
|
||||
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
|
||||
);
|
||||
session.watched(&[tree.path.join("tb.sv")]);
|
||||
let _ = session.drain();
|
||||
assert!(offered(&session, &uri).is_empty(), "and back");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 13 — close and reopen
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_closed_and_reopened_buffer_is_relinted() {
|
||||
let tree = Tree::new("lsreopen");
|
||||
let (mut session, uri) = opened(&tree, TABBED);
|
||||
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
let _ = session.drain();
|
||||
assert!(session.server.workspace.document(&uri).is_none(), "the snapshot went with it");
|
||||
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
assert!(offered(&session, &uri).is_empty(), "reopened with different text, relinted");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// row 14 — a fix's range, in UTF-16 units, off a reused snapshot
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The snapshot holds byte spans; the range on the wire is built per request
|
||||
/// from the buffer's text. A reused snapshot must therefore still produce
|
||||
/// UTF-16 columns, which is the one place a cached *position* would have gone
|
||||
/// wrong.
|
||||
#[test]
|
||||
fn a_snapshot_fix_keeps_its_utf16_range() {
|
||||
let tree = Tree::new("lsutf16");
|
||||
// The `é` is two bytes and one UTF-16 unit; `🎉` is four bytes and two.
|
||||
let text = "module m;\n // é 🎉\twire a;\nendmodule\n";
|
||||
let (mut session, uri) = opened(&tree, text);
|
||||
let ask = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 9 },
|
||||
"end": { "line": 1, "character": 9 } },
|
||||
"context": { "diagnostics": [] },
|
||||
});
|
||||
// Twice: the first request may compute, the second is the reuse — and
|
||||
// both must name the same UTF-16 column.
|
||||
let first = session.result(CodeActionRequest::METHOD, ask.clone());
|
||||
let again = session.result(CodeActionRequest::METHOD, ask);
|
||||
assert_eq!(first, again, "the reused answer is the computed one");
|
||||
let edit = &first[0]["edit"]["changes"][uri.as_str()][0];
|
||||
assert_eq!(edit["range"]["start"]["character"], 9, "in UTF-16 units, not bytes");
|
||||
assert_eq!(edit["range"]["start"]["line"], 1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the attack
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The failure the previous lane deferred this memo over: a **stale fix
|
||||
/// offer**. The buffer is edited so the bytes a previously offered fix named
|
||||
/// no longer exist; the next menu must not offer that fix, and must not offer
|
||||
/// an edit whose range runs past the end of the buffer.
|
||||
#[test]
|
||||
fn a_fix_is_never_offered_for_a_span_the_buffer_no_longer_has() {
|
||||
let tree = Tree::new("lsattack");
|
||||
// Two tabs, far apart, so the second fix's span is deep into the buffer.
|
||||
let long = format!("module m;\n\twire a;\n{}\twire z;\nendmodule\n", " // pad\n".repeat(40));
|
||||
let (mut session, uri) = opened(&tree, &long);
|
||||
let before = offered(&session, &uri);
|
||||
assert_eq!(before.len(), 2, "two tabs, two fixes: {:?}", rules(&before));
|
||||
let deepest = before.iter().map(|v| v.span.end).max().expect("a span");
|
||||
assert!(deepest as usize > 40, "premise: the fix is deep in the buffer");
|
||||
|
||||
// Now the buffer becomes three lines long. Every byte the second fix
|
||||
// named is gone.
|
||||
let after_text = "module m;\n wire a;\nendmodule\n";
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": after_text }]));
|
||||
let after = offered(&session, &uri);
|
||||
assert!(after.is_empty(), "no fix survives the text that justified it: {:?}", rules(&after));
|
||||
|
||||
// ... and through the wire, where a stale span would be a range past the
|
||||
// end of a three-line document.
|
||||
let menu = session.result(
|
||||
CodeActionRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 2, "character": 9 } },
|
||||
// The fix families alone: an extraction is offered for any whole
|
||||
// selection and is not what this row is about.
|
||||
"context": { "diagnostics": [], "only": ["quickfix", "source.fixAll.lucisv"] },
|
||||
}),
|
||||
);
|
||||
assert_eq!(menu, serde_json::json!([]), "and nothing is offered: {menu:#?}");
|
||||
assert_eq!(
|
||||
session.server.workspace.document(&uri).expect("open").text,
|
||||
after_text,
|
||||
"the buffer the answer describes is the buffer the client has"
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
|
||||
use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
@@ -19,16 +20,16 @@ use lsp_types::notification::{
|
||||
PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
|
||||
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
|
||||
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
|
||||
CodeLensRefresh, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest,
|
||||
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
|
||||
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
|
||||
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
|
||||
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
|
||||
UnregisterCapability, WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate,
|
||||
WorkspaceConfiguration, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
|
||||
@@ -39,22 +40,29 @@ use serde_json::Value;
|
||||
|
||||
use super::batch::{is_shutdown, widen_of, Widen};
|
||||
use super::progress::{reports, MAX_REPORTS};
|
||||
use super::startup::{Startup, CONFIGURATION_WAIT};
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
|
||||
|
||||
mod apply_edit;
|
||||
mod cancel;
|
||||
mod code_action;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
mod hierarchy_reach;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod lint_snapshot;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
mod settings;
|
||||
mod startup;
|
||||
mod sync;
|
||||
mod tokens;
|
||||
mod watchers;
|
||||
@@ -85,7 +93,20 @@ impl Tree {
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
std::fs::write(self.path.join(rel), text).expect("write");
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn link(&self, rel: &str, target: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,8 +178,21 @@ impl Session {
|
||||
// this module counts the messages a session produces, and the
|
||||
// timing lines are tested where they are observable as protocol
|
||||
// traffic — `tests/e2e.rs`, against the real binary and its flag.
|
||||
let server =
|
||||
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
|
||||
//
|
||||
// `wait: ZERO` is the client that never answers the settings pull:
|
||||
// the request goes out and the startup scan runs at what this
|
||||
// harness already put in `settings`, which is what every session in
|
||||
// this module was before the startup was staged. The staging itself
|
||||
// is tested in `startup.rs`, where the answer is queued.
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: settings,
|
||||
storage,
|
||||
verbose: false,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
@@ -185,7 +219,64 @@ impl Session {
|
||||
for message in on_the_wire {
|
||||
client.sender.send(message).expect("the client's wire traffic");
|
||||
}
|
||||
let server = Server::started(server_end, roots, abilities, settings, None, false, queued);
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: settings,
|
||||
storage: None,
|
||||
verbose: false,
|
||||
queued,
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// A session whose startup is **staged**: the settings pull goes out
|
||||
/// first and the startup scan waits `wait` for the answer
|
||||
/// (`server/startup.rs`). `queued` is what the client had already sent
|
||||
/// when the server was built — the answer among it, for a client that
|
||||
/// answers.
|
||||
///
|
||||
/// The settings start at the defaults, which is the whole point: what a
|
||||
/// staged session indexes is what the *answer* said, not what a test put
|
||||
/// in ahead of it.
|
||||
fn staged(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
verbose: bool,
|
||||
wait: Duration,
|
||||
queued: Vec<Message>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage: None,
|
||||
verbose,
|
||||
queued,
|
||||
wait,
|
||||
};
|
||||
Session { server: Server::started(server_end, roots, startup), client }
|
||||
}
|
||||
|
||||
/// [`Session::wide`] against a client that spawned the server with
|
||||
/// `--verbose` — the only sessions that are ever told what a scan spent
|
||||
/// its time on (`docs/features/perf5-p4/README.md`).
|
||||
fn verbose_wide(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities: ClientAbilities::default(),
|
||||
client: wide,
|
||||
storage,
|
||||
verbose: true,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ fn workspace_of(tag: &str, files: usize) -> Tree {
|
||||
}
|
||||
|
||||
/// A `workspace/symbol` request over the wire, by id.
|
||||
fn symbol_request(id: i32, query: &str) -> Message {
|
||||
pub(super) fn symbol_request(id: i32, query: &str) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
WorkspaceSymbolRequest::METHOD.to_string(),
|
||||
@@ -28,7 +28,7 @@ fn symbol_request(id: i32, query: &str) -> Message {
|
||||
/// Where the indexing bar's `end` sits among everything the server said,
|
||||
/// and where the response to `id` sits. `None` for either if it never
|
||||
/// came.
|
||||
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
pub(super) fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
let ended = messages.iter().position(|message| {
|
||||
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
//! What a scan says it spent its time on (`docs/features/perf5-p4/README.md`).
|
||||
//!
|
||||
//! Three claims, one test each: the lines exist only under `--verbose`, the
|
||||
//! counts on them are the work the scan actually did, and the stages add up
|
||||
//! to the scan they describe.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree of `files` one-package files.
|
||||
pub(super) fn trace_tree(tag: &str, files: usize) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
for n in 0..files {
|
||||
tree.package(&format!("t{n:03}.sv"), &format!("t{n:03}"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// Every `timing: scan …` line the server has said since the last drain.
|
||||
pub(super) fn scan_lines(session: &Session) -> Vec<String> {
|
||||
session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.filter(|(typ, text)| *typ == MessageType::LOG && is_trace_line(text))
|
||||
.map(|(_, text)| text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a log line is one of a scan's three trace lines — `timing: scan
|
||||
/// <number> …` — rather than the `scan started`/`scan finished` pair the
|
||||
/// verbose-timing feature already had.
|
||||
pub(super) fn is_trace_line(text: &str) -> bool {
|
||||
let Some(rest) = text.strip_prefix("timing: scan ") else { return false };
|
||||
rest.split_whitespace().next().is_some_and(|word| word.parse::<u32>().is_ok())
|
||||
}
|
||||
|
||||
/// The one line of `lines` whose prefix says it is that kind.
|
||||
pub(super) fn line_of(lines: &[String], kind: &str) -> String {
|
||||
lines
|
||||
.iter()
|
||||
.find(|line| line.contains(&format!(" {kind} (")))
|
||||
.unwrap_or_else(|| panic!("no {kind} line among {lines:#?}"))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The value of `key=` on a `key=value` line, as text.
|
||||
pub(super) fn field<'a>(line: &'a str, key: &str) -> &'a str {
|
||||
let at = line.find(&format!("{key}=")).unwrap_or_else(|| panic!("no {key} on {line}"));
|
||||
let rest = &line[at + key.len() + 1..];
|
||||
rest.split_whitespace().next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// The value of `key=` as a number.
|
||||
fn number(line: &str, key: &str) -> f64 {
|
||||
let text = field(line, key);
|
||||
text.parse().unwrap_or_else(|_| panic!("{key}={text} is not a number on {line}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_flag_a_scan_says_nothing_about_its_stages() {
|
||||
// The shipped state. `Session::wide` is every other test in this module,
|
||||
// and none of them may start seeing three extra log lines per scan.
|
||||
let tree = trace_tree("tracequiet", 12);
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(scan_lines(&session).is_empty(), "verbose is off: {:#?}", session.logged());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_makes_a_scan_say_what_it_spent_and_what_it_left() {
|
||||
let tree = trace_tree("traceverbose", 12);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let lines = scan_lines(&session);
|
||||
// Three lines, and they name the same scan.
|
||||
let stages = line_of(&lines, "stages");
|
||||
let counts = line_of(&lines, "counts");
|
||||
let memory = line_of(&lines, "memory");
|
||||
for line in [&stages, &counts, &memory] {
|
||||
assert!(line.starts_with("timing: scan 1 "), "{line}");
|
||||
assert!(line.contains("whole"), "the startup scan is a whole scan: {line}");
|
||||
}
|
||||
// The counts are this fixture's, exactly: twelve files walked and read,
|
||||
// none skipped, none open, and no store to hit.
|
||||
assert_eq!(field(&counts, "read"), "12");
|
||||
assert_eq!(field(&counts, "skipped"), "0");
|
||||
assert_eq!(field(&counts, "hits"), "0");
|
||||
assert_eq!(field(&counts, "misses"), "12");
|
||||
assert_eq!(field(&counts, "buffers"), "0");
|
||||
// Twelve files is under `INTERLEAVE_ABOVE`, so the scan is one shot and
|
||||
// nothing is published mid-way.
|
||||
assert_eq!(field(&counts, "publishes"), "0");
|
||||
assert_eq!(field(&stages, "since_start"), field(&stages, "since_start"));
|
||||
// And the index it left is those twelve packages.
|
||||
assert_eq!(field(&memory, "index_files"), "12");
|
||||
assert_eq!(field(&memory, "cache_entries"), "0", "no storage path, so no store");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warm_second_session_reports_every_file_as_a_hit() {
|
||||
// The one claim the whole warm-scan column rests on: `hits` counts
|
||||
// records served for exactly these bytes, and `misses` counts the parses.
|
||||
let tree = trace_tree("tracewarm", 9);
|
||||
let storage = std::env::temp_dir().join(format!("lucisv_trace_store_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
let cold = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let cold_lines = scan_lines(&cold);
|
||||
let cold_counts = line_of(&cold_lines, "counts");
|
||||
assert_eq!(field(&cold_counts, "hits"), "0");
|
||||
assert_eq!(field(&cold_counts, "misses"), "9");
|
||||
assert_eq!(field(&cold_counts, "records"), "9", "a cold scan writes every record through");
|
||||
drop(cold);
|
||||
|
||||
let warm = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let warm_lines = scan_lines(&warm);
|
||||
let warm_counts = line_of(&warm_lines, "counts");
|
||||
assert_eq!(field(&warm_counts, "hits"), "9", "the same bytes, so every lookup hits");
|
||||
assert_eq!(field(&warm_counts, "misses"), "0");
|
||||
assert_eq!(field(&warm_counts, "records"), "0", "a hit writes nothing back");
|
||||
let warm_memory = line_of(&warm_lines, "memory");
|
||||
assert_eq!(field(&warm_memory, "cache_entries"), "9");
|
||||
assert!(number(&warm_counts, "decoded_kib") >= 0.0);
|
||||
drop(warm);
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stages_add_up_to_the_scan_they_describe() {
|
||||
// The tolerance claim: what the trace attributes must be most of the scan
|
||||
// and can never be more than all of it. The slack is the loop itself —
|
||||
// the progress callbacks, the per-file word `Vec`, the staging pushes —
|
||||
// which is deliberately unattributed rather than silently folded into a
|
||||
// neighbouring stage.
|
||||
let tree = trace_tree("tracesums", 40);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let stages = line_of(&scan_lines(&session), "stages");
|
||||
let total = number(&stages, "total");
|
||||
let named = [
|
||||
"discovery",
|
||||
"order",
|
||||
// Since 2026-09-08 a scan reads a file's text at the step that indexes
|
||||
// it, so what `discovery` used to spend on reading the whole scope is
|
||||
// this stage instead — and a list without it accounts for a fifth of
|
||||
// the scan (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
"read",
|
||||
"cache_open",
|
||||
"lookup",
|
||||
"decode",
|
||||
"parse",
|
||||
"encode",
|
||||
"store_write",
|
||||
"publish_absorb",
|
||||
"publish_candidates",
|
||||
"publish_includes",
|
||||
"publish_overlay",
|
||||
"gone",
|
||||
"absorb",
|
||||
"compact",
|
||||
"candidates",
|
||||
"includes",
|
||||
"overlay",
|
||||
];
|
||||
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
|
||||
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
|
||||
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
|
||||
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_is_a_second_scan_with_its_own_three_lines() {
|
||||
// A session pays for more than one scan — the startup scan runs at the
|
||||
// default settings and whatever the client then says can ask for another
|
||||
// (`docs/features/perf5-p4/README.md`, the two-scan startup). Each gets
|
||||
// its own numbered triple so no reader adds two scans together.
|
||||
let tree = trace_tree("tracerescan", 8);
|
||||
let mut session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let first = scan_lines(&session);
|
||||
assert_eq!(first.len(), 3, "one scan, three lines: {first:#?}");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": {
|
||||
"index": { "scope": "workspace" },
|
||||
"exclude": ["**/t000.sv"],
|
||||
} } }),
|
||||
);
|
||||
let second = scan_lines(&session);
|
||||
assert_eq!(second.len(), 3, "the rescan says the same three things: {second:#?}");
|
||||
for line in &second {
|
||||
assert!(line.starts_with("timing: scan 2 "), "{line}");
|
||||
}
|
||||
let counts = line_of(&second, "counts");
|
||||
assert_eq!(field(&counts, "read"), "7", "the exclusion is one file fewer");
|
||||
}
|
||||
|
||||
/// A `--verbose` session at the **default** settings, against a client that
|
||||
/// cannot be asked for its settings at all — the shape every pre-2026-08-27
|
||||
/// editor starts in, and the one the startup staging leaves untouched
|
||||
/// (`server/startup.rs`). There is nothing to wait for, so the startup scan
|
||||
/// runs immediately at the defaults: with no buffer open its folder scope is
|
||||
/// empty and so is its work list.
|
||||
fn verbose_default(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities: ClientAbilities::default(),
|
||||
client: ClientSettings::default(),
|
||||
storage,
|
||||
verbose: true,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
let server = Server::started(server_end, roots, startup);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// Ask for `lucisv.index.scope: "workspace"`, which is the rescan the pulled
|
||||
/// configuration asks for in a real session.
|
||||
fn widen_to_the_workspace(session: &mut Session) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" } } } }),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none() {
|
||||
// §P4b, both halves, over the real dispatch.
|
||||
//
|
||||
// **(b1)** the startup scan indexes nothing, so it opens nothing: warm it
|
||||
// used to read a 44 MiB store and rewrite it byte-identically, 184 ms of
|
||||
// a 1.33 s start, for a scan with no files in it. **(a)** the configured
|
||||
// rescan behind it hits every record, appends nothing, and so would
|
||||
// rewrite the store it just read into itself — which it no longer does.
|
||||
let tree = trace_tree("traceemptyscan", 9);
|
||||
let storage = std::env::temp_dir().join(format!("lucisv_trace_empty_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
let store = storage.join("index-cache");
|
||||
|
||||
// Cold: scan 1 is empty and touches nothing, scan 2 fills the store.
|
||||
let mut cold = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let first = line_of(&scan_lines(&cold), "counts");
|
||||
assert_eq!(field(&first, "read"), "0", "premise: the startup scan indexes nothing");
|
||||
assert_eq!(field(&first, "opens"), "0", "and so reads no store");
|
||||
assert_eq!(field(&first, "compactions"), "0", "and rewrites none");
|
||||
assert!(!store.exists(), "a scan with no files does not even create one");
|
||||
|
||||
widen_to_the_workspace(&mut cold);
|
||||
let filled = line_of(&scan_lines(&cold), "counts");
|
||||
assert_eq!(field(&filled, "read"), "9", "the configured rescan indexes the tree");
|
||||
assert_eq!(field(&filled, "opens"), "1", "which does open the store");
|
||||
assert_eq!(field(&filled, "records"), "9");
|
||||
assert_eq!(field(&filled, "compactions"), "1", "a session that appended must rewrite");
|
||||
drop(cold);
|
||||
|
||||
let bytes = std::fs::read(&store).expect("a store");
|
||||
let stamp = std::fs::metadata(&store).expect("meta").modified().expect("mtime");
|
||||
|
||||
// Warm: the same two scans, and neither writes a byte — with a buffer
|
||||
// open, which is the shape a real session has. An open buffer is indexed
|
||||
// from its own analysis and writes its record through on every scan, and
|
||||
// that write-through is what would otherwise put a duplicate line in the
|
||||
// store and owe the rewrite back.
|
||||
let mut warm = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
|
||||
let empty = line_of(&scan_lines(&warm), "counts");
|
||||
assert_eq!(field(&empty, "read"), "0");
|
||||
assert_eq!(field(&empty, "opens"), "0", "still no store read for a scan with no files");
|
||||
assert_eq!(field(&empty, "compactions"), "0");
|
||||
|
||||
let opened = tree.path.join("t000.sv");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
warm.open(&opened, &text);
|
||||
let _ = scan_lines(&warm);
|
||||
|
||||
widen_to_the_workspace(&mut warm);
|
||||
let warmed = line_of(&scan_lines(&warm), "counts");
|
||||
assert_eq!(field(&warmed, "hits"), "8", "every file but the buffer came out of the store");
|
||||
assert_eq!(field(&warmed, "buffers"), "1", "premise: the buffer indexes itself");
|
||||
assert_eq!(field(&warmed, "repeats"), "1", "and its record was already in the store");
|
||||
assert_eq!(field(&warmed, "records"), "0", "so nothing was appended");
|
||||
assert_eq!(field(&warmed, "opens"), "1", "the store was read once, not twice");
|
||||
assert_eq!(field(&warmed, "compactions"), "0", "and the rewrite would have been identical");
|
||||
drop(warm);
|
||||
|
||||
assert_eq!(std::fs::read(&store).expect("a store"), bytes, "not one byte of the store moved");
|
||||
assert_eq!(
|
||||
std::fs::metadata(&store).expect("meta").modified().expect("mtime"),
|
||||
stamp,
|
||||
"and the file was not touched at all"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&storage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_discovery_split_is_a_split_of_discovery_and_not_stages_beside_it() {
|
||||
// §61.3. `config`, `walk`, `filelist`, `sort`, `cap` and `buffers` are
|
||||
// disjoint parts of `discovery`, so they may never add up to more than it
|
||||
// — and anything that sums the scan (`the_stages_add_up_to_the_scan_they
|
||||
// _describe`) must not sum these as well, which is why they are absent
|
||||
// from that test's list. The slack is `collect_sources`'s own bookkeeping:
|
||||
// the `spoken_for` set, the `Vec` pushes, the `Scope` moves.
|
||||
let tree = trace_tree("tracediscovery", 30);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let lines = scan_lines(&session);
|
||||
let stages = line_of(&lines, "stages");
|
||||
let discovery = number(&stages, "discovery");
|
||||
let parts: f64 = ["config", "walk", "filelist", "sort", "cap", "buffers"]
|
||||
.iter()
|
||||
.map(|key| number(&stages, key))
|
||||
.sum();
|
||||
assert!(discovery > 0.0, "a walk of 30 files takes measurable time: {stages}");
|
||||
assert!(parts <= discovery * 1.02, "the parts cannot exceed the whole: {parts} of {discovery}");
|
||||
assert!(parts > 0.0, "and at least one of them was timed: {stages}");
|
||||
// Not asserted: that the parts account for *most* of discovery. On a
|
||||
// fixture this small the whole is well under a millisecond and the
|
||||
// bookkeeping slack — the `spoken_for` set, the `Vec` pushes — rivals the
|
||||
// walk, so a ratio bound is a stopwatch under the workspace suite's
|
||||
// parallel load (it tripped once at 50 % in the lead's gate run and
|
||||
// passed alone three times). On opentitan the walk is 95 % of discovery
|
||||
// (`docs/features/perf5r-first-answer/README.md`); that ratio is the
|
||||
// README's measurement, not this test's claim.
|
||||
assert_eq!(number(&stages, "filelist"), 0.0, "no filelist is in force: {stages}");
|
||||
// Nothing was walked twice: one root, and the cap read the walk's own
|
||||
// lengths rather than asking the filesystem again.
|
||||
let counts = line_of(&lines, "counts");
|
||||
assert_eq!(field(&counts, "walk_dirs"), "1", "one root, walked once: {counts}");
|
||||
assert_eq!(field(&counts, "stats"), "0", "the cap stats nothing the walk already read");
|
||||
}
|
||||
@@ -26,12 +26,18 @@ fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
// `Server::new` calls `register_watchers` and then
|
||||
// `request_configuration`, in that order — this pins it on the actual
|
||||
// wire rather than trusting the call order in the source. Every
|
||||
// outgoing request's id is `lucisv-{n}` off one monotonically
|
||||
// increasing counter, so the numeric suffix *is* the send order.
|
||||
fn the_startup_pull_is_the_first_thing_on_the_wire() {
|
||||
// **Amended 2026-09-08 (§P4b2).** This used to pin the opposite order:
|
||||
// `Server::new` registered the watchers and *then* asked for the
|
||||
// settings, because the startup scan ran in front of both and the
|
||||
// answer could not have changed it. Staging the scan reverses that —
|
||||
// the pull is now the first thing a session sends, because the scan is
|
||||
// waiting on its answer to know which scope to run at
|
||||
// (`server/startup.rs`). The claim the test makes is unchanged in kind:
|
||||
// the order is pinned on the actual wire rather than trusted from the
|
||||
// call order in the source. Every outgoing request's id is `lucisv-{n}`
|
||||
// off one monotonically increasing counter, so the numeric suffix *is*
|
||||
// the send order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("verify on the wire").
|
||||
let tree = Tree::new("pulloraftwatch");
|
||||
@@ -46,7 +52,8 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
};
|
||||
let watchers = index_of(RegisterCapability::METHOD);
|
||||
let pull = index_of(WorkspaceConfiguration::METHOD);
|
||||
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
|
||||
assert_eq!(pull, 0, "the pull precedes everything, watchers included: {sent:#?}");
|
||||
assert!(pull < watchers, "including the watcher registration: {sent:#?}");
|
||||
|
||||
let numeric_suffix = |request: &Request| -> u32 {
|
||||
request
|
||||
@@ -57,9 +64,10 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
|
||||
};
|
||||
assert_eq!(numeric_suffix(&sent[pull]), 0, "and it takes the first id: {sent:#?}");
|
||||
assert!(
|
||||
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
|
||||
"the pull's id must be issued after the watcher registration's: {sent:#?}"
|
||||
numeric_suffix(&sent[pull]) < numeric_suffix(&sent[watchers]),
|
||||
"the watcher registration's id must be issued after the pull's: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,794 @@
|
||||
//! Which files a scan will index, how they were found, and what the finding
|
||||
//! cost.
|
||||
//!
|
||||
//! The scope ladder ([`Workspace::source_files`]) and the overlay that lets an
|
||||
//! open buffer beat the disk ([`Workspace::collect_sources`]), lifted out of
|
||||
//! `state/mod.rs` on 2026-09-08 (TODO §61.3) when discovery grew a stage split
|
||||
//! and a second entry point. It answers one question — *which files exist as
|
||||
//! far as this server is concerned, and how big are they* — and every rung of
|
||||
//! the ladder is in this file.
|
||||
//!
|
||||
//! **The size a walked file reports is the walk's own.** `lucisv_core`'s walk
|
||||
//! calls `metadata` on every directory entry to answer "directory?", so the
|
||||
//! length is a field it already holds; asking the filesystem again, once per
|
||||
//! file, was 6.9 ms of a 165 ms discovery over 3 976 files — measured, not
|
||||
//! assumed, and smaller than it looks because the walk has just warmed every
|
||||
//! one of those inodes (`docs/features/perf5r-first-answer/README.md`). A path
|
||||
//! the walk did not stat — a filelist entry, an input named rather than walked
|
||||
//! — carries no length and is stat'd here, exactly as every path used to be.
|
||||
//!
|
||||
//! **And the walk is split in two when it pays to be.** A workspace-scoped
|
||||
//! session with a buffer open walks that buffer's own folders first, so the
|
||||
//! scan can index and publish them before it discovers the other 3 850 files
|
||||
//! ([`Workspace::first_scope`]). One scan, one work list, every file once.
|
||||
//!
|
||||
//! **"Every file once" is a claim about directory identity, not about paths.**
|
||||
//! A symlinked directory gives every file under it a second path, and a walk
|
||||
//! answers that by entering each directory identity once and reporting its
|
||||
//! files under the first spelling that reached it
|
||||
//! (`docs/features/walk-cycles/README.md`). Two walks with two visited sets do
|
||||
//! not have that rule *between* them, which is how the split came to index a
|
||||
//! module twice (`docs/performance_052_review.md` F1). So the two halves share
|
||||
//! one [`DirectoryTracker`]; the head is not led with at all when a walk of the
|
||||
//! root would reach the user's own folder by an earlier name
|
||||
//! ([`Workspace::has_preceding_alias`]); and where only the remaining walk can
|
||||
//! find that out, it says so and the scan asks for one canonical walk
|
||||
//! ([`Scan::wants_rescan`](super::Scan::wants_rescan)).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::{
|
||||
collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS,
|
||||
};
|
||||
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
use super::scan::{Analyzed, HeldAnalyses, IndexEvent, PendingDiscovery, Sources};
|
||||
use super::Workspace;
|
||||
|
||||
/// One in-scope file, and the length whoever found it already knew.
|
||||
///
|
||||
/// `len` is `None` for a path nothing stat'd on the way here — a filelist
|
||||
/// entry, or an input named rather than walked. It is not "unknown size": it
|
||||
/// is "nobody has looked yet", and [`oversize`] is what looks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Found {
|
||||
pub(super) path: PathBuf,
|
||||
pub(super) len: Option<u64>,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// A path nothing has stat'd.
|
||||
fn unmeasured(path: PathBuf) -> Found {
|
||||
Found { path, len: None }
|
||||
}
|
||||
|
||||
/// One path on its own, for a caller asking the cap about a single file
|
||||
/// rather than about a walk ([`Workspace::current_text`]).
|
||||
pub(super) fn of(path: &Path) -> Found {
|
||||
Found::unmeasured(path.to_path_buf())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the scope ladder decided: the files to index, the directories an
|
||||
/// `` `include`` in them is looked for in, and what to tell the user.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Scope {
|
||||
pub(super) files: Vec<Found>,
|
||||
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
|
||||
/// but the filelist — nothing else names an include path.
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The size of `found` when it is over `cap`, else `None` — the whole of the
|
||||
/// `lucisv.index.maxFileSize` test.
|
||||
///
|
||||
/// Metadata only: the point of the cap is that a 200 MB netlist is never read
|
||||
/// into memory, so knowing how big it is has to come first. A `cap` of 0 is
|
||||
/// the client asking for no cap, and a file whose metadata cannot be read is
|
||||
/// not skipped here — it simply fails the read later, as it always did.
|
||||
///
|
||||
/// `stats` counts the `metadata` calls this one really made, so a session can
|
||||
/// prove the walk's hand-off removed them rather than assert it.
|
||||
pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option<u64> {
|
||||
if cap == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = match found.len {
|
||||
Some(size) => size,
|
||||
None => {
|
||||
*stats += 1;
|
||||
fs::metadata(&found.path).ok()?.len()
|
||||
}
|
||||
};
|
||||
(size > cap).then_some(size)
|
||||
}
|
||||
|
||||
/// The open buffers' files by **identity**, so a walked path that is a second
|
||||
/// spelling of one of them can be recognised and left out.
|
||||
///
|
||||
/// A symlinked directory gives every file under it a second path. The walk
|
||||
/// reports each file under the first spelling that reaches it, which may not be
|
||||
/// the one the buffer was opened by — and an index holding `a_alias/tb.sv` from
|
||||
/// disk beside the open `z_real/tb.sv` holds one module twice and refuses to
|
||||
/// rename it (`docs/features/walk-cycles/README.md`).
|
||||
///
|
||||
/// **The name is the gate, and it is what keeps this free.** A directory alias
|
||||
/// cannot change a file's *name*, so a walked file whose name no open buffer
|
||||
/// shares cannot be one of them and is never stat'd: an ordinary workspace pays
|
||||
/// nothing at all, and one with same-named files pays one `metadata` per
|
||||
/// same-named candidate. A **file**-level symlink under a different name is out
|
||||
/// of scope — two names for one inode that no directory relates, which every
|
||||
/// other part of this server already treats as two files.
|
||||
struct Aliased {
|
||||
/// The names those buffers' files go by — the cheap half of the test.
|
||||
names: HashSet<std::ffi::OsString>,
|
||||
/// Their `(dev, ino)` identities, read once per open buffer rather than
|
||||
/// once per walked file.
|
||||
ids: HashSet<lucisv_core::walk::DirId>,
|
||||
}
|
||||
|
||||
impl Aliased {
|
||||
/// The identities of `paths`, with the names to gate on.
|
||||
fn of(paths: &HashSet<&Path>) -> Aliased {
|
||||
let names = paths.iter().filter_map(|p| p.file_name()).map(|n| n.to_os_string()).collect();
|
||||
let ids = paths.iter().filter_map(|p| dir_id(p)).collect();
|
||||
Aliased { names, ids }
|
||||
}
|
||||
|
||||
/// Whether `path` names a file an open buffer already speaks for, by a
|
||||
/// different spelling. `stats` counts the `metadata` calls it made.
|
||||
fn speaks_for(&self, path: &Path, stats: &mut usize) -> bool {
|
||||
if self.ids.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = path.file_name() else { return false };
|
||||
if !self.names.contains(name) {
|
||||
return false;
|
||||
}
|
||||
*stats += 1;
|
||||
dir_id(path).is_some_and(|id| self.ids.contains(&id))
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
/// Resolve the scope: which files are in it, with open buffers overriding
|
||||
/// disk, and those buffers' own text.
|
||||
///
|
||||
/// **Metadata only, plus what is already in memory.** Nothing on disk is
|
||||
/// read here — a file's text is read by whoever indexes or rewrites it,
|
||||
/// one file at a time ([`Workspace::scan_step`], [`Workspace::sources`]).
|
||||
///
|
||||
/// This is where `lucisv.index.maxFileSize` applies, and it applies to the
|
||||
/// **walked** files only: an open buffer is folded in below whatever its
|
||||
/// size, because the user opened it deliberately and an editor that
|
||||
/// refused to understand the file on screen would be absurd. The check is
|
||||
/// the size the walk read, so an oversized file is still never read at all
|
||||
/// — which is the whole saving, and it is still counted and reported here
|
||||
/// so that a scan's skip count is known before its first step.
|
||||
///
|
||||
/// A refactoring reads this same list through `sources()`, so a file the
|
||||
/// cap keeps out of the index is also a file a workspace rename will not
|
||||
/// rewrite. That is the consistent answer: the cap says which files exist
|
||||
/// as far as this server is concerned.
|
||||
pub(super) fn collect_sources(
|
||||
&self,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
analyses: HeldAnalyses,
|
||||
trace: &mut ScanTrace,
|
||||
) -> Sources {
|
||||
let scope = self.source_files(trace);
|
||||
self.overlay_buffers(scope, watch, analyses, trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::collect_sources`] over one already-resolved scope — the
|
||||
/// cap, then the open buffers over the top.
|
||||
///
|
||||
/// Split out because the two-phase startup resolves the scope twice (the
|
||||
/// user's own folders, then the rest of the workspace) and both halves owe
|
||||
/// the buffers the same precedence.
|
||||
pub(super) fn overlay_buffers(
|
||||
&self,
|
||||
scope: Scope,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
analyses: HeldAnalyses,
|
||||
trace: &mut ScanTrace,
|
||||
) -> Sources {
|
||||
let cap = self.client.max_file_size;
|
||||
// Every path an open buffer speaks for. Reading such a file from disk
|
||||
// is work thrown away — the buffer's text replaces it below, whatever
|
||||
// the disk says — so the read is skipped rather than undone. The cap is
|
||||
// still consulted first, so an oversized file still reports itself
|
||||
// skipped exactly as it did before the buffer put its own text back.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
// …and every *other* spelling of those same files, which a directory
|
||||
// alias makes and a path comparison cannot see ([`Aliased`]).
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in scope.files {
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &found.path, size, cap });
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(found.path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
if aliased.speaks_for(&found.path, &mut stats) {
|
||||
continue;
|
||||
}
|
||||
files.push(found.path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.cap_ms, capping);
|
||||
trace.stats += stats;
|
||||
// Open buffers override what is on disk, and contribute themselves
|
||||
// when they are not on disk at all.
|
||||
//
|
||||
// Except a buffer on the large-file fast path, which overrides disk
|
||||
// with *nothing*: indexing it means parsing the hundred megabytes the
|
||||
// fast path exists not to parse. Removing the path rather than leaving
|
||||
// the disk copy in is the honest half of that — the alternative would
|
||||
// be an index describing a file the user is looking at by bytes it no
|
||||
// longer has. See `docs/features/large-file-mode/README.md` for the
|
||||
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
|
||||
// never capped" rule this is the one exception to.
|
||||
let buffering = trace.now();
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|p| p != &path);
|
||||
if !doc.large {
|
||||
if analyses == HeldAnalyses::Wanted {
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
}
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
ScanTrace::add(&mut trace.buffers_ms, buffering);
|
||||
Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
|
||||
}
|
||||
|
||||
/// The files the index covers, and what the user should be told about how
|
||||
/// they were chosen. The scope ladder, highest first:
|
||||
///
|
||||
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
|
||||
/// config governing a workspace root. It names *exactly* the files to
|
||||
/// index; the project said so, and guessing past it would defeat the
|
||||
/// point of having one. This is the "project file", and it is the one
|
||||
/// rung that is whole-project by definition.
|
||||
/// 2. **The workspace-folder walk**, on `lucisv.index.scope:
|
||||
/// "workspace"` — what every session did before 2026-08-27, now opt-in.
|
||||
/// 3. **The folder scope**, the default: each opened buffer's own
|
||||
/// directory raised `lucisv.index.scopeDepth` levels, walked. See
|
||||
/// `docs/features/index-scope/README.md` for what that costs, which is
|
||||
/// that a definition in another folder does not resolve until the
|
||||
/// scope reaches that folder.
|
||||
///
|
||||
/// A configured filelist that cannot be read falls back to rung 2 (or 3)
|
||||
/// with a warning. An editor that shows no symbols because of a typo in a
|
||||
/// path is worse than one that quietly indexes what it can and says so.
|
||||
///
|
||||
/// Only rung 1 can carry `+incdir+` directories: a walked workspace names
|
||||
/// none, so an `` `include`` there resolves against the including file's
|
||||
/// own directory alone (`docs/features/include-nav/README.md`).
|
||||
pub(super) fn source_files(&self, trace: &mut ScanTrace) -> Scope {
|
||||
// The walk's own warnings join the scope's, so an unreadable directory
|
||||
// reaches the output channel by the road a filelist's problems already
|
||||
// travel — said once per scan and never per keystroke.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let Some(path) = self.filelist_path() else {
|
||||
let files = self.default_files(&mut |w| warnings.push(w), trace);
|
||||
return Scope { files, warnings, ..Default::default() };
|
||||
};
|
||||
let reading = trace.now();
|
||||
let read = lucisv_core::filelist::read(&path);
|
||||
ScanTrace::add(&mut trace.filelist_ms, reading);
|
||||
match read {
|
||||
Ok(list) => Scope {
|
||||
files: list.files.into_iter().map(Found::unmeasured).collect(),
|
||||
incdirs: list.incdirs,
|
||||
warnings: list.warnings,
|
||||
},
|
||||
Err(problem) => {
|
||||
let files = self.default_files(&mut |w| warnings.push(w), trace);
|
||||
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
|
||||
Scope { files, incdirs: Vec::new(), warnings }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The filelist governing this workspace, if any: the client's setting
|
||||
/// first (absolute, or relative to the first root), else the `filelist`
|
||||
/// key of the config governing a root, in root order.
|
||||
///
|
||||
/// Public because the file watchers must name it: a `.f` edited outside
|
||||
/// the editor changes the index's scope, and nothing else on disk would
|
||||
/// tell us (`docs/features/file-watching/README.md`).
|
||||
pub fn filelist_path(&self) -> Option<PathBuf> {
|
||||
if let Some(setting) = &self.client.filelist {
|
||||
let path = Path::new(setting);
|
||||
return Some(match self.roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
let mut discovery = Discovery::new(true);
|
||||
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
|
||||
// excludes below: the user hears about it when they format.
|
||||
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
|
||||
/// asked for it, else the folder scope.
|
||||
fn default_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
|
||||
if self.walks_the_workspace() {
|
||||
return self.walked_files(&self.roots, warn, trace);
|
||||
}
|
||||
self.folder_files(warn, trace)
|
||||
}
|
||||
|
||||
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
|
||||
/// filter the workspace walk applies.
|
||||
///
|
||||
/// One exception, kept exactly as it was from before this rung became the
|
||||
/// default: **a rootless session at depth 0 reads its directories flat**,
|
||||
/// one level, no `.gitignore`. That is the "a file opened on its own"
|
||||
/// case, where descending a tree the user never named would be a surprise
|
||||
/// — and the moment the user raises `scopeDepth` they have named one, so
|
||||
/// the walk is what they asked for.
|
||||
fn folder_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
|
||||
let dirs = self.scope_dirs();
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(&dirs, trace);
|
||||
}
|
||||
self.walked_files(&dirs, warn, trace)
|
||||
}
|
||||
|
||||
/// Every source file under `dirs`, found by the CLI's own walk: the same
|
||||
/// extensions, the same `.gitignore` handling, and the `exclude` patterns
|
||||
/// of the config governing each directory. What `lucisv` skips, the index
|
||||
/// skips.
|
||||
///
|
||||
/// `dirs` is the workspace roots for rung 2 and the scope directories for
|
||||
/// rung 3. The one honest difference between the two: `.gitignore` files
|
||||
/// are read from the walk's own starting directory downwards, so a rule
|
||||
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
|
||||
/// starts below it. The `exclude` patterns are matched against whole
|
||||
/// paths and so behave identically either way.
|
||||
pub(super) fn walked_files(
|
||||
&self,
|
||||
dirs: &[PathBuf],
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
self.walked_files_tracked(dirs, &mut tracker, warn, trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::walked_files`] over an existing [`DirectoryTracker`], so
|
||||
/// two walks of one scan enter each directory identity once between them.
|
||||
pub(super) fn walked_files_tracked(
|
||||
&self,
|
||||
dirs: &[PathBuf],
|
||||
tracker: &mut DirectoryTracker,
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for root in dirs {
|
||||
// The walk names its inputs as strings; every directory here came
|
||||
// from a `file:` URI, which cannot carry a non-UTF-8 path.
|
||||
let Some(input) = root.to_str() else { continue };
|
||||
// A broken `lucisv.toml` must not stop the server from indexing: an
|
||||
// index that excludes nothing is a far better failure than a
|
||||
// server that comes up empty. The error is reported when the user
|
||||
// formats a file in this tree (`format::settings_for`).
|
||||
let configuring = trace.now();
|
||||
let mut exclude =
|
||||
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
|
||||
// The client's `lucisv.exclude` is *appended*, never substituted —
|
||||
// the CLI appends a config's excludes to `--exclude` the same way,
|
||||
// and a setting that silently dropped a checked-in exclude would
|
||||
// put vendored code back in the index for one user only.
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
ScanTrace::add(&mut trace.config_ms, configuring);
|
||||
// `.gitignore` is always honoured: it is the CLI's default, and an
|
||||
// editor has no `--no-gitignore` to type. An unreadable directory
|
||||
// is skipped and said — the warning rides out on the scope's own
|
||||
// warnings, which `server/notification.rs` logs once per scan.
|
||||
let walking = trace.now();
|
||||
let _ = collect_files_tracked(
|
||||
input,
|
||||
&exclude,
|
||||
true,
|
||||
tracker,
|
||||
&mut |path, len| out.push(Found { path, len }),
|
||||
&mut |w| warn(w.to_string()),
|
||||
);
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += 1;
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
|
||||
/// The files the directories a widen added bring into scope, by the same
|
||||
/// rules [`Workspace::folder_files`] applies to the whole scope — including
|
||||
/// the rootless-at-depth-0 flat read.
|
||||
pub(super) fn widened_files(
|
||||
&self,
|
||||
added: &[PathBuf],
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(added, trace);
|
||||
}
|
||||
self.walked_files(added, warn, trace)
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest neighbourhood a startup will index before it finds out how big
|
||||
/// the workspace is.
|
||||
///
|
||||
/// The split's whole premise is that the user's own folder is a small part of
|
||||
/// the workspace, so stepping it first costs the rest of the scan nothing a
|
||||
/// user notices. Beyond this many files that premise is not proven — the
|
||||
/// count that would prove it is the walk this order exists to postpone — so
|
||||
/// the walk is finished first and the scan is ordered exactly as it was
|
||||
/// before, `scan_order::worth_waiting` and all.
|
||||
///
|
||||
/// 512 is a measured bound and not a round number: a warm step costs about
|
||||
/// 0.2 ms a file (124 files in 25 ms, `docs/features/perf5-p4/README.md`
|
||||
/// §P4b3), so a head of this size is ~100 ms of stepping and the whole first
|
||||
/// answer still fits inside the round's 200 ms gate.
|
||||
pub(crate) const HEAD_WALK_MAX: usize = 512;
|
||||
|
||||
impl Workspace {
|
||||
/// Whether this scan may walk the user's own folders first and the rest of
|
||||
/// the workspace afterwards.
|
||||
///
|
||||
/// Three conditions, and each of them names a case the split would
|
||||
/// otherwise make *worse*:
|
||||
///
|
||||
/// * **the workspace walk is the rung in force.** It is the only rung
|
||||
/// whose discovery is a walk of everything: a filelist names its files
|
||||
/// and reads in one go, and the folder rung's own scope *is* the
|
||||
/// neighbourhood, so splitting it would put the whole scan in the head.
|
||||
/// * **a buffer is open, in a folder below a workspace root.** With no
|
||||
/// buffer there is no neighbourhood to lead with; with one opened from
|
||||
/// the root itself, the folder it raises to *is* the workspace, which is
|
||||
/// the case `scan_order::worth_waiting` exists for and the case this
|
||||
/// returns `false` for so that rule still decides it.
|
||||
/// * **the walk finds a small enough neighbourhood** — checked by the
|
||||
/// caller once the folders are walked, against [`HEAD_WALK_MAX`].
|
||||
/// * **it is the session's first scan** — checked by the caller, which is
|
||||
/// the only one that knows the scan number.
|
||||
pub(super) fn splits_discovery(&self) -> bool {
|
||||
if !self.leads_with_a_folder() {
|
||||
return false;
|
||||
}
|
||||
let dirs = self.raised_dirs();
|
||||
!dirs.is_empty() && dirs.iter().all(|dir| self.below_a_root(dir))
|
||||
}
|
||||
|
||||
/// Whether a scan of this workspace would lead with the user's own folder
|
||||
/// if it knew one — the rung half of [`Workspace::splits_discovery`],
|
||||
/// asked on its own by the startup that waits a bounded moment to be told
|
||||
/// which folder that is (`server/startup.rs`).
|
||||
pub fn leads_with_a_folder(&self) -> bool {
|
||||
self.walks_the_workspace()
|
||||
}
|
||||
|
||||
/// Whether `dir` is a **strict** descendant of some workspace root.
|
||||
///
|
||||
/// A directory that *is* a root is the whole of that root's walk, so
|
||||
/// leading with it is leading with everything.
|
||||
fn below_a_root(&self, dir: &Path) -> bool {
|
||||
self.roots.iter().any(|root| dir.starts_with(root) && dir != root)
|
||||
}
|
||||
|
||||
/// What a whole scan starts from: its scope, and whatever of that scope is
|
||||
/// still to be walked.
|
||||
///
|
||||
/// `None` for the second half means what it has always meant — the scope
|
||||
/// was resolved entire before the first file was indexed, and the work
|
||||
/// list the caller gets is the whole of it. `Some` means the caller is
|
||||
/// holding the user's own folders and owes itself the rest of the
|
||||
/// workspace once it has published them ([`PendingDiscovery`]).
|
||||
pub(super) fn first_scope(
|
||||
&self,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: &mut ScanTrace,
|
||||
) -> (Sources, Option<PendingDiscovery>) {
|
||||
// **The session's first scan only.** Every later whole rescan is one a
|
||||
// message asked for, and `must_wait`'s `answering_a_rescan` holds every
|
||||
// request for the whole of it — so leading with a folder buys no answer
|
||||
// any sooner and costs the neighbourhood one extra directory
|
||||
// traversal. The startup scan is the one nothing is queued ahead of,
|
||||
// and it is the one this order is for
|
||||
// (`docs/features/perf5r-first-answer/README.md`).
|
||||
if trace.number > 1 || !self.splits_discovery() {
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
// A directory alias that a root walk would reach *before* the folder
|
||||
// the head would lead with: leading with it would spell those files a
|
||||
// way no other scan of this workspace ever does
|
||||
// ([`Workspace::has_preceding_alias`]). The whole scope, walked once,
|
||||
// is the answer — a millisecond on a fixture and ~155 ms on
|
||||
// opentitan, and only for a session whose own folder is aliased.
|
||||
for dir in self.raised_dirs() {
|
||||
if let Some(root) = self.deepest_root(&dir) {
|
||||
if self.has_preceding_alias(&root, &dir) {
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let mut tracker = DirectoryTracker::new();
|
||||
let head = self.neighbourhood_files(&mut tracker, &mut |w| warnings.push(w), trace);
|
||||
if head.len() > HEAD_WALK_MAX {
|
||||
// Too big to lead with unproven. The head is **discarded** and the
|
||||
// whole scope walked once, ordered the way every scan before this
|
||||
// one was: keeping it and walking the rest beside it would union
|
||||
// two walks that never agreed on a directory's spelling, which is
|
||||
// the very thing the tracker exists to prevent.
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
// Every path the neighbourhood walk named, before the cap has had a
|
||||
// say: what the remaining walk must not decide about a second time.
|
||||
let mut seen: HashSet<PathBuf> = head.iter().map(|found| found.path.clone()).collect();
|
||||
seen.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let scope = Scope { files: head, incdirs: Vec::new(), warnings };
|
||||
let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace);
|
||||
(sources, Some(PendingDiscovery { roots: self.roots.clone(), seen, tracker }))
|
||||
}
|
||||
|
||||
/// Whether some directory between `root` and `dir` holds a **second
|
||||
/// spelling** of `dir` or of one of its ancestors that a walk of `root`
|
||||
/// would reach *first*.
|
||||
///
|
||||
/// The one case the split cannot lead with. A walk of the root reports
|
||||
/// each directory under the first path that reaches it, in name order, so
|
||||
/// with `a_alias -> z_real` the whole of `z_real` is spelled `a_alias/…`;
|
||||
/// a head walk starting at `z_real` would spell it `z_real/…` and the two
|
||||
/// halves of one scan would disagree with each other and with every later
|
||||
/// rescan. Asked before the head is walked, so the answer is a *fallback*
|
||||
/// to the single canonical walk and never a repair afterwards.
|
||||
///
|
||||
/// **It reads directories and stats symlinks only.** The chain from a
|
||||
/// buffer's folder to the root is a handful of directories (four on
|
||||
/// opentitan, ~150 entries between them); `read_dir` already carries each
|
||||
/// entry's kind, so an ordinary tree costs no `metadata` at all.
|
||||
fn has_preceding_alias(&self, root: &Path, dir: &Path) -> bool {
|
||||
let targets = identities_to(root, dir);
|
||||
!targets.is_empty()
|
||||
&& ancestors_to(root, dir).into_iter().any(|up| precedes_a_target(up, &targets))
|
||||
}
|
||||
|
||||
/// The user's own neighbourhood, walked: every source file under the
|
||||
/// folders the open buffers raise to, **as the walk of the workspace root
|
||||
/// would have found them**.
|
||||
///
|
||||
/// `collect_files_below` rather than `collect_files_with` is the whole of
|
||||
/// that "as": a walk starting at `hw/ip/aes` reads no `.gitignore` above
|
||||
/// itself, and the rung in force here is the *root's*, so the folder half
|
||||
/// of one scope must obey the same rules the other half does. Without it
|
||||
/// the head would index files the rest of the scan excludes, and the two
|
||||
/// halves of one scan would disagree about which files exist.
|
||||
fn neighbourhood_files(
|
||||
&self,
|
||||
tracker: &mut DirectoryTracker,
|
||||
warn: &mut dyn FnMut(String),
|
||||
trace: &mut ScanTrace,
|
||||
) -> Vec<Found> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for dir in self.raised_dirs() {
|
||||
// The root this folder was raised inside: the deepest one that
|
||||
// contains it, which is the one `Workspace::raised` clamped to.
|
||||
let Some(root) = self.deepest_root(&dir) else { continue };
|
||||
let configuring = trace.now();
|
||||
let mut exclude =
|
||||
discovery.for_dir(&root).unwrap_or_default().exclude.unwrap_or_default();
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
ScanTrace::add(&mut trace.config_ms, configuring);
|
||||
let walking = trace.now();
|
||||
let _ = collect_files_below_tracked(
|
||||
&root,
|
||||
&dir,
|
||||
&exclude,
|
||||
true,
|
||||
tracker,
|
||||
&mut |path, len| out.push(Found { path, len }),
|
||||
&mut |w| warn(w.to_string()),
|
||||
);
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += 1;
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
|
||||
/// The deepest workspace root containing `dir` — the one
|
||||
/// [`Workspace::raised`] clamped the raise to, and so the one whose walk
|
||||
/// this folder is part of.
|
||||
fn deepest_root(&self, dir: &Path) -> Option<PathBuf> {
|
||||
self.roots
|
||||
.iter()
|
||||
.filter(|root| dir.starts_with(root))
|
||||
.max_by_key(|root| root.components().count())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// The rest of the workspace: everything the roots hold that `seen` does
|
||||
/// not already name, capped and reported exactly as the neighbourhood was.
|
||||
///
|
||||
/// Returns the files to index, what the walk wants said, and how many the
|
||||
/// cap kept out. Open buffers are **not** folded in again — they were
|
||||
/// folded into the head, and a buffer's path is in `pending.seen`.
|
||||
///
|
||||
/// **It walks with the head's own directory identities.** The tracker is
|
||||
/// the one the neighbourhood filled, so a directory the head already
|
||||
/// entered is not entered again under an alias and no file is discovered
|
||||
/// twice. Where this walk reaches such a directory under a spelling the
|
||||
/// root walk would have *preferred*, the tracker says so
|
||||
/// ([`DirectoryTracker::has_conflict`]) and the caller asks for one
|
||||
/// ordinary rescan, which is that root walk.
|
||||
pub(super) fn rest_of_scope(
|
||||
&self,
|
||||
pending: &mut PendingDiscovery,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: &mut ScanTrace,
|
||||
) -> (Vec<PathBuf>, Vec<String>, usize) {
|
||||
let (roots, seen) = (&pending.roots, &pending.seen);
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let walked = self.walked_files_tracked(
|
||||
roots,
|
||||
&mut pending.tracker,
|
||||
&mut |w| warnings.push(w),
|
||||
trace,
|
||||
);
|
||||
// The same gate the neighbourhood applied: a file an open buffer
|
||||
// already speaks for, reached here by **another** spelling (a
|
||||
// same-named file symlink outside the head), must not be indexed a
|
||||
// second time. The buffer's own spelling is not an alias — a buffer
|
||||
// opened mid-scan is discovered here for the first time and must land
|
||||
// in the work list — so the gate is asked only about other paths.
|
||||
// Found by QA on §62.1, twice: the head walk had the gate and this walk
|
||||
// did not; then the gate matched a mid-scan buffer against itself.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let cap = self.client.max_file_size;
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in walked {
|
||||
// Already decided about by the neighbourhood: indexed, capped out,
|
||||
// or spoken for by an open buffer. Deciding again would step a
|
||||
// file twice or report one skip as two.
|
||||
let another_spelling = !spoken_for.contains(found.path.as_path());
|
||||
if seen.contains(&found.path)
|
||||
|| (another_spelling && aliased.speaks_for(&found.path, &mut stats))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &found.path, size, cap });
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
files.push(found.path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.cap_ms, capping);
|
||||
trace.stats += stats;
|
||||
(files, warnings, skipped)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity of `dir` and of every directory between it and `root` — what
|
||||
/// a second spelling would have to name to matter ([`Workspace::has_preceding_alias`]).
|
||||
///
|
||||
/// `root` itself is not among them: a walk of the root enters it before it
|
||||
/// reads anything, so nothing it holds can precede it.
|
||||
fn identities_to(root: &Path, dir: &Path) -> Vec<(lucisv_core::walk::DirId, PathBuf)> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = dir;
|
||||
while at != root {
|
||||
if let Some(id) = dir_id(at) {
|
||||
out.push((id, at.to_path_buf()));
|
||||
}
|
||||
let Some(parent) = at.parent() else { break };
|
||||
at = parent;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The directories a walk of `root` reads on its way down to `dir`: its
|
||||
/// parent, that one's parent, and so on up to and including `root`.
|
||||
fn ancestors_to<'a>(root: &'a Path, dir: &'a Path) -> Vec<&'a Path> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = dir.parent();
|
||||
while let Some(parent) = at {
|
||||
out.push(parent);
|
||||
if parent == root {
|
||||
break;
|
||||
}
|
||||
at = parent.parent();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `dir` holds a symlink to one of `targets` under a name that sorts
|
||||
/// before the target's own path — the entry a root walk would follow first.
|
||||
fn precedes_a_target(dir: &Path, targets: &[(lucisv_core::walk::DirId, PathBuf)]) -> bool {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|entry| {
|
||||
// Only a symlink can be a second spelling of a directory, and the kind
|
||||
// is the one `read_dir` already read — so the stat below happens once
|
||||
// per link in the chain and never once per entry.
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_symlink()) {
|
||||
return false;
|
||||
}
|
||||
let path = entry.path();
|
||||
let Some(id) = dir_id(&path) else { return false };
|
||||
targets.iter().any(|(target, spelling)| id == *target && path < *spelling)
|
||||
})
|
||||
}
|
||||
|
||||
/// Path order, one entry per path — what the walk's callers have always done
|
||||
/// with the paths of several overlapping directory walks.
|
||||
///
|
||||
/// The first entry for a path wins, which matters only for the length beside
|
||||
/// it, and two walks that found the same file read the same `metadata` for it.
|
||||
pub(super) fn sort_found(found: &mut Vec<Found>) {
|
||||
found.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
found.dedup_by(|a, b| a.path == b.path);
|
||||
}
|
||||
|
||||
/// The source files sitting in each of `dirs`, one directory deep. No walk, no
|
||||
/// `.gitignore`: this is the rootless default, where descending a tree the
|
||||
/// user never named would be a surprise.
|
||||
fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec<Found> {
|
||||
let walking = trace.now();
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for dir in dirs {
|
||||
let Ok(entries) = fs::read_dir(dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if !EXTENSIONS.contains(&extension) {
|
||||
continue;
|
||||
}
|
||||
// One `metadata` — the same call `is_file()` was, with the length
|
||||
// it always had kept rather than thrown away. It follows symlinks,
|
||||
// exactly as `is_file()` did.
|
||||
let Ok(meta) = fs::metadata(&path) else { continue };
|
||||
if meta.is_file() {
|
||||
out.push(Found { path, len: Some(meta.len()) });
|
||||
}
|
||||
}
|
||||
}
|
||||
ScanTrace::add(&mut trace.walk_ms, walking);
|
||||
trace.walk_dirs += dirs.len();
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,446 @@
|
||||
//! One workspace scan in flight: the work list it took, the text and the
|
||||
//! records it has gathered so far, and what it reports about itself as it
|
||||
//! runs.
|
||||
//!
|
||||
//! Split out of `state.rs` on 2026-09-08, as a pure move, when the lazy read
|
||||
//! gave the scan three more things to carry (`docs/features/perf5-p4/README.md`
|
||||
//! §P4b3). [`Workspace`](super::Workspace) drives it — `begin_scan` builds
|
||||
//! one, `scan_step` advances it, `finish_scan` lands it — so the fields are
|
||||
//! `pub(super)` and visible exactly where they were before the move: inside
|
||||
//! `crate::state` and nowhere else.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use crate::includes::Include;
|
||||
use crate::scan_order::{self, WorkList};
|
||||
use crate::scan_trace::{self, ScanTrace};
|
||||
|
||||
/// A `Scope` resolved: which files one index rebuild works from, and the text
|
||||
/// of the ones it already holds.
|
||||
///
|
||||
/// **Nothing on disk has been read.** Until 2026-09-08 this carried every
|
||||
/// in-scope file's text, read in one pass before the first file was indexed —
|
||||
/// 34 MiB and ~293 ms on OpenTitan, held for the whole life of the scan and
|
||||
/// spent before any request could be answered. A file's text is now read at
|
||||
/// the step that indexes it and let go again
|
||||
/// (`docs/features/perf5-p4/README.md` §P4b3). An **open buffer's** text is
|
||||
/// still taken here, with the analysis beside it, because the two must
|
||||
/// describe the same bytes and the buffer may be edited while the scan runs.
|
||||
pub(super) struct Sources {
|
||||
/// Every in-scope file, in scope order: the walked ones the cap and the
|
||||
/// open buffers left, then the buffers' own paths.
|
||||
pub(super) files: Vec<PathBuf>,
|
||||
/// The text of each open buffer among `files`, as it was when the scope
|
||||
/// was resolved.
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
/// What the open buffers among `files` already know about themselves.
|
||||
pub(super) analyzed: Analyzed,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The index facts and the completion words of the entries `texts` took from an
|
||||
/// **open buffer**, read off the analysis that buffer already holds.
|
||||
///
|
||||
/// Both maps are filled in the same loop that lets a buffer override the disk
|
||||
/// copy, so an entry here is always the analysis of exactly the text beside it
|
||||
/// in `texts` — the two cannot describe different bytes. A file that is not an
|
||||
/// open buffer appears in neither map and is parsed and lexed as it always was.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Analyzed {
|
||||
pub(super) facts: HashMap<PathBuf, FileFacts>,
|
||||
pub(super) words: HashMap<PathBuf, Vec<String>>,
|
||||
}
|
||||
|
||||
/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in.
|
||||
///
|
||||
/// An index rebuild does — it is what it indexes the open buffers from. A
|
||||
/// refactoring reads the texts and nothing else, and reading a record off every
|
||||
/// open buffer for it would be work nothing looks at.
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum HeldAnalyses {
|
||||
Wanted,
|
||||
Unused,
|
||||
}
|
||||
|
||||
/// One workspace scan in flight: the work list it took when it began, and how
|
||||
/// far through it the workspace has got.
|
||||
///
|
||||
/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because
|
||||
/// the server answers the client's messages *between* two files of a scan
|
||||
/// (`docs/features/scan-interleave/README.md`), and a message it answers needs
|
||||
/// the very workspace the scan is feeding — which a callback called from
|
||||
/// inside a `&mut self` loop can never be handed. Splitting the loop is what
|
||||
/// puts the scan's state somewhere the message can be answered around.
|
||||
pub struct Scan {
|
||||
/// Whether this scan rebuilds the index or only folds newly-in-scope files
|
||||
/// into it. The whole difference is in [`Workspace::finish_scan`]; every
|
||||
/// step in between is the same code.
|
||||
pub(super) kind: ScanKind,
|
||||
/// Every file this scan indexes, in the order it indexes them: the open
|
||||
/// buffers' own files, then the rest of their folders, then the rest in
|
||||
/// path order ([`crate::scan_order`]). For a widen that is the
|
||||
/// newly-in-scope files plus the open buffers, not the whole scope.
|
||||
///
|
||||
/// **Paths, not texts.** A file's text is read at the step that indexes
|
||||
/// it; see [`Workspace::scan_step`].
|
||||
pub(super) work: Vec<PathBuf>,
|
||||
/// How many files at the front of `work` are the user's own
|
||||
/// neighbourhood — see [`Scan::neighbourhood_indexed`].
|
||||
pub(super) head: usize,
|
||||
/// The text of each open buffer among `work`, taken when the work list
|
||||
/// was, so it describes the same bytes as that buffer's entry in
|
||||
/// `analyzed` however the buffer is edited while the scan runs.
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
/// What each file taken so far `` `include``s, read off the text at its
|
||||
/// own step. Staged for the same reason `words` is: the include graph is
|
||||
/// built once at the end and once per mid-scan publish, and by then the
|
||||
/// text is gone.
|
||||
pub(super) includes: HashMap<PathBuf, Vec<Include>>,
|
||||
/// Files of `work` whose text could not be read when their step came, and
|
||||
/// which therefore contribute nothing at all. Empty in every ordinary
|
||||
/// scan: a file has to leave the disk between the walk and its own step.
|
||||
/// Named so that the scan can leave it out of everything it lands —
|
||||
/// `collect_sources` used to drop such a file before the work list
|
||||
/// existed, and a whole scan must still take it *out* of the index.
|
||||
pub(super) unread: Vec<PathBuf>,
|
||||
/// Every file that is in scope once this scan lands, kept flat so the
|
||||
/// include graph's known-file table can be relearned from a slice. Which
|
||||
/// files *exist* is settled the moment the scope is resolved, so this never
|
||||
/// moves while the scan runs — reordering the tail of `work` does not
|
||||
/// reorder a set. Equal to `work`'s paths for a whole scan; for a widen it
|
||||
/// is the index's files plus `work`'s.
|
||||
pub(super) paths: Vec<PathBuf>,
|
||||
/// What this scan takes *out* of the index, known before it starts. Empty
|
||||
/// for a whole scan, which works out what left the scope from its own work
|
||||
/// list once it has one ([`Workspace::finish_scan`]).
|
||||
pub(super) gone: Vec<PathBuf>,
|
||||
/// What the open buffers among `work` already knew about themselves, taken
|
||||
/// from as each of them is reached.
|
||||
pub(super) analyzed: Analyzed,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
/// How many of `work` have been indexed.
|
||||
pub(super) at: usize,
|
||||
/// The rest of the workspace, still to be discovered — see
|
||||
/// [`PendingDiscovery`]. `None` for every scan that resolved its whole
|
||||
/// scope before it started, which is every scan but a workspace-scoped
|
||||
/// startup with a buffer already open.
|
||||
pub(super) pending: Option<PendingDiscovery>,
|
||||
/// The records taken since the last publish, and which files of `work`
|
||||
/// they came from. Staged rather than merged because a merge is a pass
|
||||
/// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`].
|
||||
pub(super) staged: Vec<FileFacts>,
|
||||
pub(super) staged_at: Vec<usize>,
|
||||
/// The completion words of every file taken so far, which the tables built
|
||||
/// when the scan ends are assembled from.
|
||||
pub(super) words: HashMap<PathBuf, Vec<String>>,
|
||||
/// How many files the size cap kept out, and how many came from the
|
||||
/// persistent cache instead of a parse. Facts about this scan, so they
|
||||
/// live on it — the end message names both.
|
||||
pub(super) skipped: usize,
|
||||
pub(super) cached: usize,
|
||||
/// What this scan spent its time on, when `--verbose` asked. Off, it is a
|
||||
/// bag of zeroes nobody reads (`crate::scan_trace`).
|
||||
pub(super) trace: ScanTrace,
|
||||
}
|
||||
|
||||
/// The half of a scan's scope that has not been walked yet.
|
||||
///
|
||||
/// **One scan, discovered in two goes.** A workspace-scoped session with a
|
||||
/// buffer already open walks that buffer's own folders first, indexes them,
|
||||
/// publishes them and answers the request that has been waiting — and only
|
||||
/// then walks the remaining 3 800 directories, whose 155 ms used to sit in
|
||||
/// front of every one of those steps (`docs/features/perf5r-first-answer`).
|
||||
/// It is emphatically **not** two scans: one work list, one index, one
|
||||
/// `finish_scan`, one `gone` computed against the whole of it, and every file
|
||||
/// stepped exactly once — which is what `seen` is for.
|
||||
pub(super) struct PendingDiscovery {
|
||||
/// The directories still to walk: the workspace roots.
|
||||
pub(super) roots: Vec<PathBuf>,
|
||||
/// Every path the neighbourhood walk yielded — the ones it indexed, the
|
||||
/// ones the size cap kept out, and every open buffer's own path. The
|
||||
/// remaining walk covers the roots, so it finds all of these again; each
|
||||
/// one it names here has already been decided about, and deciding twice
|
||||
/// would step a file twice or report one skip as two.
|
||||
pub(super) seen: HashSet<PathBuf>,
|
||||
/// Every directory identity the neighbourhood walk entered, and the path
|
||||
/// it entered each one by.
|
||||
///
|
||||
/// **The two walks share it, and that is what makes them one walk.** An
|
||||
/// ordinary walk visits each directory identity once and reports its files
|
||||
/// under the first spelling that reached it
|
||||
/// (`docs/features/walk-cycles/README.md`); two walks with two sets would
|
||||
/// report a symlinked directory's files twice, under two spellings a path
|
||||
/// set cannot tell apart, and the index would hold every module in it
|
||||
/// twice. Sharing the tracker restores that contract across the split.
|
||||
pub(super) tracker: lucisv_core::walk::DirectoryTracker,
|
||||
}
|
||||
|
||||
/// How many records may be staged before another mid-scan publish is worth the
|
||||
/// whole-index merge it costs — see [`Scan::publish_is_due`].
|
||||
///
|
||||
/// **512 is a work bound, and it is deliberately the same number
|
||||
/// `HEAD_WALK_MAX` is.** Both answer "how much of this workspace may a user
|
||||
/// wait for before an answer stops being worth waiting for": 512 warm steps is
|
||||
/// ~100 ms of scanning on the corpus the round measured
|
||||
/// (`docs/features/perf5r-first-answer/README.md`), so a request landing
|
||||
/// between two publishes reads an index at most that far behind and the whole
|
||||
/// scan pays at most one merge per 512 files instead of one per burst.
|
||||
pub(crate) const PUBLISH_EVERY: usize = 512;
|
||||
|
||||
/// Which of the two shapes a [`Scan`] is.
|
||||
///
|
||||
/// One enum rather than two `finish` methods so a caller cannot pair the wrong
|
||||
/// ending with a scan: the scan itself says how it must be landed.
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum ScanKind {
|
||||
/// Every in-scope file, and whatever the index holds that the work list
|
||||
/// does not name has left the scope.
|
||||
Whole,
|
||||
/// Only the files a scope widen brought in, folded into the index beside
|
||||
/// what is already there (`docs/features/index-scope/README.md`).
|
||||
Widen,
|
||||
}
|
||||
|
||||
impl Scan {
|
||||
/// How many files the size cap kept out of this scan.
|
||||
pub fn skipped(&self) -> usize {
|
||||
self.skipped
|
||||
}
|
||||
|
||||
/// How many files came from the persistent cache instead of being parsed.
|
||||
pub fn cached(&self) -> usize {
|
||||
self.cached
|
||||
}
|
||||
|
||||
/// How many files this scan will index — known before the first parse,
|
||||
/// which is what lets the caller decide whether the scan is long enough to
|
||||
/// be worth answering messages in the middle of.
|
||||
pub fn total(&self) -> usize {
|
||||
self.work.len()
|
||||
}
|
||||
|
||||
/// Whether this scan has stepped every file of the user's own
|
||||
/// neighbourhood — the open buffers and the folders they raise to
|
||||
/// ([`crate::scan_order`]).
|
||||
///
|
||||
/// **What a request held for the startup scan waits for.** A mid-scan
|
||||
/// answer reads the published prefix, and a prefix holding the user's own
|
||||
/// buffer and the alphabet after it names nothing they asked about: the
|
||||
/// first useful answer of a workspace-scoped session was measurably
|
||||
/// *empty* (`docs/features/perf5-p4/README.md` §P4b2). Waiting for the
|
||||
/// neighbourhood makes it the answer the folder scope would have given,
|
||||
/// which is what it was before the startup scan was staged. Requests that
|
||||
/// arrive after that are answered at every interleave point as they always
|
||||
/// were, and a scan with no neighbourhood (nothing open, an `untitled:`
|
||||
/// buffer, or a folder covering the workspace) has `head` 0 and answers at
|
||||
/// the first one.
|
||||
pub fn neighbourhood_indexed(&self) -> bool {
|
||||
self.at >= self.head
|
||||
}
|
||||
|
||||
/// Whether enough has been staged since the last publish for another one
|
||||
/// to be worth the merge it costs — the **publication cadence**.
|
||||
///
|
||||
/// **A publish is a pass over the whole index, and it used to be one per
|
||||
/// burst of requests.** `answer_what_is_waiting` published whenever
|
||||
/// anything at all was waiting, so a client asking ten times a second
|
||||
/// bought ten merges a second over a table that grows all the way to the
|
||||
/// end of the scan. Measured on opentitan under a definition every 100 ms
|
||||
/// (`docs/features/perf5r-publication/README.md`): 13 to 18 publishes in
|
||||
/// one warm scan, and `absorb` + `candidates` alone were 46 % of it.
|
||||
///
|
||||
/// The rule this asks is **how much new the next answer would see**, not
|
||||
/// how long ago the last publish was: a merge's cost is the index's size
|
||||
/// and its value is the records it makes answerable, so files staged is
|
||||
/// the currency both are in — and it is a count, so what a scan does is
|
||||
/// the same on a fast machine and a slow one, and a test may assert it.
|
||||
///
|
||||
/// It bounds staleness, never correctness: a request answered between two
|
||||
/// publishes reads a prefix at most [`PUBLISH_EVERY`] files older than the
|
||||
/// one it could have had, and every table in it still agrees with every
|
||||
/// other ([`Workspace::publish_scan`](super::Workspace::publish_scan)).
|
||||
/// The **first** publish of a scan is never deferred by it — that one is
|
||||
/// the session's first useful answer, and `server/index.rs` asks for it by
|
||||
/// a different door.
|
||||
pub fn publish_is_due(&self) -> bool {
|
||||
self.staged.len() >= PUBLISH_EVERY
|
||||
}
|
||||
|
||||
/// Whether this scan still owes itself the rest of its own scope — see
|
||||
/// [`PendingDiscovery`].
|
||||
///
|
||||
/// Two callers, and they want it for the same reason: `scan_once` must
|
||||
/// interleave a scan whose work list is short *so far*, and must not paint
|
||||
/// a percentage against a denominator that is going to grow
|
||||
/// (`docs/features/indexing-ux/README.md`).
|
||||
pub fn discovery_pending(&self) -> bool {
|
||||
self.pending.is_some()
|
||||
}
|
||||
|
||||
/// Take the remaining discovery, so the workspace can run it.
|
||||
pub(super) fn take_pending(&mut self) -> Option<PendingDiscovery> {
|
||||
self.pending.take()
|
||||
}
|
||||
|
||||
/// Whether this scan's answers are right but **spelled** differently from
|
||||
/// what a plain walk of the same tree would spell them, so one ordinary
|
||||
/// rescan is owed.
|
||||
///
|
||||
/// The case: a directory alias outside the open folder's ancestor chain —
|
||||
/// `other/link -> z_real`, with `other` sorting first. The head leads with
|
||||
/// `z_real`; the remaining walk meets `other/link`, recognises the
|
||||
/// directory the head already entered and skips it, so nothing is
|
||||
/// discovered twice and every answer this scan gives is one target and one
|
||||
/// file. But a walk of the root on its own — the next rescan, or a session
|
||||
/// that opens nothing — spells those same files `other/link/…`, and a
|
||||
/// startup that disagreed with every later scan about a path is the defect
|
||||
/// this whole tracker exists to close (`docs/performance_052_review.md`
|
||||
/// F1). So the scan asks for the canonical walk once it has landed, and
|
||||
/// the spelling converges there.
|
||||
///
|
||||
/// **Exactly one rescan can ever come of it.** Only a session's first scan
|
||||
/// splits its discovery ([`Workspace::first_scope`]), so the scan this
|
||||
/// asks for resolves its whole scope in one walk, has no
|
||||
/// [`PendingDiscovery`], and cannot ask again.
|
||||
///
|
||||
/// The answer is the trace's own counter, which is written whether or not
|
||||
/// anybody asked for a trace — like `publishes`, it is a fact about the
|
||||
/// scan rather than a stopwatch reading, so it lives where the scan's
|
||||
/// facts live and the `--verbose` count line says it out loud.
|
||||
pub fn wants_rescan(&self) -> bool {
|
||||
self.trace.rescan_requested > 0
|
||||
}
|
||||
|
||||
/// Fold the rest of the scope into this scan: its files onto the end of
|
||||
/// the work list, its paths into the set the include graph learns from,
|
||||
/// its warnings and its skips onto the scan's own — and whether the walk
|
||||
/// that found them disagreed with the head about a directory's spelling
|
||||
/// ([`Scan::wants_rescan`]).
|
||||
///
|
||||
/// Appended rather than re-ordered: the neighbourhood at the front has
|
||||
/// already been stepped, and `vlog_semantic::IndexBuilder` sorts by path
|
||||
/// inside `finish`, so what arrives here decides latency and nothing else
|
||||
/// ([`Scan::reorder`] makes the same argument).
|
||||
pub(super) fn land_discovery(
|
||||
&mut self,
|
||||
files: Vec<PathBuf>,
|
||||
warnings: Vec<String>,
|
||||
skipped: usize,
|
||||
conflict: bool,
|
||||
) {
|
||||
self.trace.conflict += usize::from(conflict);
|
||||
self.trace.rescan_requested += usize::from(conflict);
|
||||
self.paths.extend(files.iter().cloned());
|
||||
self.paths.sort();
|
||||
self.paths.dedup();
|
||||
self.work.extend(files);
|
||||
self.warnings.extend(warnings);
|
||||
self.skipped += skipped;
|
||||
}
|
||||
|
||||
/// The text of one file of this scan's work list, at the moment its step
|
||||
/// comes — `None` when it cannot be read.
|
||||
///
|
||||
/// An open buffer's is the copy taken when the work list was, and it is
|
||||
/// *taken*: a scan indexes each file once, so holding it afterwards would
|
||||
/// be holding a second copy of a buffer the workspace already has. Every
|
||||
/// other file is read from disk here and nowhere else in the scan.
|
||||
pub(super) fn take_text(&mut self, path: &Path) -> Option<String> {
|
||||
if let Some(text) = self.buffered.remove(path) {
|
||||
return Some(text);
|
||||
}
|
||||
let reading = self.trace.now();
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
scan_trace::count_read();
|
||||
self.trace.saw_read(text.len(), reading);
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The files this scan has not reached yet, for a caller that wants to
|
||||
/// re-order them ([`Scan::reorder`]).
|
||||
pub fn remaining(&self) -> Vec<PathBuf> {
|
||||
self.work[self.at.min(self.work.len())..].to_vec()
|
||||
}
|
||||
|
||||
/// Put `ordered` — [`Scan::remaining`] ranked again — back as what is left
|
||||
/// to index, and take its head segment as the new neighbourhood.
|
||||
///
|
||||
/// The open-first rule, applied to a buffer opened *after* the work list
|
||||
/// was taken: a `didOpen` answered mid-scan puts that file and the folder
|
||||
/// around it next rather than leaving the user waiting for the alphabet to
|
||||
/// reach them. Reordering the tail cannot change the finished index —
|
||||
/// records are merged in path order whatever order they were taken in
|
||||
/// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and
|
||||
/// nothing more.
|
||||
pub fn reorder(&mut self, ordered: WorkList) {
|
||||
let at = self.at.min(self.work.len());
|
||||
self.work.truncate(at);
|
||||
self.work.extend(ordered.files);
|
||||
// What is left to wait for, bounded against the whole scan rather than
|
||||
// against the tail it was ranked from
|
||||
// ([`crate::scan_order::worth_waiting`]), and then placed: the
|
||||
// neighbourhood ends that many files past where the scan has got to.
|
||||
self.head = match scan_order::worth_waiting(ordered.head, self.work.len()) {
|
||||
0 => 0,
|
||||
pending => at + pending,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// What each of `taken` `` `include``s, as [`IncludeGraph`] wants it.
|
||||
///
|
||||
/// Borrowed, never cloned: the lists were read at each file's own step and the
|
||||
/// graph only reads them again ([`crate::includes::IncludeGraph::from_includes`]).
|
||||
///
|
||||
/// A free function rather than a method because the two callers hold the map
|
||||
/// differently — a mid-scan publish still has the whole [`Scan`], and the two
|
||||
/// `finish` paths have taken it apart.
|
||||
pub(super) fn included<'a>(
|
||||
includes: &'a HashMap<PathBuf, Vec<Include>>,
|
||||
taken: &'a [PathBuf],
|
||||
) -> Vec<(&'a Path, &'a [Include])> {
|
||||
taken
|
||||
.iter()
|
||||
.map(|path| (path.as_path(), includes.get(path).map(Vec::as_slice).unwrap_or(&[])))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What an index rebuild reports about itself as it runs.
|
||||
///
|
||||
/// This module speaks no protocol, so an event carries numbers and paths and
|
||||
/// nothing that reads like a message; `server.rs` turns them into a progress
|
||||
/// report and a log line (`docs/features/indexing-ux/README.md`).
|
||||
pub enum IndexEvent<'a> {
|
||||
/// One file is about to be parsed into the index: how many were parsed
|
||||
/// before it, how many there are in all, and which one it is. `done`
|
||||
/// counts from 0, so the file being reported is number `done + 1` of
|
||||
/// `total`.
|
||||
Parsing { done: usize, total: usize, path: &'a Path },
|
||||
/// One file went into the index from the persistent cache instead of
|
||||
/// being parsed. The same three numbers [`IndexEvent::Parsing`] carries,
|
||||
/// because it is the same file of the same work list — it is *how* it got
|
||||
/// there that differs, and a user watching a rescan fly through a
|
||||
/// thousand files deserves to be told why.
|
||||
Cached { done: usize, total: usize, path: &'a Path },
|
||||
/// One file went into the index from the analysis an **open buffer**
|
||||
/// already holds — the parse this server did when the buffer was last
|
||||
/// opened or changed — instead of being parsed again. The same three
|
||||
/// numbers the other two carry, for the same reason.
|
||||
///
|
||||
/// Its own variant rather than [`IndexEvent::Cached`] so that "from cache"
|
||||
/// keeps meaning the persistent store and nothing else
|
||||
/// (`docs/features/index-persistence/README.md`): a buffer's own analysis
|
||||
/// is in memory, is there whether that store exists or not, and is right
|
||||
/// even when the buffer has unsaved edits — which is exactly when a
|
||||
/// content-keyed store has nothing to offer.
|
||||
Analyzed { done: usize, total: usize, path: &'a Path },
|
||||
/// A walked file was skipped without being read, because it is bigger
|
||||
/// than the size cap in force.
|
||||
Skipped { path: &'a Path, size: u64, cap: u64 },
|
||||
}
|
||||
@@ -8631,3 +8631,113 @@ fn organize_imports_is_offered_under_its_own_kind_and_runs_as_a_command() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// TODO §64.1 over the wire. `leaf` declares an internal net; `top.sv` names it
|
||||
/// through a hierarchical tail and `leaf.sv` uses it itself. Before §64.1
|
||||
/// `textDocument/references` answered `leaf.sv`'s two lines from the
|
||||
/// declaration and never the tail, while `textDocument/rename` at the same
|
||||
/// position edited both files — lucisv could change a reference it could not
|
||||
/// list. Asserted here from both ends, with `leaf.sv` the only open buffer, so
|
||||
/// the tail comes out of the persisted postings and `leaf.sv`'s own use out of
|
||||
/// the live one; then from `top.sv` with `leaf.sv` closed, where that file's
|
||||
/// own use is served by one re-analysis of it.
|
||||
#[test]
|
||||
fn a_hierarchical_nets_references_and_rename_agree_over_the_wire() {
|
||||
let dir = temp_dir("hierrefs");
|
||||
let leaf = dir.join("leaf.sv");
|
||||
let leaf_text = "\
|
||||
module leaf (input logic clk_i);
|
||||
logic sig;
|
||||
assign sig = clk_i;
|
||||
endmodule
|
||||
";
|
||||
std::fs::write(&leaf, leaf_text).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
module top;
|
||||
leaf u_leaf (.clk_i(1'b0));
|
||||
wire w;
|
||||
assign w = u_leaf.sig;
|
||||
endmodule
|
||||
";
|
||||
std::fs::write(&top, top_text).expect("write");
|
||||
|
||||
let root = format!("file://{}", dir.display());
|
||||
let leaf_uri = format!("file://{}", leaf.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
// `sig` is declared at line 1 column 8 of `leaf.sv`, used at line 2
|
||||
// column 9 there, and named at line 3 column 20 of `top.sv`.
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(WIDE_SCOPE),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{leaf_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(leaf_text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"context":{{"includeDeclaration":true}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"newName":"renamed"}}}}"#
|
||||
)),
|
||||
// Now from the other side, with `leaf.sv` shut.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didClose","params":{{"textDocument":{{"uri":"{leaf_uri}"}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(top_text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":3,"character":20}},"context":{{"includeDeclaration":true}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let response = |id: u32| -> &serde_json::Value {
|
||||
messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == id)
|
||||
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))
|
||||
};
|
||||
|
||||
// Every place naming the net, as `(file, line)`.
|
||||
let places = |id: u32| -> Vec<(String, i64)> {
|
||||
let mut out: Vec<(String, i64)> = response(id)["result"]
|
||||
.as_array()
|
||||
.expect("a list")
|
||||
.iter()
|
||||
.map(|location| {
|
||||
let uri = location["uri"].as_str().expect("a uri");
|
||||
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
|
||||
(name, location["range"]["start"]["line"].as_i64().expect("a line"))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
let everywhere =
|
||||
vec![("leaf.sv".to_string(), 1), ("leaf.sv".to_string(), 2), ("top.sv".to_string(), 3)];
|
||||
assert_eq!(places(2), everywhere, "from the declaration");
|
||||
assert_eq!(places(4), everywhere, "from the tail, with `leaf.sv` closed");
|
||||
|
||||
// And the rename that was already editing both files edits exactly those
|
||||
// places — the asymmetry §64.1 was filed for, closed from both sides.
|
||||
let changes = &response(3)["result"]["changes"];
|
||||
let own = changes[&leaf_uri].as_array().expect("edits for the declaring file");
|
||||
assert_eq!(own.len(), 2, "{own:#?}");
|
||||
let elsewhere = changes[&top_uri].as_array().expect("edits for the naming file");
|
||||
assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}");
|
||||
assert_eq!(elsewhere[0]["range"]["start"]["line"], 3);
|
||||
assert_eq!(elsewhere[0]["range"]["start"]["character"], 20);
|
||||
assert!(elsewhere.iter().all(|e| e["newText"] == "renamed"), "{elsewhere:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -14,14 +14,29 @@
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::{analyze, FileFacts, IndexBuilder, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::context::ModuleInterface;
|
||||
use crate::visit::walk_items;
|
||||
use crate::ParsedSource;
|
||||
|
||||
/// Every package one file declares, with the names it exports — `None` for a
|
||||
/// package this file alone cannot answer for.
|
||||
///
|
||||
/// The text-taking form, for a caller that has not parsed: exactly one
|
||||
/// [`ParsedSource::parse`] followed by [`package_exports_in`], so the two can
|
||||
/// only ever give the same answer.
|
||||
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let parsed = ParsedSource::parse(src);
|
||||
package_exports_in(path, parsed.file(), parsed.tokens(), src)
|
||||
}
|
||||
|
||||
/// [`package_exports`] over a parse the caller **already has** — `file` and
|
||||
/// `tokens` from one [`ParsedSource::parse`] of `src`.
|
||||
///
|
||||
/// The CLI's half of [`crate::MentionOracle::package_exports`], on the same
|
||||
/// terms [`module_interfaces`] is the CLI's half of `module_interface`: the
|
||||
/// language server reads the answer off its workspace index, and a run with
|
||||
@@ -31,8 +46,25 @@ use crate::visit::walk_items;
|
||||
/// A package writing `export q::*;` answers `None`: which names that lets
|
||||
/// through is a question only a whole-project index can settle, and a short
|
||||
/// list is what would turn a used import into an accusation.
|
||||
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
|
||||
///
|
||||
/// Two things make this cheap enough for the CLI to run over a whole project
|
||||
/// (take 5 §P3, `docs/features/perf5-p3/README.md`). The index is built from
|
||||
/// the caller's parse rather than from the text, so the file is lexed and
|
||||
/// parsed once for this and for the interface census together; and a file
|
||||
/// whose tree holds **no package item** never reaches the index at all — nine
|
||||
/// files in ten on opentitan `hw/ip`. The gate reads the AST, never the text:
|
||||
/// a `package` inside a string or a comment is not a declaration, and a file
|
||||
/// that says nothing about packages must cost nothing.
|
||||
pub fn package_exports_in(
|
||||
path: &Path,
|
||||
file: &SourceFile,
|
||||
tokens: &[Token],
|
||||
src: &str,
|
||||
) -> Vec<(String, Option<Vec<String>>)> {
|
||||
if !declares_a_package(file) {
|
||||
return Vec::new();
|
||||
}
|
||||
let index = one_file_index(path, file, tokens, src);
|
||||
index
|
||||
.units_of(SymbolKind::Package)
|
||||
.map(|(name, _)| name.to_string())
|
||||
@@ -48,6 +80,52 @@ pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether this tree holds a `package` item anywhere, which is the gate on
|
||||
/// building an index for the file at all.
|
||||
///
|
||||
/// Deliberately a **superset** of "declares a package unit": `walk_items`
|
||||
/// descends into every container, while only a package item bound in the file
|
||||
/// scope becomes a unit the index records. Answering `true` too often costs
|
||||
/// an index; answering `false` too often would lose a package, so the walk
|
||||
/// errs the one way it may.
|
||||
///
|
||||
/// A **fragment** parse — a file that is the bare middle of something, so its
|
||||
/// items list is empty and its content hangs off `SourceFile::fragment` —
|
||||
/// `walk_items` does not descend into, and is never gated out. No fragment
|
||||
/// shape can hold a package (they are statements, enum members and cover
|
||||
/// items, and a file opening with `package` is never re-read as one), but the
|
||||
/// gate does not rest on that.
|
||||
fn declares_a_package(file: &SourceFile) -> bool {
|
||||
if file.fragment.is_some() {
|
||||
return true;
|
||||
}
|
||||
let mut found = false;
|
||||
walk_items(file, &mut |item| {
|
||||
found |= matches!(item.kind, ItemKind::Package { .. });
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// The one-file index [`WorkspaceIndex::build`] would make of this file,
|
||||
/// built from the caller's parse instead of from its text.
|
||||
///
|
||||
/// `build` is `IndexBuilder::add_file` + `finish`, and `add_file` is
|
||||
/// `add_facts(FileFacts::of(path, src))`. `FileFacts::of` parses, analyses and
|
||||
/// reads the record off; [`FileFacts::from_analysis`] is that same read-off
|
||||
/// with the parse handed in. So this is `build` with the lex and the parse it
|
||||
/// would have done deleted — pinned by the equality test below, not by the
|
||||
/// reading of two functions.
|
||||
fn one_file_index(path: &Path, file: &SourceFile, tokens: &[Token], src: &str) -> WorkspaceIndex {
|
||||
let defines = collect_defines(tokens);
|
||||
let sem = analyze(file, src);
|
||||
let lines = LineIndex::new(src);
|
||||
let facts =
|
||||
FileFacts::from_analysis(path.to_path_buf(), file, &defines, &sem, src, &lines, tokens);
|
||||
let mut builder = IndexBuilder::new();
|
||||
builder.add_facts(facts);
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
/// Every module, interface and program the file declares, with what it
|
||||
/// exposes. `None` for a unit whose header cannot be read whole.
|
||||
///
|
||||
@@ -213,3 +291,196 @@ mod tests {
|
||||
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The package half: every fixture answers what a one-file `WorkspaceIndex`
|
||||
/// built from the file's **text** answers, and a file with no package item
|
||||
/// never builds one (take 5 §P3).
|
||||
#[cfg(test)]
|
||||
mod package_tests {
|
||||
use super::*;
|
||||
|
||||
/// The construction §P3 replaced, kept here as the thing to be equal to:
|
||||
/// a one-file index built from the text, queried exactly as
|
||||
/// [`package_exports_in`] queries the index it builds from a parse.
|
||||
fn from_text(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
|
||||
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
|
||||
index
|
||||
.units_of(SymbolKind::Package)
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let answer = index.reexported_packages(&name).is_empty().then(|| {
|
||||
index.members_of(&name).map(|(member, _)| member.to_string()).collect()
|
||||
});
|
||||
(name, answer)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every shape the census can meet, named so a failure says which.
|
||||
///
|
||||
/// The list is the §P3 brief's: no package, one, two, a wildcard export,
|
||||
/// a named re-export, a package behind a directive, a package after a
|
||||
/// module, text that does not lex, a parse error inside a package body, a
|
||||
/// class in a package, the word `package` in a string and in a comment,
|
||||
/// and one name declared twice in the same file.
|
||||
fn fixtures() -> Vec<(&'static str, &'static str)> {
|
||||
vec![
|
||||
("no package", "module m ();\n wire a;\nendmodule\n"),
|
||||
(
|
||||
"one package",
|
||||
"package p;\n localparam int A = 1;\n typedef logic [1:0] t;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"two packages",
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package q;\n localparam int B = 2;\nendpackage\n",
|
||||
),
|
||||
(
|
||||
"a wildcard export of itself",
|
||||
"package p;\n localparam int A = 1;\n export *::*;\nendpackage\n",
|
||||
),
|
||||
(
|
||||
"a wildcard export of another package",
|
||||
"package p;\n import q::*;\n localparam int A = 1;\n export q::*;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a named re-export",
|
||||
"package p;\n import q::x;\n localparam int A = 1;\n export q::x;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a package behind a directive",
|
||||
"`ifdef USE_PKG\npackage p;\n localparam int A = 1;\nendpackage\n`endif\n",
|
||||
),
|
||||
(
|
||||
"a package after a module",
|
||||
"module m ();\nendmodule\npackage p;\n localparam int A = 1;\nendpackage\n",
|
||||
),
|
||||
("text that does not lex", "module m;\n wire a = \"unterminated\nendmodule\n"),
|
||||
(
|
||||
"a parse error inside the package",
|
||||
"package p;\n localparam int A = 1;\n @@@ ;\n localparam int B = 2;\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"a class in a package",
|
||||
"package p;\n class c;\n int field;\n endclass\n\
|
||||
endpackage\n",
|
||||
),
|
||||
(
|
||||
"the word package in a string",
|
||||
"module m ();\n initial $display(\"package p; endpackage\");\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"the word package in a comment",
|
||||
"// package p; endpackage\nmodule m ();\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"one name declared twice",
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package p;\n localparam int B = 2;\nendpackage\n",
|
||||
),
|
||||
("an empty file", ""),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fixture_answers_what_a_text_built_index_answers() {
|
||||
for (name, src) in fixtures() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
assert_eq!(package_exports(path, src), from_text(path, src), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_and_the_text_form_agree() {
|
||||
for (name, src) in fixtures() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
let parsed = ParsedSource::parse(src);
|
||||
assert_eq!(
|
||||
package_exports_in(path, parsed.file(), parsed.tokens(), src),
|
||||
package_exports(path, src),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The gate is the whole saving, so it is asserted directly rather than
|
||||
/// inferred from an equal answer: exactly the fixtures that write a
|
||||
/// `package` item reach the index.
|
||||
#[test]
|
||||
fn only_a_package_item_opens_the_gate() {
|
||||
let gated_out = [
|
||||
"no package",
|
||||
"text that does not lex",
|
||||
"the word package in a string",
|
||||
"the word package in a comment",
|
||||
"an empty file",
|
||||
];
|
||||
for (name, src) in fixtures() {
|
||||
let opens = declares_a_package(ParsedSource::parse(src).file());
|
||||
assert_eq!(opens, !gated_out.contains(&name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that does not lex really is one, or the fixture above tests
|
||||
/// nothing about the lex-error path.
|
||||
#[test]
|
||||
fn the_unlexable_fixture_does_not_lex() {
|
||||
let src = fixtures()
|
||||
.into_iter()
|
||||
.find(|(name, _)| *name == "text that does not lex")
|
||||
.map(|(_, src)| src)
|
||||
.unwrap_or_default();
|
||||
assert!(ParsedSource::parse(src).lex_error().is_some(), "{src:?}");
|
||||
}
|
||||
|
||||
/// The answers themselves, not only their equality to the old
|
||||
/// construction: a file with no package says nothing, a plain package is
|
||||
/// a list, and a re-export is unknowable.
|
||||
#[test]
|
||||
fn the_answers_are_the_conservative_ones() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
assert!(package_exports(path, "module m ();\nendmodule\n").is_empty());
|
||||
|
||||
let plain = package_exports(path, "package p;\n localparam int A = 1;\nendpackage\n");
|
||||
assert_eq!(plain.len(), 1);
|
||||
assert_eq!(plain[0].0, "p");
|
||||
assert_eq!(plain[0].1.as_deref(), Some(["A".to_string()].as_slice()));
|
||||
|
||||
let wildcard = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int A = 1;\n export q::*;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(wildcard, vec![("p".to_string(), None)], "a re-export is unknowable");
|
||||
}
|
||||
|
||||
/// One name declared twice **in one file** — the `` `ifdef``-copied
|
||||
/// package — answers with the *first* declaration's members, not with
|
||||
/// `None`. That is what the one-file index has always said and this lane
|
||||
/// changes nothing about it; the `None` the CLI's census produces is the
|
||||
/// *cross-file* rule, applied by `Census::of`'s merge when two files each
|
||||
/// contribute an entry for one name.
|
||||
///
|
||||
/// Pinned here so a later change to either construction has to notice it.
|
||||
#[test]
|
||||
fn a_name_declared_twice_in_one_file_answers_with_the_first() {
|
||||
let path = Path::new("/w/f.sv");
|
||||
let first = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int A = 1;\nendpackage\n\
|
||||
package p;\n localparam int B = 2;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(first, vec![("p".to_string(), Some(vec!["A".to_string()]))]);
|
||||
let swapped = package_exports(
|
||||
path,
|
||||
"package p;\n localparam int B = 2;\nendpackage\n\
|
||||
package p;\n localparam int A = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(swapped, vec![("p".to_string(), Some(vec!["B".to_string()]))]);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ mod waiver_file;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
|
||||
pub use interfaces::{module_interfaces, package_exports};
|
||||
pub use interfaces::{module_interfaces, package_exports, package_exports_in};
|
||||
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
|
||||
pub use registry::{
|
||||
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
|
||||
|
||||
+280
-62
@@ -403,8 +403,14 @@ impl<'a> RawLexer<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
// Operators, longest match first.
|
||||
// Operators, longest match first. The first-byte test is not a second
|
||||
// way of matching — `starts_with` still decides — it is what keeps a
|
||||
// `;` from being compared against all 42 spellings: one byte compare
|
||||
// rejects every operator that cannot start here (TODO §63.2).
|
||||
for op in OPERATORS {
|
||||
if op.as_bytes()[0] != c {
|
||||
continue;
|
||||
}
|
||||
if self.starts_with(op) {
|
||||
for _ in 0..op.len() {
|
||||
self.bump();
|
||||
@@ -918,80 +924,111 @@ fn is_line_directive(word: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// What the attachment phase carries from one raw token to the next.
|
||||
#[derive(Default)]
|
||||
struct Attaching {
|
||||
/// Comments waiting for the real token they lead.
|
||||
pending: Vec<Comment>,
|
||||
/// Whether a blank line was seen since the last pending comment.
|
||||
pending_blank: bool,
|
||||
}
|
||||
|
||||
/// Tokenize source text, attaching comments and blank-line info to tokens.
|
||||
///
|
||||
/// The two phases are **fused**: each raw token is attached as it is lexed,
|
||||
/// rather than collected into a `Vec<RawTok>` the attachment loop then walks.
|
||||
/// Attachment only ever reads the raw token in hand and the token last pushed,
|
||||
/// so the fusion is a pure reordering — it drops a second whole-file vector
|
||||
/// (a 40 267-line file's worth of it is ~22 MB of allocation, growth copying
|
||||
/// and teardown), which is why the first request after an edit pays less for
|
||||
/// the same tokens (TODO §63.2).
|
||||
pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
|
||||
let mut raw_lexer = RawLexer::new(source.as_bytes());
|
||||
let mut raws: Vec<RawTok> = Vec::new();
|
||||
let mut tokens: Vec<Token> = Vec::with_capacity(estimated_tokens(source.len()));
|
||||
let mut state = Attaching::default();
|
||||
loop {
|
||||
let tok = raw_lexer.next_raw()?;
|
||||
let is_eof = tok.kind == RawKind::Real(TokenKind::Eof);
|
||||
raws.push(tok);
|
||||
let raw = raw_lexer.next_raw()?;
|
||||
let is_eof = raw.kind == RawKind::Real(TokenKind::Eof);
|
||||
attach(raw, &mut tokens, &mut state);
|
||||
if is_eof {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
// Attachment phase.
|
||||
let mut tokens: Vec<Token> = Vec::new();
|
||||
let mut pending: Vec<Comment> = Vec::new();
|
||||
let mut pending_blank = false;
|
||||
/// How many tokens a source of `bytes` bytes is guessed to hold.
|
||||
///
|
||||
/// Only to spare the growing vector its early doublings; a wrong guess costs
|
||||
/// nothing but the growth it would have paid anyway. Six bytes a token is the
|
||||
/// measured average over the corpus and over opentitan's generated register
|
||||
/// files alike, and the guess is capped so a pathological file (one enormous
|
||||
/// string literal) cannot reserve more than it could ever need.
|
||||
fn estimated_tokens(bytes: usize) -> usize {
|
||||
(bytes / 6).min(1 << 20)
|
||||
}
|
||||
|
||||
for raw in raws {
|
||||
match raw.kind {
|
||||
RawKind::LineComment | RawKind::BlockComment => {
|
||||
let same_line_as_prev =
|
||||
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
|
||||
let comment = Comment {
|
||||
text: raw.text,
|
||||
blank_before: raw.newlines_before > 1 || pending_blank,
|
||||
line: raw.line,
|
||||
col: raw.col,
|
||||
span: raw.span,
|
||||
};
|
||||
if same_line_as_prev {
|
||||
// Trailing comment for the previous real token.
|
||||
let prev = tokens.last_mut().unwrap();
|
||||
match &mut prev.trailing {
|
||||
Some(existing) => {
|
||||
// Two comments on one line become one node, so its
|
||||
// span has to cover both — the merge normalizes
|
||||
// the gap between them to a single space, which is
|
||||
// why a merged comment is the one comment whose
|
||||
// text can differ from `source[span]`.
|
||||
existing.text.push(' ');
|
||||
existing.text.push_str(&comment.text);
|
||||
existing.span = TextRange::new(existing.span.start, comment.span.end);
|
||||
}
|
||||
None => prev.trailing = Some(comment),
|
||||
}
|
||||
} else {
|
||||
pending.push(comment);
|
||||
pending_blank = false;
|
||||
}
|
||||
}
|
||||
RawKind::Real(kind) => {
|
||||
let blank_before = if pending.is_empty() {
|
||||
raw.newlines_before > 1
|
||||
} else {
|
||||
// Comments already carry their own blank flags; the token
|
||||
// is blank-separated only if there was a blank line
|
||||
// between the last comment and the token itself.
|
||||
raw.newlines_before > 1
|
||||
};
|
||||
tokens.push(Token {
|
||||
kind,
|
||||
text: raw.text,
|
||||
line: raw.line,
|
||||
col: raw.col,
|
||||
span: raw.span,
|
||||
leading: std::mem::take(&mut pending),
|
||||
trailing: None,
|
||||
blank_before,
|
||||
});
|
||||
/// Fold one raw token into the token stream: a comment onto its neighbour,
|
||||
/// a real token onto the end with whatever comments were waiting for it.
|
||||
fn attach(raw: RawTok, tokens: &mut Vec<Token>, state: &mut Attaching) {
|
||||
match raw.kind {
|
||||
RawKind::LineComment | RawKind::BlockComment => {
|
||||
let same_line_as_prev =
|
||||
raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty();
|
||||
let comment = Comment {
|
||||
text: raw.text,
|
||||
blank_before: raw.newlines_before > 1 || state.pending_blank,
|
||||
line: raw.line,
|
||||
col: raw.col,
|
||||
span: raw.span,
|
||||
};
|
||||
// A comment that finds no token to trail — unreachable while
|
||||
// `same_line_as_prev` requires one, kept as a rule rather than a
|
||||
// hope — leads the next token instead of vanishing (invariant 3).
|
||||
let orphan =
|
||||
if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) };
|
||||
if let Some(comment) = orphan {
|
||||
state.pending.push(comment);
|
||||
state.pending_blank = false;
|
||||
}
|
||||
}
|
||||
RawKind::Real(kind) => {
|
||||
// Comments already carry their own blank flags; the token is
|
||||
// blank-separated only if there was a blank line between the last
|
||||
// comment and the token itself — which is the same test either
|
||||
// way, so `pending` does not enter into it.
|
||||
let blank_before = raw.newlines_before > 1;
|
||||
tokens.push(Token {
|
||||
kind,
|
||||
text: raw.text,
|
||||
line: raw.line,
|
||||
col: raw.col,
|
||||
span: raw.span,
|
||||
leading: std::mem::take(&mut state.pending),
|
||||
trailing: None,
|
||||
blank_before,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
/// Hang a comment off the token before it, merging with one already there.
|
||||
/// Handed back untouched when there is no token before it.
|
||||
fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option<Comment> {
|
||||
let Some(prev) = tokens.last_mut() else { return Some(comment) };
|
||||
match &mut prev.trailing {
|
||||
Some(existing) => {
|
||||
// Two comments on one line become one node, so its span has to
|
||||
// cover both — the merge normalizes the gap between them to a
|
||||
// single space, which is why a merged comment is the one comment
|
||||
// whose text can differ from `source[span]`.
|
||||
existing.text.push(' ');
|
||||
existing.text.push_str(&comment.text);
|
||||
existing.span = TextRange::new(existing.span.start, comment.span.end);
|
||||
}
|
||||
None => prev.trailing = Some(comment),
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1510,4 +1547,185 @@ mod tests {
|
||||
assert!(texts.contains(&"!=="));
|
||||
assert!(texts.contains(&"<="));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TODO §63.2 QA: the fused attach phase, attacked
|
||||
//
|
||||
// These cover the shapes the two-phase code (a `Vec<RawTok>` fully
|
||||
// built, then walked) could tell apart from the fused one-pass code
|
||||
// (each raw token attached as it is produced) if the fusion were not a
|
||||
// pure reordering: a comment with no token before it at all, comments
|
||||
// that never see a "previous token" until much later, EOF immediately
|
||||
// after a trailing comment, and so on. Every one of these was also
|
||||
// cross-checked, file for file, against `tokenize` built from 1b8723c
|
||||
// (the pre-fusion tree) with a throwaway digest tool in the QA
|
||||
// scratchpad — token-for-token identical, hash and manual `Debug`
|
||||
// inspection alike; the assertions below pin that result durably.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_comment_as_the_very_first_thing_in_the_file_is_the_first_token_s_leading() {
|
||||
let toks = tokenize("// only thing before the module\nmodule m;\nendmodule").unwrap();
|
||||
assert_eq!(toks[0].leading.len(), 1);
|
||||
assert_eq!(toks[0].leading[0].text, "// only thing before the module");
|
||||
assert!(!toks[0].leading[0].blank_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_comments_on_the_first_line_before_any_token_both_lead_it() {
|
||||
// Two *separate* comments here means two lines, each its own line
|
||||
// comment (a line comment always runs to end of line, so "two
|
||||
// comments on one line" before any token is only possible with
|
||||
// block comments — covered by `two_block_comments_on_one_line_merge`
|
||||
// below).
|
||||
let toks = tokenize("// one\n// two\nmodule m;\nendmodule").unwrap();
|
||||
assert_eq!(toks[0].leading.len(), 2);
|
||||
assert_eq!(toks[0].leading[0].text, "// one");
|
||||
assert_eq!(toks[0].leading[1].text, "// two");
|
||||
assert!(!toks[0].leading[1].blank_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_after_the_last_real_token_reaches_eof() {
|
||||
let toks = tokenize("module m;\nendmodule // trailing at eof\n").unwrap();
|
||||
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
|
||||
let trailing = end.trailing.as_ref().expect("trailing comment on endmodule");
|
||||
assert_eq!(trailing.text, "// trailing at eof");
|
||||
assert_eq!(toks.last().unwrap().kind, TokenKind::Eof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_block_comments_on_one_line_merge_into_one_trailing_comment() {
|
||||
let toks = tokenize("wire w; /* one */ /* two */\nendmodule").unwrap();
|
||||
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
|
||||
let trailing = semi.trailing.as_ref().expect("merged trailing comment");
|
||||
assert_eq!(trailing.text, "/* one */ /* two */");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_line_between_a_comment_and_its_token_marks_both() {
|
||||
let toks = tokenize("// lead\n\nmodule m;\nendmodule").unwrap();
|
||||
assert_eq!(toks[0].leading.len(), 1);
|
||||
// The comment itself is not blank-separated from what came before it
|
||||
// (nothing did); the blank line sits between the comment and the
|
||||
// token, so the *token* carries the flag.
|
||||
assert!(!toks[0].leading[0].blank_before);
|
||||
assert!(toks[0].blank_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_lex_like_lf_with_the_same_comment_attachment() {
|
||||
let toks = tokenize("module m; // c\r\nendmodule\r\n").unwrap();
|
||||
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
|
||||
assert_eq!(semi.trailing.as_ref().unwrap().text, "// c");
|
||||
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
|
||||
assert_eq!(end.line, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_spanning_lines_still_leads_a_same_line_token() {
|
||||
let toks = tokenize("/* block\n spanning\n lines */ module m;\nendmodule").unwrap();
|
||||
assert_eq!(toks[0].leading.len(), 1);
|
||||
assert!(toks[0].leading[0].text.starts_with("/* block"));
|
||||
assert!(toks[0].leading[0].text.ends_with("lines */"));
|
||||
// The module keyword itself sits on the block comment's last line.
|
||||
assert_eq!(toks[0].line, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_between_a_macro_invocation_and_its_arguments_trails_the_macro() {
|
||||
let toks = tokenize("module m;\n`MYMACRO /*c*/ (a, b);\nendmodule").unwrap();
|
||||
let mac = toks.iter().find(|t| t.text == "`MYMACRO").unwrap();
|
||||
assert_eq!(mac.trailing.as_ref().unwrap().text, "/*c*/");
|
||||
// The macro call's parenthesized arguments are unaffected — still
|
||||
// ordinary tokens right after, comment or not.
|
||||
let open_paren_idx = toks.iter().position(|t| t.is_sym("(")).unwrap();
|
||||
assert_eq!(toks[open_paren_idx + 1].text, "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_only_comments_attaches_them_all_to_the_synthetic_eof() {
|
||||
let toks = tokenize("// only a comment, nothing else\n").unwrap();
|
||||
assert_eq!(toks.len(), 1);
|
||||
assert_eq!(toks[0].kind, TokenKind::Eof);
|
||||
assert_eq!(toks[0].leading.len(), 1);
|
||||
assert_eq!(toks[0].leading[0].text, "// only a comment, nothing else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_lexes_to_a_lone_eof_with_no_comments() {
|
||||
let toks = tokenize("").unwrap();
|
||||
assert_eq!(toks.len(), 1);
|
||||
assert_eq!(toks[0].kind, TokenKind::Eof);
|
||||
assert!(toks[0].leading.is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TODO §63.2 QA: the operator table's first-byte test
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn every_operator_s_first_byte_is_a_single_ascii_byte() {
|
||||
// `op.as_bytes()[0] != c` compares one byte of `c: u8` against the
|
||||
// table entry's first *byte*. If any entry's first character were
|
||||
// multi-byte UTF-8, its first byte alone would not identify it and
|
||||
// the guard could reject a spelling it should have let through. Every
|
||||
// entry here is pure ASCII punctuation, so the byte comparison is the
|
||||
// whole character.
|
||||
for op in OPERATORS {
|
||||
let first = op.chars().next().expect("no empty operator spellings");
|
||||
assert!(first.is_ascii(), "{op:?} does not start with an ASCII byte");
|
||||
assert_eq!(
|
||||
op.as_bytes()[0],
|
||||
first as u8,
|
||||
"{op:?}'s first byte does not match its first char"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operator_table_has_no_duplicate_or_empty_entries() {
|
||||
// A duplicate wastes a comparison; an empty entry would make
|
||||
// `op.as_bytes()[0]` panic before ever reaching `starts_with`.
|
||||
for op in OPERATORS {
|
||||
assert!(!op.is_empty());
|
||||
}
|
||||
let mut sorted = OPERATORS.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted.dedup();
|
||||
assert_eq!(sorted.len(), OPERATORS.len(), "OPERATORS has a duplicate entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_operator_followed_by_every_other_operator_still_lexes_without_a_gap() {
|
||||
// The first-byte test must not change *which* entry `starts_with`
|
||||
// picks — only how many entries are tried before it does. Lexing
|
||||
// every `op1 op2` concatenation (no space) and requiring the token
|
||||
// stream to account for every byte with no lex error is the
|
||||
// regression gate: a wrong short-circuit would either misplace the
|
||||
// split point or leave a byte unconsumed. Cross-checked pair for
|
||||
// pair against `tokenize` built from 1b8723c (pre-first-byte-test)
|
||||
// in the QA scratchpad: 1 764 pairs, 0 differ.
|
||||
for &op1 in OPERATORS {
|
||||
for &op2 in OPERATORS {
|
||||
let src = format!("{op1}{op2} ;");
|
||||
let toks = tokenize(&src)
|
||||
.unwrap_or_else(|e| panic!("lexing {op1:?} followed by {op2:?} failed: {e}"));
|
||||
// Everything up to the space must be Symbol tokens whose
|
||||
// texts concatenate back to exactly op1 followed by op2,
|
||||
// with no gap and no overlap.
|
||||
let mut consumed = String::new();
|
||||
let mut i = 0;
|
||||
while toks[i].kind == TokenKind::Symbol && toks[i].text != ";" {
|
||||
consumed.push_str(&toks[i].text);
|
||||
i += 1;
|
||||
}
|
||||
assert_eq!(
|
||||
consumed,
|
||||
format!("{op1}{op2}"),
|
||||
"{op1:?} followed by {op2:?} did not round-trip"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod lexer;
|
||||
pub mod line_index;
|
||||
pub mod parser;
|
||||
pub mod span;
|
||||
pub mod stats;
|
||||
pub mod token;
|
||||
|
||||
pub use lexer::{tokenize, LexError};
|
||||
|
||||
@@ -53,11 +53,11 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
if self.cur().kind == TokenKind::Ident && self.nth(1).is_sym(":") {
|
||||
self.bump();
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip();
|
||||
}
|
||||
// `assert` / `assume` / `cover` / `restrict`.
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_kw("property")?;
|
||||
self.expect_sym("(")?;
|
||||
self.skip_balanced("(", ")")?;
|
||||
@@ -132,22 +132,22 @@ impl<'a> Parser<'a> {
|
||||
at_stmt_start = false;
|
||||
let t = self.cur();
|
||||
if t.is_sym("(") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip_balanced("(", ")")?;
|
||||
} else if t.is_sym("[") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip_balanced("[", "]")?;
|
||||
} else if t.is_sym("{") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip_balanced("{", "}")?;
|
||||
} else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") {
|
||||
// `disable fork` / `wait fork` name the enclosing block; they
|
||||
// do not open one.
|
||||
self.bump();
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip();
|
||||
} else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) {
|
||||
depth += 1;
|
||||
self.bump();
|
||||
self.skip();
|
||||
} else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) {
|
||||
if depth == 0 {
|
||||
// A closer with nothing open: the action statement is
|
||||
@@ -156,7 +156,7 @@ impl<'a> Parser<'a> {
|
||||
return self.error("expected `;`");
|
||||
}
|
||||
depth -= 1;
|
||||
self.bump();
|
||||
self.skip();
|
||||
if depth == 0 {
|
||||
self.parse_label()?;
|
||||
if !self.eat_kw("else") {
|
||||
@@ -167,7 +167,7 @@ impl<'a> Parser<'a> {
|
||||
} else if depth == 0 && self.eat_sym(";") {
|
||||
return Ok(());
|
||||
} else {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,9 +199,9 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
let end_kw = if self.cur().is_kw("sequence") { "endsequence" } else { "endproperty" };
|
||||
self.bump();
|
||||
self.skip();
|
||||
while !self.at_eof() && !self.cur().is_kw(end_kw) {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.expect_closer(end_kw)?;
|
||||
self.parse_label()?;
|
||||
@@ -220,7 +220,7 @@ impl<'a> Parser<'a> {
|
||||
fn parse_default_disable(&mut self) -> PResult<RawText> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
self.bump(); // default
|
||||
self.skip(); // default
|
||||
self.expect_kw("disable")?;
|
||||
self.expect_kw("iff")?;
|
||||
self.skip_to_semi()?;
|
||||
@@ -252,7 +252,7 @@ impl<'a> Parser<'a> {
|
||||
fn parse_prop_seq_decl_inner(&mut self) -> PResult<PropSeqDecl> {
|
||||
let kw = self.cur().text.clone();
|
||||
let end_kw = if kw == "sequence" { "endsequence" } else { "endproperty" };
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before_name = self.take_gap();
|
||||
let name = self.expect_name()?;
|
||||
let before_args = self.take_before_open("(");
|
||||
@@ -407,7 +407,7 @@ impl<'a> Parser<'a> {
|
||||
let mut action = ActionBlock::default();
|
||||
if self.cur().is_sym(";") {
|
||||
action.before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(action);
|
||||
}
|
||||
if !self.cur().is_kw("else") {
|
||||
@@ -415,7 +415,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
if self.cur().is_kw("else") {
|
||||
action.before_else = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
action.after_else = self.take_gap();
|
||||
action.fail = Some(Box::new(self.parse_stmt()?));
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ impl<'a> Parser<'a> {
|
||||
let mut after_hash = Vec::new();
|
||||
let mut param_directives = Vec::new();
|
||||
if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
@@ -305,7 +305,7 @@ impl<'a> Parser<'a> {
|
||||
return self.parse_constraint_foreach();
|
||||
}
|
||||
if self.cur().is_kw("unique") && self.nth(1).is_sym("{") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let comments = self.take_gap();
|
||||
let items = self.parse_constraint_expr_set()?;
|
||||
return Ok(ConstraintItemKind::Unique { items, comments });
|
||||
@@ -314,9 +314,9 @@ impl<'a> Parser<'a> {
|
||||
// `soft` is matched by text, for the reason `parse_constraint_expr`
|
||||
// gives.
|
||||
if self.cur().is_kw("disable") && word_at(self.nth(1), "soft") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_gap();
|
||||
let expr = self.parse_expr()?;
|
||||
return Ok(ConstraintItemKind::DisableSoft {
|
||||
@@ -341,7 +341,7 @@ impl<'a> Parser<'a> {
|
||||
let soft = self.at_soft_constraint();
|
||||
let mut after_soft = Vec::new();
|
||||
if soft {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_soft = self.take_gap();
|
||||
}
|
||||
let mark = self.pending_trailing.len();
|
||||
@@ -374,7 +374,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
if !soft && self.cur().is_sym("->") {
|
||||
let before = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_around(mark);
|
||||
let set = self.parse_constraint_set()?;
|
||||
return Ok(ConstraintItemKind::Implication {
|
||||
@@ -403,7 +403,7 @@ impl<'a> Parser<'a> {
|
||||
let mut els = None;
|
||||
if self.cur().is_kw("else") {
|
||||
else_comments = self.take_dangling();
|
||||
self.bump();
|
||||
self.skip();
|
||||
// The gap after `else` is this item's when the set it introduces
|
||||
// opens with a token of its own — a `{`, or the `if` of a chain.
|
||||
// A set written on the next line leaves it to that item's own
|
||||
@@ -458,13 +458,13 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
fn parse_solve_before(&mut self) -> PResult<ConstraintItemKind> {
|
||||
self.bump(); // solve
|
||||
self.skip(); // solve
|
||||
let solve = self.parse_solve_operands()?;
|
||||
if !word_at(self.cur(), "before") {
|
||||
return self.error("expected `before`");
|
||||
}
|
||||
let before_comments = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before = self.parse_solve_operands()?;
|
||||
Ok(ConstraintItemKind::SolveBefore { solve, before_comments, before })
|
||||
}
|
||||
@@ -526,7 +526,7 @@ impl<'a> Parser<'a> {
|
||||
expr: Expr,
|
||||
before: Vec<Comment>,
|
||||
) -> PResult<Expr> {
|
||||
self.bump(); // dist
|
||||
self.skip(); // dist
|
||||
let after = self.take_gap();
|
||||
self.expect_sym("{")?;
|
||||
let mut weights: Vec<DistItem> = Vec::new();
|
||||
@@ -539,8 +539,8 @@ impl<'a> Parser<'a> {
|
||||
let mut op_comments = BinaryComments::default();
|
||||
if let Some(spelling) = self.dist_weight_op() {
|
||||
op_comments.before = self.take_gap();
|
||||
self.bump();
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip();
|
||||
op_comments.after = self.take_gap();
|
||||
op = Some(spelling.to_string());
|
||||
weight = Some(self.parse_ternary()?);
|
||||
|
||||
@@ -56,7 +56,7 @@ impl<'a> Parser<'a> {
|
||||
self.take_member_prefix();
|
||||
self.expect_kw("covergroup")?;
|
||||
while !self.at_eof() && !self.cur().is_kw("endgroup") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.expect_closer("endgroup")?;
|
||||
self.parse_label()?;
|
||||
@@ -139,7 +139,7 @@ impl<'a> Parser<'a> {
|
||||
fn parse_coverage_event(&mut self) -> PResult<Option<CoverageEvent>> {
|
||||
if self.cur().is_kw("with") {
|
||||
let before_with = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_with = self.take_gap();
|
||||
self.expect_kw("function")?;
|
||||
let after_function = self.take_gap();
|
||||
@@ -147,7 +147,7 @@ impl<'a> Parser<'a> {
|
||||
return self.error("expected `sample`");
|
||||
}
|
||||
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before_args = self.take_before_open("(");
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let args = self.parse_tf_ports(false)?.args;
|
||||
@@ -163,7 +163,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
if self.cur().is_sym("@") {
|
||||
let before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let sens = self.parse_sens_list()?;
|
||||
return Ok(Some(CoverageEvent::Clocking { before, sens }));
|
||||
}
|
||||
@@ -206,9 +206,9 @@ impl<'a> Parser<'a> {
|
||||
&& (word_at(self.nth(2), "coverpoint") || word_at(self.nth(2), "cross"))
|
||||
{
|
||||
let name = Name { text: self.cur().text.clone(), span: self.cur().span };
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before = self.take_gap();
|
||||
self.bump(); // :
|
||||
self.skip(); // :
|
||||
let after = self.take_gap();
|
||||
Some(CoverLabel { name, comments: Box::new(BinaryComments { before, after }) })
|
||||
} else {
|
||||
@@ -224,7 +224,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
fn parse_coverpoint(&mut self, label: Option<CoverLabel>) -> PResult<CoverpointDecl> {
|
||||
self.bump(); // coverpoint
|
||||
self.skip(); // coverpoint
|
||||
let after_kw = self.take_gap();
|
||||
let expr = self.parse_expr()?;
|
||||
let iff = self.parse_cover_iff()?;
|
||||
@@ -234,7 +234,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
fn parse_cross(&mut self, label: Option<CoverLabel>) -> PResult<CrossDecl> {
|
||||
self.bump(); // cross
|
||||
self.skip(); // cross
|
||||
let after_kw = self.take_gap();
|
||||
let mut items: Vec<ExprItem> = Vec::new();
|
||||
loop {
|
||||
@@ -265,7 +265,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let before_kw = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_kw = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let after_open = self.take_gap();
|
||||
@@ -356,13 +356,13 @@ impl<'a> Parser<'a> {
|
||||
let wildcard = word_at(self.cur(), "wildcard") && bin_kind_at(self.nth(1)).is_some();
|
||||
let mut after_wildcard = Vec::new();
|
||||
if wildcard {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_wildcard = self.take_gap();
|
||||
}
|
||||
let Some(kind) = bin_kind_at(self.cur()) else {
|
||||
return self.error("expected `bins`, `ignore_bins` or `illegal_bins`");
|
||||
};
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before_name = self.take_gap();
|
||||
let name = self.expect_name()?;
|
||||
let array = self.parse_bin_array()?;
|
||||
@@ -392,7 +392,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let inner_before = self.take_gap();
|
||||
let size = if self.cur().is_sym("]") { None } else { Some(self.parse_expr()?) };
|
||||
let inner_after = self.gap_before("]");
|
||||
@@ -412,12 +412,12 @@ impl<'a> Parser<'a> {
|
||||
/// `bins b = (1'b1[*5]);` wrong.
|
||||
fn parse_bin_spec(&mut self, in_cross: bool) -> PResult<BinSpec> {
|
||||
if self.cur().is_kw("default") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
// `sequence` really is a lexer keyword (a `sequence ... endsequence`
|
||||
// declaration), so this one is not matched by text.
|
||||
if self.cur().is_kw("sequence") {
|
||||
let comments = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(BinSpec::DefaultSequence { comments });
|
||||
}
|
||||
return Ok(BinSpec::Default);
|
||||
@@ -446,7 +446,7 @@ impl<'a> Parser<'a> {
|
||||
break;
|
||||
}
|
||||
let before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_gap();
|
||||
arrow = BinaryComments { before, after };
|
||||
}
|
||||
@@ -494,7 +494,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let before = self.take_gap();
|
||||
self.bump(); // [
|
||||
self.skip(); // [
|
||||
let after_open = self.take_gap();
|
||||
let op = self.bump().text;
|
||||
let inner_before = self.take_gap();
|
||||
@@ -503,7 +503,7 @@ impl<'a> Parser<'a> {
|
||||
let mut hi = None;
|
||||
if self.cur().is_sym(":") {
|
||||
colon.before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
colon.after = self.take_gap();
|
||||
hi = Some(self.parse_expr()?);
|
||||
}
|
||||
@@ -541,13 +541,13 @@ impl<'a> Parser<'a> {
|
||||
|
||||
fn parse_select_primary(&mut self) -> PResult<SelectExpr> {
|
||||
if self.cur().is_sym("!") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let comments = self.take_gap();
|
||||
let expr = self.parse_select_primary()?;
|
||||
return Ok(SelectExpr::Not { comments, expr: Box::new(expr) });
|
||||
}
|
||||
if self.cur().is_sym("(") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before = self.take_gap();
|
||||
let expr = self.parse_select_expr()?;
|
||||
let after = self.gap_before(")");
|
||||
@@ -577,7 +577,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
fn parse_binsof(&mut self) -> PResult<BinsofSel> {
|
||||
self.bump(); // binsof
|
||||
self.skip(); // binsof
|
||||
let after_kw = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let after_open = self.take_gap();
|
||||
@@ -589,7 +589,7 @@ impl<'a> Parser<'a> {
|
||||
let mut intersect = None;
|
||||
if word_at(self.cur(), "intersect") {
|
||||
before_intersect = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_intersect = self.take_gap();
|
||||
intersect = Some(self.parse_constraint_expr_set()?);
|
||||
}
|
||||
@@ -610,7 +610,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let before_kw = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_kw = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let after_open = self.take_gap();
|
||||
|
||||
@@ -63,6 +63,31 @@ impl<'a> Parser<'a> {
|
||||
t
|
||||
}
|
||||
|
||||
/// Consume the current token without building a copy of it.
|
||||
///
|
||||
/// Exactly [`Parser::bump`] for the caller that throws the token away —
|
||||
/// the same comment plumbing, the same cursor step, the same `self.tokens`
|
||||
/// left untouched — minus the clone. `bump` copies the token's `text`
|
||||
/// (a `String`, so an allocation) and its comment buckets for a value most
|
||||
/// callers drop on the next line; on a 40 267-line generated file that is
|
||||
/// one allocate-and-free per token consumed (TODO §63.2).
|
||||
pub(super) fn skip(&mut self) {
|
||||
let token = &self.tokens[self.pos];
|
||||
// Cloned rather than moved out, because `bump` moved them out of its
|
||||
// *copy*: the stream keeps its comments either way, which is what the
|
||||
// rewind of a speculative parse relies on.
|
||||
let (mut leading, trailing) = (token.leading.clone(), token.trailing.clone());
|
||||
if self.pos + 1 < self.tokens.len() {
|
||||
self.pos += 1;
|
||||
}
|
||||
if !leading.is_empty() {
|
||||
self.pending_leading.append(&mut leading);
|
||||
}
|
||||
if let Some(trailing) = trailing {
|
||||
self.pending_trailing.push(trailing);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open one level of nesting, refusing to recurse past
|
||||
/// [`MAX_NESTING_DEPTH`]. Callers that succeed must pair this with
|
||||
/// [`Parser::leave`] on every path out, including the error paths.
|
||||
@@ -199,7 +224,7 @@ impl<'a> Parser<'a> {
|
||||
|
||||
pub(super) fn eat_sym(&mut self, sym: &str) -> bool {
|
||||
if self.cur().is_sym(sym) {
|
||||
self.bump();
|
||||
self.skip();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
@@ -208,7 +233,7 @@ impl<'a> Parser<'a> {
|
||||
|
||||
pub(super) fn eat_kw(&mut self, kw: &str) -> bool {
|
||||
if self.cur().is_kw(kw) {
|
||||
self.bump();
|
||||
self.skip();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
||||
@@ -39,7 +39,7 @@ impl<'a> Parser<'a> {
|
||||
// this function with the `virtual` already taken into
|
||||
// `DataDecl::qualifiers`, so this only fires for the other positions.)
|
||||
if self.cur().is_kw("virtual") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
ty.virt =
|
||||
Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare });
|
||||
// `virtual spi_if.tb sif` — a modport-qualified virtual interface
|
||||
@@ -97,12 +97,12 @@ impl<'a> Parser<'a> {
|
||||
// comment inside the brackets could attach.
|
||||
let mut comments =
|
||||
SegmentComments { before_open: self.take_gap(), ..Default::default() };
|
||||
self.bump();
|
||||
self.skip();
|
||||
comments.after_open = self.take_gap();
|
||||
let kind = if self.cur().is_sym("]") {
|
||||
// `[]` — a dynamic array.
|
||||
comments.before_close = std::mem::take(&mut comments.after_open);
|
||||
self.bump();
|
||||
self.skip();
|
||||
dims.push(Dim {
|
||||
kind: DimKind::Dynamic,
|
||||
comments: Box::new(comments),
|
||||
@@ -111,7 +111,7 @@ impl<'a> Parser<'a> {
|
||||
continue;
|
||||
} else if self.cur().is_sym("*") && self.nth(1).is_sym("]") {
|
||||
// `[*]` — a wildcard-keyed associative array.
|
||||
self.bump();
|
||||
self.skip();
|
||||
DimKind::Wildcard
|
||||
} else {
|
||||
let a = self.parse_expr()?;
|
||||
@@ -303,7 +303,7 @@ impl<'a> Parser<'a> {
|
||||
// `wire /* c */ #5 w;`. Taken only here — when the read does not
|
||||
// happen the gap belongs to whatever comes next.
|
||||
let before_hash = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_hash = self.take_gap();
|
||||
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
|
||||
}
|
||||
@@ -392,7 +392,7 @@ impl<'a> Parser<'a> {
|
||||
let mut eq_comments = BinaryComments::default();
|
||||
let value = if self.cur().is_sym("=") {
|
||||
eq_comments.before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
eq_comments.after = self.take_gap();
|
||||
Some(self.parse_expr()?)
|
||||
} else {
|
||||
@@ -436,7 +436,7 @@ impl<'a> Parser<'a> {
|
||||
// grammar of their own and are still a clean parse error.
|
||||
let tagged = word_at(self.cur(), "tagged");
|
||||
if tagged {
|
||||
self.bump();
|
||||
self.skip();
|
||||
header_comments.after_tagged = self.take_gap();
|
||||
}
|
||||
let packed = self.eat_kw("packed");
|
||||
|
||||
@@ -347,8 +347,8 @@ impl<'a> Parser<'a> {
|
||||
let raw = if self.at_spaced_macro_call() {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
self.bump(); // `NAME
|
||||
self.bump(); // (
|
||||
self.skip(); // `NAME
|
||||
self.skip(); // (
|
||||
self.skip_balanced("(", ")")?;
|
||||
// Verbatim, space included: the argument text is preprocessor
|
||||
// input lucisv does not model, and closing the gap would make the
|
||||
|
||||
@@ -64,7 +64,7 @@ impl<'a> Parser<'a> {
|
||||
// Each of the four gaps inside a `? :` can hold comments; kept
|
||||
// apart so none of them drifts across the `?` or the `:`.
|
||||
let before_question = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_question = self.take_around(mark);
|
||||
let then = self.parse_expr()?;
|
||||
let before_colon = self.take_around(mark);
|
||||
@@ -144,7 +144,7 @@ impl<'a> Parser<'a> {
|
||||
// The word is an operator like any other, and keeps the
|
||||
// comments written on either side of it the same way.
|
||||
let before = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_around(mark);
|
||||
let comments = Box::new(BinaryComments { before, after });
|
||||
// `x inside `MACRO` — the macro expands to the `{...}` set,
|
||||
@@ -324,7 +324,7 @@ impl<'a> Parser<'a> {
|
||||
let base = Box::new(base);
|
||||
if self.cur().is_sym(".") || self.cur().is_sym("::") {
|
||||
let scoped = self.cur().is_sym("::");
|
||||
self.bump();
|
||||
self.skip();
|
||||
comments.after_open = self.take_gap();
|
||||
let name = self.expect_ident()?;
|
||||
let comments = Box::new(comments);
|
||||
@@ -415,7 +415,7 @@ impl<'a> Parser<'a> {
|
||||
before_open: self.take_before_open("("),
|
||||
..CallComments::default()
|
||||
};
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut args = Vec::new();
|
||||
if !self.cur().is_sym(")") {
|
||||
let arg_start = self.here();
|
||||
@@ -462,14 +462,14 @@ impl<'a> Parser<'a> {
|
||||
},
|
||||
);
|
||||
} else if self.nth(1).is_sym("[") {
|
||||
self.bump(); // with
|
||||
self.skip(); // with
|
||||
let range = self.parse_stream_range(comments)?;
|
||||
expr = self.expr_at(
|
||||
start,
|
||||
ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) },
|
||||
);
|
||||
} else {
|
||||
self.bump(); // with
|
||||
self.skip(); // with
|
||||
comments.after_kw = self.take_before_open("(");
|
||||
// `( expression )` — an ordinary parenthesized primary,
|
||||
// which is what IEEE 1800 §7.12 spells here.
|
||||
@@ -511,9 +511,9 @@ impl<'a> Parser<'a> {
|
||||
},
|
||||
);
|
||||
} else {
|
||||
self.bump(); // '
|
||||
self.skip(); // '
|
||||
comments.after_tick = self.take_gap();
|
||||
self.bump(); // (
|
||||
self.skip(); // (
|
||||
comments.after_open = self.take_gap();
|
||||
let inner = self.parse_expr()?;
|
||||
comments.before_close = self.gap_before(")");
|
||||
|
||||
@@ -24,7 +24,7 @@ impl<'a> Parser<'a> {
|
||||
let mut after_hash = Vec::new();
|
||||
let mut after_delay = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_hash = self.take_gap();
|
||||
let delay = self.parse_delay_value()?;
|
||||
// The gap between the delay and the first left-hand side is the
|
||||
@@ -82,7 +82,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
let mut comments =
|
||||
Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() });
|
||||
self.bump(); // (
|
||||
self.skip(); // (
|
||||
comments.after_open = self.take_gap();
|
||||
let first = self.bump().text;
|
||||
// The gap after the first strength ends either at the `,` or at the
|
||||
@@ -121,7 +121,7 @@ impl<'a> Parser<'a> {
|
||||
// What is written just inside the `(` belongs to the first value; the
|
||||
// gap before each `,` and the gap after it belong to the values either
|
||||
// side of it.
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut leading = self.take_gap();
|
||||
let mut out: Vec<DelayValue> = Vec::new();
|
||||
loop {
|
||||
@@ -242,7 +242,7 @@ impl<'a> Parser<'a> {
|
||||
|
||||
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
|
||||
pub(super) fn parse_bind(&mut self) -> PResult<BindDirective> {
|
||||
self.bump(); // `bind`
|
||||
self.skip(); // `bind`
|
||||
// The target is a bare string, so a comment written before it has no
|
||||
// node to attach to: harvest it here, where source order is still
|
||||
// known, rather than letting it drift onto the instance below.
|
||||
@@ -250,7 +250,7 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let mut target = vec![self.parse_path_segment()?];
|
||||
while self.cur().is_sym(".") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
target.push(self.parse_path_segment()?);
|
||||
}
|
||||
let target_span = self.span_from(start);
|
||||
@@ -278,7 +278,7 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let mut text = self.expect_ident()?;
|
||||
while self.cur().is_sym(".") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let segment = self.expect_ident()?;
|
||||
Self::push_path_segment(&mut text, &segment);
|
||||
}
|
||||
@@ -301,7 +301,7 @@ impl<'a> Parser<'a> {
|
||||
let module_start = self.here();
|
||||
let mut module = self.expect_ident()?;
|
||||
while self.cur().is_sym("::") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let segment = self.expect_ident()?;
|
||||
Self::push_scope_segment(&mut module, &segment);
|
||||
}
|
||||
@@ -312,7 +312,7 @@ impl<'a> Parser<'a> {
|
||||
let mut after_hash = Vec::new();
|
||||
let mut param_directives = Vec::new();
|
||||
if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mut list = Vec::new();
|
||||
@@ -571,7 +571,7 @@ impl<'a> Parser<'a> {
|
||||
// `.name(/* unused */)`: the comments were written inside
|
||||
// these parens and are printed back inside them.
|
||||
let inside = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some(self.expr_at(paren_start, ExprKind::Empty(inside)))
|
||||
} else {
|
||||
after_open = self.take_gap();
|
||||
@@ -684,7 +684,7 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
while self.pos < end_pos && !self.at_eof() {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
let raw = self.verbatim_since(start, col);
|
||||
self.expr_at(start, ExprKind::Verbatim(raw))
|
||||
@@ -699,7 +699,7 @@ impl<'a> Parser<'a> {
|
||||
let before_hash = self.take_before_open("#");
|
||||
let mut after_hash = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_hash = self.take_gap();
|
||||
self.parse_delay_values()?
|
||||
} else {
|
||||
|
||||
@@ -155,7 +155,7 @@ impl<'a> Parser<'a> {
|
||||
// `TokenKind` match below because punctuation is matched by text
|
||||
// everywhere in this file. See `ItemKind::Empty`.
|
||||
if self.cur().is_sym(";") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(ItemKind::Empty);
|
||||
}
|
||||
let t = self.cur();
|
||||
@@ -209,7 +209,7 @@ impl<'a> Parser<'a> {
|
||||
"modport" => self.parse_modport().map(ItemKind::Modport),
|
||||
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
|
||||
"default" if self.nth(1).is_kw("clocking") => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.parse_clocking(true).map(ItemKind::Clocking)
|
||||
}
|
||||
"default" if self.nth(1).is_kw("disable") => self.parse_default_disable_item(),
|
||||
@@ -243,7 +243,7 @@ impl<'a> Parser<'a> {
|
||||
Ok(ItemKind::PortDecl(d))
|
||||
}
|
||||
"genvar" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut names = vec![self.expect_name()?];
|
||||
while self.eat_sym(",") {
|
||||
names.push(self.expect_name()?);
|
||||
@@ -258,15 +258,15 @@ impl<'a> Parser<'a> {
|
||||
Ok(ItemKind::Always { kw, stmt })
|
||||
}
|
||||
"initial" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Ok(ItemKind::Initial(self.parse_stmt()?))
|
||||
}
|
||||
"final" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Ok(ItemKind::Final(self.parse_stmt()?))
|
||||
}
|
||||
"generate" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut items = Vec::new();
|
||||
while !self.at_body_end("endgenerate") {
|
||||
items.push(self.item_or_recover()?);
|
||||
@@ -339,7 +339,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
"defparam" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut pairs = Vec::new();
|
||||
loop {
|
||||
let lhs = self.parse_expr()?;
|
||||
@@ -492,7 +492,7 @@ impl<'a> Parser<'a> {
|
||||
loop {
|
||||
let star = self.cur().span;
|
||||
let pkg = if allow_star_pkg && self.cur().is_sym("*") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Name { text: "*".to_string(), span: star }
|
||||
} else {
|
||||
self.expect_name()?
|
||||
@@ -578,7 +578,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
let span = self.cur().span;
|
||||
let name = Name { text: self.bump().text, span };
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some(name)
|
||||
}
|
||||
|
||||
@@ -603,7 +603,7 @@ impl<'a> Parser<'a> {
|
||||
let then = self.parse_gen_block()?;
|
||||
let els = if self.cur().is_kw("else") {
|
||||
let meta = self.take_meta();
|
||||
self.bump();
|
||||
self.skip();
|
||||
if self.cur().is_kw("if") {
|
||||
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
|
||||
} else {
|
||||
@@ -688,7 +688,7 @@ impl<'a> Parser<'a> {
|
||||
// The gap between whatever came before and the `begin` belongs to
|
||||
// the block — nothing else was written where it could attach.
|
||||
let before_kw = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let before_colon = self.gap_before(":");
|
||||
let mut after_colon = Vec::new();
|
||||
let label_name = if self.eat_sym(":") {
|
||||
|
||||
@@ -22,7 +22,7 @@ impl<'a> Parser<'a> {
|
||||
let kw = self.cur().text.clone();
|
||||
match kw.as_str() {
|
||||
"begin" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let (label_comments, label_name) = self.parse_label_with()?;
|
||||
let (label, label_span) = split_label(label_name);
|
||||
let mut stmts = Vec::new();
|
||||
@@ -45,7 +45,7 @@ impl<'a> Parser<'a> {
|
||||
})
|
||||
}
|
||||
"fork" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let (label_comments, label_name) = self.parse_label_with()?;
|
||||
let (label, label_span) = split_label(label_name);
|
||||
let mut stmts = Vec::new();
|
||||
@@ -88,7 +88,7 @@ impl<'a> Parser<'a> {
|
||||
"case" | "casex" | "casez" => self.parse_case_stmt(None),
|
||||
"for" => self.parse_for_stmt(),
|
||||
"while" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.cond_or_recover()?;
|
||||
let recovered = cond.is_error();
|
||||
@@ -96,7 +96,7 @@ impl<'a> Parser<'a> {
|
||||
Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"do" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let body = Box::new(self.parse_stmt()?);
|
||||
self.expect_kw("while")?;
|
||||
let mut comments =
|
||||
@@ -110,7 +110,7 @@ impl<'a> Parser<'a> {
|
||||
Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) })
|
||||
}
|
||||
"repeat" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_sym("(")?;
|
||||
let count = self.cond_or_recover()?;
|
||||
let recovered = count.is_error();
|
||||
@@ -118,11 +118,11 @@ impl<'a> Parser<'a> {
|
||||
Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"forever" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Ok(StmtKind::Forever { body: Box::new(self.parse_stmt()?) })
|
||||
}
|
||||
"foreach" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut comments =
|
||||
HeaderComments { after_kw: self.take_gap(), ..Default::default() };
|
||||
self.expect_sym("(")?;
|
||||
@@ -141,41 +141,41 @@ impl<'a> Parser<'a> {
|
||||
})
|
||||
}
|
||||
"randcase" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let (items, dangling) = self.parse_case_body()?;
|
||||
Ok(StmtKind::RandCase { items, dangling })
|
||||
}
|
||||
"return" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_kw = self.take_gap();
|
||||
let expr = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::Return { after_kw, expr })
|
||||
}
|
||||
"break" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::Break)
|
||||
}
|
||||
"continue" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::Continue)
|
||||
}
|
||||
"disable" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
// `disable fork;` kills every process the enclosing `fork`
|
||||
// started; `fork` is a keyword, not a block name.
|
||||
if self.cur().is_kw("fork") {
|
||||
let name_span = self.cur().span;
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_stmt_semi()?;
|
||||
return Ok(StmtKind::Disable { name: "fork".to_string(), name_span });
|
||||
}
|
||||
let start = self.here();
|
||||
let mut name = self.expect_ident()?;
|
||||
while self.cur().is_sym(".") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
name.push('.');
|
||||
name.push_str(&self.expect_ident()?);
|
||||
}
|
||||
@@ -184,11 +184,11 @@ impl<'a> Parser<'a> {
|
||||
Ok(StmtKind::Disable { name, name_span })
|
||||
}
|
||||
"wait" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
// `wait fork;` waits for the enclosing `fork`'s children
|
||||
// (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition.
|
||||
if self.cur().is_kw("fork") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expect_stmt_semi()?;
|
||||
return Ok(StmtKind::WaitFork);
|
||||
}
|
||||
@@ -217,7 +217,7 @@ impl<'a> Parser<'a> {
|
||||
Ok(StmtKind::Assert { kw, cond, then, els })
|
||||
}
|
||||
"force" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let lhs = self.parse_unary()?;
|
||||
self.expect_sym("=")?;
|
||||
let rhs = self.parse_expr()?;
|
||||
@@ -290,7 +290,7 @@ impl<'a> Parser<'a> {
|
||||
/// is parsed as usual. The init entries read before the failure are kept
|
||||
/// — they are what declares the loop variable the body uses.
|
||||
fn parse_for_stmt(&mut self) -> PResult<StmtKind> {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
|
||||
self.expect_sym("(")?;
|
||||
comments.after_open = self.take_gap();
|
||||
|
||||
@@ -301,6 +301,7 @@ struct Rewind {
|
||||
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
|
||||
/// instead of returning `Err`.
|
||||
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
crate::stats::count_parse();
|
||||
Parser::new(tokens, source, false).parse_source_file()
|
||||
}
|
||||
|
||||
@@ -317,6 +318,7 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
|
||||
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
|
||||
/// parses of the same over-deep input overflow at the same depth.
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
|
||||
crate::stats::count_parse();
|
||||
let mut p = Parser::new(tokens, source, true);
|
||||
match p.parse_source_file() {
|
||||
Ok(file) => (file, p.diagnostics),
|
||||
@@ -429,7 +431,7 @@ impl<'a> Parser<'a> {
|
||||
let mut scope: Vec<ScopeSeg> = Vec::new();
|
||||
while self.cur().is_sym("::") {
|
||||
let before_sep = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_sep = self.take_gap();
|
||||
let next = self.expect_name()?;
|
||||
scope.push(ScopeSeg { name, before_sep, after_sep });
|
||||
@@ -472,7 +474,7 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let mut name = self.expect_ident()?;
|
||||
while self.cur().is_sym("::") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let segment = self.expect_ident()?;
|
||||
Self::push_scope_segment(&mut name, &segment);
|
||||
}
|
||||
|
||||
@@ -327,7 +327,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let before_dir = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_dir = self.take_gap();
|
||||
Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? }))
|
||||
}
|
||||
@@ -387,7 +387,7 @@ impl<'a> Parser<'a> {
|
||||
if !self.cur().is_sym("#") {
|
||||
return Ok(out);
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
out.after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
@@ -438,7 +438,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok((Box::default(), None));
|
||||
}
|
||||
let before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_gap();
|
||||
let value = parse(self)?;
|
||||
Ok((Box::new(BinaryComments { before, after }), Some(value)))
|
||||
@@ -507,7 +507,7 @@ impl<'a> Parser<'a> {
|
||||
if !self.cur().is_sym("(") {
|
||||
return Ok((PortList::None, Vec::new(), Vec::new()));
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
let mark = self.diags_mark();
|
||||
// Directives before the first port. Harvested here rather than in the
|
||||
// loop below because both the ANSI/non-ANSI decision and the
|
||||
@@ -517,7 +517,7 @@ impl<'a> Parser<'a> {
|
||||
if self.cur().is_sym(")") {
|
||||
// `module m (/* c */);` — the comments stay between the parens.
|
||||
let dangling = self.take_dangling();
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok((PortList::Empty, dangling, directives));
|
||||
}
|
||||
let ansi = {
|
||||
|
||||
@@ -31,7 +31,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
TokenKind::Ident | TokenKind::SystemIdent => {
|
||||
if self.at_shallow_copy() {
|
||||
self.bump(); // new
|
||||
self.skip(); // new
|
||||
let src = self.parse_postfix()?;
|
||||
return Ok(self.expr_at(start, ExprKind::New(Box::new(src))));
|
||||
}
|
||||
@@ -53,9 +53,9 @@ impl<'a> Parser<'a> {
|
||||
let ty = self.expr_at(ty_start, ExprKind::Ident(ty_text));
|
||||
let mut comments =
|
||||
CastComments { before_tick: self.take_gap(), ..Default::default() };
|
||||
self.bump(); // '
|
||||
self.skip(); // '
|
||||
comments.after_tick = self.take_gap();
|
||||
self.bump(); // (
|
||||
self.skip(); // (
|
||||
comments.after_open = self.take_gap();
|
||||
let inner = self.parse_expr()?;
|
||||
comments.before_close = self.gap_before(")");
|
||||
@@ -85,14 +85,14 @@ impl<'a> Parser<'a> {
|
||||
// work through the existing expression grammar, and lucisv
|
||||
// checks legality nowhere else either.
|
||||
"$" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Ok(self.expr_at(start, ExprKind::Ident("$".to_string())))
|
||||
}
|
||||
"(" => {
|
||||
// Comments written just inside the parens stay there;
|
||||
// anything else would move them across a token.
|
||||
let mut before = self.take_trailing_here();
|
||||
self.bump();
|
||||
self.skip();
|
||||
before.append(&mut self.take_leading_here());
|
||||
let mark = self.pending_trailing.len();
|
||||
let inner_start = self.here();
|
||||
@@ -106,7 +106,7 @@ impl<'a> Parser<'a> {
|
||||
))
|
||||
}
|
||||
"{" => {
|
||||
self.bump();
|
||||
self.skip();
|
||||
if self.cur().is_sym("<<") || self.cur().is_sym(">>") {
|
||||
return self.parse_stream_concat(start);
|
||||
}
|
||||
@@ -114,13 +114,13 @@ impl<'a> Parser<'a> {
|
||||
// `{}` — the empty queue/dynamic-array literal
|
||||
// (`q = {};`). Illegal as a Verilog concatenation,
|
||||
// but lucisv is not a legality checker.
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(self.expr_at(start, ExprKind::Concat(Vec::new())));
|
||||
}
|
||||
let first = self.parse_expr_item()?;
|
||||
if self.cur().is_sym("{") {
|
||||
// Replication {N{a, b}}
|
||||
self.bump();
|
||||
self.skip();
|
||||
let inner_first = self.parse_expr_item()?;
|
||||
let inner = self.parse_expr_list(inner_first, "}")?;
|
||||
self.expect_sym("}")?;
|
||||
@@ -241,7 +241,7 @@ impl<'a> Parser<'a> {
|
||||
/// (`ty'{...}`) keeps the type outside the pattern's span, in the `Cast`
|
||||
/// node that wraps it.
|
||||
pub(super) fn parse_assign_pattern(&mut self, start: u32) -> PResult<Expr> {
|
||||
self.bump(); // '{
|
||||
self.skip(); // '{
|
||||
if self.at_assign_pattern_repl() {
|
||||
return self.parse_assign_pattern_repl(start);
|
||||
}
|
||||
@@ -251,7 +251,7 @@ impl<'a> Parser<'a> {
|
||||
let item_start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let key_or_val = if self.cur().is_kw("default") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.expr_at(item_start, ExprKind::Ident("default".to_string()))
|
||||
} else {
|
||||
self.parse_expr_or_type()?
|
||||
@@ -352,7 +352,7 @@ impl<'a> Parser<'a> {
|
||||
/// the `.` and the next token is an identifier.
|
||||
pub(super) fn parse_named_arg(&mut self) -> PResult<Expr> {
|
||||
let start = self.here();
|
||||
self.bump(); // .
|
||||
self.skip(); // .
|
||||
let after_dot = self.take_gap();
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let before_open = self.take_before_open("(");
|
||||
@@ -365,7 +365,7 @@ impl<'a> Parser<'a> {
|
||||
// between the parens, exactly as an empty connection does. The
|
||||
// span covers the `( )` pair.
|
||||
let comments = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
(self.expr_at(paren_start, ExprKind::Empty(comments)), Vec::new())
|
||||
} else {
|
||||
after_open = self.take_gap();
|
||||
@@ -403,7 +403,7 @@ impl<'a> Parser<'a> {
|
||||
pub(super) fn parse_value_range(&mut self) -> PResult<Expr> {
|
||||
let start = self.here();
|
||||
let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() };
|
||||
self.bump(); // [
|
||||
self.skip(); // [
|
||||
comments.after_open = self.take_gap();
|
||||
let lo = self.parse_expr()?;
|
||||
comments.before_op = self.gap_before(":");
|
||||
|
||||
@@ -52,7 +52,7 @@ impl<'a> Parser<'a> {
|
||||
// The gap in front of the `|` belongs to the alternative it opens,
|
||||
// so it prints on the bar's own side of the previous one.
|
||||
let before_bar = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
alternatives.push(self.parse_alternative(before_bar)?);
|
||||
}
|
||||
let span = self.span_from(start);
|
||||
@@ -107,8 +107,8 @@ impl<'a> Parser<'a> {
|
||||
let mut weight = None;
|
||||
if self.at_weight_op() {
|
||||
before_weight = self.take_gap();
|
||||
self.bump(); // :
|
||||
self.bump(); // =
|
||||
self.skip(); // :
|
||||
self.skip(); // =
|
||||
weight = Some(self.parse_weight()?);
|
||||
}
|
||||
Ok(Alternative { before_bar, after_bar, items, before_weight, weight })
|
||||
@@ -170,7 +170,7 @@ impl<'a> Parser<'a> {
|
||||
return self.parse_rs_if();
|
||||
}
|
||||
if t.is_kw("repeat") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let count = self.parse_expr()?;
|
||||
@@ -240,7 +240,7 @@ impl<'a> Parser<'a> {
|
||||
// A `default` arm may write no `:` at all (§18.17.4).
|
||||
let has_colon = self.cur().is_sym(":");
|
||||
if has_colon {
|
||||
self.bump();
|
||||
self.skip();
|
||||
} else if !is_default {
|
||||
return self.error("expected `:` in a randsequence case arm");
|
||||
}
|
||||
@@ -271,7 +271,7 @@ impl<'a> Parser<'a> {
|
||||
let after_rand = self.take_gap();
|
||||
self.expect_kw("join")?;
|
||||
let weight = if self.cur().is_sym("(") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let e = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
Some(e)
|
||||
@@ -292,7 +292,7 @@ impl<'a> Parser<'a> {
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let mut args = Vec::new();
|
||||
if has_parens {
|
||||
self.bump();
|
||||
self.skip();
|
||||
if !self.cur().is_sym(")") {
|
||||
let first = self.parse_expr_item()?;
|
||||
args = self.parse_expr_list(first, ")")?;
|
||||
|
||||
@@ -102,7 +102,7 @@ impl<'a> Parser<'a> {
|
||||
/// error node.
|
||||
pub(super) fn expect_closer(&mut self, kw: &str) -> PResult<()> {
|
||||
if self.cur().is_kw(kw) {
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(());
|
||||
}
|
||||
if self.tolerant {
|
||||
@@ -150,7 +150,7 @@ impl<'a> Parser<'a> {
|
||||
return;
|
||||
}
|
||||
if t.is_sym(";") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@ impl<'a> Parser<'a> {
|
||||
} else if open > 0 && (t.is_sym(")") || t.is_sym("]") || t.is_sym("}")) {
|
||||
open -= 1;
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ impl<'a> Parser<'a> {
|
||||
if self.pos == start_pos {
|
||||
// The failed construct consumed nothing, so skipping might not
|
||||
// either; take one token to guarantee the enclosing loop advances.
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.skip_to_sync();
|
||||
// Comments inside the skipped range are part of the raw text below.
|
||||
|
||||
@@ -227,7 +227,7 @@ impl<'a> Parser<'a> {
|
||||
if self.pos == start_pos && !self.cur().is_sym(")") {
|
||||
// The header consumed nothing and the skip below may not either;
|
||||
// take one token so the statement cannot be re-read forever.
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.skip_inside_brackets(true);
|
||||
// As in `recover`: comments inside the skipped range are bytes of the
|
||||
@@ -247,7 +247,7 @@ impl<'a> Parser<'a> {
|
||||
// Nothing was consumed and nothing below will be: the list loop
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
self.skip();
|
||||
} else if self.at_open_bracket() {
|
||||
// The element gave up standing *on* a bracket, which is therefore
|
||||
// one it opened and never closed — the `(` of a half-typed
|
||||
@@ -258,7 +258,7 @@ impl<'a> Parser<'a> {
|
||||
// the body would be swallowed looking for a `)` that was never
|
||||
// written. Taken here, the skip starts inside it at the list's own
|
||||
// level and stops at the next line as it does everywhere else.
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
@@ -310,7 +310,7 @@ impl<'a> Parser<'a> {
|
||||
} else if closes {
|
||||
open -= 1;
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -274,7 +274,7 @@ impl<'a> Parser<'a> {
|
||||
// already moved — are dropped by `verbatim_since`.
|
||||
self.pos = mark.pos;
|
||||
while self.pos < end_pos && !self.at_eof() {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.verbatim_since(start, col)
|
||||
}
|
||||
|
||||
@@ -125,11 +125,11 @@ impl<'a> Parser<'a> {
|
||||
return Ok(StmtKind::Directive(self.take_raw_text()));
|
||||
}
|
||||
if t.is_sym(";") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(StmtKind::Null);
|
||||
}
|
||||
if t.is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_hash = self.take_gap();
|
||||
let delay = self.parse_delay_value()?;
|
||||
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
|
||||
@@ -139,7 +139,7 @@ impl<'a> Parser<'a> {
|
||||
});
|
||||
}
|
||||
if t.is_sym("@") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let sens = self.parse_sens_list()?;
|
||||
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
|
||||
return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt });
|
||||
@@ -204,7 +204,7 @@ impl<'a> Parser<'a> {
|
||||
// keyword's left; the then-branch has already taken its own
|
||||
// trailing comment.
|
||||
else_comments = self.take_dangling();
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some(Box::new(self.parse_stmt()?))
|
||||
} else {
|
||||
None
|
||||
@@ -306,7 +306,7 @@ impl<'a> Parser<'a> {
|
||||
if let Some(last) = vars.last_mut() {
|
||||
last.after = self.take_gap();
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
vars.push(self.parse_foreach_var()?);
|
||||
}
|
||||
}
|
||||
@@ -343,7 +343,7 @@ impl<'a> Parser<'a> {
|
||||
if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=")
|
||||
{
|
||||
let before = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after = self.take_gap();
|
||||
let rhs = self.parse_expr()?;
|
||||
Ok(ForStep::Assign(SimpleAssign {
|
||||
@@ -377,16 +377,16 @@ impl<'a> Parser<'a> {
|
||||
// it (`x[6:0] /* opcode */ = v;`); left in the pending buffers
|
||||
// they would be lost and the safety net would refuse the file.
|
||||
let op_comments = self.take_around(mark);
|
||||
self.bump();
|
||||
self.skip();
|
||||
let rhs_comments = self.take_around(mark);
|
||||
let timing = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some(TimingControl::Delay {
|
||||
after_hash: self.take_gap(),
|
||||
expr: self.parse_delay_value()?,
|
||||
})
|
||||
} else if self.cur().is_sym("@") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some(TimingControl::Event(self.parse_sens_list()?))
|
||||
} else {
|
||||
None
|
||||
@@ -430,7 +430,7 @@ impl<'a> Parser<'a> {
|
||||
if self.cur().is_sym("*") {
|
||||
// `@*` without parens — the gap after the `@` is the `*`'s own
|
||||
// `before` slot, which the formatter prints in the same place.
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(SensList::Star { before: after_at, after: Vec::new() });
|
||||
}
|
||||
if self.cur().kind == TokenKind::Ident {
|
||||
@@ -449,10 +449,10 @@ impl<'a> Parser<'a> {
|
||||
// to whatever node comes next.
|
||||
let mut before = after_at;
|
||||
before.append(&mut self.take_trailing_here());
|
||||
self.bump(); // (
|
||||
self.skip(); // (
|
||||
before.append(&mut self.take_leading_here());
|
||||
let mut after = self.take_trailing_here();
|
||||
self.bump(); // *
|
||||
self.skip(); // *
|
||||
after.append(&mut self.take_leading_here());
|
||||
self.expect_sym(")")?;
|
||||
return Ok(SensList::Star { before, after });
|
||||
|
||||
@@ -218,7 +218,7 @@ impl<'a> Parser<'a> {
|
||||
self.link()?;
|
||||
let before = self.take_around(mark);
|
||||
for _ in 0..tokens {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
let after = self.take_around(mark);
|
||||
let rhs = self.parse_prop_expr(Self::right_operand_prec(prec, right))?;
|
||||
@@ -316,7 +316,7 @@ impl<'a> Parser<'a> {
|
||||
let mut count = None;
|
||||
let mut after_count = Vec::new();
|
||||
if counted && self.cur().is_sym("[") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_open = self.take_gap();
|
||||
count = Some(Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? }));
|
||||
after_count = self.take_gap();
|
||||
@@ -367,7 +367,7 @@ impl<'a> Parser<'a> {
|
||||
let mut els = None;
|
||||
if self.cur().is_kw("else") {
|
||||
before_else = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_else = self.take_gap();
|
||||
els = Some(self.parse_prop_expr(0)?);
|
||||
}
|
||||
@@ -421,7 +421,7 @@ impl<'a> Parser<'a> {
|
||||
let mut labels = Vec::new();
|
||||
let is_default = self.cur().is_kw("default");
|
||||
if is_default {
|
||||
self.bump();
|
||||
self.skip();
|
||||
} else {
|
||||
loop {
|
||||
labels.push(self.parse_expr_item()?);
|
||||
@@ -463,7 +463,7 @@ impl<'a> Parser<'a> {
|
||||
while self.at_repeat_bracket() {
|
||||
self.link()?;
|
||||
let before_open = self.take_gap();
|
||||
self.bump(); // [
|
||||
self.skip(); // [
|
||||
let after_open = self.take_gap();
|
||||
// `[+]` writes no operator of its own: its `+` is the bound.
|
||||
let (op, after_op) = if self.cur().is_sym("+") {
|
||||
@@ -493,7 +493,7 @@ impl<'a> Parser<'a> {
|
||||
range.lo = Some(self.parse_expr()?);
|
||||
if self.cur().is_sym(":") {
|
||||
range.before_colon = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
range.after_colon = self.take_gap();
|
||||
range.hi = Some(self.parse_expr()?);
|
||||
}
|
||||
@@ -509,7 +509,7 @@ impl<'a> Parser<'a> {
|
||||
self.expect_sym("##")?;
|
||||
let after_hash = self.take_gap();
|
||||
if self.cur().is_sym("[") {
|
||||
self.bump();
|
||||
self.skip();
|
||||
let after_open = self.take_gap();
|
||||
let range = Box::new(SvaRange { after_open, ..self.parse_sva_bounds()? });
|
||||
return Ok(CycleDelay { after_hash, expr: None, range: Some(range) });
|
||||
@@ -707,7 +707,7 @@ impl<'a> Parser<'a> {
|
||||
let mut items = Vec::new();
|
||||
while self.cur().is_sym(",") {
|
||||
let before_comma = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
let start = self.here();
|
||||
let meta = self.take_meta();
|
||||
let lhs = self.parse_expr()?;
|
||||
|
||||
@@ -227,12 +227,12 @@ impl<'a> Parser<'a> {
|
||||
if !self.cur().is_sym("(") {
|
||||
return Ok(TfPorts::default());
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
if self.cur().is_sym(")") {
|
||||
// Only what was written *inside* the empty `()`, as an empty
|
||||
// argument list of a call keeps.
|
||||
let dangling = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
return Ok(TfPorts { args, dangling });
|
||||
}
|
||||
let mark = self.diags_mark();
|
||||
@@ -272,9 +272,9 @@ impl<'a> Parser<'a> {
|
||||
// `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104`.
|
||||
// Two keywords, so the gap between them is a slot of its own —
|
||||
// no other direction has an inside.
|
||||
self.bump();
|
||||
self.skip();
|
||||
after_const = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
Some("const ref".to_string())
|
||||
} else if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
|
||||
Some(self.bump().text)
|
||||
@@ -298,7 +298,7 @@ impl<'a> Parser<'a> {
|
||||
let mut eq_comments = BinaryComments::default();
|
||||
let default = if self.cur().is_sym("=") {
|
||||
eq_comments.before = self.take_gap();
|
||||
self.bump();
|
||||
self.skip();
|
||||
eq_comments.after = self.take_gap();
|
||||
Some(self.parse_expr()?)
|
||||
} else {
|
||||
|
||||
@@ -38,7 +38,7 @@ impl<'a> Parser<'a> {
|
||||
} else if t.is_kw(&open) {
|
||||
depth += 1;
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
self.expect_closer(close)?;
|
||||
self.parse_label()?;
|
||||
@@ -52,7 +52,7 @@ impl<'a> Parser<'a> {
|
||||
pub(super) fn parse_opaque_line(&mut self) -> PResult<RawText> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip_to_semi()?;
|
||||
Ok(self.verbatim_since(start, col))
|
||||
}
|
||||
@@ -94,7 +94,7 @@ impl<'a> Parser<'a> {
|
||||
/// than as a nested assignment. How many there are, and whether they are
|
||||
/// legal lvalues, is a checker's business.
|
||||
pub(super) fn parse_alias(&mut self) -> PResult<ItemKind> {
|
||||
self.bump(); // alias
|
||||
self.skip(); // alias
|
||||
let mut nets = vec![self.parse_expr()?];
|
||||
while self.eat_sym("=") {
|
||||
nets.push(self.parse_expr()?);
|
||||
@@ -154,7 +154,7 @@ impl<'a> Parser<'a> {
|
||||
pub(super) fn parse_expect_statement(&mut self) -> PResult<RawText> {
|
||||
let start = self.here();
|
||||
let col = self.cur().col;
|
||||
self.bump(); // expect
|
||||
self.skip(); // expect
|
||||
self.expect_sym("(")?;
|
||||
self.skip_balanced("(", ")")?;
|
||||
self.skip_action_block()?;
|
||||
@@ -176,7 +176,7 @@ impl<'a> Parser<'a> {
|
||||
} else if t.is_sym(close) {
|
||||
depth -= 1;
|
||||
}
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -215,12 +215,12 @@ impl<'a> Parser<'a> {
|
||||
"[" => ("[", "]"),
|
||||
_ => ("{", "}"),
|
||||
};
|
||||
self.bump();
|
||||
self.skip();
|
||||
self.skip_balanced(open, close)?;
|
||||
} else if self.eat_sym(";") {
|
||||
return Ok(());
|
||||
} else {
|
||||
self.bump();
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! How much parsing this thread has done — a work counter, not a timer.
|
||||
//!
|
||||
//! A `textDocument/codeAction` used to parse the same buffer five times, and
|
||||
//! the only honest way to prove that it no longer does is to count the parses
|
||||
//! rather than to time them (take 5 §P1,
|
||||
//! `docs/features/perf5-p1/README.md`). A stopwatch assertion on a 1.3 MB
|
||||
//! buffer is a flake; a count is not.
|
||||
//!
|
||||
//! **Per thread, deliberately.** A process-wide counter would be unusable as
|
||||
//! an assertion, because `cargo test` runs tests in parallel and every other
|
||||
//! test in the binary would be adding to it; and it would answer the wrong
|
||||
//! question anyway, since what a caller wants to know is what *this* request
|
||||
//! did. A request is answered on one thread, so a thread-local count is that
|
||||
//! number exactly. It costs one non-atomic add per whole-file parse.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static PARSES: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many whole-file parses this thread has run.
|
||||
///
|
||||
/// Counted in [`crate::parse`] and [`crate::parse_tolerant`], which is every
|
||||
/// way a whole file is parsed: [`crate::parse_source`] and
|
||||
/// [`crate::parse_source_tolerant`] both funnel through them. A *lex* failure
|
||||
/// parses nothing and is not counted; neither is a fragment read (macro
|
||||
/// expansion), which re-reads a token slice rather than a file.
|
||||
///
|
||||
/// The count is monotone and never reset, so a caller measures a *delta*
|
||||
/// across the work it is asking about.
|
||||
pub fn parses() -> u64 {
|
||||
PARSES.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Count one whole-file parse.
|
||||
pub(crate) fn count_parse() {
|
||||
PARSES.with(|parses| parses.set(parses.get() + 1));
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//! The state after the edits: the index the verifier compares against, and
|
||||
//! one watched file's print of it.
|
||||
//!
|
||||
//! Both used to be "do it all again". The after-index was a whole
|
||||
//! `WorkspaceIndex::build` over every in-scope file, of which an edit changes
|
||||
//! two or three; the after-print of an *unedited* watched file was a fresh
|
||||
//! parse and analysis of text nothing had touched. Take 5 §P2c replaced the
|
||||
//! first with the before-index plus the edited files' absorbed records, and
|
||||
//! the second with the analysis the before-pass already made, re-resolved
|
||||
//! against the new index.
|
||||
//!
|
||||
//! **Nothing the verifier compares changed.** The prints are the same prints,
|
||||
//! built by the same `print`, over the same watched set; what changed is where
|
||||
//! their inputs come from. The tests below are the proof that the inputs are
|
||||
//! the same inputs — including on edits crafted to make an incremental index
|
||||
//! disagree with a rebuilt one.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{resolve_external, FileFacts, Semantics, WorkspaceIndex};
|
||||
|
||||
use super::{print, Print, Shifts};
|
||||
use crate::scope::Scope;
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is — **and** the one new
|
||||
/// analysis of each edited file, which is also its after-print's.
|
||||
///
|
||||
/// The before-index already holds a record per in-scope file, and an edit
|
||||
/// changes at most a handful of them. So this is the before-index with the
|
||||
/// edited files' new records absorbed, and not one unedited file re-read:
|
||||
/// `WorkspaceIndex::absorb` promises "the index a full build over the
|
||||
/// resulting record set would have produced" (`docs/topo.md` §3), and every
|
||||
/// edited path is one the index already holds, so no file id moves either.
|
||||
/// One `absorb` of every edited record rather than an `update_facts` per
|
||||
/// record: both promise that same equality, and `absorb`'s single whole merge
|
||||
/// **measured faster** than the per-file restricted merges, which walk the
|
||||
/// same records with a name-set lookup at every declaration (tail rename
|
||||
/// 37 ms against 53; see the feature README's §P2c entry).
|
||||
/// That equality is what the verifier depends on and what
|
||||
/// `an_absorbed_after_index_is_the_index_a_rebuild_would_give` pins, on
|
||||
/// crafted adversarial edits as well as on ordinary ones (take 5 §P2c).
|
||||
///
|
||||
/// Each edited file is parsed **once**, here, and the analysis that parse
|
||||
/// produced is handed back for the after-print rather than being made again.
|
||||
pub(super) fn after_index(
|
||||
scope: &Scope,
|
||||
edited: &[(PathBuf, String)],
|
||||
) -> (WorkspaceIndex, Vec<(PathBuf, Semantics)>) {
|
||||
let mut records = Vec::with_capacity(edited.len());
|
||||
let mut analyses = Vec::with_capacity(edited.len());
|
||||
for (path, text) in edited {
|
||||
let (facts, semantics) = FileFacts::analyzed(path.clone(), text);
|
||||
records.push(facts);
|
||||
analyses.push((path.clone(), semantics));
|
||||
}
|
||||
let mut index = scope.index().clone();
|
||||
index.absorb(records, &[]);
|
||||
(index, analyses)
|
||||
}
|
||||
|
||||
/// One watched file's after-print: from the edited file's own new analysis
|
||||
/// when the edits touched it, and otherwise from the analysis the before-pass
|
||||
/// computed, re-resolved against the after-index.
|
||||
pub(super) fn after_print(
|
||||
scope: &Scope,
|
||||
i: usize,
|
||||
path: &Path,
|
||||
index: &WorkspaceIndex,
|
||||
edited: &[(PathBuf, Semantics)],
|
||||
excluded: &[TextRange],
|
||||
) -> Option<Print> {
|
||||
match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, semantics)) => {
|
||||
let external = resolve_external(semantics, index);
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
None => {
|
||||
let (semantics, external) = scope.against(i, index)?;
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
use crate::TextEdit;
|
||||
|
||||
/// What a whole `WorkspaceIndex::build` over the edited texts gives — the
|
||||
/// thing the absorbed index has to equal, and what §P2c replaced.
|
||||
fn rebuilt(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources: Vec<(PathBuf, &str)> = (0..scope.len())
|
||||
.filter_map(|i| {
|
||||
let (path, text) = (scope.path(i)?, scope.text(i)?);
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(text, |(_, edited_text)| edited_text.as_str());
|
||||
Some((path.to_path_buf(), text))
|
||||
})
|
||||
.collect();
|
||||
WorkspaceIndex::build(sources)
|
||||
}
|
||||
|
||||
/// Every query the verifier's prints reach the index through, for one
|
||||
/// name — so "the same index" is checked at the level the checks use it
|
||||
/// and not only through the fingerprint.
|
||||
fn answers(index: &WorkspaceIndex, name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for def in index.units(name) {
|
||||
out.push_str(&format!(
|
||||
"unit {} {:?} {}..{}\n",
|
||||
def.file.0, def.kind, def.name_span.start, def.name_span.end
|
||||
));
|
||||
for site in index.references_to(def) {
|
||||
out.push_str(&format!(
|
||||
" ref {} {}..{}\n",
|
||||
site.file.0, site.name_span.start, site.name_span.end
|
||||
));
|
||||
}
|
||||
}
|
||||
for edge in index.instantiations_of(name) {
|
||||
out.push_str(&format!("inst {} {}\n", edge.file.0, edge.owner.name));
|
||||
}
|
||||
for (unit, def) in index.hierarchical_declarations(name) {
|
||||
out.push_str(&format!(
|
||||
"hier {unit} {} {}..{}\n",
|
||||
def.file.0, def.name_span.start, def.name_span.end
|
||||
));
|
||||
}
|
||||
for symbol in index.workspace_symbols(name) {
|
||||
out.push_str(&format!("sym {} {:?}\n", symbol.name, symbol.container));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One (workspace, edit) case: build a scope, apply the edits, and assert
|
||||
/// the absorbed after-index is the index a rebuild would give.
|
||||
fn absorbing_equals_rebuilding(
|
||||
files: &[(&str, &str)],
|
||||
edits: &[(&str, &str, &str)],
|
||||
names: &[&str],
|
||||
) {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let mut edited: Vec<(PathBuf, String)> = Vec::new();
|
||||
for (path, from, to) in edits {
|
||||
let i = scope.index_of(Path::new(path)).expect("the edited file is in scope");
|
||||
let text = scope.text(i).expect("its text");
|
||||
let at = text.find(from).expect("the edited text is there") as u32;
|
||||
let edit = TextEdit {
|
||||
range: TextRange::new(at, at + from.len() as u32),
|
||||
new_text: (*to).to_string(),
|
||||
};
|
||||
edited.push((PathBuf::from(*path), apply(text, std::slice::from_ref(&edit))));
|
||||
}
|
||||
let (absorbed, analyses) = after_index(&scope, &edited);
|
||||
let built = rebuilt(&scope, &edited);
|
||||
assert_eq!(absorbed.fingerprint(), built.fingerprint(), "{files:?} / {edits:?}");
|
||||
assert_eq!(absorbed.files(), built.files(), "the file ids moved");
|
||||
assert_eq!(absorbed.files(), scope.index().files(), "an absorb over held paths keeps ids");
|
||||
for name in names {
|
||||
assert_eq!(answers(&absorbed, name), answers(&built, name), "`{name}` differs");
|
||||
}
|
||||
assert_eq!(analyses.len(), edited.len(), "one new analysis per edited file");
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub (input logic clk, output logic q);\n wire sig;\nendmodule\n";
|
||||
const TOP: &str = "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign sig = u_sub.sig;\nendmodule\n";
|
||||
const PKG: &str = "package pkg;\n localparam int SIG = 1;\nendpackage\n";
|
||||
const USER: &str = "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n";
|
||||
|
||||
fn workspace() -> [(&'static str, &'static str); 4] {
|
||||
[("/w/sub.sv", SUB), ("/w/top.sv", TOP), ("/w/pkg.sv", PKG), ("/w/user.sv", USER)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absorbed_after_index_is_the_index_a_rebuild_would_give() {
|
||||
// An ordinary rename edit, in one file and in two.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "logic sig;", "logic sg;")],
|
||||
&["sig", "sg", "top", "sub"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire sg;"), ("/w/top.sv", "u_sub.sig", "u_sub.sg")],
|
||||
&["sig", "sg", "sub"],
|
||||
);
|
||||
// A file that **gains** a declaration another file can name.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[(
|
||||
"/w/pkg.sv",
|
||||
"localparam int SIG = 1;",
|
||||
"localparam int SIG = 1;\n localparam int X = 2;",
|
||||
)],
|
||||
&["SIG", "X", "pkg"],
|
||||
);
|
||||
// A file that **loses** one — the use in `user.sv` is left dangling,
|
||||
// and neither index may hide that.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "localparam int SIG = 1;", "")],
|
||||
&["SIG", "pkg"],
|
||||
);
|
||||
// An edit that changes what **another** file resolves to: the package
|
||||
// is renamed, so `user.sv`'s import points at nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "package pkg;", "package pkq;")],
|
||||
&["pkg", "pkq", "SIG"],
|
||||
);
|
||||
// An edited **package**, plus the re-export chain that reads it.
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n";
|
||||
const C: &str = "module c;\n localparam int W = b_pkg::V;\nendmodule\n";
|
||||
let chain = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/c.sv", C)];
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/a.sv", "localparam int V = 1;", "localparam int V2 = 1;")],
|
||||
&["V", "V2", "a_pkg", "b_pkg"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/b.sv", "export a_pkg::*;", "")],
|
||||
&["V", "a_pkg", "b_pkg"],
|
||||
);
|
||||
// A module that stops being instantiated, and one that starts.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "sub u_sub", "other u_sub")],
|
||||
&["sub", "other", "top"],
|
||||
);
|
||||
// An edit that makes a file stop lexing: it contributes nothing, and
|
||||
// both indexes must agree that it contributes nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire \"sig;")],
|
||||
&["sig", "sub"],
|
||||
);
|
||||
}
|
||||
|
||||
/// **Attack 3 — an after-index whose file ids shifted.** The absorbed
|
||||
/// index keeps ids because every edited path is one it already holds, but
|
||||
/// the print comparison must not *depend* on that: a `Def` names a file by
|
||||
/// id, and an id is a position in a path-sorted list that any added file
|
||||
/// renumbers. So the print resolves every id back to a **path** before
|
||||
/// comparing, and this pins it — the same file's print against two indexes
|
||||
/// whose ids differ by one everywhere must be the same print.
|
||||
#[test]
|
||||
fn a_print_names_paths_so_shifted_file_ids_cannot_change_it() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let mut scope = Scope::build(&sources);
|
||||
// An index over the same four files plus one that sorts *first*, so
|
||||
// every original file's id is one higher in it.
|
||||
let mut shifted: Vec<(PathBuf, &str)> =
|
||||
sources.iter().map(|(p, t)| (p.clone(), t.as_str())).collect();
|
||||
shifted.insert(0, (PathBuf::from("/w/aaa.sv"), "module aaa; endmodule\n"));
|
||||
let shifted = WorkspaceIndex::build(shifted);
|
||||
assert_eq!(
|
||||
shifted.file_id(Path::new("/w/pkg.sv")).map(|f| f.0),
|
||||
scope.index().file_id(Path::new("/w/pkg.sv")).map(|f| f.0 + 1),
|
||||
"the ids really do shift"
|
||||
);
|
||||
|
||||
let i = scope.index_of(Path::new("/w/user.sv")).expect("user.sv is in scope");
|
||||
assert!(scope.analysis(i).is_some(), "its analysis is what a before-pass computes");
|
||||
let path = scope.path(i).expect("its path");
|
||||
let held = after_print(&scope, i, path, scope.index(), &[], &[]).expect("a print");
|
||||
let moved = after_print(&scope, i, path, &shifted, &[], &[]).expect("a print");
|
||||
assert_eq!(held, moved, "a print must not read a file id");
|
||||
}
|
||||
|
||||
/// Absorbing over a path the index already holds moves no file id — the
|
||||
/// property the after-print's path lookups and the `Def`s inside a print
|
||||
/// both stand on.
|
||||
#[test]
|
||||
fn absorbing_an_edited_file_keeps_every_file_id() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let before: Vec<PathBuf> = scope.index().files().to_vec();
|
||||
let edited = vec![(PathBuf::from("/w/pkg.sv"), PKG.replace("SIG", "SIGNAL"))];
|
||||
let (after, _) = after_index(&scope, &edited);
|
||||
assert_eq!(after.files(), before.as_slice());
|
||||
for (id, path) in before.iter().enumerate() {
|
||||
assert_eq!(after.file_id(path), Some(vlog_semantic::FileId(id as u32)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
|
||||
mod after;
|
||||
mod ledger;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -26,13 +27,14 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::{apply, Shift, TextEdit};
|
||||
|
||||
use after::{after_index, after_print};
|
||||
use ledger::{overlaps, pieces_match, region_of, Split, Transit};
|
||||
|
||||
/// Check the whole edit, or refuse it whole.
|
||||
@@ -41,6 +43,7 @@ pub(crate) fn verify(
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
old_name: &str,
|
||||
new_name: &str,
|
||||
trace: &mut VerifyTrace,
|
||||
) -> Result<(), String> {
|
||||
let edited: Vec<(PathBuf, String)> = edits
|
||||
.iter()
|
||||
@@ -57,7 +60,7 @@ pub(crate) fn verify(
|
||||
// 1. The token stream of every touched file, before and after.
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
|
||||
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
|
||||
}
|
||||
|
||||
// 2. What every name resolves to, before and after — in every file the
|
||||
@@ -68,40 +71,39 @@ pub(crate) fn verify(
|
||||
// catches a third file whose existing `new_name` reference the rename
|
||||
// would make ambiguous without touching a byte of it.
|
||||
let watched = watched_files(scope, edits, &[old_name, new_name]);
|
||||
trace.watched = watched.len();
|
||||
trace.watched_bytes = watched.iter().filter_map(|&i| scope.text(i)).map(str::len).sum();
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
if scope.analysis(i).is_none() {
|
||||
if !trace.before.measure(|| scope.analysis(i).is_some()) {
|
||||
return Err(ABANDONED.to_string());
|
||||
}
|
||||
}
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
));
|
||||
trace.before.measure(|| {
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(ABANDONED.to_string()),
|
||||
},
|
||||
let after = trace
|
||||
.after
|
||||
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(&semantics, &external, &after_index, path, &Shifts::default(), &[]);
|
||||
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
|
||||
if let Some(what) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
|
||||
@@ -319,27 +321,14 @@ pub(crate) fn verify_move(
|
||||
));
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = after_index(scope, &edited);
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(abandoned) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(abandoned),
|
||||
},
|
||||
let after =
|
||||
after_print(scope, i, path, &after_index, &edited_analyses, excluded.after(path));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(abandoned);
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(
|
||||
&semantics,
|
||||
&external,
|
||||
&after_index,
|
||||
path,
|
||||
&Shifts::default(),
|
||||
excluded.after(path),
|
||||
);
|
||||
let Some(before) = before.get(n) else { return Err(abandoned) };
|
||||
if let Some(what_moved) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"{what} would change what {what_moved} means in {}; no edits were made.",
|
||||
@@ -409,19 +398,6 @@ fn watched_files(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], names: &[&str]
|
||||
|
||||
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is.
|
||||
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources = scope.sources().iter().map(|(path, text)| {
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(*text, |(_, edited_text)| edited_text.as_str());
|
||||
(path.to_path_buf(), text)
|
||||
});
|
||||
WorkspaceIndex::build(sources.collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// token identity
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -1257,7 +1233,7 @@ mod tests {
|
||||
new_text: "sig".into(),
|
||||
}],
|
||||
)];
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig");
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig", &mut VerifyTrace::default());
|
||||
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,8 @@ 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_parser::{parse_source_tolerant, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, SymbolKind};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
@@ -81,10 +81,26 @@ pub struct ExtractSite {
|
||||
/// a whole item to move.
|
||||
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
extract_site_in(&tree, &diagnostics, text, start, end)
|
||||
}
|
||||
|
||||
/// [`extract_site`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, refusal on parse diagnostics included — `diagnostics`
|
||||
/// must be `tree`'s own list, and `text` the bytes both were built from
|
||||
/// (`Region::read` copies item text out by span). Take 5 §P1b; see
|
||||
/// `docs/features/perf5-p1/README.md`.
|
||||
pub fn extract_site_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
start: u32,
|
||||
end: u32,
|
||||
) -> Option<ExtractSite> {
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
|
||||
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 {
|
||||
@@ -165,12 +181,7 @@ impl Extraction {
|
||||
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
|
||||
));
|
||||
return Err(does_not_parse(file, problem));
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end))?;
|
||||
let module = region.module_name().to_string();
|
||||
@@ -452,6 +463,20 @@ fn occupied(path: &Path) -> String {
|
||||
format!("there is already a `{}` beside this file; pick another name.", display(path))
|
||||
}
|
||||
|
||||
/// Why a file lucisv cannot read is a file it will not extract from.
|
||||
///
|
||||
/// Reachable through `extract_module` alone: a server calls [`extract_site_in`]
|
||||
/// first, and that answers `None` for a file with any parse diagnostic, so the
|
||||
/// sentence is for the caller that comes straight to the engine.
|
||||
fn does_not_parse(file: &Path, problem: &ParseDiagnostic) -> String {
|
||||
format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
)
|
||||
}
|
||||
|
||||
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."
|
||||
|
||||
@@ -93,10 +93,26 @@ pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRang
|
||||
/// them, and nothing else, to the engine.
|
||||
pub fn imported_packages(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
imported_packages_in(&tree, &diagnostics, text, offset)
|
||||
}
|
||||
|
||||
/// [`imported_packages`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, including the refusal on a buffer that did not parse
|
||||
/// cleanly — `diagnostics` is that parse's own list and must come from the
|
||||
/// same run as `tree`. `text` is still needed: the "is the cursor at the top"
|
||||
/// question reads the source bytes of the import run's comment block. Take 5
|
||||
/// §P1b; see `docs/features/perf5-p1/README.md`.
|
||||
pub fn imported_packages_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
offset: u32,
|
||||
) -> Vec<String> {
|
||||
if !diagnostics.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(items) = container_at(&tree, offset) else { return Vec::new() };
|
||||
let Some(items) = container_at(tree, offset) else { return Vec::new() };
|
||||
let imports: Vec<&Item> = items.iter().filter(|item| is_import(item)).collect();
|
||||
if imports.is_empty() || !at_the_top(text, items, offset) {
|
||||
return Vec::new();
|
||||
@@ -142,20 +158,10 @@ fn organize(
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(file, &diagnostics)?;
|
||||
let semantics = analyze(&tree, text);
|
||||
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
|
||||
|
||||
let here = scope_at(&tree, &semantics, offset)?;
|
||||
let verdicts = import_usage(&semantics, &tokens, here.scope, scope.index())?;
|
||||
let mut blocks = Blocks::read(text, here.items, &verdicts)?;
|
||||
let (edits, warnings, removed, sorted) = blocks.plan(text)?;
|
||||
if edits.is_empty() {
|
||||
return Err(match warnings.first() {
|
||||
Some(sentence) => sentence.clone(),
|
||||
None => "these imports are already sorted, and every one of them is used.".to_string(),
|
||||
});
|
||||
}
|
||||
let (edits, warnings, removed, sorted) =
|
||||
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
|
||||
|
||||
let what = "organizing the imports";
|
||||
let plan = vec![(i, edits)];
|
||||
@@ -166,6 +172,96 @@ fn organize(
|
||||
Ok((edit, removed, sorted))
|
||||
}
|
||||
|
||||
/// Everything the organization decides **before** it is verified: its edits,
|
||||
/// the sentences about what it left alone, and the two counts a title
|
||||
/// promises.
|
||||
///
|
||||
/// One reader, so the code action's offer and the edit it resolves to cannot
|
||||
/// come to disagree about how many imports go and how many are sorted.
|
||||
/// `tree`, `diagnostics`, `semantics` and `tokens` must all be of `text`.
|
||||
#[allow(clippy::too_many_arguments)] // one call's worth of already-computed inputs, not state
|
||||
fn planned(
|
||||
index: &vlog_semantic::WorkspaceIndex,
|
||||
file: &Path,
|
||||
text: &str,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
tokens: &[vlog_parser::token::Token],
|
||||
offset: u32,
|
||||
) -> Result<(Vec<TextEdit>, Vec<String>, usize, usize), String> {
|
||||
unparsed(file, diagnostics)?;
|
||||
let here = scope_at(tree, semantics, offset)?;
|
||||
let verdicts = import_usage(semantics, tokens, here.scope, index)?;
|
||||
let mut blocks = Blocks::read(text, here.items, &verdicts)?;
|
||||
let (edits, warnings, removed, sorted) = blocks.plan(text)?;
|
||||
if edits.is_empty() {
|
||||
return Err(match warnings.first() {
|
||||
Some(sentence) => sentence.clone(),
|
||||
None => "these imports are already sorted, and every one of them is used.".to_string(),
|
||||
});
|
||||
}
|
||||
Ok((edits, warnings, removed, sorted))
|
||||
}
|
||||
|
||||
/// What an organize-imports code action's title promises — how many imports it
|
||||
/// removes and how many it writes back in order — **without** verifying the
|
||||
/// splice or keeping the edit.
|
||||
///
|
||||
/// [`organize_counts`] answers the same two numbers by computing the whole
|
||||
/// refactoring and running `check::verify_splice`, which rebuilds the index
|
||||
/// over every in-scope file and re-analyzes them. A lazily-offered code action
|
||||
/// throws that edit away and asks for it again on the click, so the offer pays
|
||||
/// for a verification whose result nothing reads: take 5 §P1c measured that
|
||||
/// verification as about two thirds of the offer's cost
|
||||
/// (`docs/features/perf5-p1/README.md`).
|
||||
///
|
||||
/// Everything the *plan* refuses is refused here identically, with the same
|
||||
/// sentence: a buffer that does not parse, no scope at the position, an
|
||||
/// unknown package (`import_usage`'s own refusal), an import sharing a line,
|
||||
/// and the "already sorted, every one used" answer. What is **not** reproduced
|
||||
/// is `check::verify_splice`; the click recomputes and verifies the whole
|
||||
/// refactoring, which is where an edit that would not survive it is refused.
|
||||
pub fn organize_offer(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
let scope = Scope::build(files);
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = analyze(&tree, text);
|
||||
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
|
||||
let (_, _, removed, sorted) =
|
||||
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
|
||||
Ok((removed, sorted))
|
||||
}
|
||||
|
||||
/// [`organize_offer`] over the parse, analysis and token stream the caller
|
||||
/// already has.
|
||||
///
|
||||
/// All four must be of exactly the text `files` holds for `file` — an open
|
||||
/// buffer's `Document` holds that quartet for its own bytes. A buffer that did
|
||||
/// not lex holds no tokens, but it also holds a parse diagnostic, so
|
||||
/// [`planned`] refuses it before the token stream is read.
|
||||
pub fn organize_offer_in(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
tokens: &[vlog_parser::token::Token],
|
||||
offset: u32,
|
||||
) -> Result<(usize, usize), String> {
|
||||
let scope = Scope::build(files);
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (_, _, removed, sorted) =
|
||||
planned(scope.index(), file, text, tree, diagnostics, semantics, tokens, offset)?;
|
||||
Ok((removed, sorted))
|
||||
}
|
||||
|
||||
/// The innermost scope covering the cursor that may write `import` items.
|
||||
fn scope_at<'t>(
|
||||
tree: &'t SourceFile,
|
||||
|
||||
@@ -34,9 +34,10 @@ mod source;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic};
|
||||
|
||||
use crate::instantiate::module_definition;
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
@@ -72,10 +73,25 @@ pub struct InlineSite {
|
||||
/// sentence from the command instead.
|
||||
pub fn inline_site(text: &str, offset: u32) -> Option<InlineSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
inline_site_in(&tree, &diagnostics, text, offset)
|
||||
}
|
||||
|
||||
/// [`inline_site`] over a parse the caller already has.
|
||||
///
|
||||
/// The same answer, refusal on parse diagnostics included — `diagnostics`
|
||||
/// must be `tree`'s own list, and `text` the bytes both were built from
|
||||
/// (`Site::read` reads the instantiation's connections out of the source).
|
||||
/// Take 5 §P1b; see `docs/features/perf5-p1/README.md`.
|
||||
pub fn inline_site_in(
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
text: &str,
|
||||
offset: u32,
|
||||
) -> Option<InlineSite> {
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let site = Site::read(&tree, text, offset)?.ok()?;
|
||||
let site = Site::read(tree, text, offset)?.ok()?;
|
||||
Some(InlineSite {
|
||||
units: vec![site.target.clone(), site.module.name.clone()],
|
||||
module: site.target.clone(),
|
||||
|
||||
@@ -36,12 +36,16 @@ mod ports;
|
||||
mod references;
|
||||
mod rename;
|
||||
mod scope;
|
||||
mod trace;
|
||||
|
||||
pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home};
|
||||
pub use imports::{
|
||||
imported_packages, organize_counts, organize_imports, organize_title, unused_imports,
|
||||
pub use extract::{
|
||||
extract_module, extract_site, extract_site_in, extract_title, ExtractSite, Home,
|
||||
};
|
||||
pub use inline::{inline_module, inline_site, inline_title, InlineSite};
|
||||
pub use imports::{
|
||||
imported_packages, imported_packages_in, organize_counts, organize_imports, organize_offer,
|
||||
organize_offer_in, organize_title, unused_imports,
|
||||
};
|
||||
pub use inline::{inline_module, inline_site, inline_site_in, inline_title, InlineSite};
|
||||
pub use references::find_references;
|
||||
|
||||
pub use instantiate::{
|
||||
@@ -50,12 +54,15 @@ pub use instantiate::{
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase,
|
||||
may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port,
|
||||
sites_phrase, ModuleRef, PortAction,
|
||||
may_have_port_action, port_action_modules, port_action_modules_in, port_actions, port_offers,
|
||||
port_offers_in, propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction, PortOffer,
|
||||
PortOfferKind,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_preflight,
|
||||
rename_traced, rename_traced_with, KnownFacts, RenameTarget,
|
||||
};
|
||||
pub use trace::{IndexTrace, RenameTrace, Stage, VerifyTrace, WarnTrace};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -64,8 +64,32 @@ pub(super) fn plan_convert(
|
||||
let Some((module, _)) = find_module(&tree, &name) else {
|
||||
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
|
||||
};
|
||||
let ports = convert_header(file, &diagnostics, module)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(elsewhere(&name));
|
||||
}
|
||||
|
||||
let mut plan = Plan::default();
|
||||
plan.add(i, convert_edits(text, file, module, &ports)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
}
|
||||
|
||||
/// Everything the conversion refuses **before** it asks where the module is
|
||||
/// declared: the header it needs, the parse, a name written twice, a directive
|
||||
/// in the port list, a declaration hidden in a generate region.
|
||||
///
|
||||
/// Split out of [`plan_convert`] so the code-action offer earns the same
|
||||
/// refusals from the buffer's own parse (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn convert_header<'t>(
|
||||
file: &Path,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
module: &'t Module,
|
||||
) -> Result<Vec<&'t NonAnsiPort>, String> {
|
||||
let name = &module.name;
|
||||
let ports = header(module)?;
|
||||
unparsed(file, &diagnostics)?;
|
||||
unparsed(file, diagnostics)?;
|
||||
let names = header_names(module, &ports)?;
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(format!(
|
||||
@@ -77,28 +101,41 @@ pub(super) fn plan_convert(
|
||||
"`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits."
|
||||
));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
Ok(ports)
|
||||
}
|
||||
|
||||
let absorbed = absorb(text, &name, &module.items, &names)?;
|
||||
attributes_clear(&name, &absorbed)?;
|
||||
/// The sentence a module whose indexed declaration is elsewhere earns.
|
||||
pub(super) fn elsewhere(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// The conversion's edits, once the module's declaration is known to be the
|
||||
/// cursor's own file: the insertions around each header name, then the
|
||||
/// deletions of the body declarations they absorbed.
|
||||
pub(super) fn convert_edits(
|
||||
text: &str,
|
||||
file: &Path,
|
||||
module: &Module,
|
||||
ports: &[&NonAnsiPort],
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let name = &module.name;
|
||||
let names: Vec<String> = ports.iter().map(|port| port.name.clone()).collect();
|
||||
let absorbed = absorb(text, name, &module.items, &names)?;
|
||||
attributes_clear(name, &absorbed)?;
|
||||
directives_clear(text, file, module, &absorbed)?;
|
||||
let comments = comments_of(text, file)?;
|
||||
let mut plan = Plan::default();
|
||||
let mut edits = Vec::new();
|
||||
// One declaration may declare several ports (`input a, b;`), and its
|
||||
// comments belong to the first of them: written onto both they would be
|
||||
// duplicated, which is as much a corruption as dropping them.
|
||||
let mut claimed: Vec<TextRange> = Vec::new();
|
||||
for (port, absorbed) in ports.iter().zip(&absorbed) {
|
||||
plan.add(i, port_edits(text, &name, port, absorbed, &comments, &mut claimed)?);
|
||||
edits.append(&mut port_edits(text, name, port, absorbed, &comments, &mut claimed)?);
|
||||
}
|
||||
plan.add(i, deletions(text, &name, &absorbed, &comments)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
edits.append(&mut deletions(text, name, &absorbed, &comments)?);
|
||||
Ok(edits)
|
||||
}
|
||||
|
||||
/// The non-ANSI port list this conversion needs, or the sentence saying why
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connection, Connections, Instance, Instantiation, Item, ListElem};
|
||||
use vlog_parser::ast::{
|
||||
Connection, Connections, Instance, Instantiation, Item, ListElem, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::SymbolKind;
|
||||
@@ -113,16 +115,16 @@ fn directives(what: &str, list: &str) -> String {
|
||||
|
||||
/// What the cursor found: an instance, its named connection list, and which
|
||||
/// element of it is the `.*`.
|
||||
struct Wildcard<'t> {
|
||||
instantiation: &'t Instantiation,
|
||||
instance: &'t Instance,
|
||||
conns: &'t [ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
pub(super) struct Wildcard<'t> {
|
||||
pub(super) instantiation: &'t Instantiation,
|
||||
pub(super) instance: &'t Instance,
|
||||
pub(super) conns: &'t [ListElem<Connection>],
|
||||
pub(super) wildcard: usize,
|
||||
}
|
||||
|
||||
/// The instantiation the cursor names and the `.*` inside it, or the sentence
|
||||
/// saying why there is none to expand.
|
||||
fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
pub(super) fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
let (instantiation, instance, bound) = instance_at(items, offset)?;
|
||||
if bound {
|
||||
return Err(format!(
|
||||
@@ -193,14 +195,26 @@ fn unconnected(
|
||||
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(path, &diagnostics)?;
|
||||
let Some((module, _)) = find_module(&tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
unconnected_in(path, &tree, &diagnostics, &site.name, conns)
|
||||
}
|
||||
|
||||
/// [`unconnected`] over the declaring file's parse, which the code-action
|
||||
/// offer makes once instead of once per refactoring (take 5 §P1c).
|
||||
pub(super) fn unconnected_in(
|
||||
path: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
module: &str,
|
||||
conns: &[ListElem<Connection>],
|
||||
) -> Result<Vec<String>, String> {
|
||||
unparsed(path, diagnostics)?;
|
||||
let Some((declaration, _)) = find_module(tree, module) else {
|
||||
return Err(not_indexed(module));
|
||||
};
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(directives(&site.name, "port list"));
|
||||
if !declaration.port_directives.is_empty() {
|
||||
return Err(directives(module, "port list"));
|
||||
}
|
||||
Ok(declared_ports(module)
|
||||
Ok(declared_ports(declaration)
|
||||
.into_iter()
|
||||
.map(|port| port.name)
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
|
||||
@@ -27,14 +27,16 @@ mod expand;
|
||||
mod find;
|
||||
mod list;
|
||||
mod merge;
|
||||
mod offer;
|
||||
mod propagate;
|
||||
mod remove;
|
||||
|
||||
pub(crate) use find::{find_module, visible_in};
|
||||
pub use offer::{port_offers, port_offers_in, PortOffer, PortOfferKind};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList};
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
@@ -268,6 +270,22 @@ pub fn may_have_port_action(text: &str, offset: u32) -> bool {
|
||||
/// the whole workspace. Empty for exactly the positions the gate refuses.
|
||||
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
port_action_modules_in(&tree, offset)
|
||||
}
|
||||
|
||||
/// [`port_action_modules`] over a parse the caller already has.
|
||||
///
|
||||
/// The same walk and the same answer; only the parse moves. A server holds
|
||||
/// the tolerant parse of the buffer it is answering about
|
||||
/// (`lucisv_server::state::Document`), so asking it to parse the same bytes
|
||||
/// again is a whole-file parse per cursor move — which is what take 5 §P1b
|
||||
/// removes (`docs/features/perf5-p1/README.md`).
|
||||
///
|
||||
/// `tree` must be the tolerant parse of the same text the offsets index. This
|
||||
/// selector reads **no** parse diagnostics, exactly as the text form does not:
|
||||
/// a port refactoring is offered on a buffer that does not fully parse, and
|
||||
/// the engine refuses later if it must.
|
||||
pub fn port_action_modules_in(tree: &SourceFile, offset: u32) -> Vec<String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let named: Vec<String> = instantiations
|
||||
@@ -284,7 +302,7 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
let Some((name, (module, _))) =
|
||||
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
|
||||
module.and_then(|name| Some((name.clone(), find_module(tree, &name)?)))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Which port refactorings a cursor would be *offered*, and what each one's
|
||||
//! title promises — without a workspace index, without an analysis of any file
|
||||
//! but the cursor's own, and without verifying anything.
|
||||
//!
|
||||
//! **Why this exists.** [`super::port_actions`] answers the same question by
|
||||
//! computing all four refactorings in full and handing back their verified
|
||||
//! edits. A client that can `codeAction/resolve` throws every one of those
|
||||
//! edits away and asks for the real one when the user clicks, so the offer was
|
||||
//! paying for four `Scope::build`s — an index over the buffer and the
|
||||
//! instantiated module's declaring file, each file lexed, parsed and analyzed
|
||||
//! once per refactoring — to render a menu. Take 5 §P1b measured what that
|
||||
//! costs at one ordinary opentitan cursor: **21.15 ms of a 21.83 ms request,
|
||||
//! for zero offered actions**. See `docs/features/perf5-p1/README.md`.
|
||||
//!
|
||||
//! **What it does instead.** Each of the four is asked its *plan-time*
|
||||
//! questions — the ones that read the cursor's own file, the module's
|
||||
//! declaration, and nothing else — in the same order, with the same helpers,
|
||||
//! so the same conditions produce the same silence. The declaring file is
|
||||
//! parsed at most once and only when a refactoring needs it; the cursor's own
|
||||
//! parse and analysis come from the caller.
|
||||
//!
|
||||
//! **What it cannot see, and who does.** Two refusals live *after* the plan
|
||||
//! and are not reproduced here: [`crate::check::verify_splice`] (the token,
|
||||
//! comment and resolution comparison of the whole edit) and `ports::confirm`
|
||||
//! (reading the edited text back and requiring the port and connection lists
|
||||
//! to say what the plan promised). An offer this query makes that one of those
|
||||
//! two would refuse is answered by `codeAction/resolve`, which recomputes and
|
||||
//! verifies the whole refactoring over the module's real fan-out and says the
|
||||
//! action is no longer available. That is the offer's existing contract —
|
||||
//! "the offer may be optimistic; the resolve is exact"
|
||||
//! (`docs/features/lazy-code-action/README.md`) — and this query widens it by
|
||||
//! exactly those two checks over one or two files, nothing else.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{ItemKind, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::ansi::{convert_edits, convert_header};
|
||||
use super::expand::{unconnected_in, wildcard_at, Wildcard};
|
||||
use super::find::{declared_ports, find_module, module_at, visible_in};
|
||||
use super::list::{append_to_list, conn_list_open, elem_spans};
|
||||
use super::propagate::{connections_of, instance_at, missing_ports};
|
||||
use super::remove::{body_uses_in, disconnections_in, header_removal, port_at};
|
||||
use super::{port_action_modules_in, sites_phrase, Plan};
|
||||
|
||||
/// Which of the four port refactorings an offer names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PortOfferKind {
|
||||
/// Remove the port under the cursor.
|
||||
Remove,
|
||||
/// Connect the ports this instantiation is missing.
|
||||
Propagate,
|
||||
/// Write out the `.*` under the cursor.
|
||||
Expand,
|
||||
/// Rewrite this Verilog-2001 header ANSI-style.
|
||||
Convert,
|
||||
}
|
||||
|
||||
/// One refactoring a cursor would be offered: the lightbulb's own words, and
|
||||
/// which refactoring will compute the edit when the user picks it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortOffer {
|
||||
/// What the lightbulb says — byte for byte what [`super::port_actions`]
|
||||
/// would have written for the same refactoring at the same cursor.
|
||||
pub title: String,
|
||||
/// The refactoring behind the title.
|
||||
pub kind: PortOfferKind,
|
||||
}
|
||||
|
||||
/// Every port refactoring available at a position, **as a menu**: the titles,
|
||||
/// with no edit computed and nothing verified.
|
||||
///
|
||||
/// The in-scope files are the same ones [`super::port_actions`] takes, and the
|
||||
/// answer is the same list of titles at every position except where one of the
|
||||
/// two post-plan checks named in this module's own documentation would have
|
||||
/// refused.
|
||||
pub fn port_offers(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec<PortOffer> {
|
||||
let Some((_, text)) = files.iter().find(|(path, _)| path == file) else { return Vec::new() };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = analyze(&tree, text);
|
||||
port_offers_in(files, file, &tree, &diagnostics, &semantics, offset)
|
||||
}
|
||||
|
||||
/// [`port_offers`] over a parse and an analysis the caller already has.
|
||||
///
|
||||
/// `tree`, `diagnostics` and `semantics` must be of exactly the text `files`
|
||||
/// holds for `file` — an open buffer's `Document` holds that trio for its own
|
||||
/// bytes, which is the whole point (take 5 §P1c). Every other file is parsed
|
||||
/// here, at most once, and only if a refactoring asks for it.
|
||||
pub fn port_offers_in(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
tree: &SourceFile,
|
||||
diagnostics: &[ParseDiagnostic],
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
) -> Vec<PortOffer> {
|
||||
let Some((_, text)) = files.iter().find(|(path, _)| path == file) else { return Vec::new() };
|
||||
if port_action_modules_in(tree, offset).is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(mut sources) = Files::new(files, file) else { return Vec::new() };
|
||||
let here = Buffer { file, text, tree, diagnostics, semantics };
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.extend(removal(&here, &mut sources, offset));
|
||||
out.extend(propagation(&here, &mut sources, offset));
|
||||
out.extend(expansion(&here, &mut sources, offset));
|
||||
out.extend(conversion(&here, &mut sources, offset));
|
||||
out
|
||||
}
|
||||
|
||||
/// The buffer the cursor is in, with the parse and analysis of exactly its
|
||||
/// bytes.
|
||||
struct Buffer<'a> {
|
||||
file: &'a Path,
|
||||
text: &'a str,
|
||||
tree: &'a SourceFile,
|
||||
diagnostics: &'a [ParseDiagnostic],
|
||||
semantics: &'a Semantics,
|
||||
}
|
||||
|
||||
/// Where the one declaration of a module is.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Declared {
|
||||
/// In the buffer the cursor is in.
|
||||
Here,
|
||||
/// In another in-scope file.
|
||||
In(usize),
|
||||
}
|
||||
|
||||
/// One file's tolerant parse, kept so a second refactoring asking the same
|
||||
/// question does not pay for it again.
|
||||
struct Parsed {
|
||||
tree: SourceFile,
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
/// The in-scope files, normalized exactly the way [`crate::scope::Scope`]
|
||||
/// normalizes them, parsed one at a time and only on demand.
|
||||
struct Files<'a> {
|
||||
sources: Vec<(&'a Path, &'a str)>,
|
||||
/// Index of the buffer the cursor is in.
|
||||
here: usize,
|
||||
parsed: Vec<Option<Parsed>>,
|
||||
}
|
||||
|
||||
impl<'a> Files<'a> {
|
||||
fn new(files: &'a [(PathBuf, String)], file: &Path) -> Option<Files<'a>> {
|
||||
let mut sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
// `Scope::build`'s own normalization, so "which file declares this"
|
||||
// is asked of the same set the eager path asks it of.
|
||||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
let here = sources.iter().position(|(path, _)| *path == file)?;
|
||||
let parsed = sources.iter().map(|_| None).collect();
|
||||
Some(Files { sources, here, parsed })
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.sources.len()
|
||||
}
|
||||
|
||||
/// One file's parse, computed on first use. Never called for the buffer:
|
||||
/// its parse is the caller's.
|
||||
fn parsed(&mut self, i: usize) -> Option<&Parsed> {
|
||||
let (_, text) = *self.sources.get(i)?;
|
||||
let slot = self.parsed.get_mut(i)?;
|
||||
if slot.is_none() {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
*slot = Some(Parsed { tree, diagnostics });
|
||||
}
|
||||
slot.as_ref()
|
||||
}
|
||||
|
||||
/// Which in-scope file declares `name`, or nothing when the files declare
|
||||
/// it twice or not at all.
|
||||
///
|
||||
/// This is `find::locate_module`'s question — `WorkspaceIndex::units(name)`
|
||||
/// filtered by `SymbolKind::is_instantiable`, of which there must be
|
||||
/// exactly one — asked of the parses instead of an index. A unit is a
|
||||
/// **file-scope** declaration, and every file-scope `module`, `interface`
|
||||
/// or `program` item is bound as `SymbolKind::Module` or
|
||||
/// `SymbolKind::Interface` (`vlog_semantic::bind::item::bind_module`), so
|
||||
/// the two counts are the same count. A module nested inside another
|
||||
/// module or a package is not a unit, and is not one here either.
|
||||
fn declaring(&mut self, tree: &SourceFile, name: &str) -> Option<Declared> {
|
||||
let mut found = None;
|
||||
let mut units = 0usize;
|
||||
for i in 0..self.sources.len() {
|
||||
let (_, text) = *self.sources.get(i)?;
|
||||
let here = i == self.here;
|
||||
// A file whose bytes never spell the name declares nothing by it,
|
||||
// so it need not be parsed to be ruled out.
|
||||
if !here && !text.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let n = match here {
|
||||
true => units_named(tree, name),
|
||||
false => self.parsed(i).map_or(0, |parsed| units_named(&parsed.tree, name)),
|
||||
};
|
||||
if n > 0 {
|
||||
units += n;
|
||||
found = Some(match here {
|
||||
true => Declared::Here,
|
||||
false => Declared::In(i),
|
||||
});
|
||||
}
|
||||
}
|
||||
(units == 1).then_some(found)?
|
||||
}
|
||||
|
||||
/// The parse of the file declaring a module, and how it is named in a
|
||||
/// refusal.
|
||||
fn declaration<'s, 'b: 's>(
|
||||
&'s mut self,
|
||||
buffer: &'b Buffer<'b>,
|
||||
at: Declared,
|
||||
) -> Option<(&'s Path, &'s SourceFile, &'s [ParseDiagnostic])> {
|
||||
match at {
|
||||
Declared::Here => Some((buffer.file, buffer.tree, buffer.diagnostics)),
|
||||
Declared::In(i) => {
|
||||
let (path, _) = *self.sources.get(i)?;
|
||||
let parsed = self.parsed(i)?;
|
||||
Some((path, &parsed.tree, &parsed.diagnostics))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's share of a removal: the refusal it may earn, and how many
|
||||
/// instantiations it would rewrite.
|
||||
fn disconnections(
|
||||
&mut self,
|
||||
buffer: &Buffer<'_>,
|
||||
i: usize,
|
||||
module: &str,
|
||||
port: &str,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(Vec<TextEdit>, usize), String> {
|
||||
let Some((path, text)) = self.sources.get(i).copied() else { return Ok((Vec::new(), 0)) };
|
||||
if !text.contains(module) {
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
if i == self.here {
|
||||
return disconnections_in(text, path, buffer.tree, module, port, warnings);
|
||||
}
|
||||
match self.parsed(i) {
|
||||
Some(parsed) => disconnections_in(text, path, &parsed.tree, module, port, warnings),
|
||||
None => Ok((Vec::new(), 0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many file-scope module or interface declarations of `name` a parse
|
||||
/// holds — see [`Files::declaring`] for why that is the index's own count.
|
||||
fn units_named(tree: &SourceFile, name: &str) -> usize {
|
||||
tree.items
|
||||
.iter()
|
||||
.filter(|item| match &item.kind {
|
||||
ItemKind::Module(module) => module.name == name && !module.name_span.is_empty(),
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// A settled plan's edits, or nothing where `finish` would have refused before
|
||||
/// verifying: two edits that overlap, or no edit at all.
|
||||
fn settled(plan: &mut Plan) -> Option<usize> {
|
||||
plan.settle().ok()?;
|
||||
let edits: usize = plan.edits.iter().map(|(_, file)| file.len()).sum();
|
||||
(edits > 0).then_some(edits)
|
||||
}
|
||||
|
||||
/// "remove port `p`" — `plan_remove`'s decisions over the buffer's own parse
|
||||
/// and analysis.
|
||||
///
|
||||
/// The count is this query's own census of the instantiations it can see,
|
||||
/// which is what the eager title counts too; a server that has read no fan-out
|
||||
/// replaces the phrase with its index's count (`ports::counted`).
|
||||
fn removal(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let (module_name, port) = port_at(buffer.tree, offset).ok()?;
|
||||
if files.declaring(buffer.tree, &module_name)? != Declared::Here {
|
||||
return None;
|
||||
}
|
||||
let (module, _) = find_module(buffer.tree, &module_name)?;
|
||||
let ports = declared_ports(module);
|
||||
let index = ports.iter().position(|declared| declared.name == port)?;
|
||||
let header = header_removal(buffer.text, module, &ports, index, &port).ok()?;
|
||||
if !body_uses_in(buffer.text, buffer.semantics, module, &port, &header).is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, header);
|
||||
let mut warnings = Vec::new();
|
||||
for i in 0..files.len() {
|
||||
let (edits, sites) =
|
||||
files.disconnections(buffer, i, &module_name, &port, &mut warnings).ok()?;
|
||||
plan.sites += sites;
|
||||
plan.add(i, edits);
|
||||
}
|
||||
settled(&mut plan)?;
|
||||
Some(PortOffer {
|
||||
title: format!("lucisv: remove port `{port}` ({})", sites_phrase(plan.sites)),
|
||||
kind: PortOfferKind::Remove,
|
||||
})
|
||||
}
|
||||
|
||||
/// "connect N missing ports" — `plan_propagate`'s decisions, and its own
|
||||
/// append loop, which is what decides N: a connection written after a `//`
|
||||
/// comment takes two edits rather than one, and the title counts edits.
|
||||
fn propagation(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let (instantiation, instance) = instance_at(buffer.tree, offset).ok()?;
|
||||
let module_name = instantiation.module.clone();
|
||||
let at = files.declaring(buffer.tree, &module_name)?;
|
||||
let conns = connections_of(instantiation, instance).ok()?;
|
||||
let missing = {
|
||||
let (_, tree, _) = files.declaration(buffer, at)?;
|
||||
let (declaration, _) = find_module(tree, &module_name)?;
|
||||
missing_ports(declaration, conns)
|
||||
};
|
||||
if missing.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
let open = conn_list_open(buffer.text, instance, spans.first().copied())?;
|
||||
let cursor = instance.name_span.start;
|
||||
let mut edits = Vec::new();
|
||||
for name in &missing {
|
||||
let expr = match visible_in(buffer.semantics, cursor, name) {
|
||||
true => name.clone(),
|
||||
false => "/* TODO: connect */".to_string(),
|
||||
};
|
||||
let mut written =
|
||||
append_to_list(buffer.text, Some(open), &spans, &format!(".{name}({expr})"));
|
||||
// Each connection is appended after the previous one, so the next
|
||||
// append sees it as the list's last element.
|
||||
let start = written.last().map_or(open, |edit| edit.range.start);
|
||||
spans.push(TextRange::new(start, start));
|
||||
edits.append(&mut written);
|
||||
}
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, edits);
|
||||
let count = settled(&mut plan)?;
|
||||
Some(PortOffer {
|
||||
title: format!("lucisv: connect {count} missing port{}", if count == 1 { "" } else { "s" }),
|
||||
kind: PortOfferKind::Propagate,
|
||||
})
|
||||
}
|
||||
|
||||
/// "expand .* (N connections)" — `plan_expand`'s decisions. N is the number of
|
||||
/// ports the wildcard stands for, which the declaration alone decides; whether
|
||||
/// each is bound only changes what is written, never how many.
|
||||
fn expansion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
if !buffer.diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let Wildcard { instantiation, instance, conns, wildcard } =
|
||||
wildcard_at(&buffer.tree.items, offset).ok()?;
|
||||
if !instance.conn_directives.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let module_name = instantiation.module.clone();
|
||||
let at = files.declaring(buffer.tree, &module_name)?;
|
||||
let missing = {
|
||||
let (path, tree, diagnostics) = files.declaration(buffer, at)?;
|
||||
unconnected_in(path, tree, diagnostics, &module_name, conns).ok()?
|
||||
};
|
||||
if missing.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
conn_list_open(buffer.text, instance, spans.first().copied())?;
|
||||
spans.get(wildcard)?;
|
||||
let count = missing.len();
|
||||
Some(PortOffer {
|
||||
title: format!(
|
||||
"lucisv: expand .* ({count} connection{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
kind: PortOfferKind::Expand,
|
||||
})
|
||||
}
|
||||
|
||||
/// "convert ports to ANSI (N ports)" — `plan_convert`'s decisions, in its own
|
||||
/// order: the header refusals first, then where the module is declared, then
|
||||
/// the merge.
|
||||
fn conversion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<PortOffer> {
|
||||
let mut found = None;
|
||||
module_at(&buffer.tree.items, offset, &mut found);
|
||||
let name = found?;
|
||||
let (module, _) = find_module(buffer.tree, &name)?;
|
||||
let ports = convert_header(buffer.file, buffer.diagnostics, module).ok()?;
|
||||
if files.declaring(buffer.tree, &name)? != Declared::Here {
|
||||
return None;
|
||||
}
|
||||
let edits = convert_edits(buffer.text, buffer.file, module, &ports).ok()?;
|
||||
let mut plan = Plan::default();
|
||||
plan.add(files.here, edits);
|
||||
settled(&mut plan)?;
|
||||
let count = ports.len();
|
||||
Some(PortOffer {
|
||||
title: format!(
|
||||
"lucisv: convert ports to ANSI ({count} port{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
kind: PortOfferKind::Convert,
|
||||
})
|
||||
}
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connections, Instance, Instantiation, ListElem};
|
||||
use vlog_parser::ast::{
|
||||
Connection, Connections, Instance, Instantiation, ListElem, Module, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex};
|
||||
|
||||
@@ -19,19 +21,17 @@ use super::find::{
|
||||
use super::list::{append_to_list, conn_list_open, elem_spans};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
pub(super) fn plan_propagate(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
/// The instance under the cursor, or the only one of the instantiation the
|
||||
/// cursor's module name belongs to.
|
||||
///
|
||||
/// Read off one file's parse, so the code-action offer asks it of the buffer's
|
||||
/// own tree (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn instance_at(
|
||||
tree: &SourceFile,
|
||||
offset: u32,
|
||||
) -> Result<(ModuleSite, Plan), String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
) -> Result<(&Instantiation, &Instance), String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
|
||||
// The instance under the cursor, or the only one of the instantiation the
|
||||
// cursor's module name belongs to.
|
||||
let mut found: Option<(&Instantiation, &Instance)> = None;
|
||||
for instantiation in &instantiations {
|
||||
for instance in &instantiation.instances {
|
||||
@@ -50,11 +50,15 @@ pub(super) fn plan_propagate(
|
||||
found = Some((instantiation, only));
|
||||
}
|
||||
}
|
||||
let Some((instantiation, instance)) = found else {
|
||||
return Err("there is no module instantiation at this position.".to_string());
|
||||
};
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
found.ok_or_else(|| "there is no module instantiation at this position.".to_string())
|
||||
}
|
||||
|
||||
/// The named connection list a propagation can append to, or the sentence
|
||||
/// saying why this instance has none.
|
||||
pub(super) fn connections_of<'t>(
|
||||
instantiation: &Instantiation,
|
||||
instance: &'t Instance,
|
||||
) -> Result<&'t [ListElem<Connection>], String> {
|
||||
let conns = match &instance.conns {
|
||||
Connections::Ordered(_) => {
|
||||
return Err(format!(
|
||||
@@ -62,7 +66,7 @@ pub(super) fn plan_propagate(
|
||||
instance.name, instantiation.module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => conns,
|
||||
Connections::Named(conns) => conns.as_slice(),
|
||||
};
|
||||
// An error element names no port: it neither connects one nor blocks one.
|
||||
if conns.iter().filter_map(ListElem::ok).any(|c| c.name == "*") {
|
||||
@@ -71,18 +75,37 @@ pub(super) fn plan_propagate(
|
||||
instance.name
|
||||
));
|
||||
}
|
||||
Ok(conns)
|
||||
}
|
||||
|
||||
/// The ports the instantiated module declares that this instance does not
|
||||
/// connect, in declaration order.
|
||||
pub(super) fn missing_ports(module: &Module, conns: &[ListElem<Connection>]) -> Vec<String> {
|
||||
declared_ports(module)
|
||||
.iter()
|
||||
.map(|p| p.name.clone())
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn plan_propagate(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(ModuleSite, Plan), String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (instantiation, instance) = instance_at(&tree, offset)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
let conns = connections_of(instantiation, instance)?;
|
||||
|
||||
let Some(module_text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (module_tree, _) = parse_source_tolerant(module_text);
|
||||
let Some((module, _)) = find_module(&module_tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
};
|
||||
let declared = declared_ports(module);
|
||||
let missing: Vec<String> = declared
|
||||
.iter()
|
||||
.map(|p| p.name.clone())
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect();
|
||||
let missing = missing_ports(module, conns);
|
||||
if missing.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` already connects every port `{}` declares.",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList};
|
||||
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex};
|
||||
use vlog_semantic::SymbolKind;
|
||||
@@ -31,12 +31,27 @@ pub(super) fn locate_port(
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let (module_name, name) = port_at(&tree, offset)?;
|
||||
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
|
||||
if site.file != i {
|
||||
return Err(ambiguous(&module_name));
|
||||
}
|
||||
Ok((site, name))
|
||||
}
|
||||
|
||||
/// The module and port name the cursor sits on, read off one file's parse —
|
||||
/// [`locate_port`] without the workspace half.
|
||||
///
|
||||
/// The cursor may be on the header port or, for a non-ANSI module, on its body
|
||||
/// declaration. Split out so the code-action *offer* can ask the same question
|
||||
/// of the buffer's own parse (take 5 §P1c, `ports::offer`).
|
||||
pub(super) fn port_at(tree: &SourceFile, offset: u32) -> Result<(String, String), String> {
|
||||
let mut module_name = None;
|
||||
module_at(&tree.items, offset, &mut module_name);
|
||||
let Some(module_name) = module_name else {
|
||||
return Err(NOT_A_PORT.to_string());
|
||||
};
|
||||
let Some((module, _)) = find_module(&tree, &module_name) else {
|
||||
let Some((module, _)) = find_module(tree, &module_name) else {
|
||||
return Err(NOT_A_PORT.to_string());
|
||||
};
|
||||
let ports = declared_ports(module);
|
||||
@@ -59,13 +74,14 @@ pub(super) fn locate_port(
|
||||
}
|
||||
}
|
||||
let Some(name) = name else { return Err(NOT_A_PORT.to_string()) };
|
||||
let site = locate_module(scope, ModuleRef::Name(&module_name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{module_name}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
||||
));
|
||||
}
|
||||
Ok((site, name))
|
||||
Ok((module_name, name))
|
||||
}
|
||||
|
||||
/// The sentence a module the in-scope files declare twice earns.
|
||||
pub(super) fn ambiguous(module: &str) -> String {
|
||||
format!(
|
||||
"`{module}` is declared in more than one indexed file; lucisv will not guess which module's ports these are."
|
||||
)
|
||||
}
|
||||
|
||||
const NOT_A_PORT: &str = "there is no module port at this position.";
|
||||
@@ -86,13 +102,13 @@ pub(super) fn plan_remove(
|
||||
return Err(format!("`{}` has no port named `{port}`.", site.name));
|
||||
};
|
||||
|
||||
let mut header: Vec<TextEdit> = remove_element(text, &element_spans(&ports), index)?;
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
|
||||
}
|
||||
let header: Vec<TextEdit> = header_removal(text, module, &ports, index, port)?;
|
||||
// A port still used by the module's own body is a refusal, not a warning:
|
||||
// deleting it would leave the body naming something that no longer exists.
|
||||
let used = body_uses(scope, site.file, module, port, &header);
|
||||
let used = match scope.analysis(site.file) {
|
||||
Some(analysis) => body_uses_in(text, &analysis.semantics, module, port, &header),
|
||||
None => Vec::new(),
|
||||
};
|
||||
if !used.is_empty() {
|
||||
return Err(format!(
|
||||
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
|
||||
@@ -169,19 +185,38 @@ fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String>
|
||||
out
|
||||
}
|
||||
|
||||
/// The header and body deletions the removal makes in the module's own file.
|
||||
///
|
||||
/// Split out of [`plan_remove`] so the code-action offer can make exactly the
|
||||
/// same two decisions — and earn exactly the same refusals — without a
|
||||
/// workspace (take 5 §P1c).
|
||||
pub(super) fn header_removal(
|
||||
text: &str,
|
||||
module: &Module,
|
||||
ports: &[super::find::DeclaredPort],
|
||||
index: usize,
|
||||
port: &str,
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut header = remove_element(text, &element_spans(ports), index)?;
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
header.append(&mut non_ansi_declaration_removal(text, module, port)?);
|
||||
}
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
/// The lines of the module's body that still name the port, ignoring the
|
||||
/// declarations the removal is itself deleting.
|
||||
fn body_uses(
|
||||
scope: &mut Scope,
|
||||
file: usize,
|
||||
///
|
||||
/// `semantics` must be the analysis of `text` — [`Scope::analysis`]'s, or the
|
||||
/// open buffer's own, which is the same thing computed once instead of twice.
|
||||
pub(super) fn body_uses_in(
|
||||
text: &str,
|
||||
semantics: &vlog_semantic::Semantics,
|
||||
module: &Module,
|
||||
port: &str,
|
||||
removed: &[TextEdit],
|
||||
) -> Vec<String> {
|
||||
let Some(text) = scope.text(file) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let Some(analysis) = scope.analysis(file) else { return Vec::new() };
|
||||
let semantics = &analysis.semantics;
|
||||
let Some(symbol) = semantics.symbols().iter().position(|s| {
|
||||
s.name == port
|
||||
&& s.kind == SymbolKind::Port
|
||||
@@ -248,13 +283,27 @@ fn disconnection_edits(
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
disconnections_in(text, path, &tree, &site.name, port, warnings)
|
||||
}
|
||||
|
||||
/// [`disconnection_edits`] over a parse the caller already has, so the offer
|
||||
/// can earn the by-position refusal and count the sites it would rewrite
|
||||
/// without building a workspace (take 5 §P1c).
|
||||
pub(super) fn disconnections_in(
|
||||
text: &str,
|
||||
path: &Path,
|
||||
tree: &SourceFile,
|
||||
module: &str,
|
||||
port: &str,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(Vec<TextEdit>, usize), String> {
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let lines = LineIndex::new(text);
|
||||
|
||||
let mut edits = Vec::new();
|
||||
let mut sites = 0usize;
|
||||
for instantiation in instantiations.iter().filter(|i| i.module == site.name) {
|
||||
for instantiation in instantiations.iter().filter(|i| i.module == module) {
|
||||
for instance in &instantiation.instances {
|
||||
match &instance.conns {
|
||||
Connections::Ordered(conns) if conns.is_empty() => {}
|
||||
@@ -263,7 +312,7 @@ fn disconnection_edits(
|
||||
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
|
||||
instance.name,
|
||||
display(path),
|
||||
site.name
|
||||
module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => {
|
||||
|
||||
@@ -12,12 +12,17 @@
|
||||
//! workspace every refactoring in this crate reads through, and `warnings` is
|
||||
//! what a finished rename says about the occurrences it could not edit.
|
||||
|
||||
mod preflight;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod warnings;
|
||||
|
||||
pub use preflight::rename_preflight;
|
||||
|
||||
// The rename was the first refactoring, so most of the crate still spells the
|
||||
// workspace `crate::rename::Scope`. It lives at `crate::scope` now (§29.1).
|
||||
// workspace `crate::rename::Scope`. It lives at `crate::scope` now (§29.1),
|
||||
// and so does the door a caller hands its own index records through.
|
||||
pub use crate::scope::KnownFacts;
|
||||
pub(crate) use crate::scope::{display, Scope};
|
||||
pub use warnings::contains_word;
|
||||
|
||||
@@ -31,6 +36,7 @@ use vlog_semantic::{
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::trace::RenameTrace;
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
/// The identifier a rename would act on: where it is, and what it spells.
|
||||
@@ -156,16 +162,98 @@ pub fn rename(
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
check_new_name(new_name)?;
|
||||
let mut scope = Scope::build(files);
|
||||
let target = scope.locate(file, offset)?;
|
||||
if target.name == new_name {
|
||||
return Err(format!("`{new_name}` is the name it already has."));
|
||||
}
|
||||
let edits = scope.collect_edits(&target, new_name)?;
|
||||
check::verify(&mut scope, &edits, &target.name, new_name)?;
|
||||
rename_traced(files, file, offset, new_name, &mut RenameTrace::default())
|
||||
}
|
||||
|
||||
let warnings = scope.warnings(&target, &edits);
|
||||
/// [`rename`], with a [`RenameTrace`] filled in as it runs.
|
||||
///
|
||||
/// The same call — `rename` is this one with a trace nobody reads — so there
|
||||
/// is no traced path that could decide anything differently from the plain
|
||||
/// one. The trace is an **out parameter** rather than part of the `Ok` value
|
||||
/// because the stage a slow *refusal* spent its time in is exactly as
|
||||
/// interesting as a successful rename's: a conflicting new name refuses inside
|
||||
/// `collect_edits`, and the extract offer that costs 800 ms refuses after the
|
||||
/// scope build alone (take 5 §P2a).
|
||||
pub fn rename_traced(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
let started = vlog_parser::stats::parses();
|
||||
let out = renaming(files, file, offset, new_name, None, trace);
|
||||
trace.parses = vlog_parser::stats::parses() - started;
|
||||
out
|
||||
}
|
||||
|
||||
/// [`rename_traced`], letting the caller answer for the index records of the
|
||||
/// files it is handing over — see [`KnownFacts`].
|
||||
///
|
||||
/// The same rename over the same files, deciding everything the same way: a
|
||||
/// record the caller answers with is one this call would otherwise have
|
||||
/// produced by parsing that file, so the only difference is that it did not
|
||||
/// parse it (review round §R3b). A caller that answers `None` to everything
|
||||
/// gets [`rename_traced`] exactly.
|
||||
pub fn rename_traced_with(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
known: &dyn KnownFacts,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
let started = vlog_parser::stats::parses();
|
||||
let out = renaming(files, file, offset, new_name, Some(known), trace);
|
||||
trace.parses = vlog_parser::stats::parses() - started;
|
||||
out
|
||||
}
|
||||
|
||||
/// The rename itself, so that [`rename_traced`] can count the parses of the
|
||||
/// whole of it — refusals included — in one place.
|
||||
fn renaming(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
known: Option<&dyn KnownFacts>,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
check_new_name(new_name)?;
|
||||
trace.selected = files.len();
|
||||
trace.bytes = files.iter().map(|(_, text)| text.len()).sum();
|
||||
// One parse per file, and the analyses this rename is going to want kept
|
||||
// from it (take 5 §P2b). The words worth keeping are the new name and the
|
||||
// name under the cursor — which the request file's own analysis, the first
|
||||
// one the build makes, is what says. A wrong guess costs a re-parse and
|
||||
// can change nothing: retention is a cache.
|
||||
let RenameTrace { index, indexing, .. } = &mut *trace;
|
||||
let mut scope = index.measure(|| {
|
||||
Scope::build_keeping(
|
||||
files,
|
||||
file,
|
||||
|here| {
|
||||
let cursor = here.and_then(|semantics| rename_name_at(semantics, offset));
|
||||
cursor.into_iter().chain(Some(new_name.to_string())).collect()
|
||||
},
|
||||
known,
|
||||
indexing,
|
||||
)
|
||||
});
|
||||
trace.selected = scope.len();
|
||||
let target = trace.locate.measure(|| scope.locate(file, offset))?;
|
||||
if target.name == new_name {
|
||||
return Err(already_named(new_name));
|
||||
}
|
||||
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
|
||||
trace.edited = edits.len();
|
||||
// Two disjoint fields of one trace: `verify` times the whole pass while
|
||||
// `checks` is filled by its stages, so they are borrowed apart.
|
||||
let RenameTrace { verify, checks, .. } = &mut *trace;
|
||||
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
|
||||
|
||||
let RenameTrace { warnings: stage, warning_scans, .. } = &mut *trace;
|
||||
let warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
|
||||
.into_iter()
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
@@ -456,10 +544,14 @@ impl<'a> Scope<'a> {
|
||||
|
||||
const NOTHING_HERE: &str = "there is no symbol to rename at this position.";
|
||||
|
||||
// The refusal sentences, each written once. Two callers reach four of them
|
||||
// now: the whole-workspace `Scope::locate` and the buffer-and-index
|
||||
// `prepare_rename_here`, which must refuse in exactly the same words or the
|
||||
// user gets two different explanations for one situation.
|
||||
// The refusal sentences, each written once. Three callers reach them now: the
|
||||
// whole-workspace `Scope::locate`, the buffer-and-index `prepare_rename_here`,
|
||||
// and the buffer-only `rename_preflight` — which must refuse in exactly the
|
||||
// same words or the user gets two different explanations for one situation.
|
||||
|
||||
fn already_named(new_name: &str) -> String {
|
||||
format!("`{new_name}` is the name it already has.")
|
||||
}
|
||||
|
||||
fn ambiguous(name: &str) -> String {
|
||||
format!(
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! The refusals a rename can reach from the request buffer alone.
|
||||
//!
|
||||
//! `renaming` builds a whole [`Scope`](crate::scope::Scope) — one parse and
|
||||
//! one analysis per in-scope file — before `locate` looks at the cursor. On
|
||||
//! OpenTitan a cursor sitting on a comment cost **3 975 parses and 1.9 s**
|
||||
//! before a 0.1 ms refusal that read nothing but the request file (take 5
|
||||
//! review, §3 item 6). This is that refusal, taken first.
|
||||
//!
|
||||
//! **What it is allowed to take.** Only a refusal `renaming` is *certain* to
|
||||
//! reach in the same words, from facts that are a pure function of the request
|
||||
//! buffer's own text: the new-name check, and the cursor refusals the buffer's
|
||||
//! own `Semantics` settles. `Semantics` is `analyze(&parse(text), text)` and
|
||||
//! consults nothing else, so the buffer's analysis and the scope's analysis of
|
||||
//! that same file are the same value.
|
||||
//!
|
||||
//! **What it must not take.** Every refusal whose answer comes from the
|
||||
//! *workspace index*: whether a name is declared in more than one file, and
|
||||
//! which file a cross-file use means. The index is rebuilt on save and on a
|
||||
//! watcher event, never on a keystroke (`state/mod.rs::set_document` reads it
|
||||
//! and does not touch it), so an unsaved edit that adds or removes a
|
||||
//! file-scope declaration is not in it. `prepare_rename_here` may read it
|
||||
//! anyway — an optimistic `prepareRename` is LSP-legal and the rename that
|
||||
//! follows corrects it — but `rename` **is** that correction, and a refusal
|
||||
//! invented here from a stale count is a rename the user cannot get. Those
|
||||
//! stay on the slow road, which re-derives the count from the current texts.
|
||||
//!
|
||||
//! `Ok(())` therefore means "proceed exactly as before", never "this rename
|
||||
//! will succeed".
|
||||
|
||||
use vlog_semantic::{Resolution, Semantics, SymbolId};
|
||||
|
||||
use super::{already_named, check_new_name, from_base, unresolved, unspelled, NOTHING_HERE};
|
||||
|
||||
/// The refusal `rename` would make for this cursor and this new name, when the
|
||||
/// request buffer alone is enough to know it — and `Ok(())` when it is not.
|
||||
///
|
||||
/// A caller must only ask this about a file it is going to hand `rename` as
|
||||
/// one of its in-scope files: `locate` refuses a file it was not given
|
||||
/// *before* it looks at the cursor, and that refusal has to keep its place in
|
||||
/// the order. Both of the server's source selectors always include the
|
||||
/// requesting buffer, so both satisfy it.
|
||||
pub fn rename_preflight(semantics: &Semantics, offset: u32, new_name: &str) -> Result<(), String> {
|
||||
// First in `renaming`, and so first here: an invalid new name outranks
|
||||
// everything the cursor could say.
|
||||
check_new_name(new_name)?;
|
||||
let found = semantics.reference_id_at(offset).and_then(|id| semantics.reference(id));
|
||||
let Some(reference) = found else {
|
||||
// The cursor is on a declaration written here, or on nothing at all.
|
||||
let Some(symbol) = semantics.symbol_at(offset) else {
|
||||
return Err(NOTHING_HERE.to_string());
|
||||
};
|
||||
return declared_here(semantics, symbol, new_name);
|
||||
};
|
||||
match &reference.resolution {
|
||||
Resolution::Resolved(symbol) => declared_here(semantics, *symbol, new_name),
|
||||
Resolution::NotFound => Err(unresolved(&reference.name)),
|
||||
Resolution::InheritedCandidate { base, .. } => Err(from_base(&reference.name, base)),
|
||||
// Which file declares this name — and whether several do — is the
|
||||
// index's word, and the index is not the authority a rename is.
|
||||
Resolution::ExternalCandidate { .. } => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Scope::declaration` for a declaration written in the request buffer, as
|
||||
/// far as the buffer can carry it.
|
||||
fn declared_here(semantics: &Semantics, symbol: SymbolId, new_name: &str) -> Result<(), String> {
|
||||
// `locate` answers a symbol id it cannot look up with `NOTHING_HERE`. It
|
||||
// came from this same analysis, so it can be looked up; deferring rather
|
||||
// than asserting keeps the impossible case on the road that handles it.
|
||||
let Some(declaration) = semantics.symbol(symbol) else { return Ok(()) };
|
||||
if declaration.name_span.is_empty() {
|
||||
return Err(unspelled(&declaration.name));
|
||||
}
|
||||
// A file-scope unit is refused when the index holds its name more than
|
||||
// once, and that count belongs to the slow road — so nothing after it may
|
||||
// be decided here either, or a refusal would jump the ambiguity check.
|
||||
if declaration.scope == semantics.file_scope() {
|
||||
return Ok(());
|
||||
}
|
||||
if declaration.name == new_name {
|
||||
return Err(already_named(new_name));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
//! against `prepare_rename` at every byte of a buffer.
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{analyze, resolve_external};
|
||||
use vlog_semantic::{analyze, resolve_external, FileFacts};
|
||||
|
||||
use crate::RefactorEdit;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -195,3 +197,306 @@ fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the trace (take 5 §P2a)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_traced_rename_and_the_plain_one_are_the_same_call() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
let traced = rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let plain = rename(&sources, &path, at, "child").expect("renames");
|
||||
assert_eq!(traced.edits, plain.edits, "same edits");
|
||||
assert_eq!(traced.warnings, plain.warnings, "same warnings");
|
||||
assert_eq!(traced.created, plain.created, "same created files");
|
||||
// And a refusal is traced too, which is why the trace is an out parameter.
|
||||
let mut refused = RenameTrace::default();
|
||||
let outcome = rename_traced(&sources, &path, at, "module", &mut refused);
|
||||
assert!(outcome.is_err(), "a keyword must refuse");
|
||||
assert_eq!(refused.selected, 0, "the refusal is taken before the scope is built");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trace_accounts_for_every_parse_the_rename_ran() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let staged = trace.index.parses
|
||||
+ trace.locate.parses
|
||||
+ trace.edits.parses
|
||||
+ trace.verify.parses
|
||||
+ trace.warnings.parses;
|
||||
assert_eq!(staged, trace.parses, "every parse belongs to a stage: {trace:?}");
|
||||
assert_eq!(
|
||||
trace.verify.parses,
|
||||
trace.checks.tokens.parses
|
||||
+ trace.checks.before.parses
|
||||
+ trace.checks.rebuild.parses
|
||||
+ trace.checks.after.parses
|
||||
+ trace.checks.checks.parses,
|
||||
"and every verification parse to a sub-stage: {trace:?}"
|
||||
);
|
||||
assert_eq!(trace.selected, 3, "three files in, whatever the rename does with them");
|
||||
assert_eq!(trace.bytes, sources.iter().map(|(_, t)| t.len()).sum::<usize>());
|
||||
assert!(trace.edited >= 1 && trace.edited <= trace.selected);
|
||||
assert!(trace.checks.watched >= trace.edited, "a watched set covers the edited one");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the reuse (take 5 §P2b/§P2c) — the parse budget, and three attacks on it
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A workspace of eight files. `sig` is declared in `sub.sv`, named through
|
||||
/// the hierarchy from `top.sv`, and merely mentioned in three others, so a
|
||||
/// rename of it edits two files and watches five.
|
||||
const EIGHT: [(&str, &str); 8] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic w;\n sub u_sub (.clk(1'b0), .q(w));\n assign w = u_sub.sig;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
("/w/note.sv", "module note;\n // sig is mentioned here in a comment\n logic other;\nendmodule\n"),
|
||||
("/w/far.sv", "module far;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("/w/quiet_a.sv", "module quiet_a;\n logic a;\nendmodule\n"),
|
||||
("/w/quiet_b.sv", "module quiet_b;\n logic b;\nendmodule\n"),
|
||||
];
|
||||
|
||||
/// **K + E.** One whole-file parse per input file, plus one per edited file —
|
||||
/// and not one more, whatever the watched set costs.
|
||||
///
|
||||
/// The counts come out of the trace, so the assertion is on the work the
|
||||
/// engine really did rather than on a stopwatch. Before §P2b/§P2c this same
|
||||
/// rename parsed `K` for the index, again for every file spelling the name,
|
||||
/// `K` again for the after-index and once more for every watched file.
|
||||
#[test]
|
||||
fn a_rename_parses_each_input_file_once_and_each_edited_file_once_more() {
|
||||
let sources = workspace(&EIGHT);
|
||||
let path = PathBuf::from("/w/sub.sv");
|
||||
let text = EIGHT[0].1;
|
||||
let at = text.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let mut trace = RenameTrace::default();
|
||||
rename_traced(&sources, &path, at, "renamed_sig", &mut trace).expect("renames");
|
||||
|
||||
let (k, e) = (trace.selected as u64, trace.edited as u64);
|
||||
assert_eq!(k, 8, "eight files in");
|
||||
assert_eq!(e, 2, "sub.sv and top.sv are edited");
|
||||
assert!(trace.checks.watched >= 4, "and several more are watched: {trace:?}");
|
||||
assert_eq!(trace.parses, k + e, "K + E and nothing else: {trace:?}");
|
||||
assert_eq!(trace.index.parses, k, "every input file, once, for the index");
|
||||
assert_eq!(trace.locate.parses, 0, "the cursor's file was kept");
|
||||
assert_eq!(trace.edits.parses, 0, "so was every file the occurrence walk reads");
|
||||
assert_eq!(trace.checks.before.parses, 0, "and every watched file");
|
||||
assert_eq!(trace.checks.rebuild.parses, e, "the after-index absorbs, it does not rebuild");
|
||||
assert_eq!(trace.checks.after.parses, 0, "and its analyses are that absorb's own");
|
||||
}
|
||||
|
||||
/// **Attack 1 — a stale retained analysis.** The reuse hands the *edited*
|
||||
/// file's after-print the analysis of its **edited** text. An implementation
|
||||
/// that handed it the retained before-analysis instead would be describing
|
||||
/// text that no longer exists, and this rename — whose edit changes what a
|
||||
/// name in the edited file resolves to — is exactly the one it would wave
|
||||
/// through.
|
||||
#[test]
|
||||
fn a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused() {
|
||||
// `taken` is already declared in `m`. Renaming `sig` to `taken` would
|
||||
// give `assign q = taken;` a different declaration — in the very file the
|
||||
// edit touches, so only a print of the *edited* text can see it.
|
||||
const CAPTURE: &str = "module m (output logic q);\n wire sig;\n wire taken;\n assign q = sig;\n assign taken = 1'b1;\nendmodule\n";
|
||||
let sources = workspace(&[("/w/m.sv", CAPTURE)]);
|
||||
let path = PathBuf::from("/w/m.sv");
|
||||
let at = CAPTURE.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let outcome = rename(&sources, &path, at, "taken");
|
||||
assert!(outcome.is_err(), "a capture inside the edited file must refuse: {outcome:?}");
|
||||
}
|
||||
|
||||
/// **Attack 2 — an after-index that forgot an unedited file.** The after-index
|
||||
/// is the before-index with the edited records absorbed; absorbing with the
|
||||
/// wrong `gone`, or building it from the edited files alone, would drop the
|
||||
/// third file's declaration and the ambiguity it creates with it. The rename
|
||||
/// below edits `a.sv` and `top.sv` and is refused **because of `b.sv`**, which
|
||||
/// it never touches.
|
||||
#[test]
|
||||
fn a_rename_that_would_make_a_third_files_use_ambiguous_is_refused() {
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package taken_pkg;\n localparam int V = 2;\nendpackage\n";
|
||||
const USE: &str = "import taken_pkg::*;\nmodule u;\n localparam int W = V;\nendmodule\n";
|
||||
let files = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/use.sv", USE)];
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("/w/a.sv");
|
||||
let at = A.find("a_pkg").expect("the package name") as u32;
|
||||
let outcome = rename(&sources, &path, at, "taken_pkg");
|
||||
assert!(outcome.is_err(), "a second `taken_pkg` makes use.sv's import ambiguous: {outcome:?}");
|
||||
// And the untouched declaration is still there to be found afterwards:
|
||||
// the refusal is about `use.sv`, not about `a.sv` alone.
|
||||
assert!(rename(&sources, &path, at, "b_pkg").is_ok(), "an unclaimed name still renames");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the known-facts door (review round §R3b) — the parse budget with reuse,
|
||||
// and the two things the engine itself can check
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// An honest caller: for the files it was told to know, it answers with the
|
||||
/// record `FileFacts::of` produces — and only when the text it is handed is
|
||||
/// byte-for-byte the text that record was read off.
|
||||
///
|
||||
/// This is what a correct [`KnownFacts`] implementation *is*, with string
|
||||
/// equality standing in for the server's content hash (a stronger key, not a
|
||||
/// weaker one). The records are read before the rename runs, so asking costs
|
||||
/// no parse and the rename's parse budget is the rename's own.
|
||||
struct Honest {
|
||||
known: Vec<(PathBuf, String, FileFacts)>,
|
||||
}
|
||||
|
||||
impl Honest {
|
||||
/// The records of those of [`EIGHT`]'s files, read off their own text.
|
||||
fn about(paths: &[&str]) -> Honest {
|
||||
let known = EIGHT
|
||||
.iter()
|
||||
.filter(|(name, _)| paths.contains(name))
|
||||
.map(|(name, text)| {
|
||||
let path = PathBuf::from(*name);
|
||||
(path.clone(), (*text).to_string(), FileFacts::of(path, text))
|
||||
})
|
||||
.collect();
|
||||
Honest { known }
|
||||
}
|
||||
}
|
||||
|
||||
impl KnownFacts for Honest {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.known
|
||||
.iter()
|
||||
.find(|(held, bytes, _)| held == path && bytes == text)
|
||||
.map(|(_, _, facts)| facts.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// The rename of `EIGHT`'s `sig`, with and without a caller that knows some
|
||||
/// records — the whole result, as a comparable value.
|
||||
fn eight_renamed(known: Option<&dyn KnownFacts>) -> (String, RenameTrace) {
|
||||
let sources = workspace(&EIGHT);
|
||||
let path = PathBuf::from("/w/sub.sv");
|
||||
let text = EIGHT[0].1;
|
||||
let at = text.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let mut trace = RenameTrace::default();
|
||||
let edit = match known {
|
||||
Some(known) => rename_traced_with(&sources, &path, at, "renamed_sig", known, &mut trace),
|
||||
None => rename_traced(&sources, &path, at, "renamed_sig", &mut trace),
|
||||
};
|
||||
(print_edit(&edit.expect("the rename succeeds")), trace)
|
||||
}
|
||||
|
||||
/// Every edit and every warning a refactoring makes, as one comparable string.
|
||||
fn print_edit(edit: &RefactorEdit) -> String {
|
||||
let mut out = String::new();
|
||||
for (path, edits) in &edit.edits {
|
||||
for one in edits {
|
||||
out.push_str(&format!(
|
||||
"{} {}..{} -> {}\n",
|
||||
path.display(),
|
||||
one.range.start,
|
||||
one.range.end,
|
||||
one.new_text
|
||||
));
|
||||
}
|
||||
}
|
||||
for warning in &edit.warnings {
|
||||
out.push_str(&format!("warn {warning}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// **The R3b proof.** A rename whose caller knows the records of the files
|
||||
/// nothing analyses makes exactly the edits and says exactly the warnings the
|
||||
/// same rename makes without it — and parses fewer files by exactly the number
|
||||
/// of records it reused.
|
||||
///
|
||||
/// `K + E` becomes `(K − reused) + E`: the reuse takes parses out of the index
|
||||
/// stage and out of nowhere else, which is what the per-stage counts assert.
|
||||
#[test]
|
||||
fn a_reused_record_removes_that_files_parse_and_changes_no_edit() {
|
||||
let (plain, plain_trace) = eight_renamed(None);
|
||||
// The three files that spell neither `sig` nor `renamed_sig`: the
|
||||
// containers a scope indexes and no later stage reads.
|
||||
let known = Honest::about(&["/w/pkg.sv", "/w/quiet_a.sv", "/w/quiet_b.sv"]);
|
||||
let (reused, trace) = eight_renamed(Some(&known));
|
||||
|
||||
assert_eq!(plain, reused, "the reuse changed an edit or a warning");
|
||||
assert_eq!(trace.indexing.reused_files, 3, "three records came from the caller: {trace:?}");
|
||||
assert_eq!(
|
||||
trace.indexing.other_files, 4,
|
||||
"and the unread class is four, so this index is part reused and part parsed"
|
||||
);
|
||||
assert_eq!(trace.indexing.reused.parses, 0, "the caller's answers cost no parse");
|
||||
assert_eq!(
|
||||
trace.parses,
|
||||
plain_trace.parses - 3,
|
||||
"three parses fewer, and no other stage moved: {trace:?}"
|
||||
);
|
||||
let (k, e) = (trace.selected as u64, trace.edited as u64);
|
||||
assert_eq!(trace.parses, (k - 3) + e, "(K - reused) + E");
|
||||
assert_eq!(trace.index.parses, k - 3, "every input file but the reused ones");
|
||||
assert_eq!(trace.locate.parses, 0, "the cursor's file was kept");
|
||||
assert_eq!(trace.edits.parses, 0, "so was every file the occurrence walk reads");
|
||||
assert_eq!(trace.checks.before.parses, 0, "and every watched file");
|
||||
assert_eq!(trace.checks.after.parses, 0);
|
||||
}
|
||||
|
||||
/// A caller that knows **every** file's record still parses the ones whose
|
||||
/// analysis a later stage reads — the record is the index's half and the
|
||||
/// `Semantics` is the other, and only the second needs the parse.
|
||||
///
|
||||
/// The reuse is therefore never a reason to skip an analysis something asks
|
||||
/// for: it removes the parse of a file nothing asks about, and nothing else.
|
||||
#[test]
|
||||
fn a_file_whose_analysis_is_read_is_still_parsed_when_its_record_is_known() {
|
||||
let all: Vec<&str> = EIGHT.iter().map(|(name, _)| *name).collect();
|
||||
let known = Honest::about(&all);
|
||||
let (plain, plain_trace) = eight_renamed(None);
|
||||
let (reused, trace) = eight_renamed(Some(&known));
|
||||
|
||||
assert_eq!(plain, reused, "knowing every record changed an answer");
|
||||
assert_eq!(trace.indexing.reused_files, 8, "every record came from the caller");
|
||||
assert_eq!(
|
||||
trace.parses,
|
||||
plain_trace.parses - trace.indexing.other_files as u64,
|
||||
"only the unread class stopped being parsed: {trace:?}"
|
||||
);
|
||||
assert!(trace.indexing.kept_files > 0, "premise: some files are read later");
|
||||
assert_eq!(
|
||||
trace.index.parses,
|
||||
trace.indexing.kept_files as u64 + 1,
|
||||
"the kept ones, and the lead"
|
||||
);
|
||||
}
|
||||
|
||||
/// A record filed under **another path** is refused, because merging it would
|
||||
/// put one file's declarations under another's name. This is one of the two
|
||||
/// things the engine can check for itself; the other is that it asks with the
|
||||
/// very text it is about to index, which is how it asks.
|
||||
#[test]
|
||||
fn a_record_that_names_another_file_is_not_taken() {
|
||||
/// A caller that answers every question with one file's record.
|
||||
struct Misfiled(FileFacts);
|
||||
impl KnownFacts for Misfiled {
|
||||
fn facts_for(&self, _path: &Path, _text: &str) -> Option<FileFacts> {
|
||||
Some(self.0.clone())
|
||||
}
|
||||
}
|
||||
// A record of a file this workspace does not hold, so the only thing that
|
||||
// could make it reach the index is the engine failing to look at its path.
|
||||
let elsewhere =
|
||||
FileFacts::of(PathBuf::from("/w/absent.sv"), "module absent;\n logic sig;\nendmodule\n");
|
||||
let (plain, plain_trace) = eight_renamed(None);
|
||||
let (guarded, trace) = eight_renamed(Some(&Misfiled(elsewhere)));
|
||||
|
||||
assert_eq!(plain, guarded, "a misfiled record must not reach the index");
|
||||
assert_eq!(trace.indexing.reused_files, 0, "and must not be counted as reuse");
|
||||
assert_eq!(trace.parses, plain_trace.parses, "so every file was parsed as it always was");
|
||||
}
|
||||
@@ -1,16 +1,26 @@
|
||||
//! What a rename could not account for, said out loud: the name inside a
|
||||
//! `` `define`` or a macro invocation's opaque token, inside an assertion the
|
||||
//! SVA grammar could not structure, a reference the workspace could not
|
||||
//! finish, and identifier occurrences no reference was recorded for — each
|
||||
//! found by its own scan of the file, and each a sentence naming where to
|
||||
//! look. The `` `define`` and macro-argument scans are shared with the port
|
||||
//! refactorings, which word their news differently.
|
||||
//! finish, and identifier occurrences no reference was recorded for — each its
|
||||
//! own scan, and each a sentence naming where to look. The `` `define`` and
|
||||
//! macro-argument scans are shared with the port refactorings, which word
|
||||
//! their news differently.
|
||||
//!
|
||||
//! **One lex and one line index per file** (take 5 §P2d's `warnings` finding).
|
||||
//! The five scans used to build their own, so a file spelling the name was
|
||||
//! tokenized twice and indexed four times inside one `warnings` call — none of
|
||||
//! it shared, and none of it the parse the scope had already made. [`FileScan`]
|
||||
//! is that memo. It is a cache of two pure functions of the file's text and
|
||||
//! nothing else, so a scan handed a shared one reads exactly what its own call
|
||||
//! would have built; what each scan *says* is untouched, and the sentences come
|
||||
//! out in the order they always did.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::{tokenize, LineIndex};
|
||||
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
|
||||
|
||||
@@ -18,38 +28,136 @@ use crate::TextEdit;
|
||||
|
||||
use super::Target;
|
||||
use crate::scope::{display, Scope};
|
||||
use crate::trace::WarnTrace;
|
||||
|
||||
/// One file's token stream and its line index, built at most once per
|
||||
/// [`Scope::warnings`] call and lent to every scan that asks.
|
||||
///
|
||||
/// Both fields are memos of pure functions of the file's text, so sharing one
|
||||
/// cannot change an answer: `tokens` is `tokenize(text).ok()` and `lines` is
|
||||
/// `LineIndex::new(text)`, computed on first use and then handed out.
|
||||
#[derive(Default)]
|
||||
struct FileScan {
|
||||
/// `None` until asked; `Some(None)` for a file that does not lex — which
|
||||
/// every scan reads as "nothing to say", exactly as `tokenize`'s `Err` did.
|
||||
tokens: Option<Option<Vec<Token>>>,
|
||||
lines: Option<LineIndex>,
|
||||
}
|
||||
|
||||
impl FileScan {
|
||||
/// The file's tokens, or `None` when it does not lex.
|
||||
fn tokens(&mut self, text: &str) -> Option<&[Token]> {
|
||||
self.tokens.get_or_insert_with(|| tokenize(text).ok()).as_deref()
|
||||
}
|
||||
|
||||
/// The file's line index.
|
||||
fn lines(&mut self, text: &str) -> &LineIndex {
|
||||
self.lines.get_or_insert_with(|| LineIndex::new(text))
|
||||
}
|
||||
|
||||
/// Whether any scan got far enough past its prefilter to ask for the
|
||||
/// tokens — what the warning pass's per-file cost really is.
|
||||
fn lexed(&self) -> bool {
|
||||
self.tokens.is_some()
|
||||
}
|
||||
|
||||
/// Both at once, for a scan that walks the tokens and asks the index for
|
||||
/// each hit's line — two borrows it cannot take one after the other.
|
||||
fn tokens_and_lines(&mut self, text: &str) -> (Option<&[Token]>, &LineIndex) {
|
||||
let tokens = self.tokens.get_or_insert_with(|| tokenize(text).ok());
|
||||
let lines = self.lines.get_or_insert_with(|| LineIndex::new(text));
|
||||
(tokens.as_deref(), lines)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// What the rename could not account for: the name inside `` `define``
|
||||
/// text, inside a macro invocation's opaque token, inside an assertion
|
||||
/// the SVA grammar could not structure, and identifier occurrences no
|
||||
/// reference was recorded for.
|
||||
///
|
||||
/// Every scan but the last runs over **every** file that spells the name,
|
||||
/// not only the edited ones: `` `BUMP(a) `` in a file the rename never
|
||||
/// touches still expands to the old name, an assertion the SVA grammar
|
||||
/// could not read is source text wherever it sits, and a reference the
|
||||
/// workspace could not finish is spelled with the old name either way.
|
||||
/// Their sentences are collected per scan and concatenated in that order,
|
||||
/// which is the order they were emitted in when each scan had its own loop.
|
||||
///
|
||||
/// `trace` is filled in as the pass runs — the per-scan split the review's
|
||||
/// §3 item 3 asked for. Nothing in the pass reads it back.
|
||||
pub(super) fn warnings(
|
||||
&mut self,
|
||||
target: &Target,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
trace: &mut WarnTrace,
|
||||
) -> Vec<String> {
|
||||
let mut warnings = self.macro_warnings(&target.name);
|
||||
// Macro *invocations* are scanned in every file that spells the name,
|
||||
// not only the edited ones: `` `BUMP(a) `` in a file the rename never
|
||||
// touches still expands to the old name.
|
||||
let name = &target.name;
|
||||
let (mut defines, mut macro_uses) = (Vec::new(), Vec::new());
|
||||
let (mut fallbacks, mut unfinished) = (Vec::new(), Vec::new());
|
||||
// The edited files' scans outlive the loop: the unaccounted scan runs
|
||||
// after all four of these and must not lex them a second time.
|
||||
let mut kept: HashMap<usize, FileScan> = HashMap::new();
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.macro_use_warnings(i, &target.name));
|
||||
let mut scan = FileScan::default();
|
||||
defines.extend(trace.defines.measure(|| self.define_warnings(i, name, &mut scan)));
|
||||
macro_uses
|
||||
.extend(trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &mut scan)));
|
||||
fallbacks.extend(trace.sva.measure(|| self.sva_fallback_warnings(i, name, &mut scan)));
|
||||
unfinished.extend(
|
||||
trace.unfinished.measure(|| self.unresolved_candidate_warnings(i, name, &mut scan)),
|
||||
);
|
||||
// Free, and the number the four times above are mostly made of: a
|
||||
// file only reaches a lex when a scan's prefilter let it through.
|
||||
trace.scanned += usize::from(scan.lexed());
|
||||
if edits.iter().any(|(file, _)| *file == i) {
|
||||
kept.insert(i, scan);
|
||||
}
|
||||
}
|
||||
// Same reason again: an assertion whose spec the SVA grammar could not
|
||||
// read is kept as source text, and the old name inside it is invisible
|
||||
// to the semantic layer wherever the file sits.
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.sva_fallback_warnings(i, &target.name));
|
||||
let mut warnings = defines;
|
||||
warnings.extend(macro_uses);
|
||||
warnings.extend(fallbacks);
|
||||
warnings.extend(unfinished);
|
||||
for (i, edits) in edits {
|
||||
let mut scan = kept.remove(i).unwrap_or_default();
|
||||
warnings.extend(
|
||||
trace.unaccounted.measure(|| self.unaccounted_warnings(*i, name, edits, &mut scan)),
|
||||
);
|
||||
}
|
||||
// Same reason: a reference the workspace could not finish is spelled
|
||||
// with the old name in a file the rename never edits, and silence
|
||||
// there is the same kind of wrong as silence about a macro argument.
|
||||
warnings.dedup();
|
||||
warnings
|
||||
}
|
||||
|
||||
/// [`Scope::warnings`] as it was written before take 5 §P2d shared the
|
||||
/// per-file lex and line index: five loops, and every scan building its
|
||||
/// own inputs from the file's text.
|
||||
///
|
||||
/// The oracle `the_shared_scan_says_exactly_what_the_per_scan_one_did`
|
||||
/// compares against, so the dedupe is pinned against the control flow it
|
||||
/// replaced — both the sharing and the order the sentences come out in —
|
||||
/// rather than against itself.
|
||||
#[cfg(test)]
|
||||
fn warnings_reference(
|
||||
&mut self,
|
||||
target: &Target,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
) -> Vec<String> {
|
||||
let name = &target.name;
|
||||
let mut warnings = Vec::new();
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.unresolved_candidate_warnings(i, &target.name));
|
||||
warnings.extend(self.define_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.macro_use_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.sva_fallback_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for i in 0..self.len() {
|
||||
warnings.extend(self.unresolved_candidate_warnings(i, name, &mut FileScan::default()));
|
||||
}
|
||||
for (i, edits) in edits {
|
||||
warnings.extend(self.unaccounted_warnings(*i, &target.name, edits));
|
||||
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut FileScan::default()));
|
||||
}
|
||||
warnings.dedup();
|
||||
warnings
|
||||
@@ -57,24 +165,22 @@ impl<'a> Scope<'a> {
|
||||
|
||||
/// lucisv does not preprocess, so a name that is also a macro name, or that
|
||||
/// appears in a macro body, is left exactly as written — and said so.
|
||||
fn macro_warnings(&self, name: &str) -> Vec<String> {
|
||||
fn define_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
|
||||
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
|
||||
let mut out = Vec::new();
|
||||
for i in 0..self.len() {
|
||||
let where_ = display(self.path(i).unwrap_or(Path::new("?")));
|
||||
for site in self.define_sites(i, name) {
|
||||
let line = site.line;
|
||||
match site.defines_the_name {
|
||||
Some(DefineKind::Define) => out.push(format!(
|
||||
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
Some(DefineKind::Undef) => out.push(format!(
|
||||
"`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
None => out.push(format!(
|
||||
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; lucisv does not preprocess.",
|
||||
site.macro_name
|
||||
)),
|
||||
}
|
||||
for site in self.define_sites_with(file, name, scan) {
|
||||
let line = site.line;
|
||||
match site.defines_the_name {
|
||||
Some(DefineKind::Define) => out.push(format!(
|
||||
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
Some(DefineKind::Undef) => out.push(format!(
|
||||
"`{name}` is also a macro undefined at {where_}:{line}; macro names and macro uses are never renamed."
|
||||
)),
|
||||
None => out.push(format!(
|
||||
"`{name}` appears in the body of macro `{}` at {where_}:{line} and was left unchanged; lucisv does not preprocess.",
|
||||
site.macro_name
|
||||
)),
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -84,9 +190,9 @@ impl<'a> Scope<'a> {
|
||||
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
|
||||
/// cannot be edited. It can be seen, though — and silence would be worse
|
||||
/// than a warning, because the expansion still spells the old name.
|
||||
fn macro_use_warnings(&self, file: usize, name: &str) -> Vec<String> {
|
||||
fn macro_use_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
|
||||
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
|
||||
self.macro_argument_sites(file, name)
|
||||
self.macro_argument_sites_with(file, name, scan)
|
||||
.into_iter()
|
||||
.map(|site| {
|
||||
format!(
|
||||
@@ -110,15 +216,19 @@ impl<'a> Scope<'a> {
|
||||
/// region is therefore already covered and already edited. So the scan may
|
||||
/// be generous — `expect(word[7:0]);`, an ordinary task call, is claimed as
|
||||
/// a region and contributes nothing.
|
||||
fn sva_fallback_warnings(&mut self, file: usize, name: &str) -> Vec<String> {
|
||||
fn sva_fallback_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !contains_word(text, name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let regions = sva_regions(&tokens);
|
||||
let Some(regions) = scan.tokens(text).map(sva_regions) else { return Vec::new() };
|
||||
if regions.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -126,9 +236,9 @@ impl<'a> Scope<'a> {
|
||||
let mut covered: Vec<TextRange> =
|
||||
analysis.semantics.symbols().iter().map(|s| s.name_span).collect();
|
||||
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
let mut at: Vec<u32> = Vec::new();
|
||||
for token in &tokens {
|
||||
for token in tokens {
|
||||
if token.kind != TokenKind::Ident || token.text != name {
|
||||
continue;
|
||||
}
|
||||
@@ -158,6 +268,11 @@ impl<'a> Scope<'a> {
|
||||
/// because "was left unchanged" and "no longer exists after the removal"
|
||||
/// are different pieces of news.
|
||||
pub(crate) fn define_sites(&self, file: usize, name: &str) -> Vec<DefineSite> {
|
||||
self.define_sites_with(file, name, &mut FileScan::default())
|
||||
}
|
||||
|
||||
/// [`Scope::define_sites`], reading the caller's shared line index.
|
||||
fn define_sites_with(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<DefineSite> {
|
||||
let (Some(text), Some(id)) = (self.text(file), self.file_id(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -165,7 +280,7 @@ impl<'a> Scope<'a> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(defines) = self.index.defines(id) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let lines = scan.lines(text);
|
||||
let mut out = Vec::new();
|
||||
for define in defines.entries() {
|
||||
let line = lines.line_col(define.span.start).0;
|
||||
@@ -187,13 +302,32 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// Every macro invocation in one file whose *arguments* spell `name`.
|
||||
///
|
||||
/// The prefilter is `text.contains(name)` and **not**
|
||||
/// `WorkspaceIndex::files_naming_in_macros` (take 5 §P2d proposed that
|
||||
/// gate; it is not equivalent, so it is not taken). That census is
|
||||
/// `FileFacts::macro_words` = `words::harvest_raw`, which reads the same
|
||||
/// invocation tokens this scan reads but **skips every double-quoted run**
|
||||
/// inside them, and skips a word a `'` precedes. So
|
||||
/// `` `uvm_info("state_q", …) `` — the commonest shape a testbench names an
|
||||
/// RTL signal in — is a site this scan reports and the census does not
|
||||
/// know about, and gating on it would silently drop that warning.
|
||||
pub(crate) fn macro_argument_sites(&self, file: usize, name: &str) -> Vec<ArgumentSite> {
|
||||
self.macro_argument_sites_with(file, name, &mut FileScan::default())
|
||||
}
|
||||
|
||||
/// [`Scope::macro_argument_sites`], reading the caller's shared tokens.
|
||||
fn macro_argument_sites_with(
|
||||
&self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<ArgumentSite> {
|
||||
let Some(text) = self.text(file) else { return Vec::new() };
|
||||
if !text.contains(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for token in tokens.iter().filter(|t| t.is_macro()) {
|
||||
// The macro's own name is reported by the `` `define`` scan when
|
||||
@@ -215,7 +349,13 @@ impl<'a> Scope<'a> {
|
||||
/// Identifier tokens spelling the name that no declaration and no
|
||||
/// reference covers — grouped by *why* lucisv could not attribute them, so
|
||||
/// the user is told where to look rather than guessing.
|
||||
fn unaccounted_warnings(&mut self, file: usize, name: &str, edits: &[TextEdit]) -> Vec<String> {
|
||||
fn unaccounted_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
edits: &[TextEdit],
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -225,8 +365,7 @@ impl<'a> Scope<'a> {
|
||||
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
|
||||
covered.extend(edits.iter().map(|e| e.range));
|
||||
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let lines = LineIndex::new(text);
|
||||
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
|
||||
// Reason → the lines it happened on, in source order.
|
||||
let mut groups: Vec<(&'static str, Vec<u32>)> = Vec::new();
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
@@ -236,7 +375,7 @@ impl<'a> Scope<'a> {
|
||||
if covered.contains(&token.span) {
|
||||
continue;
|
||||
}
|
||||
let reason = stray_reason(&tokens, i);
|
||||
let reason = stray_reason(tokens, i);
|
||||
let line = lines.line_col(token.span.start).0;
|
||||
match groups.iter_mut().find(|(r, _)| *r == reason) {
|
||||
Some((_, at)) => at.push(line),
|
||||
@@ -269,7 +408,12 @@ impl<'a> Scope<'a> {
|
||||
///
|
||||
/// Grouped one line per (file, unit), because a name used against an
|
||||
/// un-indexed module is used against it many times.
|
||||
fn unresolved_candidate_warnings(&mut self, file: usize, name: &str) -> Vec<String> {
|
||||
fn unresolved_candidate_warnings(
|
||||
&mut self,
|
||||
file: usize,
|
||||
name: &str,
|
||||
scan: &mut FileScan,
|
||||
) -> Vec<String> {
|
||||
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -279,7 +423,7 @@ impl<'a> Scope<'a> {
|
||||
return Vec::new();
|
||||
}
|
||||
let where_ = display(path).to_string();
|
||||
let lines = LineIndex::new(text);
|
||||
let lines = scan.lines(text);
|
||||
let Some(analysis) = self.analysis(file) else { return Vec::new() };
|
||||
// Unit that could not be found → the lines it was named on.
|
||||
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
|
||||
@@ -355,7 +499,7 @@ pub(crate) struct ArgumentSite {
|
||||
/// read off its neighbours in the token stream. Naming the actual construct
|
||||
/// is the difference between a warning the user can act on and one they have
|
||||
/// to decode.
|
||||
fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str {
|
||||
fn stray_reason(tokens: &[Token], i: usize) -> &'static str {
|
||||
let before = i.checked_sub(1).and_then(|n| tokens.get(n));
|
||||
if before.is_some_and(|t| t.is_sym(".")) {
|
||||
return "a hierarchical or member tail, which lucisv does not resolve";
|
||||
@@ -383,7 +527,7 @@ fn stray_reason(tokens: &[vlog_parser::token::Token], i: usize) -> &'static str
|
||||
/// structure. Deliberately generous: whether a region actually *is* a
|
||||
/// fallback is decided by its caller from the analysis, and a region that
|
||||
/// structured contributes nothing.
|
||||
fn sva_regions(tokens: &[vlog_parser::token::Token]) -> Vec<TextRange> {
|
||||
fn sva_regions(tokens: &[Token]) -> Vec<TextRange> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < tokens.len() {
|
||||
@@ -418,7 +562,7 @@ fn sva_regions(tokens: &[vlog_parser::token::Token]) -> Vec<TextRange> {
|
||||
|
||||
/// The index of the `(` that opens the spec of the concurrent assertion or
|
||||
/// `expect` statement starting at `i`, if one starts there.
|
||||
fn assertion_paren(tokens: &[vlog_parser::token::Token], i: usize) -> Option<usize> {
|
||||
fn assertion_paren(tokens: &[Token], i: usize) -> Option<usize> {
|
||||
let mut k = i;
|
||||
if tokens[i].kind == TokenKind::Ident && tokens.get(i + 1).is_some_and(|t| t.is_sym(":")) {
|
||||
k = i + 2;
|
||||
@@ -441,7 +585,7 @@ fn assertion_paren(tokens: &[vlog_parser::token::Token], i: usize) -> Option<usi
|
||||
}
|
||||
|
||||
/// The index of the `)` matching the `(` at `open`, or the last token.
|
||||
fn closing_paren(tokens: &[vlog_parser::token::Token], open: usize) -> usize {
|
||||
fn closing_paren(tokens: &[Token], open: usize) -> usize {
|
||||
let mut depth = 0usize;
|
||||
for (j, t) in tokens.iter().enumerate().skip(open) {
|
||||
if t.is_sym("(") {
|
||||
@@ -500,7 +644,9 @@ fn is_name_byte(byte: u8) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::contains_word;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::{contains_word, Scope, WarnTrace};
|
||||
|
||||
#[test]
|
||||
fn whole_word_search_ignores_substrings() {
|
||||
@@ -510,4 +656,354 @@ mod tests {
|
||||
assert!(contains_word("`WIDTH", "WIDTH"), "a macro use of the name still counts");
|
||||
assert!(!contains_word("x", ""));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// take 5 §P2d: the shared lex and line index say what the old
|
||||
// per-scan ones did
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One rename fixture: the workspace, where the cursor is, and what the
|
||||
/// warnings must say about it.
|
||||
struct Case {
|
||||
/// What this fixture is built to exercise, quoted on failure.
|
||||
what: &'static str,
|
||||
files: &'static [(&'static str, &'static str)],
|
||||
/// The file the cursor sits in, and the text it sits at the start of.
|
||||
file: &'static str,
|
||||
at: &'static str,
|
||||
new_name: &'static str,
|
||||
/// A sentence fragment the warnings must contain, so a case cannot
|
||||
/// pass by producing nothing at all. Empty for the controls, which
|
||||
/// exist to prove the *absence* of a warning is shared too.
|
||||
says: &'static str,
|
||||
}
|
||||
|
||||
/// The six sentences `warnings` can produce, so the table can assert it
|
||||
/// exercises every one of them rather than five.
|
||||
const KINDS: [&str; 6] = [
|
||||
"is also a macro",
|
||||
"appears in the body of macro",
|
||||
"appears in the arguments of the macro invocation",
|
||||
"is spelled inside an assertion lucisv could not structure",
|
||||
"could not be resolved — nothing in the indexed workspace answers",
|
||||
"lucisv records no reference there",
|
||||
];
|
||||
|
||||
/// A file that does not lex — an unterminated block comment — which every
|
||||
/// scan must treat as "nothing to say" whether it lexes the file itself or
|
||||
/// reads a shared answer.
|
||||
const UNLEXABLE: &str = "module unlexable;\n /* sig is in here and the comment never closes\n";
|
||||
|
||||
/// A file whose only spelling of the name is in a comment: `contains_word`
|
||||
/// sees it, the token stream does not.
|
||||
const COMMENT_ONLY: &str =
|
||||
"module note;\n // sig is only mentioned here\n logic other;\nendmodule\n";
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case {
|
||||
what: "a macro of the same name, and one whose body spells it, and an undef",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define sig 1\n`define USE_SIG assign z = sig;\n`undef sig\nmodule m;\n wire sig;\n assign q = sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;\n assign q",
|
||||
new_name: "signal",
|
||||
says: "is also a macro defined at",
|
||||
},
|
||||
Case {
|
||||
what: "the name inside a macro body",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define SET_A assign a = 1;\nmodule m;\n wire a;\n assign a = 0;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "a;",
|
||||
new_name: "sig",
|
||||
says: "body of macro `SET_A`",
|
||||
},
|
||||
Case {
|
||||
what: "the name inside a macro invocation's arguments",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"`define BUMP(x) x = x + 1\nmodule m;\n int a;\n initial `BUMP(a);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "a;",
|
||||
new_name: "b",
|
||||
says: "arguments of the macro invocation `BUMP`",
|
||||
},
|
||||
Case {
|
||||
what: "a macro invocation in a file the rename does not edit",
|
||||
files: &[
|
||||
("p.sv", "package p;\n localparam int WIDTH = 8;\nendpackage\n"),
|
||||
(
|
||||
"u.sv",
|
||||
"`define DECL(w) logic [w-1:0] bus\nmodule u;\n import p::*;\n `DECL(WIDTH);\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "p.sv",
|
||||
at: "WIDTH",
|
||||
new_name: "BUS_W",
|
||||
says: "macro invocation `DECL`",
|
||||
},
|
||||
Case {
|
||||
what: "a file whose only relationship to the name is a macro argument",
|
||||
files: &[
|
||||
(
|
||||
"lib.sv",
|
||||
"`define CHECK(sig) assert property (sig)\npackage p;\n localparam int WIDTH = 8;\nendpackage\n",
|
||||
),
|
||||
("user.sv", "module u;\n `CHECK(WIDTH)\nendmodule\n"),
|
||||
],
|
||||
file: "lib.sv",
|
||||
at: "WIDTH = 8",
|
||||
new_name: "BUS_W",
|
||||
says: "macro invocation `CHECK`",
|
||||
},
|
||||
Case {
|
||||
what: "an SVA spec the grammar could not structure, in the edited file",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n logic sig;\n assign x = sig;\n assert property (sig |-> $blah $blah);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "could not structure",
|
||||
},
|
||||
Case {
|
||||
what: "an SVA fallback in a file the rename does not edit",
|
||||
files: &[
|
||||
("p.sv", "package p;\n localparam int WIDTH = 8;\nendpackage\n"),
|
||||
(
|
||||
"u.sv",
|
||||
"module u;\n import p::*;\n assert property (WIDTH |-> $blah $blah);\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "p.sv",
|
||||
at: "WIDTH",
|
||||
new_name: "BUS_W",
|
||||
says: "could not structure",
|
||||
},
|
||||
Case {
|
||||
what: "an assertion the grammar did structure — the control",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n logic sig;\n assert property (sig |-> sig);\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "an unresolved candidate spelling the name",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module top;\n wire sig;\n unknown_mod u_x ();\n wire w;\n assign w = u_x.sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "could not be resolved",
|
||||
},
|
||||
Case {
|
||||
what: "an unresolved candidate in a file the rename never edits",
|
||||
files: &[
|
||||
("holder.sv", "module holder;\n wire sig;\nendmodule\n"),
|
||||
(
|
||||
"other.sv",
|
||||
"module other;\n unknown_mod u_y ();\n wire w;\n assign w = u_y.sig;\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "holder.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "other.sv",
|
||||
},
|
||||
Case {
|
||||
what: "a tail the workspace can finish — the control",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
(
|
||||
"top.sv",
|
||||
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\nendmodule\n",
|
||||
),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "a stray occurrence no reference covers — a member tail",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n wire sig;\n logic s;\n assign x = s.sig;\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "as a hierarchical or member tail",
|
||||
},
|
||||
Case {
|
||||
what: "a stray occurrence no reference covers — a mismatched end label",
|
||||
files: &[(
|
||||
"m.sv",
|
||||
"module m;\n wire sig;\n initial begin : blk\n end : sig\nendmodule\n",
|
||||
)],
|
||||
file: "m.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "as an end label lucisv could not attach",
|
||||
},
|
||||
Case {
|
||||
what: "a file that mentions the name only in a comment",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "a file that does not lex",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
},
|
||||
Case {
|
||||
what: "the §P2b eight-file workspace, whose rename edits two files",
|
||||
files: &[
|
||||
(
|
||||
"/w/sub.sv",
|
||||
"module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"/w/top.sv",
|
||||
"module top;\n logic w;\n sub u_sub (.clk(1'b0), .q(w));\n assign w = u_sub.sig;\nendmodule\n",
|
||||
),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
(
|
||||
"/w/user.sv",
|
||||
"import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n",
|
||||
),
|
||||
("/w/note.sv", COMMENT_ONLY),
|
||||
("/w/far.sv", "module far;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("/w/quiet_a.sv", "module quiet_a;\n logic a;\nendmodule\n"),
|
||||
("/w/quiet_b.sv", "module quiet_b;\n logic b;\nendmodule\n"),
|
||||
],
|
||||
file: "/w/sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "renamed_sig",
|
||||
says: "",
|
||||
},
|
||||
// The order test: every kind of warning at once, from several files,
|
||||
// with two files edited — so a concatenation that grouped by file
|
||||
// instead of by scan, or that ran the unaccounted scan too early,
|
||||
// would come out in a different order and be caught.
|
||||
Case {
|
||||
what: "every shape in one workspace, two files edited",
|
||||
files: &[
|
||||
(
|
||||
"sub.sv",
|
||||
"`define sig 1\n`define USE_SIG assign z = sig;\nmodule sub;\n wire sig;\n assign sig = 1'b0;\n logic s;\n assign y = s.sig;\n assert property (sig |-> $blah $blah);\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"top.sv",
|
||||
"`define BUMP(x) x + 1\nmodule top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\n assign w = `BUMP(sig);\n assign w = elsewhere.sig;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"stray.sv",
|
||||
"module stray;\n unknown_mod u_y ();\n wire w;\n assign w = u_y.sig;\nendmodule\n",
|
||||
),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;\n assign sig",
|
||||
new_name: "signal",
|
||||
says: "could not be resolved",
|
||||
},
|
||||
];
|
||||
|
||||
/// One case's warnings, computed both ways over **separate** scopes, so a
|
||||
/// cache the first call warmed cannot flatter the second.
|
||||
fn both_ways(case: &Case) -> (Vec<String>, Vec<String>) {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
case.files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let path = PathBuf::from(case.file);
|
||||
let text = case.files.iter().find(|(p, _)| *p == case.file).expect("the cursor's file").1;
|
||||
let at = text.find(case.at).expect("the cursor text is in the file") as u32;
|
||||
|
||||
let mut shared = Scope::build(&sources);
|
||||
let target = shared.locate(&path, at).expect("the cursor names something renameable");
|
||||
let edits = shared.collect_edits(&target, case.new_name).expect("the rename has edits");
|
||||
let said = shared.warnings(&target, &edits, &mut WarnTrace::default());
|
||||
|
||||
let mut apart = Scope::build(&sources);
|
||||
let target = apart.locate(&path, at).expect("the cursor names something renameable");
|
||||
let edits = apart.collect_edits(&target, case.new_name).expect("the rename has edits");
|
||||
(said, apart.warnings_reference(&target, &edits))
|
||||
}
|
||||
|
||||
/// **The §P2d proof.** Sharing one lex and one line index per file per call
|
||||
/// changes no sentence and no order: fifteen fixtures — every warning-
|
||||
/// producing shape `crates/vlog_refactor/tests/rename.rs` pins, the three
|
||||
/// controls that must stay silent, a file that only mentions the name in a
|
||||
/// comment, a file that does not lex, and one workspace holding all of them
|
||||
/// with two files edited — asked both ways and compared as lists.
|
||||
#[test]
|
||||
fn the_shared_scan_says_exactly_what_the_per_scan_one_did() {
|
||||
let mut seen = [false; KINDS.len()];
|
||||
for case in CASES {
|
||||
let (shared, reference) = both_ways(case);
|
||||
assert_eq!(shared, reference, "{}: the shared scan disagrees", case.what);
|
||||
if case.says.is_empty() {
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
shared.iter().any(|warning| warning.contains(case.says)),
|
||||
"{}: no warning says `{}`: {shared:?}",
|
||||
case.what,
|
||||
case.says
|
||||
);
|
||||
for (kind, seen) in KINDS.iter().zip(seen.iter_mut()) {
|
||||
*seen |= shared.iter().any(|warning| warning.contains(kind));
|
||||
}
|
||||
}
|
||||
let missed: Vec<&str> =
|
||||
KINDS.iter().zip(seen).filter_map(|(kind, seen)| (!seen).then_some(*kind)).collect();
|
||||
assert!(missed.is_empty(), "these warnings are never exercised: {missed:?}");
|
||||
}
|
||||
|
||||
/// The controls are silent *and* silent in the same way: a workspace where
|
||||
/// the only other spellings of the name are a comment and a file that does
|
||||
/// not lex warns about nothing at all.
|
||||
#[test]
|
||||
fn a_comment_and_an_unlexable_file_are_warned_about_by_neither_scan() {
|
||||
let case = Case {
|
||||
what: "a comment and an unlexable file, together",
|
||||
files: &[
|
||||
("sub.sv", "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("note.sv", COMMENT_ONLY),
|
||||
("unlexable.sv", UNLEXABLE),
|
||||
],
|
||||
file: "sub.sv",
|
||||
at: "sig;",
|
||||
new_name: "signal",
|
||||
says: "",
|
||||
};
|
||||
let (shared, reference) = both_ways(&case);
|
||||
assert!(shared.is_empty(), "nothing there can be warned about: {shared:?}");
|
||||
assert_eq!(shared, reference);
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,151 @@
|
||||
//! Nothing here is specific to a rename: `ports`, `references` and
|
||||
//! `instantiate` read the same workspace, which is why it sits at the crate
|
||||
//! root rather than under one of them.
|
||||
//!
|
||||
//! **One parse per file** (take 5 §P2b). Building the index parses and
|
||||
//! analyses every in-scope file already — `FileFacts::of` is a parse, an
|
||||
//! `analyze` and a read-off — and used to throw that analysis away, so the
|
||||
//! first thing every refactoring did was parse a third of those files a
|
||||
//! second time. [`FileFacts::analyzed`] hands the analysis back instead, and
|
||||
//! [`Scope::build_keeping`] retains the ones a caller says it will want. What
|
||||
//! is retained is a *cache and nothing else*: a file whose analysis was not
|
||||
//! kept is analysed on demand exactly as before, so a retention rule that
|
||||
//! guesses wrong costs time and cannot change an answer.
|
||||
//!
|
||||
//! **And no parse at all, for a file the caller already has the record of**
|
||||
//! (review round §R3b). Two thirds of that per-file cost is the lexer and the
|
||||
//! parser, and a third of a rename's files are containers it indexes and never
|
||||
//! reads again — so [`KnownFacts`] lets a caller hand back the [`FileFacts`]
|
||||
//! it holds *for exactly the bytes it is handing over*, and those files are
|
||||
//! never parsed. Unlike retention, this one is not merely a cache: a record
|
||||
//! that does not describe the text it is filed against is a wrong index. The
|
||||
//! contract, and the two halves of it this crate can check itself, are on
|
||||
//! [`KnownFacts`]; `docs/features/perf5r-scope-reuse/README.md` has the rest.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, FileId, Semantics, WorkspaceIndex,
|
||||
analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::trace::IndexTrace;
|
||||
|
||||
/// What the caller already knows about the files it is handing over.
|
||||
///
|
||||
/// A refactoring's scope is built by parsing and analysing every in-scope
|
||||
/// file, and most of that work exists only to produce each file's
|
||||
/// [`FileFacts`] — the record the workspace index is merged from. A caller
|
||||
/// that has already read that record off *these very bytes* can hand it back
|
||||
/// here, and the build skips the parse (review round §R3b, TODO §61.5).
|
||||
///
|
||||
/// **The whole contract is the one sentence in `facts_for`**, and it is the
|
||||
/// caller's to keep: this crate cannot check a record against the text it
|
||||
/// claims to describe without doing the parse the record exists to save. The
|
||||
/// engine does the two checks it can — it asks with the exact text it is about
|
||||
/// to index, and it refuses a record filed under another path — and nothing
|
||||
/// else. So an implementation must key its answer on the *content* of the text
|
||||
/// it is handed, from a record and a key it read out of one place; a modified
|
||||
/// time, a size or a path alone is not that key, and neither is a record whose
|
||||
/// hash was recorded by something other than the read that produced it.
|
||||
///
|
||||
/// A wrong answer here is a wrong index, which is a wrong refactoring: this is
|
||||
/// the one thing in the door that is not merely a cache. `None` is always
|
||||
/// safe — the file is analysed exactly as it always was.
|
||||
pub trait KnownFacts {
|
||||
/// The record [`FileFacts::of(path, text)`](FileFacts::of) would produce,
|
||||
/// if the caller can promise it is exactly that; `None` otherwise.
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts>;
|
||||
}
|
||||
|
||||
/// What the build does with one file, which is also what decides whether its
|
||||
/// analysis is worth keeping.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Class {
|
||||
/// The file the request was made in: analysed first, always kept.
|
||||
Lead,
|
||||
/// A file the retention rule asked for: analysed, and kept.
|
||||
Kept,
|
||||
/// Everything else: it contributes a record to the index and nothing
|
||||
/// reads its analysis, so with a known record it is never analysed.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// One scope build in progress: the records collected so far, the analyses
|
||||
/// kept, and where the time went.
|
||||
struct Building<'k, 't> {
|
||||
builder: IndexBuilder,
|
||||
kept: HashMap<usize, Semantics>,
|
||||
known: Option<&'k dyn KnownFacts>,
|
||||
trace: &'t mut IndexTrace,
|
||||
}
|
||||
|
||||
impl Building<'_, '_> {
|
||||
/// Take one file's contribution: its record, reused when the caller knows
|
||||
/// it for exactly these bytes and read off a fresh analysis otherwise, and
|
||||
/// its analysis when a later stage will read it.
|
||||
///
|
||||
/// The two halves of a reused file are computed apart — the record from
|
||||
/// the caller, the [`Semantics`] from this text — where an analysed file's
|
||||
/// come from one call. They agree because both are pure functions of the
|
||||
/// same bytes, which is the same reason `Scope::analysis`'s on-demand path
|
||||
/// has always been allowed to analyse a file the index build already read.
|
||||
fn take(&mut self, i: usize, path: &Path, text: &str, class: Class) {
|
||||
let known = self.known;
|
||||
let record = self
|
||||
.trace
|
||||
.reused
|
||||
.measure(|| known?.facts_for(path, text))
|
||||
// A record filed under another path would be merged as that file.
|
||||
// The caller cannot mean this, so it is a miss rather than a trust.
|
||||
.filter(|facts| facts.path() == path);
|
||||
self.count(class, text.len(), record.is_some());
|
||||
let wanted = class != Class::Other;
|
||||
let stage = match class {
|
||||
Class::Lead => &mut self.trace.lead,
|
||||
Class::Kept => &mut self.trace.kept,
|
||||
Class::Other => &mut self.trace.other,
|
||||
};
|
||||
let (facts, semantics) = match record {
|
||||
Some(facts) => {
|
||||
let analysed = || stage.measure(|| analyze(&parse_source_tolerant(text).0, text));
|
||||
(facts, wanted.then(analysed))
|
||||
}
|
||||
None => {
|
||||
let (facts, semantics) =
|
||||
stage.measure(|| FileFacts::analyzed(path.to_path_buf(), text));
|
||||
(facts, wanted.then_some(semantics))
|
||||
}
|
||||
};
|
||||
self.builder.add_facts(facts);
|
||||
if let Some(semantics) = semantics {
|
||||
self.kept.insert(i, semantics);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file counted into its class, and into the reuse count when its
|
||||
/// record came from the caller.
|
||||
fn count(&mut self, class: Class, bytes: usize, reused: bool) {
|
||||
match class {
|
||||
Class::Lead => {}
|
||||
Class::Kept => {
|
||||
self.trace.kept_files += 1;
|
||||
self.trace.kept_bytes += bytes;
|
||||
}
|
||||
Class::Other => {
|
||||
self.trace.other_files += 1;
|
||||
self.trace.other_bytes += bytes;
|
||||
}
|
||||
}
|
||||
if reused {
|
||||
self.trace.reused_files += 1;
|
||||
self.trace.reused_bytes += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's two analysis layers, as `textDocument/definition` uses them.
|
||||
pub(crate) struct Analysis {
|
||||
pub(crate) semantics: Semantics,
|
||||
@@ -30,10 +166,64 @@ pub(crate) struct Scope<'a> {
|
||||
/// Source index → the index's own file id.
|
||||
file_ids: Vec<Option<FileId>>,
|
||||
cache: HashMap<usize, Analysis>,
|
||||
/// The `Semantics` the index build kept, by source index — the half of an
|
||||
/// [`Analysis`] that does not depend on the finished index. Moved into
|
||||
/// `cache` the first time that file's analysis is asked for.
|
||||
kept: HashMap<usize, Semantics>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// The in-scope files, indexed, keeping no analysis.
|
||||
///
|
||||
/// Each file is still parsed and analysed exactly once — that is what
|
||||
/// building the index costs — and every later `analysis` call parses
|
||||
/// again, which is the behaviour every caller but the rename has always
|
||||
/// had. [`Scope::build_keeping`] is the one that keeps them.
|
||||
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
|
||||
Scope::assemble(files, None, |_| Vec::new(), None, &mut IndexTrace::default())
|
||||
}
|
||||
|
||||
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
|
||||
/// every file whose text mentions one of the words `keep` asks for.
|
||||
///
|
||||
/// `lead` — the file the request was made in — is analysed first, and
|
||||
/// `keep` is then asked which words are worth retaining *given that
|
||||
/// analysis*. That ordering is the whole trick: a rename cannot know the
|
||||
/// name under the cursor until something has analysed the cursor's file,
|
||||
/// and this way that analysis is the file's own one-and-only parse rather
|
||||
/// than an extra one.
|
||||
///
|
||||
/// The rule is `text.contains(word)` — a substring test, deliberately the
|
||||
/// same prefilter [`Scope::collect_occurrences`] uses, so every file the
|
||||
/// occurrence walk will analyse and every file
|
||||
/// [`crate::check`] will watch (a whole-word subset) is retained, and
|
||||
/// nothing else is.
|
||||
///
|
||||
/// `known`, when the caller has one, is asked for each file's index record
|
||||
/// before that file is analysed — see [`KnownFacts`]. It changes what the
|
||||
/// build *costs* and nothing else: a record it does not answer for is read
|
||||
/// off a fresh analysis exactly as it always was.
|
||||
///
|
||||
/// `trace` is filled in as the build runs — the per-file-class split the
|
||||
/// review's §3 item 1 asked for. A caller with nothing to measure passes
|
||||
/// `&mut IndexTrace::default()`; nothing in the build reads it back.
|
||||
pub(crate) fn build_keeping(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: &Path,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
known: Option<&dyn KnownFacts>,
|
||||
trace: &mut IndexTrace,
|
||||
) -> Scope<'a> {
|
||||
Scope::assemble(files, Some(lead), keep, known, trace)
|
||||
}
|
||||
|
||||
fn assemble(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: Option<&Path>,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
known: Option<&dyn KnownFacts>,
|
||||
trace: &mut IndexTrace,
|
||||
) -> Scope<'a> {
|
||||
let mut sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
// The same normalization `WorkspaceIndex::build` applies: a stable
|
||||
@@ -41,7 +231,30 @@ impl<'a> Scope<'a> {
|
||||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.to_path_buf(), *t)));
|
||||
let mut building =
|
||||
Building { builder: IndexBuilder::new(), kept: HashMap::new(), known, trace };
|
||||
// The lead file first, so its analysis can be read before the rest are
|
||||
// parsed. `IndexBuilder::finish` sorts by path, so feeding it out of
|
||||
// order cannot reach the index.
|
||||
let first = lead.and_then(|path| sources.iter().position(|(held, _)| *held == path));
|
||||
if let Some(i) = first {
|
||||
let (path, text) = sources[i];
|
||||
building.take(i, path, text, Class::Lead);
|
||||
}
|
||||
let words = keep(first.and_then(|i| building.kept.get(&i)));
|
||||
for (i, (path, text)) in sources.iter().enumerate() {
|
||||
if Some(i) == first {
|
||||
continue;
|
||||
}
|
||||
// Asked before the file is taken rather than after it — the same
|
||||
// pure question of the same two values, moved so the class it
|
||||
// answers decides what the build does with the file at all.
|
||||
let wanted = words.iter().any(|word| text.contains(word.as_str()));
|
||||
building.take(i, path, text, if wanted { Class::Kept } else { Class::Other });
|
||||
}
|
||||
|
||||
let Building { builder, kept, trace, .. } = building;
|
||||
let index = trace.merge.measure(|| builder.finish());
|
||||
let ids: HashMap<&Path, FileId> = index
|
||||
.files()
|
||||
.iter()
|
||||
@@ -49,7 +262,7 @@ impl<'a> Scope<'a> {
|
||||
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
|
||||
.collect();
|
||||
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
|
||||
Scope { sources, index, file_ids, cache: HashMap::new() }
|
||||
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
@@ -64,10 +277,6 @@ impl<'a> Scope<'a> {
|
||||
self.sources.get(i).map(|(_, text)| *text)
|
||||
}
|
||||
|
||||
pub(crate) fn sources(&self) -> &[(&'a Path, &'a str)] {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
|
||||
self.file_ids.get(i).copied().flatten()
|
||||
}
|
||||
@@ -77,11 +286,17 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// The two analysis layers for one file, computed on first use.
|
||||
///
|
||||
/// The local half is the one the index build already made, when it was
|
||||
/// kept; otherwise it is parsed here, exactly as it always was. The
|
||||
/// external half is this scope's index resolved against it, and is
|
||||
/// computed here either way — it cannot exist before the index does.
|
||||
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
|
||||
let Scope { sources, index, cache, .. } = self;
|
||||
let Scope { sources, index, cache, kept, .. } = self;
|
||||
let text = sources.get(i).map(|(_, text)| *text)?;
|
||||
Some(cache.entry(i).or_insert_with(|| {
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let semantics =
|
||||
kept.remove(&i).unwrap_or_else(|| analyze(&parse_source_tolerant(text).0, text));
|
||||
let external = resolve_external(&semantics, index);
|
||||
Analysis { semantics, external }
|
||||
}))
|
||||
@@ -93,6 +308,27 @@ impl<'a> Scope<'a> {
|
||||
self.cache.get(&i)
|
||||
}
|
||||
|
||||
/// One watched file's after-print inputs: the local analysis the
|
||||
/// before-pass already computed, and its uses resolved against `index`.
|
||||
///
|
||||
/// A file the edits did not touch has the same declarations and the same
|
||||
/// uses afterwards — its text did not change — so only what the workspace
|
||||
/// answers *for* those uses can have moved, and re-resolving is the whole
|
||||
/// of the difference. Re-parsing it to learn that is the work take 5 §P2c
|
||||
/// removes.
|
||||
///
|
||||
/// `None` when that file's local analysis has not been computed. The
|
||||
/// caller's own before-pass is what computes it, so that is a
|
||||
/// contradiction rather than a fallback.
|
||||
pub(crate) fn against(
|
||||
&self,
|
||||
i: usize,
|
||||
index: &WorkspaceIndex,
|
||||
) -> Option<(&Semantics, ExternalResolutions)> {
|
||||
let semantics = &self.cached(i)?.semantics;
|
||||
Some((semantics, resolve_external(semantics, index)))
|
||||
}
|
||||
|
||||
/// The workspace index the edits were computed against.
|
||||
pub(crate) fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
@@ -104,3 +340,212 @@ impl<'a> Scope<'a> {
|
||||
pub(crate) fn display(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FILES: [(&str, &str); 4] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign u_sub.sig = 1'b0;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
];
|
||||
|
||||
fn files() -> Vec<(PathBuf, String)> {
|
||||
FILES.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect()
|
||||
}
|
||||
|
||||
/// Every declaration and use one analysis holds, as comparable text — the
|
||||
/// whole observable of a `Semantics` plus its overlay.
|
||||
fn print(analysis: &Analysis) -> String {
|
||||
let mut out = String::new();
|
||||
for symbol in analysis.semantics.symbols() {
|
||||
out.push_str(&format!(
|
||||
"sym {} {:?} {}..{}\n",
|
||||
symbol.name, symbol.kind, symbol.name_span.start, symbol.name_span.end
|
||||
));
|
||||
}
|
||||
for (id, reference) in analysis.semantics.references().iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"ref {} {}..{} -> {:?} / {:?}\n",
|
||||
reference.name,
|
||||
reference.name_span.start,
|
||||
reference.name_span.end,
|
||||
reference.resolution,
|
||||
analysis.external.get(vlog_semantic::ReferenceId(id as u32))
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The scope's index is the index a plain `WorkspaceIndex::build` gives —
|
||||
/// same fingerprint, same file ids — however the scope was assembled.
|
||||
#[test]
|
||||
fn assembling_the_scope_file_by_file_builds_the_same_index() {
|
||||
let files = files();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let plain = Scope::build(&files);
|
||||
assert_eq!(plain.index().fingerprint(), built.fingerprint());
|
||||
let keeping = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/top.sv"),
|
||||
|_| vec!["sig".to_string()],
|
||||
None,
|
||||
&mut IndexTrace::default(),
|
||||
);
|
||||
assert_eq!(keeping.index().fingerprint(), built.fingerprint());
|
||||
for i in 0..plain.len() {
|
||||
assert_eq!(plain.file_id(i), keeping.file_id(i), "file ids move with retention");
|
||||
assert_eq!(plain.path(i), keeping.path(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// A retained analysis is the analysis the on-demand path would compute.
|
||||
/// This is the whole of §P2b's correctness: what is kept is not a second
|
||||
/// opinion, it is the same one, not thrown away.
|
||||
#[test]
|
||||
fn a_retained_analysis_is_the_one_the_on_demand_path_would_compute() {
|
||||
let files = files();
|
||||
let mut plain = Scope::build(&files);
|
||||
let mut trace = IndexTrace::default();
|
||||
let mut keeping = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/top.sv"),
|
||||
|here| {
|
||||
// Every word in play, so every file is retained.
|
||||
assert!(here.is_some(), "the lead file's analysis is made first");
|
||||
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
|
||||
},
|
||||
None,
|
||||
&mut trace,
|
||||
);
|
||||
for i in 0..plain.len() {
|
||||
let one = plain.analysis(i).map(print);
|
||||
let two = keeping.analysis(i).map(print);
|
||||
assert_eq!(one, two, "file {i} analyses differently when it is retained");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lead file's analysis is made **before** the rest are parsed, which
|
||||
/// is what lets a caller read the cursor's name off it and ask for that
|
||||
/// name to be kept — without a second parse of anything.
|
||||
#[test]
|
||||
fn the_lead_files_analysis_is_available_to_the_retention_rule() {
|
||||
let files = files();
|
||||
let mut seen = None;
|
||||
let mut trace = IndexTrace::default();
|
||||
let scope = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/user.sv"),
|
||||
|here| {
|
||||
seen = here.map(|semantics| semantics.symbols().len());
|
||||
Vec::new()
|
||||
},
|
||||
None,
|
||||
&mut trace,
|
||||
);
|
||||
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
|
||||
assert_eq!(scope.len(), 4);
|
||||
}
|
||||
|
||||
/// **The R3b fingerprint proof.** An index part *reused* and part parsed is
|
||||
/// the index every file's own text builds — same fingerprint, same file
|
||||
/// ids — and the analyses it keeps are the same analyses either way.
|
||||
///
|
||||
/// This is the whole of the door's correctness at this level: a record
|
||||
/// handed in by a caller who kept the promise is the record the parse
|
||||
/// would have produced, so an index merged from a mixture of the two
|
||||
/// cannot be told from one merged from either.
|
||||
#[test]
|
||||
fn an_index_part_reused_and_part_parsed_is_the_index_the_texts_build() {
|
||||
/// A caller that knows `pkg.sv` and `user.sv`, read off their own text.
|
||||
struct Two(Vec<(PathBuf, String, FileFacts)>);
|
||||
impl KnownFacts for Two {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.0
|
||||
.iter()
|
||||
.find(|(held, bytes, _)| held == path && bytes == text)
|
||||
.map(|(_, _, facts)| facts.clone())
|
||||
}
|
||||
}
|
||||
let files = files();
|
||||
let known = Two(files
|
||||
.iter()
|
||||
.filter(|(path, _)| path.ends_with("pkg.sv") || path.ends_with("user.sv"))
|
||||
.map(|(path, text)| (path.clone(), text.clone(), FileFacts::of(path.clone(), text)))
|
||||
.collect());
|
||||
assert_eq!(known.0.len(), 2, "premise: two of the four are known");
|
||||
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut trace = IndexTrace::default();
|
||||
let mut mixed = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/top.sv"),
|
||||
|_| vec!["sig".to_string()],
|
||||
Some(&known),
|
||||
&mut trace,
|
||||
);
|
||||
assert_eq!(trace.reused_files, 2, "both known records were taken: {trace:?}");
|
||||
assert_eq!(mixed.index().fingerprint(), built.fingerprint());
|
||||
|
||||
let mut plain = Scope::build(&files);
|
||||
for i in 0..plain.len() {
|
||||
assert_eq!(plain.file_id(i), mixed.file_id(i), "file ids move with reuse");
|
||||
assert_eq!(plain.path(i), mixed.path(i));
|
||||
assert_eq!(
|
||||
plain.analysis(i).map(print),
|
||||
mixed.analysis(i).map(print),
|
||||
"file {i} analyses differently when its record is reused"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller that answers for nothing is the build as it always was — the
|
||||
/// door is opt-in per file, not a mode.
|
||||
#[test]
|
||||
fn a_caller_that_knows_nothing_builds_exactly_what_it_always_did() {
|
||||
struct Nothing;
|
||||
impl KnownFacts for Nothing {
|
||||
fn facts_for(&self, _path: &Path, _text: &str) -> Option<FileFacts> {
|
||||
None
|
||||
}
|
||||
}
|
||||
let files = files();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut trace = IndexTrace::default();
|
||||
let scope = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/top.sv"),
|
||||
|_| vec!["sig".to_string()],
|
||||
Some(&Nothing),
|
||||
&mut trace,
|
||||
);
|
||||
assert_eq!(trace.reused_files, 0);
|
||||
assert_eq!(scope.index().fingerprint(), built.fingerprint());
|
||||
}
|
||||
|
||||
/// A lead the scope does not hold is not an error: nothing is retained,
|
||||
/// and the rest of the build is what it always was.
|
||||
#[test]
|
||||
fn a_lead_outside_the_scope_retains_nothing_and_still_builds() {
|
||||
let files = files();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut asked = false;
|
||||
let mut trace = IndexTrace::default();
|
||||
let mut scope = Scope::build_keeping(
|
||||
&files,
|
||||
Path::new("/w/absent.sv"),
|
||||
|here| {
|
||||
asked = true;
|
||||
assert!(here.is_none(), "there is no lead analysis to offer");
|
||||
vec!["sig".to_string()]
|
||||
},
|
||||
None,
|
||||
&mut trace,
|
||||
);
|
||||
assert!(asked, "the retention rule is asked either way");
|
||||
assert_eq!(scope.index().fingerprint(), built.fingerprint());
|
||||
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Where a rename's time and its whole-file parses went.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`): the tail rename costs
|
||||
//! ~780 ms and nobody could say which stage that is. A stopwatch on the wire
|
||||
//! cannot, because every stage of a rename is "read the workspace" in some
|
||||
//! form. So the engine says it itself — one value the caller fills as it goes,
|
||||
//! carrying a wall time and a *parse count* per stage.
|
||||
//!
|
||||
//! **Nothing here changes what a rename decides.** A trace is written to, read
|
||||
//! once and dropped; no branch anywhere reads a field of it. The counters are
|
||||
//! `vlog_parser::stats::parses()` deltas, which is a thread-local `Cell` read,
|
||||
//! and the timers are `Instant`s taken at stage boundaries — the cost of the
|
||||
//! whole instrument is a few dozen nanoseconds on a request measured in
|
||||
//! hundreds of milliseconds.
|
||||
//!
|
||||
//! The counts are the honest half. A wall time moves with the machine's load;
|
||||
//! "this rename parsed 5 200 whole files where 1 300 would do" does not, which
|
||||
//! is why the parse-count assertions in the tests are written against these
|
||||
//! fields rather than against a stopwatch.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
/// A stage's wall time and the whole-file parses it ran.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Stage {
|
||||
/// Milliseconds spent inside the stage.
|
||||
pub ms: f64,
|
||||
/// Whole-file parses the stage ran — a `vlog_parser::stats::parses()`
|
||||
/// delta, so a lex failure (which parses nothing) is not counted.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
/// Run `work`, recording its wall time and its parses into `self`.
|
||||
///
|
||||
/// Additive: a stage measured twice accumulates, which is what the
|
||||
/// per-file loops want.
|
||||
pub(crate) fn measure<T>(&mut self, work: impl FnOnce() -> T) -> T {
|
||||
let (started, parses) = (Instant::now(), vlog_parser::stats::parses());
|
||||
let out = work();
|
||||
self.ms += started.elapsed().as_secs_f64() * 1000.0;
|
||||
self.parses += vlog_parser::stats::parses() - parses;
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the scope build's time went, by what the build does with each file.
|
||||
///
|
||||
/// The review's §3 item 1 asked for the 229 ms scope stage split, because an
|
||||
/// aggregate cannot say whether a parser or an index optimization is the
|
||||
/// lever. The split that answers it is **by file class**: the request's own
|
||||
/// file, the files whose text spells one of the names in play (whose
|
||||
/// `Semantics` every later stage reads), and the rest — the container files
|
||||
/// §P2d counted, which are analysed for their index record alone and whose
|
||||
/// analysis is dropped unread. `merge` is `IndexBuilder::finish`, the sort and
|
||||
/// the whole-index merge, which is index work and not parse work.
|
||||
///
|
||||
/// `reused` is R3b's: records taken from the caller's known set instead of
|
||||
/// analysed. Zero for every caller that hands none.
|
||||
///
|
||||
/// The lead file is in `lead` and in neither `kept_files` nor `other_files` —
|
||||
/// it is always analysed and always kept, so counting it with either class
|
||||
/// would blur exactly the comparison this exists to make.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct IndexTrace {
|
||||
/// The request's own file, analysed before any other so the retention rule
|
||||
/// can read it.
|
||||
pub lead: Stage,
|
||||
/// The files the retention rule keeps, analysed.
|
||||
pub kept: Stage,
|
||||
/// The files it does not, analysed for the record alone.
|
||||
pub other: Stage,
|
||||
/// Records taken from the caller's known set — the lookup and the clone,
|
||||
/// with no parse in it.
|
||||
pub reused: Stage,
|
||||
/// How many files fell in each class, and their bytes.
|
||||
pub kept_files: usize,
|
||||
pub kept_bytes: usize,
|
||||
pub other_files: usize,
|
||||
pub other_bytes: usize,
|
||||
pub reused_files: usize,
|
||||
pub reused_bytes: usize,
|
||||
/// `IndexBuilder::finish`: the per-file records sorted and merged.
|
||||
pub merge: Stage,
|
||||
}
|
||||
|
||||
impl IndexTrace {
|
||||
/// One group of the trace line, in the order the build runs.
|
||||
fn line(&self) -> String {
|
||||
format!(
|
||||
"index{{lead={:.1}ms kept={:.1} other={:.1} reused={:.1} merge={:.1} \
|
||||
kept_files={} kept_bytes={} other_files={} other_bytes={} \
|
||||
reused_files={} reused_bytes={}}}",
|
||||
self.lead.ms,
|
||||
self.kept.ms,
|
||||
self.other.ms,
|
||||
self.reused.ms,
|
||||
self.merge.ms,
|
||||
self.kept_files,
|
||||
self.kept_bytes,
|
||||
self.other_files,
|
||||
self.other_bytes,
|
||||
self.reused_files,
|
||||
self.reused_bytes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the warning pass's time went, scan by scan.
|
||||
///
|
||||
/// The five scans of `rename::warnings`, in the order they run. Each is a
|
||||
/// whole pass over the in-scope files, so the split says which of them the
|
||||
/// stage's milliseconds are — `scanned` is how many files got past the
|
||||
/// `text.contains(name)` prefilter into a lex, which is the work the times are
|
||||
/// mostly made of.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct WarnTrace {
|
||||
/// The `` `define`` scan.
|
||||
pub defines: Stage,
|
||||
/// The macro-invocation-argument scan.
|
||||
pub macro_uses: Stage,
|
||||
/// The unstructured-SVA scan.
|
||||
pub sva: Stage,
|
||||
/// The unresolved-candidate scan.
|
||||
pub unfinished: Stage,
|
||||
/// The edited files' unaccounted-occurrence scan.
|
||||
pub unaccounted: Stage,
|
||||
/// Files whose text spelled the name, and which were therefore lexed.
|
||||
pub scanned: usize,
|
||||
}
|
||||
|
||||
impl WarnTrace {
|
||||
/// One group of the trace line, in the order the scans run.
|
||||
fn line(&self) -> String {
|
||||
format!(
|
||||
"warnings{{defines={:.1}ms macro_uses={:.1} sva={:.1} unfinished={:.1} \
|
||||
unaccounted={:.1} scanned={}}}",
|
||||
self.defines.ms,
|
||||
self.macro_uses.ms,
|
||||
self.sva.ms,
|
||||
self.unfinished.ms,
|
||||
self.unaccounted.ms,
|
||||
self.scanned,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the verification pass did, stage by stage.
|
||||
///
|
||||
/// The five sub-stages of [`crate::check`]'s `verify`, in the order it runs
|
||||
/// them. `checks` is the comments/attributes ledger and the parse-diagnostic
|
||||
/// comparison — zero for a rename, which runs neither (a rename may not change
|
||||
/// the token stream at all, which is a stronger statement than the ledger's).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct VerifyTrace {
|
||||
/// Token identity over every edited file, before against after.
|
||||
pub tokens: Stage,
|
||||
/// How many files the resolution check watches, and their total bytes.
|
||||
pub watched: usize,
|
||||
/// Bytes of those watched files.
|
||||
pub watched_bytes: usize,
|
||||
/// The pre-edit analysis of every watched file (cached ones are free).
|
||||
pub before: Stage,
|
||||
/// Building the index as it would be after the edits.
|
||||
pub rebuild: Stage,
|
||||
/// The post-edit analysis of every watched file, and the comparison.
|
||||
pub after: Stage,
|
||||
/// The ledger and parse-diagnostic checks a splice runs; zero for a
|
||||
/// rename.
|
||||
pub checks: Stage,
|
||||
}
|
||||
|
||||
/// Where one rename's work went: the input it was given, the time and parses
|
||||
/// of each stage, and what came out.
|
||||
///
|
||||
/// Filled by [`crate::rename_traced`] as it runs. Every field is written
|
||||
/// exactly once except the [`Stage`]s inside `verify`, which accumulate over
|
||||
/// their per-file loops.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct RenameTrace {
|
||||
/// Files handed to the engine, after the scope's own dedup.
|
||||
pub selected: usize,
|
||||
/// Their total bytes.
|
||||
pub bytes: usize,
|
||||
/// Building the request-local scope: the index over every selected file.
|
||||
pub index: Stage,
|
||||
/// Where that build's time went, by file class (review §3 item 1).
|
||||
pub indexing: IndexTrace,
|
||||
/// Resolving the cursor to the declaration the rename acts on.
|
||||
pub locate: Stage,
|
||||
/// Collecting every occurrence and turning it into edits.
|
||||
pub edits: Stage,
|
||||
/// The whole verification pass.
|
||||
pub verify: Stage,
|
||||
/// Its five sub-stages.
|
||||
pub checks: VerifyTrace,
|
||||
/// Describing the occurrences the rename deliberately left alone.
|
||||
pub warnings: Stage,
|
||||
/// Where that pass's time went, scan by scan (review §3 item 3).
|
||||
pub warning_scans: WarnTrace,
|
||||
/// Files the rename edits.
|
||||
pub edited: usize,
|
||||
/// Whole-file parses over the entire request, from the first byte of the
|
||||
/// scope build to the last warning.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl RenameTrace {
|
||||
/// One line, in the server's `timing:` style — the whole trace, in the
|
||||
/// order the stages ran.
|
||||
///
|
||||
/// The two per-stage splits come last, each as its own `name{…}` group, so
|
||||
/// a reader of the old fields sees exactly what it always did.
|
||||
pub fn line(&self) -> String {
|
||||
format!("{} {} {}", self.stages(), self.indexing.line(), self.warning_scans.line())
|
||||
}
|
||||
|
||||
/// The stage totals — the line as it was before the splits were added.
|
||||
fn stages(&self) -> String {
|
||||
format!(
|
||||
"selected={} bytes={} edited={} index={:.1}ms locate={:.1} edits={:.1} \
|
||||
verify{{total={:.1} tokens={:.1} watched={} watched_bytes={} before={:.1} \
|
||||
rebuild={:.1} after={:.1} checks={:.1}}} warnings={:.1} \
|
||||
parses={} parses{{index={} locate={} edits={} before={} rebuild={} after={}}}",
|
||||
self.selected,
|
||||
self.bytes,
|
||||
self.edited,
|
||||
self.index.ms,
|
||||
self.locate.ms,
|
||||
self.edits.ms,
|
||||
self.verify.ms,
|
||||
self.checks.tokens.ms,
|
||||
self.checks.watched,
|
||||
self.checks.watched_bytes,
|
||||
self.checks.before.ms,
|
||||
self.checks.rebuild.ms,
|
||||
self.checks.after.ms,
|
||||
self.checks.checks.ms,
|
||||
self.warnings.ms,
|
||||
self.parses,
|
||||
self.index.parses,
|
||||
self.locate.parses,
|
||||
self.edits.parses,
|
||||
self.checks.before.parses,
|
||||
self.checks.rebuild.parses,
|
||||
self.checks.after.parses,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,10 @@ use std::time::Instant;
|
||||
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
|
||||
use vlog_refactor::{
|
||||
add_port, convert_to_ansi, expand_wildcard, extract_module, instantiation_plan,
|
||||
module_definition, port_actions, prepare_rename, rename, Home, Layout, ModuleRef,
|
||||
module_definition, port_actions, prepare_rename, rename, rename_traced, rename_traced_with,
|
||||
Home, KnownFacts, Layout, ModuleRef, RenameTrace,
|
||||
};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
use vlog_semantic::{FileFacts, WorkspaceIndex};
|
||||
|
||||
fn corpus() -> Option<Vec<PathBuf>> {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
@@ -1181,3 +1182,122 @@ fn borne(
|
||||
}
|
||||
gained
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the known-facts door over real RTL (review round §R3b, TODO §61.5)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The corpus's own records, read once, answered back the way a correct
|
||||
/// caller answers: only for the exact bytes each record was read off.
|
||||
///
|
||||
/// The server's implementation is this answer taken out of a store keyed by
|
||||
/// content hash instead of computed here; what this stands in for is the
|
||||
/// promise, not the saving.
|
||||
struct CorpusFacts {
|
||||
known: Vec<(PathBuf, String, FileFacts)>,
|
||||
}
|
||||
|
||||
impl CorpusFacts {
|
||||
/// Every source's record, or every second one when `half` — so a run can
|
||||
/// build an index that is **part reused and part parsed**, which is the
|
||||
/// mixture a real rename gets.
|
||||
fn of(sources: &[(PathBuf, String)], half: bool) -> CorpusFacts {
|
||||
let known = sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !half || i % 2 == 0)
|
||||
.map(|(_, (path, text))| {
|
||||
(path.clone(), text.clone(), FileFacts::of(path.clone(), text))
|
||||
})
|
||||
.collect();
|
||||
CorpusFacts { known }
|
||||
}
|
||||
}
|
||||
|
||||
impl KnownFacts for CorpusFacts {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.known
|
||||
.iter()
|
||||
.find(|(held, bytes, _)| held == path && bytes == text)
|
||||
.map(|(_, _, facts)| facts.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// **The R3b corpus probe.** Over 800 files of real RTL, the same rename asked
|
||||
/// three ways — with no records, with every record, and with every second one
|
||||
/// — makes byte-identical edits and says byte-identical warnings, and the
|
||||
/// reuse removes parses.
|
||||
///
|
||||
/// `#[ignore]`d because it renames a corpus-wide module three times over; run
|
||||
/// it with `cargo test -p vlog_refactor --test corpus -- --ignored --nocapture`
|
||||
/// (through `tools/guard.sh`), which also prints the parse counts.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn a_corpus_rename_says_the_same_thing_however_many_records_are_reused() {
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
let Some((path, text)) =
|
||||
sources.iter().find(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv"))
|
||||
else {
|
||||
eprintln!("prim_fifo_sync.sv not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let offset =
|
||||
text.find("module prim_fifo_sync").map(|i| i + 7).expect("the module's name") as u32;
|
||||
|
||||
let mut plain = RenameTrace::default();
|
||||
let one = rename_traced(&sources, path, offset, "prim_fifo_sync_renamed", &mut plain);
|
||||
|
||||
let all = CorpusFacts::of(&sources, false);
|
||||
let mut every = RenameTrace::default();
|
||||
let two =
|
||||
rename_traced_with(&sources, path, offset, "prim_fifo_sync_renamed", &all, &mut every);
|
||||
|
||||
let half = CorpusFacts::of(&sources, true);
|
||||
let mut mixed = RenameTrace::default();
|
||||
let three =
|
||||
rename_traced_with(&sources, path, offset, "prim_fifo_sync_renamed", &half, &mut mixed);
|
||||
|
||||
println!(
|
||||
"corpus reuse over {} files: parses {} (none) / {} (every record) / {} (every second); \
|
||||
reused {} / {}; index {:.1} / {:.1} / {:.1} ms",
|
||||
sources.len(),
|
||||
plain.parses,
|
||||
every.parses,
|
||||
mixed.parses,
|
||||
every.indexing.reused_files,
|
||||
mixed.indexing.reused_files,
|
||||
plain.index.ms,
|
||||
every.index.ms,
|
||||
mixed.index.ms,
|
||||
);
|
||||
|
||||
let say = |outcome: &Result<vlog_refactor::RefactorEdit, String>| match outcome {
|
||||
Ok(edit) => {
|
||||
let mut out: Vec<String> = edit
|
||||
.edits
|
||||
.iter()
|
||||
.flat_map(|(p, edits)| {
|
||||
edits.iter().map(move |e| {
|
||||
format!("{} {}..{} {}", p.display(), e.range.start, e.range.end, e.new_text)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
out.extend(edit.warnings.iter().cloned());
|
||||
out.join("\n")
|
||||
}
|
||||
Err(message) => format!("refused: {message}"),
|
||||
};
|
||||
assert_eq!(say(&one), say(&two), "reusing every record changed an edit or a warning");
|
||||
assert_eq!(say(&one), say(&three), "reusing half the records changed an edit or a warning");
|
||||
|
||||
assert_eq!(every.indexing.reused_files, sources.len(), "every record was offered and taken");
|
||||
assert!(mixed.indexing.reused_files > 0, "and half of them in the mixed run");
|
||||
assert!(
|
||||
every.parses < plain.parses,
|
||||
"the reuse must remove parses: {} against {}",
|
||||
every.parses,
|
||||
plain.parses
|
||||
);
|
||||
assert!(mixed.parses < plain.parses, "and so must the mixture");
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The organize-imports offer promises exactly what the refactoring delivers.
|
||||
//!
|
||||
//! Take 5 §P1c (`docs/features/perf5-p1/README.md`) added
|
||||
//! [`vlog_refactor::organize_offer`], which answers the two counts a code
|
||||
//! action's title carries without rendering a verified edit. This file is the
|
||||
//! proof that its answer — the counts *and* the refusal sentence — is
|
||||
//! [`vlog_refactor::organize_counts`]'s answer at **every byte offset** of
|
||||
//! every fixture, and that the only thing it does not reproduce is
|
||||
//! `check::verify_splice`, which no fixture here reaches.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_refactor::{organize_counts, organize_offer, organize_offer_in, organize_title};
|
||||
|
||||
/// A module importing two packages, one of them unused and written first, so
|
||||
/// there is both a removal and a sort to promise.
|
||||
const USER: &str = "\
|
||||
module user (
|
||||
input logic clk_i
|
||||
);
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// Imports already sorted with every one used: the refusal that is not an
|
||||
/// error, and the one a lightbulb must not appear for.
|
||||
const TIDY: &str = "\
|
||||
module tidy;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A duplicate import and a commented one, which is the shape that produces a
|
||||
/// warning instead of a deletion.
|
||||
const COMMENTED: &str = "\
|
||||
module commented;
|
||||
import a_pkg::*;
|
||||
// why this one is here
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// An import of a package nothing in scope declares — the conservative
|
||||
/// silence, which the offer must keep.
|
||||
const UNKNOWN: &str = "\
|
||||
module unknown;
|
||||
import nowhere_pkg::*;
|
||||
import a_pkg::*;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A compilation-unit import run above a module, and a package with its own.
|
||||
const FILE_SCOPE: &str = "\
|
||||
import b_pkg::*;
|
||||
import a_pkg::*;
|
||||
package inner_pkg;
|
||||
import a_pkg::*;
|
||||
localparam int K = A_ONE;
|
||||
endpackage
|
||||
module uses;
|
||||
logic q;
|
||||
assign q = A_ONE;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A buffer that does not parse: refused by both, with the same sentence.
|
||||
const BROKEN: &str = "\
|
||||
module broken;
|
||||
import a_pkg::*;
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
const A_PKG: &str = "\
|
||||
package a_pkg;
|
||||
localparam int A_ONE = 1;
|
||||
endpackage
|
||||
";
|
||||
|
||||
const B_PKG: &str = "\
|
||||
package b_pkg;
|
||||
localparam int B_ONE = 2;
|
||||
endpackage
|
||||
";
|
||||
|
||||
fn file(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
fn workspace(name: &str, text: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![
|
||||
(file(name), text.to_string()),
|
||||
(file("a_pkg.sv"), A_PKG.to_string()),
|
||||
(file("b_pkg.sv"), B_PKG.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// The counts the refactoring promises, without its edit.
|
||||
fn eager(files: &[(PathBuf, String)], path: &Path, offset: u32) -> Result<(usize, usize), String> {
|
||||
organize_counts(files, path, offset).map(|(_, removed, sorted)| (removed, sorted))
|
||||
}
|
||||
|
||||
fn agree_everywhere(name: &str, text: &str) {
|
||||
let files = workspace(name, text);
|
||||
let path = file(name);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
eager(&files, &path, offset),
|
||||
organize_offer(&files, &path, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_promises_what_the_refactoring_delivers_at_every_offset() {
|
||||
agree_everywhere("user.sv", USER);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_tidy_run_is_refused_by_both_with_the_same_sentence() {
|
||||
agree_everywhere("tidy.sv", TIDY);
|
||||
let files = workspace("tidy.sv", TIDY);
|
||||
let at = TIDY.find("import a_pkg").expect("the import") as u32;
|
||||
assert_eq!(
|
||||
organize_offer(&files, &file("tidy.sv"), at),
|
||||
Err("these imports are already sorted, and every one of them is used.".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commented_import_counts_the_same_in_both_answers() {
|
||||
agree_everywhere("commented.sv", COMMENTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_package_silences_both_answers() {
|
||||
agree_everywhere("unknown.sv", UNKNOWN);
|
||||
let files = workspace("unknown.sv", UNKNOWN);
|
||||
let at = UNKNOWN.find("import nowhere_pkg").expect("the import") as u32;
|
||||
assert!(organize_offer(&files, &file("unknown.sv"), at).is_err(), "the offer stays silent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_run_and_a_package_run_agree_at_every_offset() {
|
||||
agree_everywhere("file_scope.sv", FILE_SCOPE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_is_refused_by_both() {
|
||||
agree_everywhere("broken.sv", BROKEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_agrees_over_crlf_line_endings() {
|
||||
agree_everywhere("user.sv", &crlf(USER));
|
||||
agree_everywhere("commented.sv", &crlf(COMMENTED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_answers_what_the_text_form_answers_at_every_offset() {
|
||||
for (name, text) in [("user.sv", USER), ("commented.sv", COMMENTED), ("broken.sv", BROKEN)] {
|
||||
let files = workspace(name, text);
|
||||
let path = file(name);
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let tokens = tokenize(text).expect("the fixture lexes");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
organize_offer(&files, &path, offset),
|
||||
organize_offer_in(&files, &path, &tree, &diagnostics, &semantics, &tokens, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixtures really do reach an offer — a parity suite over an action that
|
||||
/// is never offered proves nothing.
|
||||
#[test]
|
||||
fn the_fixture_really_is_offered_the_action_with_the_title_it_promises() {
|
||||
let files = workspace("user.sv", USER);
|
||||
let at = USER.find("import b_pkg").expect("the import") as u32;
|
||||
let (removed, sorted) = organize_offer(&files, &file("user.sv"), at).expect("an offer");
|
||||
assert_eq!((removed, sorted), (1, 1), "one unused import goes and one is written back");
|
||||
assert_eq!(organize_title(removed, sorted), "lucisv: organize imports (removes 1, sorts 1)");
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! The four cheap gates answer the same thing over a parse the caller already
|
||||
//! has as they do over the text they would parse themselves.
|
||||
//!
|
||||
//! Take 5 §P1b (`docs/features/perf5-p1/README.md`) added `*_in` forms of
|
||||
//! `port_action_modules`, `imported_packages`, `extract_site` and
|
||||
//! `inline_site` so a server can spend the parse it already made. The text
|
||||
//! forms stayed and became wrappers, and this file is the proof that the two
|
||||
//! agree — over clean buffers, over buffers that do not parse, over CRLF, over
|
||||
//! text with a non-BMP character in front of the cursor, and at every byte of
|
||||
//! a small buffer rather than at a cursor chosen to pass.
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_refactor::{
|
||||
extract_site, extract_site_in, imported_packages, imported_packages_in, inline_site,
|
||||
inline_site_in, port_action_modules, port_action_modules_in,
|
||||
};
|
||||
|
||||
/// A module that instantiates another, imports two packages, and has items
|
||||
/// worth extracting — so every one of the four gates has something to find
|
||||
/// somewhere in it.
|
||||
const CLEAN: &str = "\
|
||||
module m (
|
||||
input logic clk_i,
|
||||
output logic q_o
|
||||
);
|
||||
import a_pkg::*;
|
||||
import b_pkg::*;
|
||||
logic w;
|
||||
sub u_sub (.a(clk_i), .b(w));
|
||||
assign q_o = w;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The same text with a construct the parser cannot recover into an item, so
|
||||
/// the tolerant parse reports diagnostics — the case three of the four gates
|
||||
/// refuse over.
|
||||
const BROKEN: &str = "\
|
||||
module m;
|
||||
sub u_sub (.a(1));
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A Verilog-2001 header, which is the one shape `convert to ANSI` answers at
|
||||
/// and the one `port_action_modules` finds without an instantiation.
|
||||
const NON_ANSI: &str = "\
|
||||
module old (a, b);
|
||||
input a;
|
||||
output b;
|
||||
assign b = a;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A non-BMP character in a comment before everything else: the bytes before
|
||||
/// every cursor differ from the UTF-16 units, which is the shape a client's
|
||||
/// position conversion produces.
|
||||
const ASTRAL: &str = "\
|
||||
// \u{1F600} a comment
|
||||
module m;
|
||||
sub u_sub (.a(1));
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// Every gate, both ways, at one offset — asserting the two agree.
|
||||
fn agree_at(text: &str, offset: u32) {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
assert_eq!(
|
||||
port_action_modules(text, offset),
|
||||
port_action_modules_in(&tree, offset),
|
||||
"port_action_modules at {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
imported_packages(text, offset),
|
||||
imported_packages_in(&tree, &diagnostics, text, offset),
|
||||
"imported_packages at {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
inline_site(text, offset),
|
||||
inline_site_in(&tree, &diagnostics, text, offset),
|
||||
"inline_site at {offset}"
|
||||
);
|
||||
// Extraction answers for a range: the empty one at the cursor (which is
|
||||
// what an editor sends on a cursor move) and one covering the rest of the
|
||||
// buffer.
|
||||
let end = text.len() as u32;
|
||||
assert_eq!(
|
||||
extract_site(text, offset, offset),
|
||||
extract_site_in(&tree, &diagnostics, text, offset, offset),
|
||||
"extract_site at the cursor {offset}"
|
||||
);
|
||||
assert_eq!(
|
||||
extract_site(text, offset, end),
|
||||
extract_site_in(&tree, &diagnostics, text, offset, end),
|
||||
"extract_site over {offset}..{end}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every byte offset of a buffer, and one past its end.
|
||||
fn agree_everywhere(text: &str) {
|
||||
for offset in 0..=text.len() as u32 {
|
||||
agree_at(text, offset);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_answer_a_clean_buffer_exactly_as_the_text_gates_do() {
|
||||
agree_everywhere(CLEAN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_answer_a_buffer_that_does_not_parse_exactly_as_the_text_gates_do() {
|
||||
agree_everywhere(BROKEN);
|
||||
// And the three that refuse over diagnostics really do refuse here, so
|
||||
// this case is not agreeing by both answering about a clean buffer.
|
||||
let (tree, diagnostics) = parse_source_tolerant(BROKEN);
|
||||
assert!(!diagnostics.is_empty(), "the fixture must not parse cleanly");
|
||||
let cursor = BROKEN.find("u_sub").expect("the instance") as u32;
|
||||
assert!(imported_packages_in(&tree, &diagnostics, BROKEN, cursor).is_empty());
|
||||
assert!(inline_site_in(&tree, &diagnostics, BROKEN, cursor).is_none());
|
||||
assert!(extract_site_in(&tree, &diagnostics, BROKEN, cursor, cursor).is_none());
|
||||
// The port gate has no diagnostics check and never had one: it still finds
|
||||
// the instantiation under the cursor.
|
||||
assert_eq!(port_action_modules_in(&tree, cursor), vec!["sub".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_over_crlf_line_endings() {
|
||||
agree_everywhere(&crlf(CLEAN));
|
||||
agree_everywhere(&crlf(BROKEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_with_a_non_bmp_character_before_the_cursor() {
|
||||
agree_everywhere(ASTRAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_on_a_non_ansi_header() {
|
||||
agree_everywhere(NON_ANSI);
|
||||
// Again, not vacuously: the header cursor really does name its module.
|
||||
let (tree, _) = parse_source_tolerant(NON_ANSI);
|
||||
let cursor = NON_ANSI.find("(a, b)").expect("the header") as u32;
|
||||
assert_eq!(port_action_modules_in(&tree, cursor), vec!["old".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_agree_on_an_empty_buffer() {
|
||||
agree_everywhere("");
|
||||
agree_everywhere("\n\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_gates_find_what_the_fixture_was_written_to_offer() {
|
||||
// A guard on the fixture itself: if `CLEAN` stopped offering anything,
|
||||
// every assertion above would still pass and prove nothing.
|
||||
let (tree, diagnostics) = parse_source_tolerant(CLEAN);
|
||||
let import = CLEAN.find("import a_pkg").expect("the import run") as u32;
|
||||
assert_eq!(
|
||||
imported_packages_in(&tree, &diagnostics, CLEAN, import),
|
||||
vec!["a_pkg".to_string(), "b_pkg".to_string()]
|
||||
);
|
||||
let instance = CLEAN.find("u_sub").expect("the instance") as u32;
|
||||
assert_eq!(port_action_modules_in(&tree, instance), vec!["sub".to_string()]);
|
||||
assert!(inline_site_in(&tree, &diagnostics, CLEAN, instance).is_some());
|
||||
let assign = CLEAN.find("assign q_o").expect("the assign") as u32;
|
||||
assert!(extract_site_in(&tree, &diagnostics, CLEAN, assign, assign).is_some());
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! The offer predicate answers exactly what the four full refactorings answer.
|
||||
//!
|
||||
//! Take 5 §P1c (`docs/features/perf5-p1/README.md`) added
|
||||
//! [`vlog_refactor::port_offers`], which asks each of the four port
|
||||
//! refactorings its plan-time questions and writes the title it would carry —
|
||||
//! no workspace index, no verification, no edits kept. This file is the proof
|
||||
//! that the menu it writes is the menu [`vlog_refactor::port_actions`] writes,
|
||||
//! at **every byte offset** of every fixture, not at cursors chosen to pass.
|
||||
//!
|
||||
//! Where the two may legitimately differ is stated in `ports::offer`'s own
|
||||
//! documentation: `check::verify_splice` and `ports::confirm` run after the
|
||||
//! plan and the predicate does not reproduce them. Every fixture below is
|
||||
//! asserted to be free of that difference, so a change that starts producing
|
||||
//! one fails here rather than reaching a user's lightbulb.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_refactor::{port_actions, port_offers, port_offers_in, PortOfferKind};
|
||||
|
||||
/// A module with a port its body never mentions (so the removal is offered),
|
||||
/// written the ANSI way, instantiating another module by name.
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic clk_i,
|
||||
input logic spare_i,
|
||||
output logic q_o
|
||||
);
|
||||
logic w;
|
||||
logic b;
|
||||
sub u_sub (.a(clk_i));
|
||||
sub u_star (.*);
|
||||
assign q_o = w;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The module `top` instantiates: two ports, so the instantiation above is
|
||||
/// missing one and the `.*` stands for both.
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
input logic b
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A Verilog-2001 header — the one shape `convert to ANSI` answers at.
|
||||
const OLD: &str = "\
|
||||
module old (a, b);
|
||||
input a;
|
||||
output b;
|
||||
assign b = a;
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// An instantiation connecting by position, a `bind` directive's own, and a
|
||||
/// second `.*`: three of the shapes the planners refuse over.
|
||||
const AWKWARD: &str = "\
|
||||
module awkward;
|
||||
logic a;
|
||||
logic b;
|
||||
sub u_ordered (a, b);
|
||||
sub u_two (.a(a), .b(b));
|
||||
bind awkward sub u_bound (.*);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A module nested inside another and one inside a package: neither is a
|
||||
/// *unit*, so `locate_module` refuses over both and so must the predicate.
|
||||
const NESTED: &str = "\
|
||||
package p;
|
||||
module inner (input logic a);
|
||||
endmodule
|
||||
endpackage
|
||||
module outer (input logic a);
|
||||
module deep (input logic b);
|
||||
endmodule
|
||||
sub u_sub (.a(a));
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A file that does not parse cleanly: the expansion and the conversion refuse
|
||||
/// over it, the removal and the propagation do not.
|
||||
const BROKEN: &str = "\
|
||||
module m (input logic a);
|
||||
sub u_sub (.a(a));
|
||||
logic ;;; w
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A second declaration of `sub`, which makes the name ambiguous and every
|
||||
/// refactoring that has to look it up silent.
|
||||
const TWIN: &str = "\
|
||||
module sub (
|
||||
input logic a
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn file(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
fn workspace(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
entries.iter().map(|(name, text)| (file(name), (*text).to_string())).collect()
|
||||
}
|
||||
|
||||
fn crlf(text: &str) -> String {
|
||||
text.replace('\n', "\r\n")
|
||||
}
|
||||
|
||||
/// The eager menu and the offered menu at one offset, as comparable lists.
|
||||
fn agree_at(files: &[(PathBuf, String)], path: &Path, offset: u32) {
|
||||
let eager: Vec<String> =
|
||||
port_actions(files, path, offset).into_iter().map(|a| a.title).collect();
|
||||
let offered: Vec<String> =
|
||||
port_offers(files, path, offset).into_iter().map(|o| o.title).collect();
|
||||
assert_eq!(eager, offered, "at offset {offset} of {}", path.display());
|
||||
}
|
||||
|
||||
/// Every byte of one file of a workspace, the end included.
|
||||
fn agree_everywhere(files: &[(PathBuf, String)], name: &str) {
|
||||
let path = file(name);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
agree_at(files, &path, offset);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_at_every_offset_of_an_ansi_module() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
agree_everywhere(&files, "sub.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_at_every_offset_of_a_non_ansi_header() {
|
||||
let files = workspace(&[("old.sv", OLD), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "old.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_over_the_shapes_the_planners_refuse() {
|
||||
let files = workspace(&[("awkward.sv", AWKWARD), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "awkward.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_module_is_no_more_a_unit_to_the_offer_than_to_the_index() {
|
||||
let files = workspace(&[("nested.sv", NESTED), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "nested.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_on_a_buffer_that_does_not_parse() {
|
||||
let files = workspace(&[("broken.sv", BROKEN), ("sub.sv", SUB)]);
|
||||
agree_everywhere(&files, "broken.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_two_files_declare_is_silent_in_both_answers() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB), ("twin.sv", TWIN)]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
// And the ambiguity really is what silences it: the same cursor offers
|
||||
// with only one declaration in scope.
|
||||
let one = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32;
|
||||
assert!(!port_offers(&one, &file("top.sv"), at).is_empty(), "one declaration offers");
|
||||
assert!(port_offers(&files, &file("top.sv"), at).is_empty(), "two declarations do not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_matches_the_eager_menu_over_crlf_line_endings() {
|
||||
let files = workspace(&[("top.sv", &crlf(TOP)), ("sub.sv", &crlf(SUB))]);
|
||||
agree_everywhere(&files, "top.sv");
|
||||
let files = workspace(&[("old.sv", &crlf(OLD)), ("sub.sv", &crlf(SUB))]);
|
||||
agree_everywhere(&files, "old.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_is_empty_for_a_file_the_workspace_does_not_hold() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB)]);
|
||||
assert!(port_offers(&files, &file("absent.sv"), 0).is_empty());
|
||||
assert!(port_actions(&files, &file("absent.sv"), 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parsed_form_answers_what_the_text_form_answers_at_every_offset() {
|
||||
let files = workspace(&[("top.sv", TOP), ("sub.sv", SUB), ("old.sv", OLD)]);
|
||||
for name in ["top.sv", "old.sv"] {
|
||||
let path = file(name);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
let (tree, diagnostics) = parse_source_tolerant(&text);
|
||||
let semantics = vlog_semantic::analyze(&tree, &text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
assert_eq!(
|
||||
port_offers(&files, &path, offset),
|
||||
port_offers_in(&files, &path, &tree, &diagnostics, &semantics, offset),
|
||||
"at offset {offset} of {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each of the four really is reached by one of the fixtures — a parity suite
|
||||
/// over four refactorings none of which ever offers proves nothing.
|
||||
#[test]
|
||||
fn every_one_of_the_four_refactorings_is_offered_somewhere_in_the_fixtures() {
|
||||
let mut seen: Vec<PortOfferKind> = Vec::new();
|
||||
for (entries, name) in [
|
||||
(workspace(&[("top.sv", TOP), ("sub.sv", SUB)]), "top.sv"),
|
||||
(workspace(&[("old.sv", OLD), ("sub.sv", SUB)]), "old.sv"),
|
||||
] {
|
||||
let path = file(name);
|
||||
let text = entries
|
||||
.iter()
|
||||
.find(|(held, _)| *held == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
for offer in port_offers(&entries, &path, offset) {
|
||||
if !seen.contains(&offer.kind) {
|
||||
seen.push(offer.kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for wanted in [
|
||||
PortOfferKind::Remove,
|
||||
PortOfferKind::Propagate,
|
||||
PortOfferKind::Expand,
|
||||
PortOfferKind::Convert,
|
||||
] {
|
||||
assert!(seen.contains(&wanted), "{wanted:?} is never offered: {seen:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
//! `rename_preflight` against the road it short-circuits, refusal by refusal.
|
||||
//!
|
||||
//! The preflight answers, from the request file alone, a question `rename`
|
||||
//! would otherwise answer after parsing and analyzing the whole in-scope
|
||||
//! workspace. That is only sound if the two answers are the *same sentence*,
|
||||
//! so this file is the equality oracle: at **every byte** of seven hostile
|
||||
//! buffers, and for every new name worth trying, the fast road's refusal must
|
||||
//! be the slow road's refusal, word for word.
|
||||
//!
|
||||
//! Two directions, and only one of them is allowed:
|
||||
//!
|
||||
//! * the preflight refuses and the whole road refuses **differently**, or
|
||||
//! accepts — an *invented* refusal, which is a rename the user cannot get.
|
||||
//! Always a failure.
|
||||
//! * the preflight says `Ok(())` and the whole road refuses — a *deferral*,
|
||||
//! which is the normal case for everything the request file cannot settle.
|
||||
//! Counted, never asserted away, and asserted to be non-zero where the
|
||||
//! fixture is built to produce one.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_refactor::{rename, rename_name_at, rename_preflight};
|
||||
use vlog_semantic::analyze;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
const SUB: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
|
||||
const TOP: &str = "module top;\n logic c, d;\n sub #(.W(2)) u_sub (.clk(c), .q(d));\n sub u_two (.clk(c), .q(d));\nendmodule\n";
|
||||
const PKG: &str =
|
||||
"package cfg_pkg;\n parameter int DEPTH = 4;\n typedef logic [1:0] mode_t;\nendpackage\n";
|
||||
const USER: &str = "module user;\n import cfg_pkg::*;\n cfg_pkg::mode_t m;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
|
||||
/// A name that resolves to nothing, and one that could only come from a base
|
||||
/// class nothing in the workspace declares.
|
||||
const STRAY: &str = "class kid extends absent_base;\n function void go();\n inherited_thing = 1;\n endfunction\nendclass\nmodule holder;\n missing u_missing (.a(b));\nendmodule\n";
|
||||
/// Macro invocations, a generate block and a genvar.
|
||||
const GEN: &str = "`define BUMP(x) x + 1\n`define WIDTH 8\nmodule gen_holder;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_lane (.clk(1'b0), .q());\n end\n endgenerate\n wire [`WIDTH-1:0] w;\n assign w = `BUMP(sub);\nendmodule\n";
|
||||
/// Every byte a cursor can sit on that is *not* a symbol: line comments,
|
||||
/// block comments, a string literal, a system task, an attribute, and — for
|
||||
/// the offsets in between — punctuation and whitespace.
|
||||
const PROSE: &str = "// a leading line comment naming clk and sub\n/* a block comment\n naming local_net too */\nmodule prose;\n // clk here is prose\n logic clk;\n initial begin\n $display(\"clk and sub and local_net, all in a string\");\n end\n (* keep = \"true\" *)\n wire tagged_net;\nendmodule\n";
|
||||
const BROKEN: &str = "module broken (input logic clk;\n wire a\n assign a = clk\nendmodule\n";
|
||||
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from(name), (*text).to_string())).collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// The rename oracle
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/// Ask both roads the same rename at every byte of `file`, for every new name
|
||||
/// worth asking about there, and return `(refused, deferred)`.
|
||||
///
|
||||
/// The new names are the four `check_new_name` shapes plus two that can only
|
||||
/// be judged after the cursor is resolved: a novel valid name, and **the name
|
||||
/// the cursor already spells**, which is the one way to reach the "is the name
|
||||
/// it already has" refusal at an arbitrary offset.
|
||||
fn rename_oracle(files: &[(&str, &str)], file: &str) -> (usize, usize) {
|
||||
let sources = workspace(files);
|
||||
let path = PathBuf::from(file);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(name, _)| *name == file)
|
||||
.map(|(_, text)| *text)
|
||||
.expect("the file is in the workspace");
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
|
||||
let (mut refused, mut deferred) = (0usize, 0usize);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let here = rename_name_at(&semantics, offset);
|
||||
let mut names: Vec<&str> = vec!["", "module", "1bad", "has space", "renamed_thing"];
|
||||
if let Some(name) = &here {
|
||||
names.push(name.as_str());
|
||||
}
|
||||
for new_name in names {
|
||||
let fast = rename_preflight(&semantics, offset, new_name);
|
||||
let slow = rename(&sources, &path, offset, new_name);
|
||||
match (&fast, &slow) {
|
||||
(Err(fast), Err(slow)) => {
|
||||
assert_eq!(
|
||||
fast, slow,
|
||||
"byte {offset} of {file} renamed to {new_name:?}: \
|
||||
the preflight and the workspace refuse in different words"
|
||||
);
|
||||
refused += 1;
|
||||
}
|
||||
(Err(fast), Ok(_)) => panic!(
|
||||
"byte {offset} of {file} renamed to {new_name:?}: the preflight \
|
||||
invented the refusal {fast:?} for a rename the workspace performs"
|
||||
),
|
||||
// The preflight stood aside. Whatever the workspace then says
|
||||
// is today's answer, unchanged — which is the whole contract.
|
||||
(Ok(()), Err(_)) => deferred += 1,
|
||||
(Ok(()), Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
(refused, deferred)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preflight_refuses_a_rename_exactly_as_the_workspace_does() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP)];
|
||||
let (refused, _) = rename_oracle(&files, "top.sv");
|
||||
assert!(refused > 0, "the sweep must actually reach the preflight's refusals");
|
||||
rename_oracle(&files, "sub.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_prose_is_refused_from_the_buffer_alone() {
|
||||
// Comments, a string literal, a system task and an attribute: the whole
|
||||
// "there is no symbol to rename at this position" family, which is the
|
||||
// 2,192 ms refusal this preflight exists for.
|
||||
let files = [("prose.sv", PROSE), ("sub.sv", SUB), ("top.sv", TOP)];
|
||||
let (refused, _) = rename_oracle(&files, "prose.sv");
|
||||
assert!(refused > 0);
|
||||
|
||||
// And named exactly, so a reworded refusal cannot hide inside the sweep.
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("prose.sv");
|
||||
let semantics = analyze(&parse_source_tolerant(PROSE).0, PROSE);
|
||||
for (what, at) in [
|
||||
("a line comment", PROSE.find("a leading line").expect("the comment")),
|
||||
("a block comment", PROSE.find("naming local_net").expect("the comment")),
|
||||
("a string literal", PROSE.find("all in a string").expect("the string")),
|
||||
] {
|
||||
let at = at as u32;
|
||||
let fast = rename_preflight(&semantics, at, "renamed_thing").expect_err(what);
|
||||
assert_eq!(fast, "there is no symbol to rename at this position.", "{what}");
|
||||
assert_eq!(fast, rename(&sources, &path, at, "renamed_thing").expect_err(what), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unresolved_and_an_inherited_reference_keep_their_own_sentences() {
|
||||
let files = [("stray.sv", STRAY), ("sub.sv", SUB)];
|
||||
rename_oracle(&files, "stray.sv");
|
||||
|
||||
// Which byte carries which refusal is the binder's business, so the
|
||||
// fixture is swept for the two sentences rather than told where they are —
|
||||
// and both must be found, or the fixture has stopped exercising them.
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("stray.sv");
|
||||
let semantics = analyze(&parse_source_tolerant(STRAY).0, STRAY);
|
||||
let (mut unresolved, mut inherited) = (0usize, 0usize);
|
||||
for at in 0..=STRAY.len() as u32 {
|
||||
let Err(fast) = rename_preflight(&semantics, at, "renamed_thing") else { continue };
|
||||
if fast.contains("is not resolved to any declaration") {
|
||||
unresolved += 1;
|
||||
} else if fast.contains("could only come from the base class") {
|
||||
inherited += 1;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
let slow = rename(&sources, &path, at, "renamed_thing").expect_err("the same refusal");
|
||||
assert_eq!(fast, slow, "at byte {at} of stray.sv");
|
||||
}
|
||||
assert!(unresolved > 0, "the fixture no longer holds a reference that resolves to nothing");
|
||||
assert!(inherited > 0, "the fixture no longer holds an inherited candidate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_invocation_and_a_generate_block_keep_parity() {
|
||||
rename_oracle(&[("gen.sv", GEN), ("sub.sv", SUB)], "gen.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_keeps_parity() {
|
||||
rename_oracle(&[("broken.sv", BROKEN), ("sub.sv", SUB)], "broken.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_and_its_qualified_users_keep_parity() {
|
||||
let files = [("pkg.sv", PKG), ("user.sv", USER)];
|
||||
rename_oracle(&files, "user.sv");
|
||||
rename_oracle(&files, "pkg.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_in_two_files_stays_on_the_slow_road() {
|
||||
// Two modules called `sub`. The ambiguity is the *index's* answer, and the
|
||||
// index is rebuilt on save, never on a keystroke — so the preflight must
|
||||
// not take this refusal, and the sweep must show it deferring instead.
|
||||
let files = [("a.sv", SUB), ("b.sv", SUB), ("top.sv", TOP)];
|
||||
let (_, deferred) = rename_oracle(&files, "top.sv");
|
||||
assert!(deferred > 0, "the ambiguous declaration must reach the workspace to be refused");
|
||||
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
assert!(
|
||||
rename_preflight(&semantics, at, "renamed_thing").is_ok(),
|
||||
"the preflight must stand aside for a name the index answers ambiguously"
|
||||
);
|
||||
assert!(rename(&sources, &path, at, "renamed_thing").is_err(), "and the workspace refuses it");
|
||||
}
|
||||
|
||||
/// TODO §63.1 QA. A `bind`'s connection expressions resolve in the *target's*
|
||||
/// scope, which a single buffer never holds — so both shapes must defer, and
|
||||
/// the fixture is swept to prove neither is ever an *invented* refusal.
|
||||
const AES_FOR_BIND: &str = "module aes (input logic clk_i, output logic idle_o);\n \
|
||||
logic entropy_masking_req;\n aes_core u_aes_core (.clk_i(clk_i));\n \
|
||||
assign idle_o = entropy_masking_req;\nendmodule : aes\n";
|
||||
const AES_CORE_FOR_BIND: &str =
|
||||
"module aes_core (input logic clk_i);\n logic seed_en;\n assign seed_en = clk_i;\nendmodule : aes_core\n";
|
||||
const RESEED_IF_FOR_BIND: &str =
|
||||
"module aes_reseed_if (input logic entropy_masking_req, input logic seed_en);\nendmodule : aes_reseed_if\n";
|
||||
const AES_BIND: &str = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \
|
||||
.entropy_masking_req(entropy_masking_req),\n .seed_en(u_aes_core.seed_en)\n );\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_binds_connection_expressions_defer_rather_than_invent_a_refusal() {
|
||||
// Before this lane a bare-name connection carried a one-segment external
|
||||
// candidate (deferred already) but a hierarchical tail carried *no*
|
||||
// reference at all — `symbol_at` finds no declaration either, so the
|
||||
// preflight fell to `NOTHING_HERE`, a refusal the workspace does not
|
||||
// agree with (it resolves and edits the tail). The oracle's own
|
||||
// `(Err, Ok)` branch panics on exactly that shape, so a plain sweep is the
|
||||
// proof: nothing here may ever be an invented refusal.
|
||||
let files = [
|
||||
("aes.sv", AES_FOR_BIND),
|
||||
("aes_core.sv", AES_CORE_FOR_BIND),
|
||||
("aes_reseed_if.sv", RESEED_IF_FOR_BIND),
|
||||
("aes_bind.sv", AES_BIND),
|
||||
];
|
||||
let (_, deferred) = rename_oracle(&files, "aes_bind.sv");
|
||||
assert!(deferred > 0, "every connection expression in a bind file defers to the workspace");
|
||||
|
||||
// And named exactly, at the hierarchical tail's own byte: this is the one
|
||||
// Handshakes calls out as changed — `NOTHING_HERE` before, `Ok(())` now.
|
||||
let semantics = analyze(&parse_source_tolerant(AES_BIND).0, AES_BIND);
|
||||
let at =
|
||||
AES_BIND.find("u_aes_core.seed_en").expect("the tail") as u32 + "u_aes_core.".len() as u32;
|
||||
assert!(
|
||||
rename_preflight(&semantics, at, "renamed_thing").is_ok(),
|
||||
"the preflight must stand aside for a bind's hierarchical tail, which only the \
|
||||
workspace can root at the bind target"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_symbol_to_the_name_it_already_has_is_refused_from_the_buffer() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP)];
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("sub.sv");
|
||||
let semantics = analyze(&parse_source_tolerant(SUB).0, SUB);
|
||||
// `local_net` is a declaration inside the module — not at file scope, so
|
||||
// no index question stands between the cursor and this refusal.
|
||||
let at = SUB.find("local_net").expect("the declaration") as u32;
|
||||
let fast = rename_preflight(&semantics, at, "local_net").expect_err("the same name");
|
||||
assert_eq!(fast, "`local_net` is the name it already has.");
|
||||
assert_eq!(fast, rename(&sources, &path, at, "local_net").expect_err("the same name"));
|
||||
|
||||
// A file-scope unit's same-name refusal is the index's to reach, because
|
||||
// the ambiguity check comes first.
|
||||
let at = SUB.find("sub").expect("the module name") as u32;
|
||||
assert!(rename_preflight(&semantics, at, "sub").is_ok(), "deferred, not taken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_new_name_outranks_every_cursor_refusal() {
|
||||
// Precedence: `renaming` checks the new name before it builds a scope and
|
||||
// before it looks at the cursor, so a bad name on a cursor that sits on
|
||||
// nothing must produce the *name's* sentence, not the cursor's.
|
||||
let files = [("prose.sv", PROSE), ("sub.sv", SUB)];
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("prose.sv");
|
||||
let semantics = analyze(&parse_source_tolerant(PROSE).0, PROSE);
|
||||
let at = PROSE.find("a leading line").expect("the comment") as u32;
|
||||
for (name, expected) in [
|
||||
("", "a new name cannot be empty."),
|
||||
("module", "`module` is a Verilog keyword."),
|
||||
("1bad", "`1bad` is not a valid Verilog identifier."),
|
||||
] {
|
||||
let fast = rename_preflight(&semantics, at, name).expect_err(name);
|
||||
assert_eq!(fast, expected, "{name}");
|
||||
assert_eq!(fast, rename(&sources, &path, at, name).expect_err(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preflight_reads_only_the_buffer_it_was_given() {
|
||||
// The proof behind the gate: resolving a cursor that sits on nothing costs
|
||||
// no whole-file parse at all, however large the workspace around it.
|
||||
let semantics = analyze(&parse_source_tolerant(PROSE).0, PROSE);
|
||||
let at = PROSE.find("a leading line").expect("the comment") as u32;
|
||||
let before = vlog_parser::stats::parses();
|
||||
let refusal = rename_preflight(&semantics, at, "renamed_thing").expect_err("no symbol");
|
||||
assert_eq!(vlog_parser::stats::parses() - before, 0, "the preflight parsed something");
|
||||
assert_eq!(refusal, "there is no symbol to rename at this position.");
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
//! A `bind` directive's own occurrences of a renamed name (TODO §63.1).
|
||||
//!
|
||||
//! `bind aes aes_reseed_if u_x (.entropy_masking_req(entropy_masking_req));`
|
||||
//! writes the target module's internal net down in a file that instantiates
|
||||
//! nothing in the chain. IEEE 1800 §23.11 evaluates such a connection in the
|
||||
//! **target's** scope, so the name is a use of `aes`'s net and a rename must
|
||||
//! edit it — or say out loud that it could not. Silence is a wrong answer: the
|
||||
//! design no longer elaborates after the rename.
|
||||
//!
|
||||
//! Every test here is one of the shapes §63.1 lists, driven through the public
|
||||
//! `rename` over a little in-memory workspace: the bare-name connection, the
|
||||
//! positional one, the two-level hierarchical tail, a `: u_x` instance-list
|
||||
//! target, a hierarchical target path, a `bind` inside a generate block, and
|
||||
//! the one the engine must *not* resolve — a target module the workspace does
|
||||
//! not hold, which is warned about and never edited.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{rename, rename_traced, rename_traced_with, RefactorEdit, RenameTrace};
|
||||
|
||||
/// A workspace of `(file name, text)` pairs, rooted at a fake directory.
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
|
||||
}
|
||||
|
||||
fn path(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
/// The offset of the first whole-word `name` at or after `prefix`.
|
||||
fn at(text: &str, prefix: &str, name: &str) -> u32 {
|
||||
let from = match prefix.is_empty() {
|
||||
true => 0,
|
||||
false => {
|
||||
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text"))
|
||||
+ prefix.len()
|
||||
}
|
||||
};
|
||||
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
|
||||
let bytes = text.as_bytes();
|
||||
let mut search = from;
|
||||
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
|
||||
let start = search + hit;
|
||||
let end = start + name.len();
|
||||
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
|
||||
return start as u32;
|
||||
}
|
||||
search = start + 1;
|
||||
}
|
||||
panic!("`{name}` does not occur after `{prefix}`");
|
||||
}
|
||||
|
||||
/// Apply a refactoring's edits for one file.
|
||||
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for e in edit.edits_for(file) {
|
||||
out.push_str(&text[cursor..e.range.start as usize]);
|
||||
out.push_str(&e.new_text);
|
||||
cursor = e.range.end as usize;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the little AES the fixtures bind into
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The target module: it declares the net every fixture renames, and it
|
||||
/// instantiates the core the two-level tail walks through.
|
||||
const AES: &str = "\
|
||||
module aes (input logic clk_i, output logic idle_o);
|
||||
logic entropy_masking_req;
|
||||
aes_core u_aes_core (.clk_i(clk_i));
|
||||
assign idle_o = entropy_masking_req;
|
||||
endmodule : aes
|
||||
";
|
||||
|
||||
const AES_CORE: &str = "\
|
||||
module aes_core (input logic clk_i);
|
||||
aes_prng_clearing u_aes_prng_clearing (.clk_i(clk_i));
|
||||
endmodule : aes_core
|
||||
";
|
||||
|
||||
const AES_PRNG: &str = "\
|
||||
module aes_prng_clearing (input logic clk_i);
|
||||
logic seed_en;
|
||||
assign seed_en = clk_i;
|
||||
endmodule : aes_prng_clearing
|
||||
";
|
||||
|
||||
/// The checker a `bind` binds in. Its ports are deliberately spelled like the
|
||||
/// names being renamed, so a fixture also proves the `.port` half is left
|
||||
/// alone: it names *this* module's port, not the target's net.
|
||||
const RESEED_IF: &str = "\
|
||||
module aes_reseed_if (input logic entropy_masking_req, input logic seed_en);
|
||||
endmodule : aes_reseed_if
|
||||
";
|
||||
|
||||
/// The RTL half of every fixture's workspace.
|
||||
fn rtl(bind_file: &str) -> Vec<(PathBuf, String)> {
|
||||
workspace(&[
|
||||
("aes.sv", AES),
|
||||
("aes_core.sv", AES_CORE),
|
||||
("aes_prng_clearing.sv", AES_PRNG),
|
||||
("aes_reseed_if.sv", RESEED_IF),
|
||||
("aes_bind.sv", bind_file),
|
||||
])
|
||||
}
|
||||
|
||||
/// Rename `name` (declared in `decl_file`, at the first whole-word occurrence
|
||||
/// after `prefix`) to `new_name`, and return the bind file's new text together
|
||||
/// with the rename's warnings.
|
||||
fn rename_with_bind(
|
||||
bind_file: &str,
|
||||
decl_file: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
new_name: &str,
|
||||
) -> (String, Vec<String>) {
|
||||
let files = rtl(bind_file);
|
||||
let text = files
|
||||
.iter()
|
||||
.find(|(p, _)| *p == path(decl_file))
|
||||
.map(|(_, t)| t.clone())
|
||||
.expect("the declaring file is in the workspace");
|
||||
let edit = rename(&files, &path(decl_file), at(&text, prefix, name), new_name)
|
||||
.unwrap_or_else(|e| panic!("the rename was refused: {e}"));
|
||||
(apply(bind_file, &edit, &path("aes_bind.sv")), edit.warnings.clone())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the shapes that must be edited
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_bare_name_in_a_bind_connection_is_renamed() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(masking_req)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"the expression half names the target's net; the `.port` half names the checker's port"
|
||||
);
|
||||
assert!(warnings.is_empty(), "nothing was left unaccounted for: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_connection_in_a_bind_is_renamed() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (entropy_masking_req, 1'b0);
|
||||
endmodule
|
||||
";
|
||||
let (after, _) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (masking_req, 1'b0);
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_level_hierarchical_tail_in_a_bind_is_renamed() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.seed_en(u_aes_core.u_aes_prng_clearing.seed_en)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) =
|
||||
rename_with_bind(bind, "aes_prng_clearing.sv", "logic", "seed_en", "reseed_en");
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.seed_en(u_aes_core.u_aes_prng_clearing.reseed_en)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"the tail is rooted at the bind target and walks two instances to the declaration"
|
||||
);
|
||||
assert!(warnings.is_empty(), "nothing was left unaccounted for: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_list_target_still_names_the_target_module_scope() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes : u_aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, _) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert!(
|
||||
after.contains(".entropy_masking_req(masking_req)"),
|
||||
"`bind aes : u_aes` still binds into `aes`'s scope: {after}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_inside_a_generate_block_is_renamed() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
if (1) begin : gen_prng_bind
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (after, _) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert!(
|
||||
after.contains(".entropy_masking_req(masking_req)"),
|
||||
"a generate block changes where the directive is written, not what it binds into: {after}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_target_path_is_followed_through_the_instance_it_names() {
|
||||
let tb = "\
|
||||
module tb;
|
||||
aes u_aes (.clk_i(1'b0), .idle_o());
|
||||
endmodule : tb
|
||||
";
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind tb.u_aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let mut files = rtl(bind);
|
||||
files.push((path("tb.sv"), tb.to_string()));
|
||||
let edit =
|
||||
rename(&files, &path("aes.sv"), at(AES, "logic", "entropy_masking_req"), "masking_req")
|
||||
.expect("renames");
|
||||
assert_eq!(
|
||||
apply(bind, &edit, &path("aes_bind.sv")),
|
||||
"\
|
||||
module aes_bind;
|
||||
bind tb.u_aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(masking_req)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"`tb.u_aes` is one instance hop the index can take, so the connection resolves"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the shape the engine must not resolve
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_bind_into_a_module_the_workspace_does_not_hold_is_warned_about_never_edited() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes_shadow aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_eq!(after, bind, "nothing in the bind file was edited");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("aes_bind.sv")
|
||||
&& w.contains("aes_shadow::entropy_masking_req")
|
||||
&& w.contains("could not be resolved")),
|
||||
"the miss is said out loud, with the file and the unit that was searched: {warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the edited bind file is an ordinary file to everything downstream
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
// A regression guard rather than a flipped fixture: the collision is an
|
||||
// ordinary same-file one (`aes.sv` already declares `masking_req`), so
|
||||
// `check::verify` refused it before the bind file was understood at all
|
||||
// (it passes at 2675131 unmodified — QA §63.1, finding 1). What it pins is
|
||||
// that the refusal survives the bind file joining the edited set.
|
||||
#[test]
|
||||
fn a_new_name_the_bind_target_already_declares_is_refused() {
|
||||
let aes = "\
|
||||
module aes (input logic clk_i, output logic idle_o);
|
||||
logic entropy_masking_req;
|
||||
logic masking_req;
|
||||
assign idle_o = entropy_masking_req & masking_req;
|
||||
endmodule : aes
|
||||
";
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let files =
|
||||
workspace(&[("aes.sv", aes), ("aes_reseed_if.sv", RESEED_IF), ("aes_bind.sv", bind)]);
|
||||
let refusal =
|
||||
rename(&files, &path("aes.sv"), at(aes, "logic", "entropy_masking_req"), "masking_req")
|
||||
.expect_err("the new name is already taken in the scope the bind reaches into");
|
||||
assert!(refusal.contains("masking_req"), "the refusal names the collision: {refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_bind_connection_back_restores_the_file_byte_for_byte() {
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req),
|
||||
.seed_en (u_aes_core.u_aes_prng_clearing.seed_en)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (once, _) = rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_ne!(once, bind, "the first rename moved the bind file");
|
||||
|
||||
// The same workspace with both edits applied, renamed back: the engine
|
||||
// resolves the new spelling exactly as it resolved the old one, so the
|
||||
// bind file returns to the text it started with.
|
||||
let aes_after = AES.replace("entropy_masking_req", "masking_req");
|
||||
let files = workspace(&[
|
||||
("aes.sv", &aes_after),
|
||||
("aes_core.sv", AES_CORE),
|
||||
("aes_prng_clearing.sv", AES_PRNG),
|
||||
("aes_reseed_if.sv", RESEED_IF),
|
||||
("aes_bind.sv", &once),
|
||||
]);
|
||||
let back = rename(
|
||||
&files,
|
||||
&path("aes.sv"),
|
||||
at(&aes_after, "logic", "masking_req"),
|
||||
"entropy_masking_req",
|
||||
)
|
||||
.expect("renames back");
|
||||
assert_eq!(apply(&once, &back, &path("aes_bind.sv")), bind);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// QA attack fixtures (TODO §63.1, task 3): shapes not in the dev's seven
|
||||
// plus two, each aimed at a specific way the fix could be half right.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_bind_connections_bare_name_naming_the_targets_port_is_still_renamed() {
|
||||
// `in_bind_target`'s widened surface is `Connection` records first, then
|
||||
// `Hierarchical`-only ones (`workspace/hierarchy.rs::member`) — so a port
|
||||
// (which was already reachable through the narrow surface) must still
|
||||
// resolve exactly as it did before this lane, through the same fallback
|
||||
// that answers a net. `clk_i` is `aes`'s own port, connected bare in the
|
||||
// `bind`; the `.port` half names the checker's unrelated port of the same
|
||||
// name and must stay put.
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(clk_i)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) = rename_with_bind(bind, "aes.sv", "input logic", "clk_i", "clk_ix");
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(clk_ix)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"the expression half names `aes`'s port; the `.port` half is the checker's own, untouched"
|
||||
);
|
||||
assert!(warnings.is_empty(), "nothing was left unaccounted for: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_connection_resolves_in_the_target_not_a_same_named_decoy_in_the_writing_scope() {
|
||||
// The writing module — normally empty — now declares its own
|
||||
// `entropy_masking_req`, spelling the same name `aes` does. If the
|
||||
// connection ever fell back to the scope the directive is *written* in
|
||||
// (finding 2's bug, for a bare name rather than a hierarchical tail),
|
||||
// this decoy is exactly what it would capture instead of `aes`'s net.
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
logic entropy_masking_req;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
logic entropy_masking_req;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(masking_req)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"the connection is `aes`'s net, never `aes_bind`'s own decoy of the same name, \
|
||||
which must still read `entropy_masking_req` after the rename"
|
||||
);
|
||||
assert!(warnings.is_empty(), "nothing was left unaccounted for: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_name_the_two_level_tails_terminal_scope_already_declares_is_refused() {
|
||||
// The bare-name path's collision refusal
|
||||
// (`a_new_name_the_bind_target_already_declares_is_refused`) exercises
|
||||
// only `in_bind_target`. This is the same shape one link further down the
|
||||
// spine — the tail rooted at the bind target and walked through
|
||||
// `bind_member`/`member_at`/`descend` — so a collision at the *end* of a
|
||||
// two-level tail must refuse exactly as readily, with no gap specific to
|
||||
// the new code path.
|
||||
let aes_prng = "\
|
||||
module aes_prng_clearing (input logic clk_i);
|
||||
logic seed_en;
|
||||
logic reseed_en;
|
||||
assign seed_en = clk_i;
|
||||
endmodule : aes_prng_clearing
|
||||
";
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if (
|
||||
.seed_en(u_aes_core.u_aes_prng_clearing.seed_en)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let files = workspace(&[
|
||||
("aes.sv", AES),
|
||||
("aes_core.sv", AES_CORE),
|
||||
("aes_prng_clearing.sv", aes_prng),
|
||||
("aes_reseed_if.sv", RESEED_IF),
|
||||
("aes_bind.sv", bind),
|
||||
]);
|
||||
let refusal = rename(
|
||||
&files,
|
||||
&path("aes_prng_clearing.sv"),
|
||||
at(aes_prng, "logic", "seed_en"),
|
||||
"reseed_en",
|
||||
)
|
||||
.expect_err("`reseed_en` already exists in the tail's terminal scope");
|
||||
assert!(refusal.contains("reseed_en"), "the refusal names the collision: {refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_bind_target_is_still_resolved() {
|
||||
// `\aes.escaped ` is one identifier (an escaped identifier ends at
|
||||
// whitespace, IEEE 1800 §5.6.2), spelling a name a plain identifier
|
||||
// cannot. `bind_target_path` joins `b.target`'s segments verbatim, so
|
||||
// this is a one-segment path exactly like `bind aes …` — the escaping is
|
||||
// the parser's problem, not the resolver's.
|
||||
let aes_escaped = "\
|
||||
module \\aes.escaped (input logic clk_i, output logic idle_o);
|
||||
logic entropy_masking_req;
|
||||
assign idle_o = entropy_masking_req;
|
||||
endmodule
|
||||
";
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind \\aes.escaped aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let files = workspace(&[
|
||||
("aes.sv", aes_escaped),
|
||||
("aes_reseed_if.sv", RESEED_IF),
|
||||
("aes_bind.sv", bind),
|
||||
]);
|
||||
let edit = rename(
|
||||
&files,
|
||||
&path("aes.sv"),
|
||||
at(aes_escaped, "logic", "entropy_masking_req"),
|
||||
"masking_req",
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("the rename was refused: {e}"));
|
||||
let after = apply(bind, &edit, &path("aes_bind.sv"));
|
||||
assert_eq!(
|
||||
after,
|
||||
"\
|
||||
module aes_bind;
|
||||
bind \\aes.escaped aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(masking_req)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
"the escaped target's connection still resolves and is edited: {edit:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_with_no_connections_naming_the_renamed_signal_is_untouched() {
|
||||
// An empty connection list plus a `defparam` — a shape with nothing for
|
||||
// any connection-surface rung to walk. Nothing here spells the renamed
|
||||
// name, so the file must come back byte for byte and warn about nothing.
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind aes aes_reseed_if u_aes_reseed_if ();
|
||||
defparam u_aes_reseed_if.SOME_PARAM = 1;
|
||||
endmodule
|
||||
";
|
||||
let (after, warnings) =
|
||||
rename_with_bind(bind, "aes.sv", "logic", "entropy_masking_req", "masking_req");
|
||||
assert_eq!(after, bind, "no connection in this bind file spells the renamed name");
|
||||
assert!(warnings.is_empty(), "nothing was left unaccounted for: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_target_reached_through_a_generate_block_is_warned_about_never_guessed() {
|
||||
// `bind tb.gen[0].u_aes …`: the middle hop is a generate block, which the
|
||||
// index has no record of at all (an indexed segment "keeps only its
|
||||
// name", per `bind_target_path`'s doc comment) — so the path is one the
|
||||
// index cannot walk, and the contract is a warning, never a silent miss
|
||||
// and never a guess at which `u_aes` is meant.
|
||||
let tb = "\
|
||||
module tb;
|
||||
if (1) begin : gen
|
||||
aes u_aes (.clk_i(1'b0), .idle_o());
|
||||
end
|
||||
endmodule : tb
|
||||
";
|
||||
let bind = "\
|
||||
module aes_bind;
|
||||
bind tb.gen[0].u_aes aes_reseed_if u_aes_reseed_if (
|
||||
.entropy_masking_req(entropy_masking_req)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let mut files = rtl(bind);
|
||||
files.push((path("tb.sv"), tb.to_string()));
|
||||
let edit =
|
||||
rename(&files, &path("aes.sv"), at(AES, "logic", "entropy_masking_req"), "masking_req")
|
||||
.expect("the rename over the rest of the design still succeeds");
|
||||
assert_eq!(
|
||||
apply(bind, &edit, &path("aes_bind.sv")),
|
||||
bind,
|
||||
"a path through a generate block is never guessed at: {edit:?}"
|
||||
);
|
||||
assert!(
|
||||
edit.warnings
|
||||
.iter()
|
||||
.any(|w| w.contains("aes_bind.sv") && w.contains("could not be resolved")),
|
||||
"the miss is said out loud rather than silently dropped: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the real tree (TODO §63.1, the three QA renames)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// §61.5's QA renames, run against a real checkout: `WidthPRDSBox` (a package
|
||||
/// parameter used bare through `module aes_sbox import aes_pkg::*;`),
|
||||
/// `entropy_masking_req` (the bare-name `bind` connection this lane is about)
|
||||
/// and `seed_en` (the two-level tail in the same `bind` file). Each is asked
|
||||
/// three ways — with no index records, with every record, and with every
|
||||
/// second one — and the three must answer identically; the two `bind` ones
|
||||
/// must edit `aes_bind.sv`.
|
||||
///
|
||||
/// `#[ignore]`d, and skipped unless `LUCISV_BIND_ROOT` names a tree (it is
|
||||
/// **read** and never written). Run it with
|
||||
/// `LUCISV_BIND_ROOT=$HOME/repo/opentitan tools/guard.sh -m 8 -t 1800 -- \
|
||||
/// cargo test -p vlog_refactor --test rename_bind -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn the_three_qa_renames_agree_across_reuse_modes_and_edit_the_bind_file() {
|
||||
let Ok(root) = std::env::var("LUCISV_BIND_ROOT") else {
|
||||
eprintln!("LUCISV_BIND_ROOT unset — skipping");
|
||||
return;
|
||||
};
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_dir() {
|
||||
eprintln!("{} is not a directory — skipping", root.display());
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
files.iter().filter_map(|p| Some((p.clone(), std::fs::read_to_string(p).ok()?))).collect();
|
||||
assert!(!sources.is_empty(), "the tree holds no Verilog");
|
||||
println!("{} files read from {}", sources.len(), root.display());
|
||||
|
||||
// (file, the text the cursor is placed after, the name, the new name,
|
||||
// whether `aes_bind.sv` must be among the edited files)
|
||||
let cases: [(&str, &str, &str, &str, bool); 3] = [
|
||||
(
|
||||
"aes_pkg.sv",
|
||||
"parameter int unsigned WidthPRDSBox",
|
||||
"WidthPRDSBox",
|
||||
"WidthPRDSBoxX",
|
||||
false,
|
||||
),
|
||||
("aes.sv", "entropy_clearing_req, ", "entropy_masking_req", "masking_req_x", true),
|
||||
("aes_prng_clearing.sv", "logic seed_en", "seed_en", "seed_en_x", true),
|
||||
];
|
||||
for (file, prefix, name, new_name, bind_edited) in cases {
|
||||
let Some((path, text)) =
|
||||
sources.iter().find(|(p, _)| p.file_name().is_some_and(|n| n == file))
|
||||
else {
|
||||
eprintln!("{file} not in this tree — skipping that case");
|
||||
continue;
|
||||
};
|
||||
let offset = at(text, prefix, name);
|
||||
|
||||
let mut plain = RenameTrace::default();
|
||||
let none = rename_traced(&sources, path, offset, new_name, &mut plain);
|
||||
let all = Records::of(&sources, false);
|
||||
let mut every = RenameTrace::default();
|
||||
let full = rename_traced_with(&sources, path, offset, new_name, &all, &mut every);
|
||||
let half = Records::of(&sources, true);
|
||||
let mut mixed = RenameTrace::default();
|
||||
let some = rename_traced_with(&sources, path, offset, new_name, &half, &mut mixed);
|
||||
|
||||
let shape = |r: &Result<vlog_refactor::RefactorEdit, String>| match r {
|
||||
Ok(edit) => Ok((edit.edits.clone(), edit.warnings.clone())),
|
||||
Err(e) => Err(e.clone()),
|
||||
};
|
||||
assert_eq!(shape(&none), shape(&full), "{name}: every record changed the answer");
|
||||
assert_eq!(shape(&none), shape(&some), "{name}: half the records changed the answer");
|
||||
|
||||
let edit = none.unwrap_or_else(|e| panic!("{name} was refused: {e}"));
|
||||
let touched: Vec<String> = edit
|
||||
.edits
|
||||
.iter()
|
||||
.filter_map(|(p, _)| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
println!(
|
||||
"{name} -> {new_name}: {} files, {} edits, {} warnings; parses {} / {} / {}",
|
||||
edit.edits.len(),
|
||||
edit.edits.iter().map(|(_, e)| e.len()).sum::<usize>(),
|
||||
edit.warnings.len(),
|
||||
plain.parses,
|
||||
every.parses,
|
||||
mixed.parses
|
||||
);
|
||||
for (p, edits) in &edit.edits {
|
||||
println!(" {} x{}", p.display(), edits.len());
|
||||
}
|
||||
for w in &edit.warnings {
|
||||
println!(" warn: {w}");
|
||||
}
|
||||
assert_eq!(
|
||||
touched.iter().any(|n| n == "aes_bind.sv"),
|
||||
bind_edited,
|
||||
"{name}: aes_bind.sv among {touched:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every source's index record, or every second one — the mixture a real
|
||||
/// rename gets from a partly warm store.
|
||||
struct Records {
|
||||
known: Vec<(PathBuf, String, vlog_semantic::FileFacts)>,
|
||||
}
|
||||
|
||||
impl Records {
|
||||
fn of(sources: &[(PathBuf, String)], half: bool) -> Records {
|
||||
let known = sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !half || i % 2 == 0)
|
||||
.map(|(_, (path, text))| {
|
||||
(path.clone(), text.clone(), vlog_semantic::FileFacts::of(path.clone(), text))
|
||||
})
|
||||
.collect();
|
||||
Records { known }
|
||||
}
|
||||
}
|
||||
|
||||
impl vlog_refactor::KnownFacts for Records {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<vlog_semantic::FileFacts> {
|
||||
self.known
|
||||
.iter()
|
||||
.find(|(held, bytes, _)| held == path && bytes == text)
|
||||
.map(|(_, _, facts)| facts.clone())
|
||||
}
|
||||
}
|
||||
@@ -333,14 +333,18 @@ impl<'a> Binder<'a> {
|
||||
/// `bind prim_fifo_sync …` names the declaration a `go to definition`
|
||||
/// should jump to. A hierarchical *instance* path (`top.u_dut.u_core`,
|
||||
/// `top.gen[0].u_core`) names a place in an elaborated hierarchy that no
|
||||
/// single file knows, so it records nothing at all: the alternative is a
|
||||
/// guess, and a guess here is a wrong answer.
|
||||
/// single file knows, so it records **no reference of its own**: the
|
||||
/// alternative is a guess, and a guess here is a wrong answer. It is
|
||||
/// still the scope the connections elaborate in, and
|
||||
/// [`bind_target_path`] is that scope written the way the index reads a
|
||||
/// path.
|
||||
/// * the **instantiated module**, exactly as before, so a bind still makes
|
||||
/// the bound module a dependency of this file.
|
||||
/// * each connection: the `.port` half against the module being bound in
|
||||
/// (an ordinary [`Target::Port`], the same one a plain instantiation
|
||||
/// uses), and the expression half in the target's scope
|
||||
/// ([`Target::BindScope`]).
|
||||
/// uses), and the expression half in the target's scope — a bare name
|
||||
/// through [`Target::BindScope`], a hierarchical path through
|
||||
/// [`Target::BindMember`].
|
||||
///
|
||||
/// The instance name is still **not** declared here: it belongs to the
|
||||
/// target scope, and declaring it in this one would put a name in a scope
|
||||
@@ -357,7 +361,7 @@ impl<'a> Binder<'a> {
|
||||
let i = &b.inst;
|
||||
let ns = self.exact_or_empty(i.module_span, &i.module);
|
||||
self.use_name(scope, &i.module, ns, Target::Module);
|
||||
let previous = std::mem::replace(&mut self.bind_target, head.map(|h| h.name.clone()));
|
||||
let previous = std::mem::replace(&mut self.bind_target, bind_target_path(b));
|
||||
for c in i.params.iter().flatten().filter_map(ListElem::ok) {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
@@ -588,3 +592,29 @@ impl<'a> Binder<'a> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The scope a `bind`'s connection expressions are elaborated in, spelled the
|
||||
/// way the workspace's member tables read a path: one `::` per segment.
|
||||
///
|
||||
/// A lone segment is the target module or interface, and `aes` is the unit the
|
||||
/// index answers `aes::entropy_masking_req` in. A hierarchical path is the
|
||||
/// same question one hop at a time — `tb.u_aes` is `tb::u_aes`, which
|
||||
/// `fold_path` walks by asking `tb` for the declared type of its instance
|
||||
/// `u_aes` — so the path resolves whenever the index holds every hop and is
|
||||
/// *said out loud* when it does not, instead of silently resolving the
|
||||
/// connection in the scope the directive is written in, which is not the
|
||||
/// scope it elaborates in.
|
||||
///
|
||||
/// An indexed segment (`gen[0]`) keeps only its name: the index has no record
|
||||
/// of a generate block, so such a path answers nothing either way, and a
|
||||
/// spelling the user can recognize is what the warning needs.
|
||||
fn bind_target_path(b: &BindDirective) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
for seg in &b.target {
|
||||
if !out.is_empty() {
|
||||
out.push_str("::");
|
||||
}
|
||||
out.push_str(&seg.name);
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
@@ -103,6 +103,14 @@ pub(crate) enum Target {
|
||||
/// answers first and the scope the directive is written in second — the
|
||||
/// [`Target::InlineConstraint`] shape, with the same refusal to guess.
|
||||
BindScope { target: String },
|
||||
/// A **hierarchical path** written in the expression half of a `bind`
|
||||
/// directive's connection: `bind aes chk u (.s(u_core.u_prng.seed_en));`.
|
||||
/// The spine is rooted in the target's scope exactly as a bare name is, so
|
||||
/// `head` is looked up there (and not in the scope the directive is
|
||||
/// written in, which is a bind module declaring nothing at all) and each
|
||||
/// of `mids` walks one link further — the [`Target::MemberOf`] walk, with
|
||||
/// its start moved from the writing scope to the target's.
|
||||
BindMember { target: String, head: String, mids: Vec<String> },
|
||||
/// The `x` of `this.x`: the enclosing class's scope only.
|
||||
ThisMember,
|
||||
/// The `x` of `super.x`: always the base class's business.
|
||||
@@ -312,6 +320,12 @@ impl<'a> Binder<'a> {
|
||||
// else. A name written with a head of its own already carries the
|
||||
// right target and is left alone.
|
||||
(None, Some(scope), Target::Lexical) => Target::BindScope { target: scope.clone() },
|
||||
// And the same rule for a hierarchical path in one: its head is a
|
||||
// name in the target's scope, so the whole spine is rooted there
|
||||
// rather than in the scope the directive is written in.
|
||||
(None, Some(scope), Target::MemberOf { head, mids }) => {
|
||||
Target::BindMember { target: scope.clone(), head: head.clone(), mids: mids.clone() }
|
||||
}
|
||||
_ => target,
|
||||
};
|
||||
self.pending.push(Pending { name: name.to_string(), name_span, scope, target });
|
||||
|
||||
Loaded 100 of 200 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user