Compare commits
No files matched your search
+29
-2
@@ -1,7 +1,11 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
# CI: the three checks CLAUDE.md requires before any work is finished,
|
||||
# plus the extension's JavaScript tests and the corpus gate, enforced on
|
||||
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
|
||||
# containers), so the toolchain is the same one releases are built with.
|
||||
# every push. Runs on the self-hosted macOS runner in host mode (no
|
||||
# containers), so the toolchain is the same one releases are built with —
|
||||
# and, since 0.65.9, the same checks on Linux (the `linux` job below), where
|
||||
# the released Linux binaries had never been compiled-and-tested before.
|
||||
name: ci
|
||||
on:
|
||||
push:
|
||||
@@ -41,3 +45,26 @@ jobs:
|
||||
run: cargo build --release -p lucisv
|
||||
- name: Score and gate
|
||||
run: scripts/corpus_gate.sh "$CORPUS"
|
||||
|
||||
# The suite on Linux x86-64: the luhpe-linux-x64 runner starts each job in
|
||||
# the runner image (as root, 4 CPUs / 8 GB for the whole runner), with no
|
||||
# Rust in it, so the toolchain is installed per job and the build is cold
|
||||
# (a few minutes). Clippy is here as well as on macOS because code behind
|
||||
# cfg(unix)/cfg(target_os) is only compiled on the platform it names: the
|
||||
# first Linux trial failed clippy on imports macOS never saw. To run the
|
||||
# same thing from a working tree without a push: tools/linux_check.sh.
|
||||
linux:
|
||||
runs-on: linux-x64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the Rust toolchain
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
| sh -s -- -y --profile minimal -c clippy,rustfmt
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- name: cargo clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
- name: cargo test
|
||||
run: cargo test --workspace
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
|
||||
# publishes a Gitea release with the CHANGELOG section for that version as
|
||||
# its notes. What the release page carries is the seven .vsix packages —
|
||||
@@ -14,6 +16,12 @@
|
||||
# The release fails, deliberately, when the tag does not match the
|
||||
# workspace version or CHANGELOG.md has no section for it: every release
|
||||
# ships with real, written notes (see tools/RELEASING.md).
|
||||
#
|
||||
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
|
||||
# tests, the corpus gate, the extension's node tests) runs first, and a red
|
||||
# gate means nothing is built or published. The ci workflow runs on the
|
||||
# branch push, not the tag, so without this step a tag published whatever
|
||||
# it pointed at (0.65.0 went out while its ci run was still stuck).
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
@@ -25,6 +33,15 @@ jobs:
|
||||
runs-on: macos-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# The corpus is pinned-rev clones cached on the runner host, as in
|
||||
# ci.yml; gates.sh skips its corpus step when the cache is absent, so
|
||||
# fetch it here rather than release without that gate.
|
||||
- name: Ensure the cached corpus
|
||||
run: |
|
||||
corpus="$HOME/.cache/lucisv-corpus"
|
||||
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
|
||||
- name: Gate the release
|
||||
run: tools/gates.sh
|
||||
- name: Build release artifacts for every target
|
||||
run: tools/release.sh --cross
|
||||
- name: Audit the cross-built artifacts
|
||||
@@ -52,3 +69,5 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
|
||||
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
/target
|
||||
/corpus
|
||||
/corpus-check-results.tsv
|
||||
@@ -8,3 +10,5 @@
|
||||
/.zcode
|
||||
/.claude
|
||||
__pycache__/
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
+599
@@ -1,9 +1,606 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# Changelog
|
||||
|
||||
All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.66.2 — 2026-11-24
|
||||
|
||||
### Every source file names its author
|
||||
|
||||
- **No behaviour change.** Every tracked file that can carry a comment — 880
|
||||
of them: the Rust sources, the extension's JavaScript, the scripts, the
|
||||
manifests, the workflows and the documentation — now opens with an author
|
||||
line and closes with one. The binaries and the formatter's, linter's and
|
||||
language server's output are what 0.66.1 produced.
|
||||
- `tools/stamp_author.py` writes the lines and is idempotent; run it after
|
||||
adding files (`--check` lists what is missing). It leaves alone what a
|
||||
comment would break or what is regenerated: test fixtures, cases and
|
||||
snapshots, JSON and JSONL, logs, images, lockfiles, the built site under
|
||||
`docs/site/dist` and the `LICENSE` files.
|
||||
- `tools/linux_check.sh --help` reads its own header one line further down,
|
||||
since the author line now sits under the shebang.
|
||||
|
||||
## 0.66.1 — 2026-11-19
|
||||
|
||||
### Sticky scroll pins the module instance
|
||||
|
||||
- **A module instantiation folds, so its header lines stay pinned** (TODO
|
||||
§72, `docs/features/instance-folding`). `textDocument/foldingRange` answers
|
||||
one range per multi-line instantiation from its module-type line, and one
|
||||
more per instance from the line its name is on when that is a later line,
|
||||
so both `aes_control_fsm #(` and `) u_aes_control_fsm (` are pinned while
|
||||
the reader is in the connection list. The closing `);` line stays visible.
|
||||
What is an instantiation comes from `vlog_semantic::instantiations::sites`;
|
||||
where it closes is re-read from the tokens, and a statement whose tokens
|
||||
are not exactly that shape folds nothing.
|
||||
- Every fold answered before is unchanged and first on a shared start line
|
||||
(0.66.0 against this tree on 4 933 files: 75 256 ranges identical once the
|
||||
instance folds are removed). OpenTitan `hw`: 18 200 multi-line
|
||||
instantiations, none without its fold. Worst file about 2 ms per request
|
||||
(1.1 ms before).
|
||||
- Not folded: two-dimensional instance arrays; an instance whose head an
|
||||
`` `ifdef `` splits.
|
||||
|
||||
## 0.66.0 — 2026-11-19
|
||||
|
||||
### The overnight queue, complete
|
||||
|
||||
0.66.0 closes TODO §71: eight owner-ordered features, each shipped as its own
|
||||
0.65.x release with a dev round, a QA round and the full gates. Nothing in
|
||||
the engine changed between 0.65.11 and this release; it adds the topology
|
||||
and size re-measurement (`docs/topo.md`, `CLAUDE.md`) and is the version to
|
||||
install. Each line names the release that carries the detail below.
|
||||
|
||||
- **Editing and saving no longer re-index the workspace** (0.65.6/0.65.7).
|
||||
A saved or changed file updates its own records and the files that depend
|
||||
on it; only a change that can reach everything (a config, a filelist)
|
||||
rescans.
|
||||
- **Actions on the open file do not wait for the workspace** (0.65.11).
|
||||
Hover, go-to-definition, highlights, the outline and folding for names the
|
||||
file declares answer in milliseconds during a scan or a rescan, and
|
||||
completion lists what the file can reach first.
|
||||
- **Highlighting does not wait for the index** (0.65.10). Colours come from
|
||||
the buffer at once, as a best guess for cross-file names, and are
|
||||
corrected by one refresh when the index settles.
|
||||
- **`` `ifdef `` / `` `else `` / `` `endif `` branches fold** and take part
|
||||
in sticky scroll (0.65.4).
|
||||
- **Formatter styles** (0.65.5): `auto` follows the file's own style, or
|
||||
choose `lucisv`, `ansi`, `google`, `lowrisc`, `microsoft` or `nxp`; the presets are one readable
|
||||
table in `vlog_formatter/src/style.rs`.
|
||||
- **The module view marks where you are** (0.65.2): the current file's
|
||||
module and its parents, in shades of orange.
|
||||
- **Find References next to a name** (0.65.8): a caret just past a name's
|
||||
last letter now finds it — the cause of "no references" that worked on a
|
||||
second try — and edits arriving during a rescan are applied in order.
|
||||
- **Comments are comments** (0.65.3): no bracket or code colouring inside
|
||||
them, and `TODO`, `FIXME`, `FIX_ME`, `TBD` and your own words
|
||||
(`lucisv.commentKeywords.custom`) are highlighted.
|
||||
|
||||
Also since 0.65.0: releases are gated by `tools/gates.sh`, which
|
||||
compile-checks Windows and Linux (0.65.1, 0.65.7); CI runs the suite on
|
||||
Linux as well as macOS, and `lucisv-mcp` no longer serves stale contents
|
||||
after a same-instant rewrite (0.65.9).
|
||||
|
||||
One test change in this release: 0.65.11's Linux CI run failed on a
|
||||
wall-clock test of the large-file path (24.9x measured against a 24x limit
|
||||
on a loaded runner; nothing in that path had changed). The test now
|
||||
re-measures up to three times before failing — a real quadratic regression
|
||||
measures ~64x every time.
|
||||
|
||||
**Not yet seen in a running editor by a human** — every feature above was
|
||||
verified through the server's protocol and the extension's tests, on
|
||||
OpenTitan's `hw` tree. Open follow-ups are listed in TODO §71.
|
||||
|
||||
## 0.65.11 — 2026-11-19
|
||||
|
||||
### Actions on the open file no longer wait for the workspace
|
||||
|
||||
(`docs/features/fast-actions`; TODO §71.2. Measured on OpenTitan's `hw` tree
|
||||
and on generated 20 000- and 40 000-file trees, with the server driven the
|
||||
way VS Code drives it.)
|
||||
|
||||
- **Same-file answers come from the file.** A hover, a go-to-definition, a
|
||||
type definition, highlights, a rename's first check or a signature help on
|
||||
a name the file itself declares — and the outline, folding and selection
|
||||
ranges — are answered from the open buffer at once, even while the index
|
||||
is being built or rebuilt. Anything that might live in another file still
|
||||
waits for the index it needs.
|
||||
|
||||
| hover on a local name (4 000 / 20 000 / 40 000 files) | 0.65.10 | now |
|
||||
|---|---:|---:|
|
||||
| during the startup scan | 547 / 665 / 831 ms | 2.4 / 1.5 / 1.9 ms |
|
||||
| a new file triggers a rescan, request 5 ms later | 1.2 / 6.0 / 12.3 s | 47 / 167 / 321 ms |
|
||||
| the same, request read together with the event | 1.2 / 6.0 / 12.3 s | 0.3 / 0.1 / 0.1 ms |
|
||||
| the same, server busy with a previous delete | 1.3 / 7.0 / 14.3 s | 0.17 / 0.99 / 2.2 s |
|
||||
|
||||
- **Every early answer is the settled answer.** A request goes ahead only
|
||||
when its buffer is open, every older message that could change the buffer
|
||||
has been applied, its analysis is current, no settings are still on their
|
||||
way, and the answer is the buffer's alone. 2.9 million early answers were
|
||||
compared with the answer the finished index gives; none differed.
|
||||
- **Completion keeps what the file can reach near the top.** Right after the
|
||||
file's own names it now offers the members of the packages the file
|
||||
imports, what its class inherits and the macros of the headers it
|
||||
includes, so a huge workspace no longer pushes them out of the list; such
|
||||
a name shows the icon and detail of the declaration the file actually
|
||||
reaches. Completion answers are half the size for VS Code.
|
||||
- **A new `lucisv.largeFile.threshold` applies to files already open,** the
|
||||
editor's first settings answer included — not at each file's next edit.
|
||||
- **Fixed on the way** (present since 0.65.8 and 0.65.10): the editor's
|
||||
answer to a settings request could be applied ahead of an older settings
|
||||
change or edit; colours answered while a file-watcher event was waiting
|
||||
were not refreshed afterwards.
|
||||
- **What it costs.** Until the editor has answered the server's first
|
||||
settings request, same-file requests wait (the threshold may change how
|
||||
the file is read): with an editor that takes 0.5 s to answer, the first
|
||||
outline arrives after 515 ms — it was 1 043 ms on 0.65.10.
|
||||
- **Still to come.** Not yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.10 — 2026-11-19
|
||||
|
||||
### Highlighting no longer waits for the index
|
||||
|
||||
(`docs/features/viewport-highlight`; TODO §71.3. Measured on OpenTitan's `hw`
|
||||
tree with the server driven the way VS Code drives it.)
|
||||
|
||||
- **Colours arrive at once.** Building a file's colours takes 0.3–6.5 ms;
|
||||
nearly all of the wait before first colour was the server holding every
|
||||
request until the index was ready. A colouring request for a buffer whose
|
||||
text is current is now answered from that buffer alone, even while a scan
|
||||
or a widening of the index holds everything else.
|
||||
|
||||
| first colour after opening a file | before | now |
|
||||
|---|---:|---:|
|
||||
| cold start, whole-workspace scope | 660–685 ms | 3.5–39 ms |
|
||||
| cold start, folder scope (the default) | 38–74 ms | 3–32 ms |
|
||||
| a file opened after startup settled, folder scope | 611–641 ms | 2–32 ms |
|
||||
| a file in a folder not indexed yet, mid-session | 375 ms | 6 ms |
|
||||
| while a rescan runs | 325–791 ms | 70–159 ms |
|
||||
|
||||
The larger figure in each range is a 545 KB file, whose own parse is most
|
||||
of what remains.
|
||||
- **Imperfect first, then corrected — once.** Before the index settles,
|
||||
names that resolve through it (a module or package in another file, an
|
||||
inherited method) are coloured as local guesses: 96.8 % of tokens already
|
||||
match the final answer, and nothing is ever coloured as code inside a
|
||||
comment or a string. When the index settles the server sends one
|
||||
`workspace/semanticTokens/refresh` and the editor's next answer is the
|
||||
accurate one. This also fixes colours that used to stay wrong until the
|
||||
next edit: the first answer was built from a half-finished index and never
|
||||
revisited (2 745 tokens in one OpenTitan file).
|
||||
- **The viewport request costs the viewport.** `semanticTokens/range` built
|
||||
the whole file's tokens and filtered them; it now classifies only the
|
||||
visible lines (0.3 ms for 60 lines of a 4 000-module buffer, against 98 ms).
|
||||
- **What it will not do.** A buffer with edits the server has not applied
|
||||
yet still waits — its existing colours stay on screen. An editor that
|
||||
cannot be asked to refresh gets early viewport colours only, and its
|
||||
whole-file answer waits as before. Hover, go-to-definition and every other
|
||||
request still wait for the index they need; QA compared 978 such answers
|
||||
with 0.65.8's and they are identical.
|
||||
- **Still to come.** The file-discovery walk at the start of every scan
|
||||
answers nothing while it runs, which is what is left of the wait in
|
||||
whole-workspace scope (62–86 ms for a late open) and during rescans. Not
|
||||
yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.9 — 2026-11-19
|
||||
|
||||
### `lucisv-mcp` no longer serves stale contents; the suite runs on Linux
|
||||
|
||||
(`docs/features/linux-test-portability`, Round 2; TODO §70.)
|
||||
|
||||
- **`lucisv-mcp` no longer answers from a file's old contents after a
|
||||
same-size rewrite that restores its old modification time.** The server
|
||||
decides whether a file changed from its size, mtime, change time and
|
||||
inode, and re-reads a file whose mtime is too fresh to trust — but it did
|
||||
not apply that caution to the change time. On Linux, where the change time
|
||||
moves in 1 ms ticks, a file rewritten at the same size with its mtime put
|
||||
back (`cp -p`, `rsync -t`, `touch -r`, a rename-over) inside the same tick
|
||||
as the server's read matched in every field, and index-based answers
|
||||
(`find`, `hierarchy`, `check`) came from the old text until the file
|
||||
changed again. `read` and `outline` were never affected. The rule now
|
||||
covers every timestamp the stamp trusts, its window is 3 s (2 s was too
|
||||
close to FAT's 2-second timestamps), and a wall clock stepped backwards
|
||||
since a read distrusts the stamp. Reproduced on purpose on 0.65.8 (every
|
||||
run with an identical stat was stale) and gone on this build across
|
||||
overlayfs, tmpfs and APFS; ordinary reads cause no extra re-read.
|
||||
- **What it still cannot see**, now written down in
|
||||
`docs/features/mcp-transport`: on Windows there is no change time or
|
||||
inode, so a same-size rewrite that restores the old mtime more than 3 s
|
||||
after a read goes unseen; and a store through a writable memory map that
|
||||
the kernel has not yet reflected in the file's timestamps. A tree whose
|
||||
files carry modification times in the future is re-read on every call.
|
||||
- **The test suite is stable on Linux, and CI runs it there.** It was green
|
||||
on Linux most of the time and failed about one run in three: two test
|
||||
helpers insisted that writing to a child's input succeed (a usage error
|
||||
exits before reading), one latency test used a fixed 200 ms budget (it now
|
||||
measures against a parse of the same buffer in the same process), and one
|
||||
MCP test could hang on macOS under load on a pipe inherited across
|
||||
threads. Ten consecutive green runs as root and ten as an unprivileged
|
||||
user, then six and six by QA. `ci.yml` has a `linux` job (clippy and the
|
||||
whole suite on Linux x86-64) beside the macOS one.
|
||||
|
||||
## 0.65.8 — 2026-11-19
|
||||
|
||||
### Find References next to a name, edits kept in order, and a startup that could take minutes
|
||||
|
||||
(`docs/features/scan-ordering`; TODO §71.7. Three bugs, all older than this
|
||||
series of releases.)
|
||||
|
||||
- **Find All References, Go to Definition, hover, highlight and rename work
|
||||
with the cursor just after a name.** A double-click, a click on the right
|
||||
half of a name's last letter, or a click on a row of lucisv's References
|
||||
view leaves the cursor there, and the server used to look at the character
|
||||
*after* the name — so VS Code said "No references found" until you clicked
|
||||
away and back. Nine requests now resolve the name the cursor touches
|
||||
(hover, definition, type definition, references, document highlight,
|
||||
prepare-rename, rename, and the call- and type-hierarchy prepares); the
|
||||
ones with boundary rules of their own (completion, signature help, linked
|
||||
editing, selection range) are unchanged. The References view now opens a
|
||||
row with the cursor at the start of the name. Checked on every identifier
|
||||
of 350 files: the answer at the end of a name equals the answer at its
|
||||
start, and a rename there never touches the neighbouring token.
|
||||
- **Edits made while the workspace is re-indexing are applied in order.**
|
||||
The server held requests during a scan but applied notifications at once,
|
||||
so a newer edit could overtake an older one still queued — and since the
|
||||
editor sends edits as differences, the server's copy of the file then
|
||||
differed from the editor's until the file was closed and reopened: wrong
|
||||
symbols, wrong diagnostics, wrong references. Edits, opens, closes, saves
|
||||
and the other notifications the editor sends are now applied in the order
|
||||
sent. QA's independent driver: 9 118 bursts, 87 % of them sent mid-scan,
|
||||
no wrong text, no lost or duplicated answer; the same check fails on
|
||||
0.65.7 at once.
|
||||
- **Opening a file while the first index is built no longer makes that index
|
||||
take minutes.** A request followed by a file open in the same batch was
|
||||
handed back and re-held at every file of the startup scan: about 300–400 s
|
||||
on OpenTitan instead of 2 s. Now a held batch is handed back at most once
|
||||
per file actually opened; the same sequence takes 2.6–3.3 s.
|
||||
- **Known and left for later**, all present before: a request held during a
|
||||
scan is answered against the newest text, so a position-based request can
|
||||
land on a different symbol if an edit moved the text under it (and rename
|
||||
edits carry no document version for the client to reject a stale one by);
|
||||
deleting a directory is not seen by the server (VS Code reports the folder,
|
||||
which the client's source-file filter drops); an excluded file stays in the
|
||||
index after it is closed; symlinked files can be held under two spellings;
|
||||
renaming a port of a module defined twice gives an edit or a refusal at
|
||||
random.
|
||||
|
||||
## 0.65.7 — 2026-11-19
|
||||
|
||||
### 0.65.6, built for every platform
|
||||
|
||||
0.65.6 was tagged but never published: it passed every gate on the Mac and
|
||||
then failed to compile for Windows, so the release stopped before anything
|
||||
was built for distribution. This release is 0.65.6 with that fixed; its
|
||||
notes are below, unchanged.
|
||||
|
||||
- **The Windows build compiles again.** One comparison in the language
|
||||
server's new "is this file already held under another spelling" check moved
|
||||
a directory identity that is a small copyable pair on macOS and Linux but an
|
||||
owned path on Windows (`lucisv_server/src/state/incremental.rs`).
|
||||
- **The gates now compile for the other platforms.** `tools/gates.sh` has a
|
||||
new `cross` step: `cargo check` of the three shipped binaries for Windows
|
||||
and Linux, with the same toolchain the release build uses. Until now
|
||||
platform-conditional code was first compiled by the release build itself,
|
||||
after the gates.
|
||||
|
||||
### Saving a file no longer re-indexes the workspace
|
||||
|
||||
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
|
||||
tree, 4 058 files, with the server driven the way VS Code drives it.)
|
||||
|
||||
- **What was happening.** Every save cost about 160 ms of whole-index work
|
||||
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
|
||||
references — and VS Code triggered it twice, once for the save and once for
|
||||
its own file watcher. Watcher events for files the index could not hold (a
|
||||
generated file in a gitignored directory, a file outside the filelist or
|
||||
folder scope, a held file reported through a symlinked root or in another
|
||||
letter case) started a whole rescan with the progress bar, 270–750 ms.
|
||||
- **Now the index does only what the edit can reach.**
|
||||
|
||||
| edit, then save | before | now |
|
||||
|---|---:|---:|
|
||||
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
|
||||
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
|
||||
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
|
||||
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
|
||||
| a member added to a package 677 files import | ~162 ms | 92 ms |
|
||||
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
|
||||
|
||||
The index records which names each file looked up — including the ones it
|
||||
did not find — and re-resolves only the readers of names whose meaning
|
||||
changed. A save whose index record is unchanged merges nothing.
|
||||
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
|
||||
files in one watcher event than half the index holds (a branch switch),
|
||||
which takes the one rescan it always did; an edit above a declaration many
|
||||
files use. Every save still re-checks every open file's diagnostics, so a
|
||||
`lucisv.toml` or waiver edit takes effect at the next save as before — with
|
||||
200 files open that is most of a save (53 ms, against ~205 ms before).
|
||||
- **The price.** Every whole rescan costs a few per cent more for the table
|
||||
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
|
||||
depending on machine load.
|
||||
- **How it is known to be right.** After any sequence of edits, everything
|
||||
the server answers must equal what a freshly started server answers for the
|
||||
same files. QA built that oracle independently and it failed the first cut
|
||||
on four stale answers (include links to headers outside the scope, lint
|
||||
configuration, a file-age check macOS defeats, excluded open buffers); all
|
||||
four are fixed and are now tests. The final build: 312 hand-written
|
||||
comparisons and twelve random 300–500-step runs over the corpus and
|
||||
OpenTitan with no divergence it caused.
|
||||
- **Also.** The language server's `line-length` lint now follows the chosen
|
||||
formatting style's width (80 under `ansi` and `nxp`, 120 under
|
||||
`microsoft`), closing the limit noted in 0.65.5. Removing an included
|
||||
header no longer leaves other files' include links pointing at it.
|
||||
- **Known, and next.** Found by this round's QA and present in earlier
|
||||
releases too: an edit made while a whole rescan is running can be applied
|
||||
out of order, leaving the server's copy of the buffer wrong until the file
|
||||
is reopened; a watcher event that names only a directory leaves stale
|
||||
state; an excluded file stays indexed after it is closed. These are the
|
||||
next round's work.
|
||||
|
||||
## 0.65.6 — 2026-11-19
|
||||
|
||||
### Saving a file no longer re-indexes the workspace
|
||||
|
||||
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
|
||||
tree, 4 058 files, with the server driven the way VS Code drives it.)
|
||||
|
||||
- **What was happening.** Every save cost about 160 ms of whole-index work
|
||||
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
|
||||
references — and VS Code triggered it twice, once for the save and once for
|
||||
its own file watcher. Watcher events for files the index could not hold (a
|
||||
generated file in a gitignored directory, a file outside the filelist or
|
||||
folder scope, a held file reported through a symlinked root or in another
|
||||
letter case) started a whole rescan with the progress bar, 270–750 ms.
|
||||
- **Now the index does only what the edit can reach.**
|
||||
|
||||
| edit, then save | before | now |
|
||||
|---|---:|---:|
|
||||
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
|
||||
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
|
||||
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
|
||||
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
|
||||
| a member added to a package 677 files import | ~162 ms | 92 ms |
|
||||
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
|
||||
|
||||
The index records which names each file looked up — including the ones it
|
||||
did not find — and re-resolves only the readers of names whose meaning
|
||||
changed. A save whose index record is unchanged merges nothing.
|
||||
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
|
||||
files in one watcher event than half the index holds (a branch switch),
|
||||
which takes the one rescan it always did; an edit above a declaration many
|
||||
files use. Every save still re-checks every open file's diagnostics, so a
|
||||
`lucisv.toml` or waiver edit takes effect at the next save as before — with
|
||||
200 files open that is most of a save (53 ms, against ~205 ms before).
|
||||
- **The price.** Every whole rescan costs a few per cent more for the table
|
||||
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
|
||||
depending on machine load.
|
||||
- **How it is known to be right.** After any sequence of edits, everything
|
||||
the server answers must equal what a freshly started server answers for the
|
||||
same files. QA built that oracle independently and it failed the first cut
|
||||
on four stale answers (include links to headers outside the scope, lint
|
||||
configuration, a file-age check macOS defeats, excluded open buffers); all
|
||||
four are fixed and are now tests. The final build: 312 hand-written
|
||||
comparisons and twelve random 300–500-step runs over the corpus and
|
||||
OpenTitan with no divergence it caused.
|
||||
- **Also.** The language server's `line-length` lint now follows the chosen
|
||||
formatting style's width (80 under `ansi` and `nxp`, 120 under
|
||||
`microsoft`), closing the limit noted in 0.65.5. Removing an included
|
||||
header no longer leaves other files' include links pointing at it.
|
||||
- **Known, and next.** Found by this round's QA and present in earlier
|
||||
releases too: an edit made while a whole rescan is running can be applied
|
||||
out of order, leaving the server's copy of the buffer wrong until the file
|
||||
is reopened; a watcher event that names only a directory leaves stale
|
||||
state; an excluded file stays indexed after it is closed. These are the
|
||||
next round's work.
|
||||
|
||||
## 0.65.5 — 2026-11-19
|
||||
|
||||
### Named formatting styles
|
||||
|
||||
(`docs/features/format-styles`; TODO §71.5.)
|
||||
|
||||
- **One setting picks a house layout.** `[format] style = "<name>"` in
|
||||
`lucisv.toml`, `--style <name>` on the command line, or the new
|
||||
`lucisv.format.style` drop-down in VS Code. Seven layout rules, one row per
|
||||
style, in one table in `crates/vlog_formatter/src/style.rs`:
|
||||
|
||||
| style | indent / width | `begin` | `else` | lists | list indent | alignment |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `lucisv` (default) | 2 / 100 | same line | same line | fit | 1 level | keep |
|
||||
| `google` | 2 / 100 | same line | same line | one per line | 2 levels | keep |
|
||||
| `lowrisc` | 2 / 100 | same line | same line | one per line | 1 level | always |
|
||||
| `ansi` | 4 / 80 | own line | own line | fit | 1 level | keep |
|
||||
| `microsoft` | 4 / 120 | own line | own line | one per line | 1 level | keep |
|
||||
| `nxp` | 2 / 80 | same line | own line | one per line | 1 level | always |
|
||||
|
||||
- **Where the styles come from.** `google` follows the Google Verilog Style
|
||||
Guide and `lowrisc` the lowRISC (OpenTitan) guide, both read for this
|
||||
release, including `else` on its own line after a labelled `end`. **`ansi`,
|
||||
`microsoft` and `nxp` are lucisv's educated guesses** — Allman-style
|
||||
`begin`/`else` after iStyle's and clang-format's styles of those names, and
|
||||
a conservative aligned RTL style — not rules those organisations publish
|
||||
for Verilog.
|
||||
- **The default does not move a byte.** `lucisv` output is identical to
|
||||
0.65.4 on all 4 921 files of the corpus and OpenTitan's `hw` tree, checked
|
||||
against an independently rebuilt 0.65.4. An explicit `indent` or
|
||||
`line-length` still wins over a style's.
|
||||
- **Every style goes through the same safety net.** Each was formatted three
|
||||
times over those 4 921 files: no verification error, no crash, no token or
|
||||
comment difference (checked with a lexer that is not the formatter's), and
|
||||
no change on a second or third run. `verify.rs` is untouched.
|
||||
- **`style = "auto"` keeps a file in the layout it is already closest to.**
|
||||
It formats with each preset and keeps the result that changes the fewest
|
||||
lines, so a file written the Google way stays that way. It picks a layout
|
||||
for the configured indent and width and **never infers them** — set
|
||||
`indent` to match the file first, or a 4-space file formatted at the
|
||||
default 2 comes out in the default layout. Small edits do not flip a file:
|
||||
over 500 files and ten kinds of edit, none rewrote more than 12 lines
|
||||
outside the edit. `auto` costs a search — 2.4 s against 0.4 s on a
|
||||
42 000-line file for a whole-document format — so the language server
|
||||
remembers each document's layout, and selection and on-type formatting stay
|
||||
at 0.1 s after the first request.
|
||||
- **Known limits.** A declaration with several instances in one statement
|
||||
gets the older hanging layout under the one-per-line styles. The language
|
||||
server's `line-length` lint still assumes 100 columns under `ansi`,
|
||||
`microsoft` and `nxp` (the CLI's `check` follows the style). Switching from
|
||||
one keep-alignment style to another and back is not always a round trip:
|
||||
alignment a style added stays.
|
||||
|
||||
## 0.65.4 — 2026-11-19
|
||||
|
||||
### `` `ifdef `` blocks fold, and pin in sticky scroll
|
||||
|
||||
(`docs/features/ifdef-folding`; TODO §71.4.)
|
||||
|
||||
- **Every conditional-compilation branch folds on its own.** `` `ifdef ``,
|
||||
`` `ifndef ``, `` `elsif `` and `` `else `` each fold from their own line to
|
||||
the line before the next branch (or before `` `endif ``). Collapse the
|
||||
`` `ifdef `` branch and the `` `else `` line stays visible and separately
|
||||
collapsible; `` `endif `` stays visible too, the way `end` does for a
|
||||
`begin` fold. Nesting works to any depth.
|
||||
- **They pin in sticky scroll.** The floating header lines already follow the
|
||||
server's folds, so while you scroll inside a long branch its `` `ifdef `` or
|
||||
`` `else `` line stays at the top with the module and blocks around it.
|
||||
- **Only real directives count.** The folds are built from the lexer's own
|
||||
directive tokens, so a directive-looking line inside a comment, a string or
|
||||
a `` `define `` body is not folded (35 such lines in OpenTitan). An
|
||||
unterminated `` `ifdef `` folds the branches it finished and never runs to
|
||||
the end of the file; a stray `` `else `` or `` `endif `` is ignored.
|
||||
- **No existing fold is lost or changed.** On OpenTitan's `hw` tree (4 061
|
||||
files) and the 860-file corpus every fold the previous release returned is
|
||||
still returned, byte for byte, with the 1 061 and 511 branch folds added.
|
||||
Where a branch would share its start line with an existing fold — a
|
||||
directive written after code on the same line — the existing fold is sent
|
||||
first and keeps its place; that never occurs in either tree.
|
||||
- **Cost:** one extra pass over the tokens: folding all of OpenTitan goes from
|
||||
29.9 ms to about 34 ms, and a 50 000-branch file answers in 0.2 s.
|
||||
- **Limits.** Files over the large-file threshold (4 MiB) return no folds, as
|
||||
before. Not yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.3 — 2026-11-19
|
||||
|
||||
### Comment keywords, and the brackets in comments explained
|
||||
|
||||
(`docs/features/comment-highlighting`; TODO §71.8.)
|
||||
|
||||
- **`TODO`, `FIXME`, `FIX_ME` and `TBD` stand out inside comments.** In `//`
|
||||
and `/* */` comments they are drawn bold in a new theme colour,
|
||||
`lucisv.commentKeyword` — as whole words only (`TODO_reg` and `$TODO` are
|
||||
left alone), and never in strings or code.
|
||||
- **Your own words too.** `lucisv.commentKeywords.custom` adds words that are
|
||||
highlighted the same way and only in comments (matched literally, up to 50
|
||||
words of 1–40 characters); `lucisv.commentKeywords.builtIn: false` turns the
|
||||
four built-ins off, and `lucisv.commentKeywords.caseSensitive: false`
|
||||
ignores case. Every change applies at once, with no reload.
|
||||
- **It follows what the editor draws as a comment.** The extension finds
|
||||
comments with the grammar's own comment and string rules; against VS Code's
|
||||
real tokenizer that agreed on every one of the 1 185 823 lines of
|
||||
OpenTitan's `hw` tree. It is client-side, so it paints while the language
|
||||
server is still starting.
|
||||
- **Cheap on big files.** Only the lines on screen (and 50 either side) are
|
||||
searched for words; an edit above the screen re-reads the lines from the
|
||||
edit down to it (7.9 ms at worst on a 100 000-line file). A file VS Code
|
||||
itself does not tokenize (over 20 MiB or 300 000 lines) is not painted.
|
||||
- **Brackets coloured inside comments: explained, not changed.** The `[]` of
|
||||
a `signal[]` that sometimes lights up in a comment is VS Code's bracket-pair
|
||||
colourisation, which ignores comments until it has finished tokenizing a
|
||||
newly opened file in the background and then removes the colour itself.
|
||||
lucisv's grammar and semantic tokens were measured to colour nothing inside
|
||||
a comment (309 OpenTitan files, and the large-file path). An extension
|
||||
cannot change that behaviour short of switching bracket colours off for the
|
||||
whole language, code included — which stays your choice
|
||||
(`editor.bracketPairColorization.enabled`, or `colorizedBracketPairs`
|
||||
under `[systemverilog]`).
|
||||
- **Not yet seen in a running editor by a human**: the tests are headless.
|
||||
|
||||
## 0.65.2 — 2026-11-19
|
||||
|
||||
### The Hierarchy pane shows where you are
|
||||
|
||||
(`docs/features/hierarchy-current-path`; TODO §71.6.)
|
||||
|
||||
- **The rows leading to the file you are editing are lit.** Every instance of
|
||||
the module the open file declares gets a light, bright orange tint with a
|
||||
solid bar at its left edge and a bold label; each row above it is one shade
|
||||
dimmer with a narrower bar, down to a faint floor for distant ancestors. A
|
||||
module instantiated in several places lights every copy, and where two
|
||||
chains meet the nearer one wins. It works on a closed tree and on DUT
|
||||
sections: a section header is tinted when the section holds the file or its
|
||||
parents.
|
||||
- **Switching files repaints, it does not reload.** There is no request to the
|
||||
language server and no rebuild of the tree; only the rows whose shade
|
||||
changed are touched, so nothing collapses (about 5 ms on a 6 000-module
|
||||
design).
|
||||
- **Readable in every built-in theme.** The default tints keep label text at
|
||||
4.5:1 or better on every lit level in the dark, light and high-contrast
|
||||
themes, hovered rows included — a test computes that from the shipped
|
||||
defaults — and the bar's width and style change with the level, so the
|
||||
grading does not rest on colour alone.
|
||||
- **Yours to restyle or switch off.** The shades and the bar are theme colours
|
||||
(`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
|
||||
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) for
|
||||
`workbench.colorCustomizations`; `lucisv.hierarchy.highlightCurrent: false`
|
||||
turns the highlighting off.
|
||||
- **Known limits.** Nothing lights when a folder name's letter case differs
|
||||
between the filelist and the editor, or on Windows network-share paths; in a
|
||||
recursive design a row can be lit with nothing lit beneath it. Not yet seen
|
||||
in a running editor by a human: the tests are headless.
|
||||
|
||||
## 0.65.1 — 2026-11-19
|
||||
|
||||
### Releases are gated
|
||||
|
||||
No change to the formatter, the linter, the language server or the editor
|
||||
extension: the packages are 0.65.0 rebuilt. What changed is how a release is
|
||||
made (`tools/RELEASING.md`).
|
||||
|
||||
- **A tag no longer publishes unless every gate is green.** The release
|
||||
workflow now runs `tools/gates.sh` — `cargo fmt`, `cargo clippy`, each
|
||||
crate's test suites, the doc tests, the corpus gate and the extension's node
|
||||
tests — before it builds anything, and a failing gate stops the release.
|
||||
Until now only the branch push was checked, by a separate workflow the
|
||||
release did not wait for, so 0.65.0 was published while its checks had not
|
||||
finished.
|
||||
- **The build is clean on Rust 1.100.** An unused import in the language
|
||||
server's test module, which that toolchain's clippy rejects under
|
||||
`-D warnings`, is gone. It is what turned 0.65.0's checks red after the
|
||||
fact; the released binaries were never affected.
|
||||
|
||||
## 0.65.0 — 2026-11-19
|
||||
|
||||
### Module instantiation syntax highlighting
|
||||
|
||||
(`docs/features/instantiation-highlighting`; TODO §69.)
|
||||
|
||||
- **Every part of a module instantiation gets its own colour.** Module names,
|
||||
instance names, `.PARAM` overrides, `.port` names and connected signals used
|
||||
to collapse to the same default foreground colour whenever the instantiated
|
||||
module lived in another file or a theme left bare semantic tokens unstyled.
|
||||
The language server now layers AST-guided semantic token overrides (and
|
||||
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
|
||||
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
|
||||
`namespace`, and lone `bind` targets) highlight as `class`.
|
||||
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
|
||||
the `#` introducing a module, class, `extends`, instantiation or
|
||||
parameterized-type parameter list, every `.PARAM` override (`.` and name),
|
||||
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
|
||||
tokens (`#5`, `#(1:2:3)`) are left unemitted.
|
||||
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
|
||||
hierarchical uses like `u_uart.sig`) highlight as `function`.
|
||||
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
|
||||
`.*`), including unfinished entries being typed, highlight as `property`.
|
||||
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
|
||||
consistent colour across the file.
|
||||
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
|
||||
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
|
||||
`[verilog]` and `[systemverilog]` (user settings still win), and
|
||||
`contributes.semanticTokenScopes` maps the language's semantic token types to
|
||||
distinct TextMate scopes so every role renders in colour across Dark+, Dark
|
||||
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
### Completion that keeps up with typing
|
||||
@@ -2864,3 +3461,5 @@ compiler directive any more. Details:
|
||||
[macro items](docs/features/macro-items/README.md),
|
||||
[directives in lists](docs/features/directives-in-lists/README.md) and
|
||||
[in instances](docs/features/directives-in-instances/README.md).
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
@@ -1,3 +1,5 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# CLAUDE.md — rules for all agents working on lucisv
|
||||
|
||||
lucisv is a ruff-style Verilog/SystemVerilog formatter/linter in Rust.
|
||||
@@ -89,6 +91,16 @@ Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-
|
||||
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
|
||||
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
|
||||
|
||||
Re-measured 2026-11-19 at 0.66.0, after the overnight queue (TODO §71; non-blank,
|
||||
non-comment lines before `mod tests`): two files over 600 — `perf.rs` 907
|
||||
(reasoned) and `lexer.rs` 771 — then `vlog_semantic/src/resolve.rs` 587 and
|
||||
`vlog_parser/src/parser/item.rs` 582, both at the mark: the next addition to
|
||||
either goes in a new module. The queue's new modules are all small
|
||||
(`server/ahead.rs`, `same_file.rs`, `completion/related.rs`, `server/viewport.rs`,
|
||||
`server/caret.rs`, `state/watched.rs`, `folding/directives.rs`, formatter
|
||||
`style.rs` / `auto.rs`); `server/dispatch.rs` is 503 and `server/index.rs`
|
||||
is where four of the eight features met.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
@@ -215,3 +227,5 @@ proven independent and run serially. Rules for a parallel wave:
|
||||
not actually independent, which is a planning failure to record.
|
||||
- After merging, the lead updates `docs/topo.md` for any edge a lane added
|
||||
or amended, so the next wave plans against reality.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+5
-1
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
@@ -13,7 +15,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.64.0"
|
||||
version = "0.66.2"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
@@ -44,3 +46,5 @@ serde_json = "=1.0.140"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# lucisv — Language Utility for Coding In SystemVerilog
|
||||
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
@@ -144,6 +146,9 @@ indent = 2 # 1..8, same as --indent
|
||||
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
||||
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
|
||||
|
||||
[format]
|
||||
style = "google" # a named layout, same as --style (see Named styles)
|
||||
|
||||
[lint]
|
||||
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
||||
ignore = ["module-filename"] # removed after selection
|
||||
@@ -173,11 +178,20 @@ error (exit 2) and nothing is processed. Details:
|
||||
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
|
||||
with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of
|
||||
the [named styles](#named-styles). The style is resolved first and supplies
|
||||
the starting indent and line length; an explicit `indent` or `line-length` —
|
||||
from a flag or from the file — then wins over the preset's, so
|
||||
`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An
|
||||
unknown style name is the same hard error as an unknown key, and lists the
|
||||
valid names. In the editor, `lucisv.toml` outranks the editor settings as for
|
||||
every formatting key, and a chosen style (other than `lucisv` or `auto`) also
|
||||
outranks the editor's tab size.
|
||||
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
|
||||
off by default, indents the `` `uvm_field_* `` macros written between
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
|
||||
formatting choice lucisv leaves to the project, because it changes bytes
|
||||
in existing UVM code (21 of the 860 corpus files).
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
|
||||
it is a formatting choice lucisv leaves to the project, because it changes
|
||||
bytes in existing UVM code (21 of the 860 corpus files).
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||
@@ -512,7 +526,8 @@ Key ideas carried over from ruff/prettier:
|
||||
|
||||
Defaults follow Verible: **2-space indent**, **100-column lines** (both
|
||||
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
|
||||
[Configuration](#configuration)).
|
||||
[Configuration](#configuration)). The list below is the default `lucisv`
|
||||
style; the [named styles](#named-styles) change some of it.
|
||||
|
||||
- One port / parameter / connection per line once a header doesn't fit
|
||||
- Cuddled `begin`/`end` (`end else begin`)
|
||||
@@ -521,6 +536,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
|
||||
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
|
||||
through verbatim
|
||||
|
||||
### Named styles
|
||||
|
||||
`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down
|
||||
pick one of a handful of house layouts. Every style moves whitespace only —
|
||||
which line a token starts on and how many spaces precede it — so the same
|
||||
token-equivalence check guards all of them, and each one is a fixed point of
|
||||
itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for
|
||||
every preset; `docs/features/format-styles/README.md`).
|
||||
|
||||
| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them |
|
||||
| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them |
|
||||
| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned |
|
||||
| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them |
|
||||
| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them |
|
||||
| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned |
|
||||
| `auto` | — | — | the preset the file is already closest to | | | | | |
|
||||
|
||||
`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html)
|
||||
and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md)
|
||||
(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses**
|
||||
at what those names suggest — C formatters' ANSI/Allman layout, clang-format's
|
||||
`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house
|
||||
style — not rules those organisations publish; none of them publishes a Verilog
|
||||
style that we could find. A `case` item's and a `do`'s `begin` stays on its
|
||||
own line's end in every style. "Header & connection lists" are module
|
||||
headers' parameter and port lists and instances' *named* overrides and
|
||||
connections — not `#(16)`, ordered connections or function ports. `lowrisc`
|
||||
differs from its guide in two places: the widest aligned connection keeps one
|
||||
space before its `(`, and a comment line ends an aligned table.
|
||||
|
||||
`auto` formats the file once per preset, at the configured indent and width,
|
||||
and keeps the output that changes the fewest lines (indentation included, so
|
||||
a one-line edit does not flip a whole file to another preset); it never
|
||||
guesses an indent or a width, and it is idempotent by construction.
|
||||
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under
|
||||
`auto`, range and selection formatting use the style of the whole file, not
|
||||
of the selected lines; the language server remembers each document's preset
|
||||
from its last whole-file format, so a keystroke or a selection does not
|
||||
search again, and a buffer with a parse error keeps its preset. One that has
|
||||
never resolved — no memory, and it does not parse — gets the default layout.
|
||||
|
||||
### Alignment is inferred, not imposed
|
||||
|
||||
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
|
||||
@@ -1089,3 +1147,5 @@ where the version number lives, how the `.vsix` is packaged, and what
|
||||
marketplace publishing would take if it ever happens — is in
|
||||
[`tools/RELEASING.md`](tools/RELEASING.md). lucisv is MIT licensed
|
||||
([`LICENSE`](LICENSE)).
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
@@ -1,3 +1,5 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# ROADMAP — autonomous coverage loop
|
||||
|
||||
Running log of the coverage-improvement loop (started 2026-08-20). The metric
|
||||
@@ -175,3 +177,5 @@ needs macro expansion, a deliberate non-goal) or not valid standalone
|
||||
Verilog. The stop condition holds before round 1 of a restart, so **no dev
|
||||
round was dispatched**. The loop resumes only if open question 2 is decided
|
||||
(a preprocessing model would put ~1.7% back in reach) or the corpus grows.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
@@ -1,3 +1,5 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# TODO-MCP — the Model Context Protocol block
|
||||
|
||||
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
|
||||
@@ -498,3 +500,5 @@ Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
|
||||
item's lines through `format_range` automatically — costs a refusal
|
||||
path when the safety net objects. Default in this plan: not automatic;
|
||||
the agent calls `format` with `lines`.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
@@ -1,3 +1,5 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# TODO — best practices adopted from ruff and Verible
|
||||
|
||||
Curated backlog for lucisv, drawn from `astral-sh/ruff` (architecture, CLI/UX,
|
||||
@@ -7247,3 +7249,282 @@ Feature README: `docs/features/port-entry-grace/README.md`. Files:
|
||||
- [x] The server withholds the diagnostics that fall inside the entry the
|
||||
last edit touched, and releases them after a quiet period or when the
|
||||
next edit lands elsewhere.
|
||||
|
||||
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
|
||||
|
||||
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
|
||||
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
|
||||
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
|
||||
`docs/features/{lucisv-server,large-file-mode}/README.md`.
|
||||
|
||||
- [x] Distinct semantic highlights across module instantiations (14-type wire
|
||||
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
|
||||
parameter values (`parameter`, distinct from `()`), instance name
|
||||
(`function`), `.port`/`.*` (`property`), and port connections
|
||||
(`variable`), including unfinished entries while typing.
|
||||
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
|
||||
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
|
||||
non-white TextMate scopes across themes.
|
||||
|
||||
## 70. The tests pass on Linux, and one cleaning round (2026-11-19, owner's order)
|
||||
|
||||
Every suite had only ever run on macOS arm64; the Linux and Windows binaries
|
||||
ship unexecuted. A `linux-x64` Actions runner now exists (`luhpe-linux-x64`,
|
||||
a resource-capped Docker-in-Docker container on the Gitea host), and the
|
||||
first trial of the suite in its job image found: clippy red on three unused
|
||||
imports in `lucisv_server` test modules (their only users are tests compiled
|
||||
on macOS/Windows alone), and 11 distinct failing tests out of ~5 300 — eight
|
||||
that set up an unreadable/unwritable path and so cannot fail as root (the
|
||||
job image's user), one that assumes a case-insensitive filesystem, two
|
||||
`…_in_linear_time` timing assertions. No product failure among them as far
|
||||
as the trial shows. One lane, `docs/features/linux-test-portability`;
|
||||
`tools/linux_check.sh` runs the working tree in that image without a push.
|
||||
|
||||
- [x] `cargo clippy --all-targets -- -D warnings` clean on Linux and on
|
||||
macOS (`crates/lucisv_server/src/hover.rs`, `includes.rs` test modules,
|
||||
and whatever else the Linux build names).
|
||||
- [x] The permission-denied tests (`crates/lucisv/tests/cli.rs`,
|
||||
`crates/lucisv_core/src/walk.rs`, `crates/lucisv_mcp/src/apply.rs` and
|
||||
`tests/cache.rs`, `tests/qa_m6.rs`, `crates/lucisv_server/src/state/tests/filelist.rs`)
|
||||
pass both as root and as an unprivileged user: where the platform does
|
||||
not enforce the permission the test says so and stops, it does not
|
||||
assert the opposite.
|
||||
- [x] `crates/lucisv_server/src/file_ops.rs`
|
||||
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`
|
||||
holds on a case-sensitive filesystem or is scoped to the insensitive
|
||||
ones, with the reason written at the test.
|
||||
- [x] `crates/lucisv_server/src/large.rs` — the two `…_in_linear_time`
|
||||
tests pass on the runner **and still fail when the conversion is
|
||||
quadratic** (shown, not asserted).
|
||||
- [x] The cleaning round: test code only, driven by what the tools report on
|
||||
either platform — unused imports and dead helpers, platform assumptions
|
||||
left implicit, assertions on wall-clock or environment that the runner
|
||||
shows to be fragile. No test is deleted and the test count does not
|
||||
drop; no production code and nothing in `verify.rs` changes.
|
||||
- [x] `cargo test --workspace` green on Linux as root and with `--user`,
|
||||
and `tools/gates.sh` green on macOS.
|
||||
- [x] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
|
||||
`docs/topo.md` and `tools/RELEASING.md` updated.
|
||||
|
||||
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
|
||||
|
||||
Ordered by the owner on 2026-11-19, to be done unattended after §70 lands:
|
||||
each item goes through the dev → QA → lead-review loop, is committed, and
|
||||
ships as its own release — `0.65.2`, `0.65.3`, … `0.65.n` in the order they
|
||||
finish — and once all are done, `0.66.0`. The lead has the owner's standing
|
||||
go-ahead to commit, tag and push for this queue. Every feature is tried on
|
||||
the OpenTitan tree (not only on unit fixtures) before it is called done.
|
||||
The items are the owner's words, lightly condensed; each gets its own
|
||||
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
||||
|
||||
- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`)
|
||||
Today every
|
||||
file edit re-indexes everything. A change to a `define` may have to;
|
||||
a typical, localized edit must not.
|
||||
- [x] **71.2 Actions stay fast on a huge, heavily-dependent tree.** (0.65.11, `docs/features/fast-actions`) Do the
|
||||
work dynamically: answer first from what is already in the same file
|
||||
(hover to a definition in this file), and use the relationship map to
|
||||
load completion candidates on demand.
|
||||
- [x] **71.3 Highlighting does not wait for the index.** (0.65.10, `docs/features/viewport-highlight`)
|
||||
Always run a
|
||||
localized, viewport-only highlight; it may be imperfect and be
|
||||
corrected later, but basic colours must not wait for the whole
|
||||
database.
|
||||
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
|
||||
sticky-scroll ("floating") bars.
|
||||
- [x] **71.5 The formatter adapts to the file's own style** (0.65.5, `docs/features/format-styles`: six named styles and `auto`)
|
||||
— where lines
|
||||
break, what is grouped, how ports align. If inferring that is too
|
||||
ambiguous, a setting with a drop-down of named styles instead (ANSI,
|
||||
Google, Microsoft, NXP — educated guesses), with the rules easy to
|
||||
read in the source.
|
||||
- [x] **71.6 The module view shows where you are.** (0.65.2, `docs/features/hierarchy-current-path`; not yet seen in a running editor.)
|
||||
Highlight the open
|
||||
file's instance and its parents in different shades — bright light
|
||||
orange for the instance, dimmer the further up — or anything in that
|
||||
spirit that makes the hierarchy easy to read.
|
||||
- [x] **71.7 Find References sometimes answers "not found"** (0.65.8, `docs/features/scan-ordering`: a server bug — the caret just past a name)
|
||||
on a
|
||||
port/signal, then works after clicking elsewhere and back. VS Code or
|
||||
the server? Investigate, then fix what is ours.
|
||||
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
|
||||
(the `[]` of
|
||||
`signal[]` gets highlighted today), **but do highlight `TODO`,
|
||||
`FIXME`, `FIX_ME`, `TBD`**, plus a user setting for custom words that
|
||||
are highlighted only in comments.
|
||||
- [x] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
|
||||
|
||||
### 71 — wave 1 (lead, 2026-11-19): 71.6 runs beside §70
|
||||
|
||||
The owner asked not to wait for §70's Linux runs. §70 is test code in the
|
||||
Rust crates and touches no contract; 71.6 is the extension's hierarchy view
|
||||
(`editors/vscode/hierarchy*.js`, `package.json`, the extension README and
|
||||
changelog). Disjoint file sets, and the one edge between the two areas
|
||||
(`editors/vscode ◀──▶ lucisv_server`, the spawn contract) is touched by
|
||||
neither — so they run as two lanes: §70 on trunk's tree (already in flight
|
||||
there), 71.6 in the worktree `../lucisv-wt/71.6` on `lane/71.6-module-view`,
|
||||
branched from `88546c8`. 71.1–71.3 all live in `lucisv_server`'s state and
|
||||
indexing, collide with each other and with §70's test files, and wait for
|
||||
§70 to merge.
|
||||
|
||||
- Lane 71.6 owns: `editors/vscode/hierarchyView.js`, `hierarchyModel.js`,
|
||||
`hierarchySections.js` and their `_test.js` files, new
|
||||
`editors/vscode/*.js` modules it adds, `editors/vscode/package.json`
|
||||
(`contributes` only — not `version`), `editors/vscode/.vscodeignore`,
|
||||
`tools/release.sh`'s runtime-module checks if a new module needs listing,
|
||||
`docs/features/hierarchy-current-path/README.md`.
|
||||
|
||||
- Wave 2 (lead, 2026-11-19): 71.6 shipped as 0.65.2 (`e9f5090`). §70 is still
|
||||
in flight on trunk's tree, so the next lane is again one that stays out of
|
||||
the Rust test files: **71.8** (comments), in `../lucisv-wt/71.8` on
|
||||
`lane/71.8-comments` from `e9f5090`. It owns
|
||||
`editors/vscode/syntaxes/*`, `language-configuration.json`, new
|
||||
`editors/vscode/*.js` modules and tests, `extension.js` wiring,
|
||||
`package.json` `contributes`, `.vscodeignore`, the extension README, and —
|
||||
only if the stray colour turns out to come from the server's semantic
|
||||
tokens — `crates/lucisv_server/src/tokens.rs` and `tokens/`, which §70
|
||||
does not touch. `docs/features/comment-highlighting/README.md`.
|
||||
|
||||
- Wave 3 (lead, 2026-11-19): 71.8 shipped as 0.65.3 (`948f8a0`) and 71.4 as
|
||||
0.65.4 (`d574969`), each from its own worktree; both tagged locally and
|
||||
**not pushed** — the owner's ssh key left the agent at about 05:00 (its
|
||||
`AddKeysToAgent 1h`), which also stops `tools/linux_check.sh`. §70 is
|
||||
committed on macOS evidence with its Linux line left open. 71.5 (formatter
|
||||
styles) runs in `../lucisv-wt/71.5` from `d574969`. Owed once ssh is back,
|
||||
in this order: push master and the tags one at a time; re-run §70 on Linux
|
||||
(root twice, `--user`); add the `linux` job to `ci.yml`.
|
||||
|
||||
- Wave 4 (lead, 2026-11-19): 71.5 shipped as 0.65.5 from `../lucisv-wt/71.5`,
|
||||
rebased onto §70's commit. 71.1 (localized re-index) is with QA in
|
||||
`../lucisv-wt/71.1`. Found on the way by 71.5's QA, all present in 0.65.4
|
||||
and filed here, not fixed:
|
||||
- [ ] A comment between a generate `end` and `else` (also a trailing `// c`
|
||||
after a labelled generate `end` before `else`) is a verification
|
||||
error: the file is left unformatted. The safety net works; the
|
||||
formatter should not need it.
|
||||
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
|
||||
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
|
||||
- [x] The server's `line-length` lint falls back to 100 columns under the
|
||||
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
|
||||
when 71.1 merges.
|
||||
- [ ] One-per-line styles give multi-instance declarations
|
||||
(`p1 u8 (...), u9 (...)`) the hanging layout.
|
||||
|
||||
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
|
||||
stale answers), a fix round, a QA pass and a last small round. What the
|
||||
QA rounds and a read-only investigation turned up, all present before this
|
||||
wave, becomes lane **71.7** (the owner's Find References item, widened):
|
||||
- [x] A caret just past an identifier's last letter asks about the next
|
||||
character: references, definition, hover and highlight come back
|
||||
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
|
||||
"not found, then works after clicking back".
|
||||
- [x] A `didChange` arriving during a whole rescan can overtake an older
|
||||
one still queued (`server/mod.rs` `process_batch`): with incremental
|
||||
sync the server's buffer is corrupted until the file is reopened.
|
||||
- [x] A burst `[request, didOpen]` during the startup scan is re-held at
|
||||
every file (`server/index.rs` `answer_what_is_waiting`): the scan
|
||||
takes ~300 s on OpenTitan instead of ~1.7 s.
|
||||
- [ ] A watcher event naming only a directory leaves stale state; an
|
||||
excluded buffer stays indexed after close; symlinked files are held
|
||||
under one or both spellings depending on what was open.
|
||||
71.3 (viewport highlighting) passed QA with a gap in the default folder
|
||||
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
|
||||
closes that in its fix round. Then 71.2.
|
||||
|
||||
- 0.65.6 never published (lead, 2026-11-19): the release build failed to
|
||||
compile `lucisv-server` for Windows — `dir_id` is a `Copy` pair on unix and
|
||||
a `PathBuf` elsewhere, and 71.1's new code moved it in a closure
|
||||
(`state/incremental.rs`). The gate caught nothing because nothing before
|
||||
the release build compiles for another platform. Fixed by the lead (one
|
||||
line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a
|
||||
`cross` step so the next one is caught before the tag. Seven of the eight
|
||||
§71 items therefore have releases 0.65.2–0.65.5 and 0.65.7.
|
||||
|
||||
- Wave 6 (lead, 2026-11-19): 71.7 shipped as 0.65.8. Left open from it and
|
||||
from its QA, all older than this series:
|
||||
- [ ] A request held during a scan is answered against the newest text; a
|
||||
position-based one can resolve a different symbol when an edit moved
|
||||
the text under it, and rename edits carry no document version.
|
||||
- [ ] An unheld buffer opened while a scan runs is never taken in
|
||||
afterwards; closing an unsaved in-scope buffer a rescan had indexed
|
||||
leaves its text in the index.
|
||||
- [ ] Renaming a port of a module defined twice gives an edit or a refusal
|
||||
at random (`qa717/drv/dup.py`).
|
||||
- [ ] Directory-only watcher events (needs a broader watcher
|
||||
registration — the owner's call), excluded buffers after close (a
|
||||
cheap fix belongs in the index layer: adding a file is a wide
|
||||
change), symlink spellings.
|
||||
|
||||
- §70 closed (lead, 2026-11-19), shipped with 0.65.9. Once ssh was back the
|
||||
suite proved flaky on Linux (3 of 9 runs): two test helpers that insisted
|
||||
a write to a child's stdin succeed, a 200 ms wall-clock bound, an MCP test
|
||||
that could hang on an inherited pipe — and one real bug, `lucisv-mcp`
|
||||
serving stale contents after a same-tick, same-size rewrite on Linux
|
||||
(`project/files.rs`, the racy rule covered the mtime alone). All fixed in
|
||||
lane 70b (`docs/features/linux-test-portability`, Round 2); Linux is green
|
||||
10/10 as root and as a user (dev) and 6/6 each (QA); `ci.yml` has its
|
||||
`linux` job. Left open:
|
||||
- [ ] A file with an mtime in the future is re-read by `lucisv-mcp` on
|
||||
every call, forever (67 ms against 7 ms per `find` on 4 000 files).
|
||||
- [ ] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
|
||||
exit code.
|
||||
- [ ] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
|
||||
`cargo check --all-targets` for Windows fails there (tests only).
|
||||
- [ ] The release is still gated on macOS alone; Windows is compile-checked
|
||||
(`cross`), never executed.
|
||||
|
||||
- Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto
|
||||
0.65.8's message loop by hand and re-validated by a second QA round. Left
|
||||
open from it:
|
||||
- [ ] The discovery walk at the start of every scan answers nothing while
|
||||
it runs: a late open in workspace scope still waits 62–86 ms for
|
||||
colour and a rescan holds colours 70–159 ms. Making the walk
|
||||
resumable needs its own identical-result proof (`state/discover.rs`).
|
||||
- [ ] A `range` answered during a rescan always counts as a guess and
|
||||
costs one refresh at settle even when nothing changed.
|
||||
- [ ] An edit in one file that changes how another OPEN file colours sends
|
||||
no refresh (as before this lane).
|
||||
|
||||
- Wave 8 (lead, 2026-11-19): 71.2 shipped as 0.65.11 after four dev rounds
|
||||
and four QA rounds — two QA failures, so the last round ran with Fable 5.2
|
||||
as dev and QA (`docs/features/fast-actions`, Review). Left open from it:
|
||||
- [ ] Inside the startup settings wait, the client's answer to the pull is
|
||||
applied ahead of an older settings push held with it
|
||||
(`server/startup.rs`, `take_the_answer_out_of_held`; predates the
|
||||
lane; needs a client whose push and answer disagree in one burst).
|
||||
- [ ] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the
|
||||
reference gives after any later message of the round: 2–9 % of
|
||||
injected stale answers pass when a later message restores the state.
|
||||
- [ ] Whether a large open buffer is in the index depends on when it was
|
||||
opened, saved or scanned (predates the lane; 77–98 answers differ
|
||||
between a settled session and a fresh server on OpenTitan).
|
||||
- [ ] The 40 000-file rescan after a delete takes either 12.3 s or
|
||||
14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found.
|
||||
|
||||
## 72. Sticky scroll pins the module instance (planned 2026-11-19, owner's order)
|
||||
|
||||
Owner: "only the module definition is floating. I want to extend this a
|
||||
little so that the module instance would be floating as well." Folds come
|
||||
only from keyword pairs and `` `ifdef `` branches, so nothing delimited by
|
||||
`( )` pins. Surveyed on OpenTitan `hw` (4 047 files): 162 instances of 50+
|
||||
lines, none pinned; 132 of them write `#(` on the type line, so the instance
|
||||
name sits on a later `) u_name (` line. Example:
|
||||
`hw/ip/aes/rtl/aes_control_fsm_n.sv:382-594`. One lane (dev, then QA),
|
||||
feature README `docs/features/instance-folding/README.md`.
|
||||
|
||||
- [x] `crates/lucisv_server/src/folding/instances.rs` (new): one fold per
|
||||
multi-line module instantiation from its module-type line, and one more
|
||||
per instance from the line its name is on when that is a different
|
||||
line, so both `aes_control_fsm #(` and `) u_aes_control_fsm (` pin
|
||||
while the reader is in the connection list. The closing line stays
|
||||
visible, as for every scope fold.
|
||||
- [x] `crates/lucisv_server/src/folding.rs`: the third source merged through
|
||||
`in_answer_order`; every fold the server answered before is still
|
||||
there, unchanged and first on a shared start line.
|
||||
- [x] Tests in the same change, and `folding/opentitan_sweep.rs` extended:
|
||||
instances counted independently, existing folds proven unchanged.
|
||||
- [x] `editors/vscode/README.md`: the sticky-scroll row names the instance.
|
||||
- [x] Seen in a running VS Code (owner, 2026-11-19, on the local 0.66.1
|
||||
build). Shipped as 0.66.1.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
[package]
|
||||
name = "lucisv"
|
||||
version.workspace = true
|
||||
@@ -15,3 +17,5 @@ vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
rayon = { workspace = true }
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,7 +1,9 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Hand-rolled command line parsing for the `lucisv` binary.
|
||||
|
||||
use lucisv_core::cache;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use lucisv_core::config::{self, FileConfig};
|
||||
use vlog_formatter::{Config, LineRanges};
|
||||
|
||||
/// Which tool this invocation runs.
|
||||
@@ -58,6 +60,8 @@ pub struct Options {
|
||||
pub line_length: Option<usize>,
|
||||
/// `--indent`, if given; otherwise the config file decides.
|
||||
pub indent: Option<usize>,
|
||||
/// `--style`, if given; otherwise the config file decides.
|
||||
pub style: Option<&'static str>,
|
||||
/// `--lines`: format only the constructs meeting these lines. `None` is a
|
||||
/// whole-file run.
|
||||
pub lines: Option<LineRanges>,
|
||||
@@ -98,8 +102,13 @@ impl Options {
|
||||
}
|
||||
|
||||
/// Formatter settings for one file: CLI flag > config file > default.
|
||||
///
|
||||
/// The style is resolved first and supplies the starting indent and line
|
||||
/// length; an explicit `indent`/`line-length`, from the flag or the file,
|
||||
/// is then written over the preset's, whichever rung named the style.
|
||||
pub fn config_with(&self, file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
let name = self.style.or(file.format_style);
|
||||
let mut config = name.and_then(Config::named).unwrap_or_default();
|
||||
if let Some(n) = self.line_length.or(file.line_length) {
|
||||
config.max_width = n;
|
||||
}
|
||||
@@ -196,6 +205,12 @@ OPTIONS:
|
||||
filelist, and neither reads nor writes the cache
|
||||
--line-length <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
--style <NAME> layout preset: lucisv (the default), google,
|
||||
lowrisc, ansi, microsoft or nxp. It sets the indent
|
||||
and line length too; --indent/--line-length (or the
|
||||
config file's keys) still win over the preset's.
|
||||
`auto` lays each file out in the preset it is
|
||||
already closest to, at the default indent/width
|
||||
--no-config ignore lucisv.toml / .lucisv.toml files
|
||||
-h, --help show this help
|
||||
-V, --version show version
|
||||
@@ -275,7 +290,7 @@ FILELISTS:
|
||||
|
||||
CACHE:
|
||||
A file whose exact content lucisv has already verified is formatted — under
|
||||
the same line-length, indent and lucisv version — is skipped on the next run
|
||||
the same line-length, indent, style and lucisv version — is skipped on the next run
|
||||
and reported as `N files from cache`. Only that \"already formatted\"
|
||||
verdict is ever cached: a file that would be reformatted, or that failed,
|
||||
is re-checked every run. The cache is one text file under `.lucisv_cache/`;
|
||||
@@ -288,10 +303,12 @@ CONFIGURATION:
|
||||
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
||||
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
||||
paths, resolved against the config file's own directory). A command line
|
||||
one, so `lucisv rtl/` always means the directory it was given). The
|
||||
`[format]` table takes `style` (a preset name, as `--style`) and
|
||||
`uvm-utils-indent` (true/false). The `[lint]` table takes `select` and
|
||||
`ignore` (arrays of rule names, `--select`/`--ignore` semantics) and
|
||||
`waivers` (an array of waiver file paths, resolved against the config
|
||||
file's own directory). A command line
|
||||
flag overrides the file's corresponding key; the other keys still apply —
|
||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||
replacing it.
|
||||
@@ -335,6 +352,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
exclude: Vec::new(),
|
||||
line_length: None,
|
||||
indent: None,
|
||||
style: None,
|
||||
lines: None,
|
||||
output_format: OutputFormat::Text,
|
||||
fix: false,
|
||||
@@ -400,6 +418,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let v = args.next().ok_or("--indent requires a value")?;
|
||||
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
|
||||
}
|
||||
"--style" => {
|
||||
let v = args.next().ok_or("--style requires a value")?;
|
||||
opts.style = Some(config::parse_style(&v)?);
|
||||
}
|
||||
"--lines" => {
|
||||
let v = args.next().ok_or("--lines requires a value")?;
|
||||
line_specs.push(v);
|
||||
@@ -526,6 +548,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_formatter::style;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_from(args.iter().map(|s| s.to_string()))
|
||||
@@ -568,6 +591,52 @@ mod tests {
|
||||
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_sets_the_starting_values_and_explicit_ones_win() {
|
||||
let none = FileConfig::default();
|
||||
let opts = parse(&["--style", "microsoft", "rtl"]).unwrap();
|
||||
let config = opts.config_with(&none);
|
||||
assert_eq!(config.style, style::MICROSOFT);
|
||||
assert_eq!((config.indent_width, config.max_width), (4, 120));
|
||||
// The file's explicit keys beat the flag's preset...
|
||||
let file = FileConfig { indent: Some(3), ..Default::default() };
|
||||
assert_eq!(opts.config_with(&file).indent_width, 3);
|
||||
assert_eq!(opts.config_with(&file).max_width, 120);
|
||||
// ...and the flag beats the file's style.
|
||||
let google = FileConfig { format_style: Some("google"), ..Default::default() };
|
||||
assert_eq!(opts.config_with(&google).style, style::MICROSOFT);
|
||||
let opts = parse(&["--indent", "2", "rtl"]).unwrap();
|
||||
let config = opts.config_with(&google);
|
||||
assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2));
|
||||
// No style anywhere is exactly the old default.
|
||||
let config = parse(&["rtl"]).unwrap().config_with(&none);
|
||||
assert_eq!(config.style, style::LUCISV);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_style_names_the_styles() {
|
||||
let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") };
|
||||
assert!(message.contains("unknown style `allman`"), "{message}");
|
||||
assert!(
|
||||
message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(parse(&["--style"]).is_err());
|
||||
}
|
||||
|
||||
/// `lucisv_core` keeps its own copy of the names so it can reject a bad
|
||||
/// `[format] style` without depending on the formatter; this is the test
|
||||
/// that keeps the copy honest.
|
||||
#[test]
|
||||
fn the_core_style_names_are_the_formatter_presets() {
|
||||
let mut names: Vec<&str> = style::names().collect();
|
||||
names.push("auto");
|
||||
assert_eq!(names, config::STYLE_NAMES);
|
||||
for name in config::STYLE_NAMES {
|
||||
assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_excludes_are_appended_to_cli_excludes() {
|
||||
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
|
||||
@@ -684,3 +753,5 @@ mod tests {
|
||||
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,5 +1,9 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `--diff`'s unified diff. The printer lives in `lucisv_core::diff`, shared
|
||||
//! with the MCP server's `dry_run` (Handshake MCP-1, a pure move); this module
|
||||
//! keeps the CLI's `diff::unified` path.
|
||||
|
||||
pub use lucisv_core::diff::unified;
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The `lucisv check` driver: lint files, print diagnostics, apply fixes.
|
||||
//!
|
||||
//! Everything about *which* files are linted — the walk, `--exclude`,
|
||||
@@ -880,3 +882,5 @@ mod tests {
|
||||
assert_eq!(quote("bell\u{7}"), "\"bell\\u0007\"");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! lucisv — a Verilog/SystemVerilog formatter and linter in the spirit of
|
||||
//! `ruff format` and `ruff check`.
|
||||
//!
|
||||
@@ -338,6 +340,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
line_length: config.max_width,
|
||||
indent: config.indent_width,
|
||||
uvm_utils_indent: config.uvm_utils_indent,
|
||||
style: config.style_name(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,3 +668,5 @@ mod tests {
|
||||
assert!(err.contains("parse error"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
+56
-12
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! End-to-end tests that drive the real `lucisv` binary.
|
||||
//!
|
||||
//! Fixtures use the most trivial Verilog possible so these tests stay
|
||||
@@ -92,16 +94,29 @@ fn run_in(dir: &TempDir, args: &[&str]) -> Output {
|
||||
Command::new(LUCISV).args(args).current_dir(&dir.path).output().expect("run lucisv")
|
||||
}
|
||||
|
||||
/// Runs lucisv with the cache switched off, `input` on its stdin.
|
||||
fn run_with_stdin(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(LUCISV)
|
||||
.args(with_no_cache(args))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn lucisv");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
child.wait_with_output().expect("run lucisv")
|
||||
run_with_stdin_raw(&with_no_cache(args), input)
|
||||
}
|
||||
|
||||
/// Writes `input` to the child's stdin and closes it.
|
||||
///
|
||||
/// A child that exits without reading — a usage error refuses before it
|
||||
/// looks at stdin — is legitimate, and the write then races its exit: it
|
||||
/// fails with `BrokenPipe` when the child is already gone. That one error is
|
||||
/// not the test's business; the exit code and output the caller asserts on
|
||||
/// are. (A successful write never meant the child read anything either:
|
||||
/// every input here is far smaller than a pipe's buffer, so the write lands
|
||||
/// in the buffer whether or not the child ever reads it.) Any other error is
|
||||
/// a failure.
|
||||
fn feed(child: &mut std::process::Child, input: &str) {
|
||||
let mut stdin = child.stdin.take().expect("stdin");
|
||||
match stdin.write_all(input.as_bytes()) {
|
||||
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
panic!("write stdin: {error:?}")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn code(out: &Output) -> i32 {
|
||||
@@ -1268,7 +1283,8 @@ impl TempDir {
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries. The
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`,
|
||||
/// and the style is always the default, `lucisv`.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
@@ -1278,7 +1294,7 @@ fn cache_line(
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1754,6 +1770,7 @@ fn lines_neither_reads_nor_writes_the_cache() {
|
||||
assert!(!fresh.cache_file().exists(), "a range run must not seed the cache");
|
||||
}
|
||||
|
||||
/// Runs lucisv exactly as given, cache and all, `input` on its stdin.
|
||||
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(LUCISV)
|
||||
.args(args)
|
||||
@@ -1762,7 +1779,7 @@ fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn lucisv");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
feed(&mut child, input);
|
||||
child.wait_with_output().expect("run lucisv")
|
||||
}
|
||||
|
||||
@@ -2241,11 +2258,33 @@ fn unlock(dir: &TempDir) {
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 directory refuses to be
|
||||
/// listed. Root lists it anyway (Linux CI jobs run as root), and there a
|
||||
/// directory the walk cannot read cannot be built, so the tests below say so
|
||||
/// and stop instead of asserting a warning that cannot happen.
|
||||
#[cfg(unix)]
|
||||
fn listing_is_refused() -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let probe = TempDir::new("mode-probe");
|
||||
let shut = probe.path.join("shut");
|
||||
std::fs::create_dir(&shut).expect("probe dir");
|
||||
std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
let refused = std::fs::read_dir(&shut).is_err();
|
||||
let _ = std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o755));
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
|
||||
// The finding TODO §45.2 closes: one permission-denied directory used to
|
||||
// propagate `read_dir`'s error and fail the whole run.
|
||||
if !listing_is_refused() {
|
||||
return;
|
||||
}
|
||||
let dir = unwalkable_tree("walk-warn");
|
||||
let out = run(&[&dir.root()]);
|
||||
unlock(&dir);
|
||||
@@ -2262,6 +2301,9 @@ fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted()
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
|
||||
if !listing_is_refused() {
|
||||
return;
|
||||
}
|
||||
let dir = unwalkable_tree("walk-warn-check");
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
@@ -2423,3 +2465,5 @@ fn text_that_merely_says_package_changes_no_finding() {
|
||||
"{plain}\n---\n{with_noise}"
|
||||
);
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,175 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `--style` and `[format] style` through the real `lucisv` binary: the
|
||||
//! flag, the config key, their precedence over each other and under the
|
||||
//! explicit `indent`/`line-length`, the error for a name that is not a
|
||||
//! preset, and the format cache keyed on the style.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const LUCISV: &str = env!("CARGO_BIN_EXE_lucisv");
|
||||
|
||||
/// One `if`/`else` whose layout every switch of `ansi` changes.
|
||||
const SOURCE: &str =
|
||||
"module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n";
|
||||
const LUCISV_OUT: &str = "\
|
||||
module m;
|
||||
initial
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end else begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
const ANSI_OUT: &str = "\
|
||||
module m;
|
||||
initial
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
else
|
||||
begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A throwaway directory under the system temp dir, removed on drop.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv-style-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
// Discovery stops at a `.git`, so no config above the temp dir leaks in.
|
||||
std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, contents: &str) -> String {
|
||||
let path = self.path.join(rel);
|
||||
std::fs::write(&path, contents).expect("write fixture");
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn read(&self, rel: &str) -> String {
|
||||
std::fs::read_to_string(self.path.join(rel)).expect("read fixture")
|
||||
}
|
||||
|
||||
fn cache(&self) -> String {
|
||||
self.path.join("cache").to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(LUCISV).args(args).output().expect("run lucisv")
|
||||
}
|
||||
|
||||
fn code(out: &Output) -> i32 {
|
||||
out.status.code().expect("exit code")
|
||||
}
|
||||
|
||||
fn stdout(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
fn stderr(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stderr).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_picks_a_preset() {
|
||||
let dir = TempDir::new("flag");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stdout(&out), ANSI_OUT);
|
||||
let out = run(&["--no-cache", "--stdout", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "no style is the default layout");
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "and `lucisv` is that same layout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_config_key_picks_a_preset_and_the_flag_beats_it() {
|
||||
let dir = TempDir::new("toml");
|
||||
dir.write("lucisv.toml", "[format]\nstyle = \"ansi\"\n");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
assert_eq!(code(&run(&["--no-cache", &path])), 0);
|
||||
assert_eq!(dir.read("a.sv"), ANSI_OUT);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "CLI flag > config file");
|
||||
let out = run(&["--no-cache", "--stdout", "--no-config", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "--no-config drops the style with the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_indent_wins_over_the_presets() {
|
||||
let dir = TempDir::new("indent");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", "--indent", "2", &path]);
|
||||
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
|
||||
// The file's `indent` beats the flag's preset too: an explicit value is
|
||||
// explicit wherever it was written.
|
||||
dir.write("lucisv.toml", "indent = 2\n");
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
|
||||
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_style_is_an_error_that_lists_the_presets() {
|
||||
let dir = TempDir::new("unknown");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--style", "allman", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
|
||||
assert!(
|
||||
stderr(&out).contains("lucisv, google, lowrisc, ansi, microsoft, nxp"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
// The same in `lucisv.toml`, naming the file and the line; nothing written.
|
||||
let config = dir.write("lucisv.toml", "indent = 2\n[format]\nstyle = \"allman\"\n");
|
||||
let out = run(&["--no-cache", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains(&format!("{config}:3:")), "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), SOURCE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_style_invalidates_the_cache_entry() {
|
||||
let dir = TempDir::new("cache");
|
||||
let path = dir.write("a.sv", LUCISV_OUT);
|
||||
let cache = dir.cache();
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
// The same bytes are not clean under another style, cache or no cache.
|
||||
let out = run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "the style is part of the key: {}", stderr(&out));
|
||||
// And a clean verdict under `ansi` is not one under the default.
|
||||
dir.write("a.sv", ANSI_OUT);
|
||||
assert_eq!(code(&run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache])), 0);
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
[package]
|
||||
name = "lucisv_core"
|
||||
version.workspace = true
|
||||
@@ -10,3 +12,5 @@ name = "lucisv_core"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Replacing a file's contents without ever leaving it half written.
|
||||
//!
|
||||
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
||||
@@ -449,3 +451,5 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The "already formatted" cache: a per-path record of content that a
|
||||
//! previous run verified is a fixed point, so a repeat run can skip the
|
||||
//! file entirely.
|
||||
@@ -12,6 +14,8 @@ use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::STYLE_NAMES;
|
||||
|
||||
/// The default cache directory, resolved against the current directory.
|
||||
pub const DEFAULT_DIR: &str = ".lucisv_cache";
|
||||
|
||||
@@ -35,6 +39,10 @@ pub struct Entry {
|
||||
/// The `[format] uvm-utils-indent` that verdict was reached under: it
|
||||
/// changes the output of a UVM class, so it is part of the key.
|
||||
pub uvm_utils_indent: bool,
|
||||
/// The `[format] style` that verdict was reached under, one of
|
||||
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
|
||||
/// differently, so it is part of the key.
|
||||
pub style: &'static str,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
@@ -107,8 +115,8 @@ impl Cache {
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
||||
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
|
||||
);
|
||||
}
|
||||
text
|
||||
@@ -154,28 +162,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let fields: Vec<&str> = line.splitn(6, '\t').collect();
|
||||
let fields: Vec<&str> = line.splitn(7, '\t').collect();
|
||||
match fields[..] {
|
||||
[content, line_length, indent, uvm, version, path] => {
|
||||
[content, line_length, indent, uvm, style, version, path] => {
|
||||
let (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||
let uvm_utils_indent = uvm.parse().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
// A style this build does not know is another build's
|
||||
// entry: stale, not corrupt.
|
||||
let known = STYLE_NAMES.into_iter().find(|n| *n == style);
|
||||
if let (Some(style), true) = (known, version == VERSION) {
|
||||
entries.insert(
|
||||
path.to_string(),
|
||||
Entry { content, line_length, indent, uvm_utils_indent },
|
||||
Entry { content, line_length, indent, uvm_utils_indent, style },
|
||||
);
|
||||
}
|
||||
}
|
||||
// A store written before `uvm-utils-indent` joined the key: a
|
||||
// well-formed line of that older shape says nothing about the
|
||||
// option, so it is dropped individually, exactly like another
|
||||
// version's entry. (The version field alone already makes such
|
||||
// a store miss; the codec stays self-describing anyway.)
|
||||
// Anything else on five fields is corruption and discards the
|
||||
// file like any other malformed line.
|
||||
// A store written before `style` joined the key: a well-formed
|
||||
// line of that older shape says nothing about the style, so it is
|
||||
// dropped individually, exactly like another version's entry.
|
||||
[content, line_length, indent, uvm, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
uvm.parse::<bool>().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// And the same for the shape before `uvm-utils-indent` joined it.
|
||||
// (The version field alone already makes such a store miss; the
|
||||
// codec stays self-describing anyway.) Anything else on five or
|
||||
// six fields is corruption and discards the file like any other
|
||||
// malformed line.
|
||||
[content, line_length, indent, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
if path.is_empty() {
|
||||
@@ -228,7 +247,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,6 +281,7 @@ mod tests {
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
@@ -276,7 +296,7 @@ mod tests {
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, on);
|
||||
cache.store();
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\tlucisv\t"), "{}", dir.cache_text());
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, on));
|
||||
@@ -291,7 +311,7 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
@@ -308,6 +328,37 @@ mod tests {
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() {
|
||||
// The six-field shape lucisv wrote before `style` joined the key, and
|
||||
// a style this build does not know: both stale, never corruption.
|
||||
let dir = TempDir::new("nostyle");
|
||||
let old = dir.file("old.sv");
|
||||
let other = dir.file("other.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
other.to_string_lossy(),
|
||||
3,
|
||||
mine.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), text).unwrap();
|
||||
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted");
|
||||
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) }));
|
||||
assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) }));
|
||||
assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key");
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
@@ -325,7 +376,7 @@ mod tests {
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
@@ -350,13 +401,19 @@ mod tests {
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
|
||||
"\0\0\0\n",
|
||||
] {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let file = dir.file("a.sv");
|
||||
// A good line first: a bad one anywhere discards all of them.
|
||||
let good =
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
let good = format!(
|
||||
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
file.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
@@ -369,8 +426,8 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
@@ -484,3 +541,5 @@ mod tests {
|
||||
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
|
||||
//!
|
||||
//! Only what a small config file needs is supported (comments, `key = int`,
|
||||
@@ -11,7 +13,14 @@ use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// Config file names, in the order a directory is probed.
|
||||
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
|
||||
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
|
||||
|
||||
/// The names `[format] style` accepts: the formatter's presets, in its
|
||||
/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so
|
||||
/// does not depend on the formatter; the two lists are held equal by a test
|
||||
/// in the `lucisv` crate, which sees both.
|
||||
pub const STYLE_NAMES: [&str; 7] =
|
||||
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
|
||||
|
||||
/// The settings one config file carries. Every key is optional; an unset
|
||||
/// key leaves the CLI flag (or the built-in default) in charge.
|
||||
@@ -34,6 +43,9 @@ pub struct FileConfig {
|
||||
/// statements written between `` `uvm_*_utils_begin `` and
|
||||
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
||||
pub format_uvm_utils_indent: Option<bool>,
|
||||
/// `[format] style`: the named layout preset, one of [`STYLE_NAMES`].
|
||||
/// Checked here, so a misspelt name fails the run like a misspelt key.
|
||||
pub format_style: Option<&'static str>,
|
||||
/// `[lint] select`: run exactly these rules, replacing the default set.
|
||||
/// The names are **not** validated here — this crate does not know the
|
||||
/// rule registry; `lucisv check` validates them the moment it resolves the
|
||||
@@ -176,23 +188,30 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
uvm-utils-indent under `[format]`; \
|
||||
style, uvm-utils-indent under `[format]`; \
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[format]` table: a boolean that defaults to off, because
|
||||
/// it changes how already-clean files are laid out and a project has to opt
|
||||
/// in before anything of its moves.
|
||||
/// One key of the `[format]` table: the named `style`, or a boolean that
|
||||
/// defaults to off, because it changes how already-clean files are laid out
|
||||
/// and a project has to opt in before anything of its moves.
|
||||
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "style" {
|
||||
if config.format_style.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
config.format_style = Some(parse_style(&parse_string(value)?)?);
|
||||
return Ok(());
|
||||
}
|
||||
let slot = match key {
|
||||
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[format]` \
|
||||
(the only key is uvm-utils-indent)"
|
||||
(known keys: style, uvm-utils-indent)"
|
||||
))
|
||||
}
|
||||
};
|
||||
@@ -203,6 +222,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One of [`STYLE_NAMES`], exactly as spelt there.
|
||||
pub fn parse_style(name: &str) -> Result<&'static str, String> {
|
||||
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
|
||||
format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", "))
|
||||
})
|
||||
}
|
||||
|
||||
/// `true` or `false`, and nothing else — a misspelling is a typo the user
|
||||
/// wants to hear about, not a silent `false`.
|
||||
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
||||
@@ -614,6 +640,32 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
}
|
||||
|
||||
/// `[format] style` names a preset; anything else is an error that lists
|
||||
/// the presets, the way an unknown key lists the keys.
|
||||
#[test]
|
||||
fn the_format_table_carries_a_style() {
|
||||
assert_eq!(ok("[format]\nstyle = \"google\"").format_style, Some("google"));
|
||||
assert_eq!(ok("[format]\nstyle = \"lucisv\" # the default").format_style, Some("lucisv"));
|
||||
assert_eq!(ok("indent = 4").format_style, None);
|
||||
for name in STYLE_NAMES {
|
||||
assert_eq!(ok(&format!("[format]\nstyle = \"{name}\"")).format_style, Some(name));
|
||||
}
|
||||
let unknown = err("[format]\nstyle = \"gogle\"");
|
||||
assert!(unknown.contains("unknown style `gogle`"), "{unknown}");
|
||||
assert!(
|
||||
unknown.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
|
||||
"{unknown}"
|
||||
);
|
||||
assert!(err("[format]\nstyle = \"Google\"").contains("unknown style `Google`"));
|
||||
assert!(err("[format]\nstyle = google").contains("expected a quoted string"));
|
||||
assert!(
|
||||
err("[format]\nstyle = \"ansi\"\nstyle = \"nxp\"").contains("duplicate key `style`")
|
||||
);
|
||||
// Like `uvm-utils-indent`, it lives in `[format]` and nowhere else.
|
||||
assert!(err("style = \"google\"").contains("unknown key `style`"));
|
||||
assert!(err("[lint]\nstyle = \"google\"").contains("unknown key `style` under `[lint]`"));
|
||||
}
|
||||
|
||||
/// Everything about the table's shape, the way the `[lint]` table's is
|
||||
/// pinned: an unknown key is named, a non-boolean value is refused, and a
|
||||
/// repeated key is an error rather than a last-one-wins.
|
||||
@@ -937,3 +989,5 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
assert_eq!(discovery.for_file(Path::new("y.sv")).unwrap().indent, Some(4));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! A small line-oriented unified diff: the CLI's `--diff` and the MCP
|
||||
//! server's `dry_run` print the same hunks through this one function.
|
||||
//! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1,
|
||||
@@ -219,3 +221,5 @@ mod tests {
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! EDA filelist (`-f`) parsing: the project file every Verilog build
|
||||
//! already has.
|
||||
//!
|
||||
@@ -591,3 +593,5 @@ missing.sv
|
||||
assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The parts of lucisv that decide *which* files are processed and *with what
|
||||
//! settings*, shared by the `lucisv` CLI and the `lucisv-server` language server.
|
||||
//!
|
||||
@@ -20,3 +22,5 @@ pub mod config;
|
||||
pub mod diff;
|
||||
pub mod filelist;
|
||||
pub mod walk;
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! File discovery: directory walking, `--exclude` matching and the
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
@@ -731,6 +733,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for TempTree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_linking_to_itself_is_entered_once() {
|
||||
@@ -794,12 +803,41 @@ mod tests {
|
||||
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 `rel` (a directory
|
||||
/// when `rel` ends in `/`, else a file) refuses to be read. Root reads it
|
||||
/// anyway (Linux CI jobs run as root), so the unreadable-path tests below
|
||||
/// cannot build their path there; they say so and stop.
|
||||
#[cfg(unix)]
|
||||
fn reading_is_refused(rel: &str) -> bool {
|
||||
let probe = TempTree::new("mode-probe");
|
||||
let path = probe.path.join(rel);
|
||||
if rel.ends_with('/') {
|
||||
std::fs::create_dir(&path).expect("probe dir");
|
||||
} else {
|
||||
probe.write(rel, "");
|
||||
}
|
||||
probe.chmod(rel, 0o000);
|
||||
let refused = if rel.ends_with('/') {
|
||||
std::fs::read_dir(&path).is_err()
|
||||
} else {
|
||||
std::fs::File::open(&path).is_err()
|
||||
};
|
||||
probe.chmod(rel, 0o755);
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 `{rel}` is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
||||
// The finding this channel exists for: one permission-denied directory
|
||||
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
||||
// every file already found and failing the run.
|
||||
if !reading_is_refused("shut/") {
|
||||
return;
|
||||
}
|
||||
let tree = TempTree::new("unreadable");
|
||||
tree.source("a.sv");
|
||||
tree.source("locked/hidden.sv");
|
||||
@@ -815,6 +853,9 @@ mod tests {
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
||||
if !reading_is_refused("shut") {
|
||||
return;
|
||||
}
|
||||
let tree = TempTree::new("lockedignore");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
@@ -1064,3 +1105,5 @@ mod tests {
|
||||
assert!(!tracker.has_conflict());
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
[package]
|
||||
name = "lucisv_mcp"
|
||||
version.workspace = true
|
||||
@@ -21,3 +23,5 @@ vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The one write path every edit tool goes through.
|
||||
//!
|
||||
//! A tool hands over a [`Plan`] — per file, the text it computed against and
|
||||
@@ -274,6 +276,25 @@ mod tests {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-555 directory under `dir`
|
||||
/// refuses a new file. Root writes it anyway (Linux CI jobs run as root),
|
||||
/// so there the half of the test below that needs a directory refusing
|
||||
/// the temp file cannot be built; it says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn creating_is_refused(dir: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = dir.join("mode-probe");
|
||||
fs::create_dir(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = fs::write(shut.join("x"), "").is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_write_that_fails_after_another_landed_says_what_was_written() {
|
||||
@@ -290,6 +311,10 @@ mod tests {
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
|
||||
if !creating_is_refused(&dir) {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
return;
|
||||
}
|
||||
// … but a directory that will not take the temp file fails only at
|
||||
// the write, after `a.sv` landed: said, not hidden.
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
@@ -338,3 +363,5 @@ mod tests {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The index caches a startup reads instead of parsing (PLAN §6): the
|
||||
//! language server's `index-cache`, **read only, never written**, and this
|
||||
//! server's own `index-cache-mcp` beside it, in the same codec, written once
|
||||
@@ -221,3 +223,5 @@ fn store_lines(bytes: &[u8]) -> Vec<&[u8]> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
Vendored
+4
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The caches against the rebuild oracle: an index started from records is
|
||||
//! the index a cold build over the same files makes
|
||||
//! (`WorkspaceIndex::fingerprint`), and every record that is not exactly
|
||||
@@ -141,3 +143,5 @@ fn a_record_filed_under_another_path_or_hash_is_not_taken() {
|
||||
assert!(parse("0000000000000007\tx").is_none(), "no checksum");
|
||||
assert!(parse("7\tx\t0000000000000000").is_none(), "a hash of the wrong width");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `lucisv-mcp` — lucisv as a Model Context Protocol server, over stdio.
|
||||
//!
|
||||
//! A coding agent (Claude Code, Cursor, VS Code's agent mode) spawns this
|
||||
@@ -142,3 +144,5 @@ mod tests {
|
||||
assert_eq!(parse(&[]).unwrap(), Options::default());
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! One file, fully analyzed, and a small cache of them keyed by content.
|
||||
//!
|
||||
//! The index answers workspace questions without keeping any file's text;
|
||||
@@ -140,3 +142,5 @@ mod tests {
|
||||
assert!(cache.get(Path::new("a"), 1).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Which files the project is made of, and what each one looked like when it
|
||||
//! was last read: the filelist-or-walk ladder of PLAN §4.4 over
|
||||
//! `lucisv_core`, and the per-file stamp the freshness sweep compares against.
|
||||
@@ -5,7 +7,7 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use lucisv_core::config::Discovery;
|
||||
@@ -16,11 +18,25 @@ use lucisv_core::walk::collect_files_with;
|
||||
/// something an agent wants summarised.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// A file whose mtime is this close to the moment it was read may have been
|
||||
/// written again within the filesystem's timestamp resolution, so its stamp
|
||||
/// proves nothing: it is re-read (and re-hashed) until it is older than
|
||||
/// this. Git's "racy clean" rule, for the same reason.
|
||||
const RACY: Duration = Duration::from_secs(2);
|
||||
/// A file whose mtime or ctime is this close to the moment it was read may
|
||||
/// have been written again within the filesystem's timestamp resolution, so
|
||||
/// its stamp proves nothing: it is re-read (and re-hashed) until it is older
|
||||
/// than this. Git's "racy clean" rule, for the same reason.
|
||||
///
|
||||
/// The window must outlast the coarsest timestamp a filesystem keeps plus
|
||||
/// how far its clock can lag the one `read_at` comes from. Linux stamps
|
||||
/// files from a clock that moves in 1–4 ms ticks; ext3 and many network
|
||||
/// mounts keep whole seconds, FAT two. Three seconds covers FAT's two with
|
||||
/// a second to spare. A just-changed file costs a few more re-reads; a
|
||||
/// window too short costs stale contents.
|
||||
const RACY: Duration = Duration::from_secs(3);
|
||||
|
||||
/// How far the wall clock may fall behind the monotonic one since a read
|
||||
/// before the stamp stops being trusted: a clock stepped back can give a
|
||||
/// later write the very timestamp the stamp holds. Large next to the
|
||||
/// microseconds between the paired clock reads, small next to the margin
|
||||
/// [`RACY`] keeps over the coarsest timestamps.
|
||||
const STEP_BACK: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The files one discovery found, and what it had to say about the rest.
|
||||
#[derive(Debug, Default)]
|
||||
@@ -137,13 +153,16 @@ pub struct Stamp {
|
||||
pub mtime: Option<SystemTime>,
|
||||
/// `content_hash` of its bytes.
|
||||
pub hash: u64,
|
||||
/// When it was read.
|
||||
/// When it was read, by the wall clock file timestamps are compared with.
|
||||
pub read_at: SystemTime,
|
||||
/// The same moment by the monotonic clock: what tells a wall clock that
|
||||
/// was stepped back since the read.
|
||||
pub read_mono: Instant,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. Zero off Unix, where size, mtime and the racy rule
|
||||
/// the same problem. `None` off Unix, where size, mtime and the racy rule
|
||||
/// are all there is.
|
||||
pub identity: (i64, i64, u64),
|
||||
pub identity: Option<Identity>,
|
||||
/// Whether its text spells `endprogram` — the cheap test that says a
|
||||
/// `Module`-kind unit in it might be a `program` (the semantic layer
|
||||
/// models both as a module).
|
||||
@@ -161,6 +180,42 @@ pub enum Change {
|
||||
Gone,
|
||||
}
|
||||
|
||||
/// A file's inode change time and inode number (Unix only).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Identity {
|
||||
/// The ctime, `None` when it does not fit a `SystemTime`.
|
||||
pub ctime: Option<SystemTime>,
|
||||
/// The inode number.
|
||||
pub ino: u64,
|
||||
}
|
||||
|
||||
/// What one `stat` says about a file, as far as a stamp is concerned.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Seen {
|
||||
size: u64,
|
||||
mtime: Option<SystemTime>,
|
||||
identity: Option<Identity>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn of(meta: &fs::Metadata) -> Seen {
|
||||
Seen { size: meta.len(), mtime: meta.modified().ok(), identity: identity(meta) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The two clocks, read back to back.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Clocks {
|
||||
wall: SystemTime,
|
||||
mono: Instant,
|
||||
}
|
||||
|
||||
impl Clocks {
|
||||
fn now() -> Clocks {
|
||||
Clocks { wall: SystemTime::now(), mono: Instant::now() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Compare the file on disk with this stamp, by one `stat`.
|
||||
pub fn check(&self, path: &Path) -> Change {
|
||||
@@ -170,18 +225,56 @@ impl Stamp {
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return Change::Gone;
|
||||
}
|
||||
let mtime = meta.modified().ok();
|
||||
let racy = match mtime {
|
||||
Some(mtime) => mtime + RACY > self.read_at,
|
||||
None => true,
|
||||
};
|
||||
let moved = meta.len() != self.size || mtime != self.mtime;
|
||||
if moved || identity(&meta) != self.identity || racy {
|
||||
self.compare(Seen::of(&meta), Clocks::now())
|
||||
}
|
||||
|
||||
/// The decision [`Stamp::check`] makes, from what the `stat` saw and
|
||||
/// what the clocks say now.
|
||||
fn compare(&self, seen: Seen, now: Clocks) -> Change {
|
||||
let moved =
|
||||
seen.size != self.size || seen.mtime != self.mtime || seen.identity != self.identity;
|
||||
if moved || self.racy() || self.clock_stepped_back(now) {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
|
||||
/// **Invariant: a stamp is trusted on a later match only if every
|
||||
/// timestamp it trusts (the mtime, and the ctime where there is one) is
|
||||
/// at least [`RACY`] older than the moment the stamp was taken** —
|
||||
/// otherwise a write inside the same timestamp tick, after the read,
|
||||
/// leaves every one of them as it was. A timestamp that is missing, or
|
||||
/// later than the read (a clock behind the filesystem's), is racy too.
|
||||
fn racy(&self) -> bool {
|
||||
let ctime = self.identity.map(|identity| identity.ctime);
|
||||
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
|
||||
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
|
||||
None => true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the wall clock is now more than [`STEP_BACK`] behind where
|
||||
/// the monotonic clock says it would be had it only run forward since
|
||||
/// the read. After such a step a new write can be stamped with an old
|
||||
/// time, so no timestamp match means anything until the file is re-read.
|
||||
fn clock_stepped_back(&self, now: Clocks) -> bool {
|
||||
let expected = match now.mono.checked_duration_since(self.read_mono) {
|
||||
Some(elapsed) => self.read_at.checked_add(elapsed),
|
||||
None => self.read_at.checked_sub(self.read_mono - now.mono),
|
||||
};
|
||||
match (expected, now.wall.checked_add(STEP_BACK)) {
|
||||
(Some(expected), Some(tolerated)) => tolerated < expected,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// This stamp as if it had been taken `by` later, on both clocks: how a
|
||||
/// test ages a stamp past the racy window without waiting for it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn taken_later(self, by: Duration) -> Stamp {
|
||||
Stamp { read_at: self.read_at + by, read_mono: self.read_mono + by, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one source file and stamp it. `Err` for a file that is gone or is
|
||||
@@ -191,33 +284,43 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
// Stat before reading: a write that lands between the two leaves a stamp
|
||||
// older than the bytes, which the next sweep sees as a change.
|
||||
let meta = fs::metadata(path)?;
|
||||
let read_at = SystemTime::now();
|
||||
let read = Clocks::now();
|
||||
let bytes = fs::read(path)?;
|
||||
let hash = content_hash(&bytes);
|
||||
let text = String::from_utf8(bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
|
||||
let seen = Seen::of(&meta);
|
||||
let stamp = Stamp {
|
||||
size: meta.len(),
|
||||
mtime: meta.modified().ok(),
|
||||
size: seen.size,
|
||||
mtime: seen.mtime,
|
||||
hash,
|
||||
read_at,
|
||||
identity: identity(&meta),
|
||||
read_at: read.wall,
|
||||
read_mono: read.mono,
|
||||
identity: seen.identity,
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
Ok((text, stamp))
|
||||
}
|
||||
|
||||
/// A file's ctime (seconds, nanoseconds) and inode number.
|
||||
/// A file's ctime and inode number.
|
||||
#[cfg(unix)]
|
||||
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
|
||||
fn identity(meta: &fs::Metadata) -> Option<Identity> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(meta.ctime(), meta.ctime_nsec(), meta.ino())
|
||||
let nanos = Duration::from_nanos(u64::try_from(meta.ctime_nsec()).unwrap_or(0));
|
||||
let ctime = match u64::try_from(meta.ctime()) {
|
||||
Ok(secs) => SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(secs) + nanos),
|
||||
Err(_) => SystemTime::UNIX_EPOCH
|
||||
.checked_sub(Duration::from_secs(meta.ctime().unsigned_abs()))
|
||||
.and_then(|time| time.checked_add(nanos)),
|
||||
};
|
||||
Some(Identity { ctime, ino: meta.ino() })
|
||||
}
|
||||
|
||||
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
|
||||
/// No ctime or inode off Unix (std has no change time on Windows): the
|
||||
/// stamp falls back to size and mtime, and the racy rule on the mtime.
|
||||
#[cfg(not(unix))]
|
||||
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
|
||||
(0, 0, 0)
|
||||
fn identity(_: &fs::Metadata) -> Option<Identity> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -273,7 +376,7 @@ mod tests {
|
||||
let (_, stamp) = read_source(&path).unwrap();
|
||||
// Just written: racy, so suspect even though nothing moved.
|
||||
assert_eq!(stamp.check(&path), Change::Suspect);
|
||||
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
|
||||
let settled = stamp.taken_later(RACY + RACY);
|
||||
assert_eq!(settled.check(&path), Change::Same);
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Suspect);
|
||||
@@ -281,4 +384,131 @@ mod tests {
|
||||
assert_eq!(settled.check(&path), Change::Gone);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
// The racy rule, decided from values: no file, no waiting, no clock but
|
||||
// the ones given.
|
||||
|
||||
/// A stamp taken at `read` (wall) / `mono`, of a file whose mtime and
|
||||
/// ctime are `mtime_age` and `ctime_age` before the read.
|
||||
fn stamp_aged(
|
||||
read: SystemTime,
|
||||
mono: Instant,
|
||||
mtime_age: Duration,
|
||||
ctime_age: Duration,
|
||||
) -> Stamp {
|
||||
Stamp {
|
||||
size: 20,
|
||||
mtime: Some(read - mtime_age),
|
||||
hash: 7,
|
||||
read_at: read,
|
||||
read_mono: mono,
|
||||
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
|
||||
program: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `stat` of the unchanged file sees.
|
||||
fn unchanged(stamp: &Stamp) -> Seen {
|
||||
Seen { size: stamp.size, mtime: stamp.mtime, identity: stamp.identity }
|
||||
}
|
||||
|
||||
/// The clocks a second after the read, both having run forward.
|
||||
fn a_second_later(stamp: &Stamp) -> Clocks {
|
||||
let second = Duration::from_secs(1);
|
||||
Clocks { wall: stamp.read_at + second, mono: stamp.read_mono + second }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let fresh = Duration::from_millis(1);
|
||||
let cases = [
|
||||
("neither racy", old, old, Change::Same),
|
||||
("mtime racy", fresh, old, Change::Suspect),
|
||||
// The Linux hole: an old mtime put back, a ctime from this tick.
|
||||
("ctime racy", old, fresh, Change::Suspect),
|
||||
("both racy", fresh, fresh, Change::Suspect),
|
||||
("just inside the window", old, RACY - Duration::from_nanos(1), Change::Suspect),
|
||||
("exactly the window old", old, RACY, Change::Same),
|
||||
];
|
||||
for (what, mtime_age, ctime_age, expected) in cases {
|
||||
let stamp = stamp_aged(read, mono, mtime_age, ctime_age);
|
||||
assert_eq!(
|
||||
stamp.compare(unchanged(&stamp), a_second_later(&stamp)),
|
||||
expected,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timestamp_later_than_the_read_or_missing_is_racy() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let mut ahead = stamp_aged(read, mono, old, old);
|
||||
ahead.identity = Some(Identity { ctime: Some(read + Duration::from_secs(60)), ino: 42 });
|
||||
assert_eq!(ahead.compare(unchanged(&ahead), a_second_later(&ahead)), Change::Suspect);
|
||||
let mut no_ctime = stamp_aged(read, mono, old, old);
|
||||
no_ctime.identity = Some(Identity { ctime: None, ino: 42 });
|
||||
assert_eq!(
|
||||
no_ctime.compare(unchanged(&no_ctime), a_second_later(&no_ctime)),
|
||||
Change::Suspect
|
||||
);
|
||||
let mut no_mtime = stamp_aged(read, mono, old, old);
|
||||
no_mtime.mtime = None;
|
||||
assert_eq!(
|
||||
no_mtime.compare(unchanged(&no_mtime), a_second_later(&no_mtime)),
|
||||
Change::Suspect
|
||||
);
|
||||
// Off Unix there is no ctime to trust: the mtime alone decides.
|
||||
let mut off_unix = stamp_aged(read, mono, old, old);
|
||||
off_unix.identity = None;
|
||||
assert_eq!(off_unix.compare(unchanged(&off_unix), a_second_later(&off_unix)), Change::Same);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let stamp = stamp_aged(read, mono, old, old);
|
||||
let ten = Duration::from_secs(10);
|
||||
// Ten seconds of real time, but the wall clock shows one: stepped back.
|
||||
let back = Clocks { wall: read + Duration::from_secs(1), mono: mono + ten };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), back), Change::Suspect);
|
||||
// Behind the read itself.
|
||||
let behind = Clocks { wall: read - ten, mono: mono + Duration::from_secs(1) };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), behind), Change::Suspect);
|
||||
// A wall clock that ran ahead (a suspend the monotonic clock slept
|
||||
// through) is no reason to doubt anything.
|
||||
let ahead = Clocks { wall: read + ten, mono: mono + Duration::from_secs(1) };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), ahead), Change::Same);
|
||||
// Jitter under the tolerance is not a step.
|
||||
let jitter = Clocks { wall: read + ten - STEP_BACK / 2, mono: mono + ten };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), jitter), Change::Same);
|
||||
// A stamp aged on both clocks at once is not a step either.
|
||||
let aged = stamp.taken_later(ten);
|
||||
assert_eq!(aged.compare(unchanged(&aged), a_second_later(&stamp)), Change::Same);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_moved_field_is_suspect_however_settled() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let stamp = stamp_aged(read, mono, old, old);
|
||||
let now = a_second_later(&stamp);
|
||||
let same = unchanged(&stamp);
|
||||
let identity = stamp.identity.unwrap();
|
||||
let moved = [
|
||||
Seen { size: 21, ..same },
|
||||
Seen { mtime: Some(read), ..same },
|
||||
Seen { identity: Some(Identity { ino: 43, ..identity }), ..same },
|
||||
Seen { identity: Some(Identity { ctime: Some(read - old / 2), ..identity }), ..same },
|
||||
];
|
||||
for seen in moved {
|
||||
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The project one server answers about: its roots, its files, the workspace
|
||||
//! index over them, and the promise that no answer is older than the disk
|
||||
//! was when the call arrived (PLAN §4.4).
|
||||
@@ -359,3 +361,5 @@ fn relative_to(roots: &[PathBuf], path: &Path) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,10 +1,12 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The freshness promise, against the rebuild oracle: after every update
|
||||
//! path the incrementally maintained index is the index a full build over
|
||||
//! the files now on disk produces (`WorkspaceIndex::fingerprint`).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::Duration;
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
@@ -29,9 +31,8 @@ fn rebuilt(project: &Project) -> String {
|
||||
|
||||
/// Age every stamp past the racy window, so only a real change is suspect.
|
||||
fn settle(project: &mut Project) {
|
||||
let later = SystemTime::now() + Duration::from_secs(10);
|
||||
for stamp in project.files.values_mut() {
|
||||
stamp.read_at = later;
|
||||
*stamp = stamp.taken_later(Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,3 +108,5 @@ fn a_path_argument_must_land_inside_a_root() {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
fs::remove_dir_all(outside).unwrap();
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
|
||||
//! token budget is the product.
|
||||
//!
|
||||
@@ -205,3 +207,5 @@ mod tests {
|
||||
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The `lucisv://` resources: the project overview, the lint rule
|
||||
//! reference, one unit's outline and one file's outline — the same answers
|
||||
//! `hierarchy` and `outline` give, addressable by URI for a host that
|
||||
@@ -176,3 +178,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
|
||||
//! `initialize` handshake and its version negotiation, `ping`, the tool
|
||||
//! methods, the `lucisv://` resources, and an empty prompt list.
|
||||
@@ -421,3 +423,5 @@ mod tests {
|
||||
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The declarations the files' own symbol tables hold — every one the
|
||||
//! semantic model knows and `outline` lists: typedefs, enum values,
|
||||
//! functions, tasks, genvars, generate blocks and what they declare,
|
||||
@@ -94,3 +96,5 @@ fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
|
||||
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
|
||||
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `check`: what `lucisv check` would say about one file or the whole
|
||||
//! design — the tolerant parse's errors, then the lint findings — one line
|
||||
//! each, `file:line:col severity message [rule]`, errors first.
|
||||
@@ -161,7 +163,9 @@ impl Runs {
|
||||
}
|
||||
waivers.absorb(file);
|
||||
}
|
||||
let format = vlog_formatter::Config::default();
|
||||
// The width and indent the file would be formatted with, its style's
|
||||
// included, so the linter and the formatter cannot disagree.
|
||||
let format = super::format::formatter_config(config);
|
||||
Ok(Run {
|
||||
rules,
|
||||
options,
|
||||
@@ -323,3 +327,5 @@ impl MentionOracle for Mentions<'_> {
|
||||
PackageExports::exports(self.index, package)
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `rename`, and what every design-wide edit shares: the whole-set read the
|
||||
//! engines are handed, and the step from a verified `RefactorEdit` to a
|
||||
//! written plan with the name's unresolved mentions listed.
|
||||
@@ -221,3 +223,5 @@ fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `find`: where a name is declared and, on `refs`, where each declaration
|
||||
//! is used — the question an agent otherwise answers by grepping and
|
||||
//! reading. Declarations come from the index (`names.rs`); uses from
|
||||
@@ -197,3 +199,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `format`: the CLI's `lucisv format` over a path or a glob, and with
|
||||
//! `fix` the CLI's `lucisv check --fix` first — each file through the one
|
||||
//! write path (`apply.rs`).
|
||||
@@ -119,9 +121,10 @@ fn fixed_and_formatted(
|
||||
}
|
||||
|
||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||
/// `Options::config_with` with no command-line flags.
|
||||
fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
/// `Options::config_with` with no command-line flags: the style first, then
|
||||
/// the explicit keys over the preset's indent and width.
|
||||
pub(super) fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = file.format_style.and_then(Config::named).unwrap_or_default();
|
||||
if let Some(width) = file.line_length {
|
||||
config.max_width = width;
|
||||
}
|
||||
@@ -195,3 +198,27 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
.iter()
|
||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_formatter::style;
|
||||
|
||||
/// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no
|
||||
/// flags does: the style first, the explicit keys over its numbers.
|
||||
#[test]
|
||||
fn the_style_comes_first_and_explicit_keys_win() {
|
||||
let none = formatter_config(&FileConfig::default());
|
||||
assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100));
|
||||
let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() };
|
||||
let config = formatter_config(&ansi);
|
||||
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80));
|
||||
let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi };
|
||||
let config = formatter_config(&narrowed);
|
||||
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90));
|
||||
let auto = FileConfig { format_style: Some("auto"), ..Default::default() };
|
||||
assert!(formatter_config(&auto).auto_style);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
|
||||
//! path component, `**` for any run of components, and a bare directory
|
||||
//! for everything below it — the `.gitignore` / `rg -g` reading.
|
||||
@@ -100,3 +102,5 @@ mod tests {
|
||||
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
|
||||
//! top modules; with one, the instance tree down from it or every
|
||||
//! instantiation of it up to `depth` levels — read off the index's
|
||||
@@ -369,3 +371,5 @@ fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String>
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `outline unit:` — what a unit offers the code that uses it: a module's
|
||||
//! or interface's parameters and ports in declaration order (plus an
|
||||
//! interface's modports), a package's or class's members — without the
|
||||
@@ -228,3 +230,5 @@ fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
|
||||
}
|
||||
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `edit_item` — the structural edits under one name (`replace`,
|
||||
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
|
||||
//! agent sends one item's text, never the file.
|
||||
@@ -373,3 +375,5 @@ fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result<Spot, String>
|
||||
|
||||
/// The keywords that close a unit `end` may name.
|
||||
const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"];
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The verifier's lexical rules — what a splice may do to the token stream
|
||||
//! and its comments, before any parse is asked:
|
||||
//!
|
||||
@@ -173,3 +175,5 @@ fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> {
|
||||
.map(|e| e.text.trim())
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `op: delete`'s macro rule: a name spelled inside a macro call's
|
||||
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
|
||||
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
|
||||
@@ -106,3 +108,5 @@ mod tests {
|
||||
assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
|
||||
//! name it owns (`verify::owned`) is still used anywhere in the project.
|
||||
//!
|
||||
@@ -260,3 +262,5 @@ fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) ->
|
||||
let (line, col) = LineIndex::new(text).line_col(span.start);
|
||||
format!("{}:{line}:{col}", project.relative(file))
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
|
||||
//! work on, and the span its `replace` replaces when its text brings comments.
|
||||
//!
|
||||
@@ -155,3 +157,5 @@ mod tests {
|
||||
assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
|
||||
//! spelling it, so `find_references` (which returns only spans that spell
|
||||
//! the name) never lists it. For each deleted name, every `.*`
|
||||
@@ -94,3 +96,5 @@ fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option<bool> {
|
||||
}
|
||||
Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port))
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The verifier the three structural edits share — the one new piece of
|
||||
//! logic in the MCP block, so it is guilty until proven innocent: every rule
|
||||
//! here has an attack in `tests/attacks.rs`.
|
||||
@@ -573,3 +575,5 @@ mod tests {
|
||||
assert!(owned_names(&analysis, always).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Unresolved mentions: every whole-word spelling of a name that no engine
|
||||
//! answer accounted for and that sits where no lucisv engine looks — inside
|
||||
//! a string literal, a comment, a macro call's text, a `` `define`` body, or
|
||||
@@ -345,3 +347,5 @@ mod tests {
|
||||
assert_eq!(shared_components(a, b), 4);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The tool registry: every tool's name, description, argument list and
|
||||
//! handler, in one table. The argument list is the single source of both the
|
||||
//! `inputSchema` a host shows the agent and the validation a call's
|
||||
@@ -313,3 +315,5 @@ mod tests {
|
||||
assert_eq!(schema(hierarchy.params)["properties"]["depth"], json!({"type": "integer"}));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Names looked up — the by-name half every lean tool shares: every
|
||||
//! declaration of a name (the index's units, exported members and module
|
||||
//! internals, every declaration the files' own symbol tables hold, and the
|
||||
@@ -232,3 +234,5 @@ mod tests {
|
||||
assert_eq!(qualified(".x"), (None, ".x"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `outline`: a file's declarations as a tree with line ranges (its parse
|
||||
//! errors first), or — for `unit` — what a unit offers the code that uses
|
||||
//! it (`interface.rs`), so an agent reads the shape before the source.
|
||||
@@ -59,3 +61,5 @@ fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut V
|
||||
tree(analysis, &node.children, level + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `port`'s `after`: the new port placed right after a named one, in the
|
||||
//! layout of the line it follows, and each named connection placed right
|
||||
//! after the instance's `.after(…)`.
|
||||
@@ -446,3 +448,5 @@ mod tests {
|
||||
assert_eq!(appended_expr(".e(x)", "d"), None);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Where a new list element goes after its anchor, and how it is written.
|
||||
//!
|
||||
//! The element always goes **after the separator that follows the anchor**
|
||||
@@ -304,3 +306,5 @@ mod tests {
|
||||
assert_eq!(split_declaration("input dbg_i").unwrap().ty, "");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The check a placement must pass before anything is written: the placed
|
||||
//! edit is the engine's verified edit with elements **moved and nothing
|
||||
//! else**. Per file, against the engine's result:
|
||||
@@ -308,3 +310,5 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `port`: add a port to a module and connect it by name in every
|
||||
//! instantiation, or remove one and its connection everywhere — the
|
||||
//! design-wide edit a file write cannot do safely. `add` is
|
||||
@@ -144,3 +146,5 @@ fn instantiations(project: &Project, module: &str) -> (usize, usize) {
|
||||
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
|
||||
(count, files.len())
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `read`: one item's exact source — a slice, never the file — preceded by
|
||||
//! `file:first–last`. In a named `file` the item is sliced as
|
||||
//! `read_item::select` slices it; without one the name is looked up
|
||||
@@ -78,3 +80,5 @@ fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The item slicer `read` and `edit_item` share: one item's exact span in
|
||||
//! a file — a module, a function, a declaration, an instance, or an
|
||||
//! unlabelled `always` block named by the line it covers.
|
||||
@@ -317,3 +319,5 @@ module n; logic q; endmodule
|
||||
assert!(refused.contains("`\\b` on line 12"), "{refused}");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Declaration sites read back off the disk: `find` and the by-name tools
|
||||
//! answer with `file:line` for declarations in files no analysis is held
|
||||
//! for. One read per file per call ([`Texts`]); the index's spans are
|
||||
@@ -271,3 +273,5 @@ mod tests {
|
||||
assert_eq!(capped("x y", 3), "x y");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The MCP stdio transport: one JSON-RPC message per line in, one per line
|
||||
//! out. stdout carries protocol lines and nothing else; stderr is the log.
|
||||
//!
|
||||
@@ -93,3 +95,5 @@ mod tests {
|
||||
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The dev's attack suite on the structural edits' verifier (lane M4) —
|
||||
//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every
|
||||
//! case is an edit the verifier could plausibly let through, asserted
|
||||
@@ -784,3 +786,5 @@ fn a_signal_bound_by_a_dot_star_is_still_referenced() {
|
||||
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
|
||||
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The index caches over the wire (TODO-MCP M6, PLAN §6): the language
|
||||
//! server's `index-cache` is read and never written — its bytes are hashed
|
||||
//! before and after a whole session that indexes, answers and edits — every
|
||||
@@ -242,11 +244,32 @@ fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
|
||||
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-555 directory refuses a new
|
||||
/// file. Root writes it anyway (Linux CI jobs run as root), so there an
|
||||
/// unwritable cache directory cannot be built; the test says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn creating_is_refused(scratch: &Scratch) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = scratch.0.join("mode-probe");
|
||||
fs::create_dir_all(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = fs::write(shut.join("x"), "").is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let scratch = Scratch::new();
|
||||
if !creating_is_refused(&scratch) {
|
||||
return;
|
||||
}
|
||||
fs::create_dir_all(scratch.cache()).unwrap();
|
||||
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let stderr = whole_session(&scratch);
|
||||
@@ -255,3 +278,5 @@ fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
|
||||
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
|
||||
assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The `hierarchy` cap counts instances, never `peek` lines (census round 5,
|
||||
//! 2026-09-29): an agent asking for every instantiation of a module with
|
||||
//! `peek` gets every one up to 100 (300 without `peek`), each with its
|
||||
@@ -135,3 +137,5 @@ fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
|
||||
assert_eq!(plain.lines().count(), 301);
|
||||
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The opentitan census (TODO-MCP M2, ported to the lean catalogue in M7):
|
||||
//! `find`, `hierarchy`, `check` and `outline` over a real checkout,
|
||||
//! read-only, each answer checked against what the language server answers
|
||||
@@ -288,3 +290,5 @@ fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
|
||||
let _ = std::fs::remove_dir_all(&cache);
|
||||
assert_eq!(status(&root), before, "the checkout was only read");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
|
||||
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
|
||||
//! 2026-09-23 — ported to the lean catalogue: `add_port` is `port` with
|
||||
@@ -696,3 +698,5 @@ fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
|
||||
}
|
||||
assert!(dir.join("inside").is_dir(), "a directory is never swept");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
|
||||
//! `in` path glob, the post-edit check line), 2026-09-23 — ported to the
|
||||
//! lean catalogue: paging, `in` and the check line are gone (PLAN §10.2),
|
||||
@@ -282,3 +284,5 @@ fn qa_the_glob_matches_paths_never_names_even_escaped_ones_holding_a_star() {
|
||||
assert_eq!(formatted("esc/*.sv"), "1");
|
||||
assert!(formatted("\\esc*mod").contains("\\esc*mod"), "a unit name is not a path");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M1 (transport + read tools), 2026-09-23.
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
@@ -954,3 +956,5 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
|
||||
set_mtime(&scratch.path("c.sv"), long_ago);
|
||||
assert_eq!(s.text("find", json!({"name": "chyrlie"})), "module chyrlie c.sv:1\n");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M2 (navigation, diagnostics, defines, resources),
|
||||
//! 2026-09-23 — ported to the lean catalogue (`find`, `hierarchy`, `check`;
|
||||
//! `docs/features/mcp-lean-catalogue/README.md` lists what was deleted: the
|
||||
@@ -796,3 +798,5 @@ fn qa_recheck_one_files_check_is_its_lines_of_lucisv_check_dot() {
|
||||
);
|
||||
assert_eq!(s.text("check", json!({"file": "leaf.sv"})), "ok\n");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M3 (the edit tools and their one write path),
|
||||
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
|
||||
//! `edit_item`, `format`); the tools it dropped took their attacks with
|
||||
@@ -706,6 +708,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
copy_tree(&scratch.0, &reference.0);
|
||||
let status = Command::new(&cli).arg("--no-cache").arg(&reference.0).output().unwrap();
|
||||
assert!(status.status.success(), "{status:?}");
|
||||
// The server is spawned before the checker starts, never while it runs.
|
||||
// A spawn on one thread can inherit a pipe another thread is just
|
||||
// creating for its child: macOS has no `pipe2`, so close-on-exec is set
|
||||
// in a second step. Seen once under load (2026-11-19, `lsof`): the
|
||||
// server held the write end of a `lucisv --check`'s stdout. That
|
||||
// `output()` never saw EOF, `join` below waited on it, and the server,
|
||||
// which lives until this test ends, never let go, so the test hung.
|
||||
// Spawned first, the server cannot hold any of the checker's pipes.
|
||||
let mut server = Session::over(&scratch);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let checker = {
|
||||
let (stop, cli, root) = (Arc::clone(&stop), cli.clone(), scratch.0.clone());
|
||||
@@ -719,7 +730,6 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
codes
|
||||
})
|
||||
};
|
||||
let mut server = Session::over(&scratch);
|
||||
for _ in 0..5 {
|
||||
for (name, text) in &messy {
|
||||
scratch.write(name, text);
|
||||
@@ -1218,3 +1228,5 @@ fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
|
||||
let text = text_of(&server.rename_d());
|
||||
assert!(!text.contains(outside.root()), "{text}");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M4 (the structural edits and their verifier),
|
||||
//! 2026-09-23.
|
||||
//!
|
||||
@@ -1308,3 +1310,5 @@ fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() {
|
||||
}
|
||||
assert!(strict(&tree.read("rtl/d.sv")));
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M6 (the index caches and the rule-6 ruling),
|
||||
//! 2026-09-23.
|
||||
//!
|
||||
@@ -444,6 +446,24 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 directory refuses to be
|
||||
/// listed. Root lists it anyway (Linux CI jobs run as root), so there a cache
|
||||
/// directory without permission cannot be built; the test says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn listing_is_refused(scratch: &Scratch) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = scratch.0.join("mode-probe");
|
||||
fs::create_dir_all(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
let refused = fs::read_dir(&shut).is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
/// A cache directory with no permissions at all (mode 000, holding a whole
|
||||
/// honest editor store): nothing can be read, so the start is cold; the
|
||||
/// answers are right; the exit says it could not write, once; the store in
|
||||
@@ -453,6 +473,9 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
|
||||
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let scratch = Scratch::new();
|
||||
if !listing_is_refused(&scratch) {
|
||||
return;
|
||||
}
|
||||
let (cold, _) = probe(&scratch, None);
|
||||
scratch.write_editor_store(&honest_store(&scratch));
|
||||
let before = hash_file(&scratch.editor_store());
|
||||
@@ -681,3 +704,5 @@ fn qa_the_instructions_are_short_and_name_only_real_tools() {
|
||||
assert!(text.contains(phrase), "{phrase}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
|
||||
//!
|
||||
//! Every test writes a small design into its own scratch directory, spawns
|
||||
@@ -867,3 +869,5 @@ fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
|
||||
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
|
||||
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
|
||||
//!
|
||||
//! Every test copies a fixture into its own scratch directory, spawns the
|
||||
@@ -113,7 +115,14 @@ fn run(args: &[&str], lines: &[Value]) -> Output {
|
||||
Value::String(raw) => raw.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
writeln!(stdin, "{text}").unwrap();
|
||||
// A refused argument list exits 2 before reading a byte, so the write
|
||||
// races that exit and can fail with `BrokenPipe`. That is the child
|
||||
// being gone, not the test failing: what it said and its exit code
|
||||
// are what the caller asserts on. Any other error is a failure.
|
||||
match writeln!(stdin, "{text}") {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => break,
|
||||
result => result.unwrap(),
|
||||
}
|
||||
}
|
||||
drop(stdin);
|
||||
child.wait_with_output().unwrap()
|
||||
@@ -555,3 +564,5 @@ fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
|
||||
//! five read tools within their budget, the edit tools unknown, full mode as
|
||||
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
|
||||
@@ -339,3 +341,5 @@ fn the_edit_calls_write_in_full_mode() {
|
||||
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The wire contract, pinned against the real binary: each test copies the
|
||||
//! fixture design into its own temporary directory, spawns `lucisv-mcp` over
|
||||
//! it and talks newline-delimited JSON-RPC to it, as a host would.
|
||||
@@ -1264,3 +1266,5 @@ fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() {
|
||||
assert!(young.exists(), "a young one may be a live writer's");
|
||||
assert!(other.exists(), "only `<store>.<pid>.tmp` is ours to sweep");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
[package]
|
||||
name = "lucisv_server"
|
||||
version.workspace = true
|
||||
@@ -19,3 +21,5 @@ lsp-server = { workspace = true }
|
||||
lsp-types = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,408 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The preset `style = "auto"` last settled on, per document.
|
||||
//!
|
||||
//! Under `auto`, every formatting request needs a concrete preset, and
|
||||
//! finding one means formatting the whole buffer once per preset. That is
|
||||
//! fine for a whole-document format, which formats the whole buffer anyway,
|
||||
//! but not for an on-type `;` or a selection, which would pay it on every
|
||||
//! keystroke — and on a buffer that does not parse (exactly when on-type
|
||||
//! runs), no preset can be found at all.
|
||||
//!
|
||||
//! So a whole-document format remembers the preset it used, and the range,
|
||||
//! selection and on-type requests reuse it. Without a memory they resolve
|
||||
//! once from the buffer — when it parses — and remember that. Without a
|
||||
//! memory and without a parse they lay out in the default preset's layout,
|
||||
//! as the formatter itself does. The memory is a small most-recent list.
|
||||
//!
|
||||
//! A remembered preset is only right while the buffer is still the text it
|
||||
//! was resolved from, edited by hand. So it is **forgotten** whenever that
|
||||
//! may no longer be true: the document is opened, closed, renamed or deleted;
|
||||
//! it is formatted or laid out under a named style; and — for every document
|
||||
//! — whenever the settings change or a `lucisv.toml` change is seen.
|
||||
//! Forgetting costs one search on the next request; remembering wrongly would
|
||||
//! lay the file out in a preset it no longer uses.
|
||||
//!
|
||||
//! A change that replaces the **whole** buffer (a reload from disk, an
|
||||
//! external formatter, or every change of a full-sync client) marks the
|
||||
//! entry *replaced* rather than dropping it: the next request resolves
|
||||
//! afresh from the new text, and only if that text does not parse — so there
|
||||
//! is nothing to resolve from — does it fall back to the old preset, which is
|
||||
//! still a better guess than the default layout. A full-sync client's every
|
||||
//! keystroke is such a change, and a half-typed buffer is exactly when
|
||||
//! on-type runs; dropping the entry there would lose the file's preset at the
|
||||
//! moment the memory exists for.
|
||||
//! See `docs/features/format-styles/README.md`.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use lsp_server::Notification;
|
||||
use lsp_types::notification::{
|
||||
DidChangeWatchedFiles, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, Notification as _,
|
||||
};
|
||||
use lsp_types::{
|
||||
DeleteFilesParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
|
||||
DidOpenTextDocumentParams, RenameFilesParams, TextDocumentContentChangeEvent, TextEdit, Uri,
|
||||
};
|
||||
use vlog_formatter::{format_auto, style, Config, Style};
|
||||
|
||||
use crate::format;
|
||||
use crate::state::Document;
|
||||
|
||||
/// How many documents' presets are remembered.
|
||||
const CAPACITY: usize = 64;
|
||||
|
||||
/// The presets of the most recently formatted documents, newest last.
|
||||
#[derive(Default)]
|
||||
pub struct AutoStyles {
|
||||
recent: VecDeque<Entry>,
|
||||
}
|
||||
|
||||
/// One remembered document.
|
||||
struct Entry {
|
||||
uri: Uri,
|
||||
preset: Style,
|
||||
/// A change replaced the whole buffer since `preset` was resolved, so it
|
||||
/// is only a fallback: resolve again when the buffer parses.
|
||||
replaced: bool,
|
||||
}
|
||||
|
||||
impl AutoStyles {
|
||||
/// Format a whole buffer. Under `auto` this resolves afresh and
|
||||
/// remembers the preset it used; under a named style it is
|
||||
/// [`format::formatting`].
|
||||
pub fn format_document(
|
||||
&mut self,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
if !config.auto_style {
|
||||
// Formatted under a named style, the buffer may now be in it.
|
||||
self.forget(uri);
|
||||
return format::formatting(doc, config);
|
||||
}
|
||||
let (formatted, preset) = format_auto(&doc.text, config).map_err(|e| e.to_string())?;
|
||||
self.remember(uri, preset);
|
||||
Ok(format::whole_document_edit(doc, formatted))
|
||||
}
|
||||
|
||||
/// `config` made concrete for a range, selection or on-type request on
|
||||
/// `doc`: unchanged under a named style; under `auto`, the remembered
|
||||
/// preset, else the one the buffer resolves to (then remembered), else —
|
||||
/// the buffer does not parse — the default preset's layout.
|
||||
pub fn concrete(&mut self, uri: &Uri, doc: &Document, config: Config) -> Config {
|
||||
if !config.auto_style {
|
||||
self.forget(uri);
|
||||
return config;
|
||||
}
|
||||
let held = self.recall(uri);
|
||||
let preset = match held {
|
||||
Some((preset, false)) => preset,
|
||||
// Nothing trustworthy held: resolve from the buffer when it
|
||||
// parses; otherwise the old preset if there is one, else the
|
||||
// default layout. A fallback is never stored as fresh.
|
||||
_ => match format_auto(&doc.text, &config) {
|
||||
Ok((_, preset)) => {
|
||||
self.remember(uri, preset);
|
||||
preset
|
||||
}
|
||||
Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset),
|
||||
},
|
||||
};
|
||||
Config { style: preset, auto_style: false, ..config }
|
||||
}
|
||||
|
||||
/// Whether nothing is remembered yet.
|
||||
#[cfg(test)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.recent.is_empty()
|
||||
}
|
||||
|
||||
/// Forget what a notification may have made stale: the document a
|
||||
/// `didOpen`/`didClose` names, the old and new names of a renamed file,
|
||||
/// a deleted file, and every document when a watched-file event names a
|
||||
/// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored.
|
||||
pub fn notice(&mut self, notification: &Notification) {
|
||||
let params = || notification.params.clone();
|
||||
match notification.method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(params()) {
|
||||
self.forget(&p.text_document.uri);
|
||||
}
|
||||
}
|
||||
DidCloseTextDocument::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
|
||||
self.forget(&p.text_document.uri);
|
||||
}
|
||||
}
|
||||
DidRenameFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(params()) {
|
||||
self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri]));
|
||||
}
|
||||
}
|
||||
DidDeleteFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DeleteFilesParams>(params()) {
|
||||
self.forget_named(p.files.iter().map(|f| &f.uri));
|
||||
}
|
||||
}
|
||||
DidChangeWatchedFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(params()) {
|
||||
if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) {
|
||||
self.forget_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `uri`'s entry replaced when a `didChange` replaced its whole
|
||||
/// text: a change with no range (full sync), or one that starts at the
|
||||
/// top and leaves nothing of the old text after it — `result` is exactly
|
||||
/// its text.
|
||||
pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) {
|
||||
let rangeless = changes.iter().any(|c| c.range.is_none());
|
||||
let from_the_top = changes.last().is_some_and(|c| {
|
||||
c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result
|
||||
});
|
||||
if rangeless || from_the_top {
|
||||
if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) {
|
||||
entry.replaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget every document: the settings, or a `lucisv.toml`, changed.
|
||||
pub fn forget_all(&mut self) {
|
||||
self.recent.clear();
|
||||
}
|
||||
|
||||
fn forget(&mut self, uri: &Uri) {
|
||||
self.recent.retain(|e| e.uri != *uri);
|
||||
}
|
||||
|
||||
fn forget_named<'a>(&mut self, uris: impl Iterator<Item = &'a String>) {
|
||||
for uri in uris {
|
||||
self.recent.retain(|e| e.uri.as_str() != uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// The remembered preset, and whether it has been marked replaced.
|
||||
fn recall(&self, uri: &Uri) -> Option<(Style, bool)> {
|
||||
self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced))
|
||||
}
|
||||
|
||||
fn remember(&mut self, uri: &Uri, preset: Style) {
|
||||
self.forget(uri);
|
||||
if self.recent.len() == CAPACITY {
|
||||
self.recent.pop_front();
|
||||
}
|
||||
self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`.
|
||||
fn names_a_config(uri: &str) -> bool {
|
||||
let name = uri.rsplit('/').next().unwrap_or(uri);
|
||||
lucisv_core::config::NAMES.contains(&name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A google-formatted module: one port per line at a 4-space list indent.
|
||||
const GOOGLE: &str = "\
|
||||
module m (
|
||||
input logic a,
|
||||
output logic b
|
||||
);
|
||||
sub u_sub (
|
||||
.a(a),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn open(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
fn auto() -> Config {
|
||||
Config::named("auto").expect("auto")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_document_format_remembers_the_preset_it_used() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let mut styles = AutoStyles::default();
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted");
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)));
|
||||
let concrete = styles.concrete(&uri, doc, auto());
|
||||
assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_style_is_left_alone_and_nothing_is_remembered() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let mut styles = AutoStyles::default();
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let ansi = Config::styled(style::ANSI);
|
||||
assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI);
|
||||
assert!(styles.format_document(&uri, doc, &ansi).is_ok());
|
||||
assert_eq!(styles.recall(&uri), None);
|
||||
}
|
||||
|
||||
/// The memory is what lets a half-typed buffer keep its file's preset:
|
||||
/// without it, a buffer that does not parse gets the default's layout.
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_uses_the_remembered_preset() {
|
||||
let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule");
|
||||
let (ws, uri) = open(&broken);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse");
|
||||
assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered");
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_memory_a_buffer_that_parses_resolves_once() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_memory_is_bounded_and_keeps_the_most_recent() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri");
|
||||
for n in 0..CAPACITY + 10 {
|
||||
styles.remember(&uri(n), style::NXP);
|
||||
}
|
||||
assert_eq!(styles.recent.len(), CAPACITY);
|
||||
assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten");
|
||||
assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false)));
|
||||
// Remembering again moves a document to the back and replaces its preset.
|
||||
styles.remember(&uri(10), style::ANSI);
|
||||
styles.remember(&uri(10), style::GOOGLE);
|
||||
assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false)));
|
||||
assert_eq!(styles.recent.len(), CAPACITY);
|
||||
}
|
||||
|
||||
fn notification(method: &str, params: serde_json::Value) -> Notification {
|
||||
Notification { method: method.to_string(), params }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_close_rename_and_delete_forget_the_document() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let (a, b) = (
|
||||
Uri::from_str("file:///rtl/a.sv").expect("uri"),
|
||||
Uri::from_str("file:///rtl/b.sv").expect("uri"),
|
||||
);
|
||||
let doc = |uri: &Uri| {
|
||||
serde_json::json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } })
|
||||
};
|
||||
for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] {
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(¬ification(method, doc(&a)));
|
||||
assert_eq!(styles.recall(&a), None, "{method}");
|
||||
}
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.remember(&b, style::NXP);
|
||||
styles.notice(¬ification(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }),
|
||||
));
|
||||
assert!(styles.is_empty(), "both names of a renamed file are forgotten");
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(¬ification(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "uri": a.as_str() }] }),
|
||||
));
|
||||
assert_eq!(styles.recall(&a), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_file_change_or_a_settings_change_forgets_everything() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let a = Uri::from_str("file:///rtl/a.sv").expect("uri");
|
||||
let watched = |name: &str| {
|
||||
notification(
|
||||
DidChangeWatchedFiles::METHOD,
|
||||
serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }),
|
||||
)
|
||||
};
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(&watched("other.sv"));
|
||||
assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets");
|
||||
for name in ["lucisv.toml", ".lucisv.toml"] {
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(&watched(name));
|
||||
assert!(styles.is_empty(), "{name}");
|
||||
}
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.forget_all();
|
||||
assert!(styles.is_empty());
|
||||
}
|
||||
|
||||
/// A whole-buffer change makes the entry a fallback: the next request
|
||||
/// resolves from the new text if it parses, and keeps the old preset
|
||||
/// only if it does not. A partial edit leaves the entry alone.
|
||||
#[test]
|
||||
fn a_whole_buffer_replacement_resolves_again_when_it_can() {
|
||||
let lucisv =
|
||||
"module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n";
|
||||
let (ws, uri) = open(lucisv);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
let edit: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } },
|
||||
"text": " " })).expect("change");
|
||||
styles.changed(&uri, &[edit], lucisv);
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit");
|
||||
let whole: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change");
|
||||
styles.changed(&uri, std::slice::from_ref(&whole), lucisv);
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true)));
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh");
|
||||
assert_eq!(styles.recall(&uri), Some((style::LUCISV, false)));
|
||||
// A full range from the top counts as a whole replacement too.
|
||||
let ranged: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } },
|
||||
"text": lucisv })).expect("change");
|
||||
styles.changed(&uri, &[ranged], lucisv);
|
||||
assert_eq!(styles.recall(&uri), Some((style::LUCISV, true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_style_request_forgets_the_document() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
styles.concrete(&uri, doc, Config::styled(style::LUCISV));
|
||||
assert_eq!(styles.recall(&uri), None, "a range under a named style");
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
|
||||
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The tables a completion request reads instead of walking the workspace.
|
||||
//!
|
||||
//! Completion fires on every keystroke, so nothing here may be computed per
|
||||
@@ -197,17 +199,86 @@ impl Candidates {
|
||||
/// patched: this file's old words are given back and its new ones taken,
|
||||
/// so nothing else is re-lexed. The result is what a whole
|
||||
/// [`Candidates::build`] over the same files would have produced.
|
||||
#[cfg(test)]
|
||||
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
|
||||
self.update_words(index, path, words_in(text));
|
||||
}
|
||||
|
||||
/// [`Candidates::update_file`] for a file whose words the caller already
|
||||
/// has — an open buffer's, read off the tokens it was analyzed from.
|
||||
#[cfg(test)]
|
||||
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
|
||||
self.take_index_tables(index);
|
||||
self.set_words(path, words);
|
||||
}
|
||||
|
||||
/// [`Candidates::update_words`] in two halves, for a caller that knows
|
||||
/// which it needs: the word table patched by this file alone…
|
||||
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
|
||||
self.set_words(path, words);
|
||||
}
|
||||
|
||||
/// …and the two index-derived tables re-derived for the names one file declared
|
||||
/// before or declares now — `symbols` its units and connection members,
|
||||
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
|
||||
/// the only entries its update can move.
|
||||
///
|
||||
/// Exact because every table here is one block per exact name ([`word_cmp`]
|
||||
/// is total, so equal keys are equal names) and each block is read off
|
||||
/// the index for that name alone: the unit block from the symbol listing
|
||||
/// restricted to the name, in the listing's order and deduplicated the
|
||||
/// same way; a module name present exactly when some unit of it is
|
||||
/// instantiable; a macro's entry from its first definition in file order.
|
||||
/// So a block re-derived here is the block a whole re-derivation gives,
|
||||
/// and every other block is untouched by an update that does not name it.
|
||||
///
|
||||
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
|
||||
pub fn refresh_names(
|
||||
&mut self,
|
||||
index: &WorkspaceIndex,
|
||||
symbols: &HashSet<&str>,
|
||||
macros: &HashSet<&str>,
|
||||
) {
|
||||
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
|
||||
let mut held = std::mem::take(&mut self.units);
|
||||
held.retain(|unit| !symbols.contains(unit.name.as_str()));
|
||||
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
|
||||
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
|
||||
for name in symbols {
|
||||
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
|
||||
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
|
||||
(Ok(at), false) => {
|
||||
self.modules.remove(at);
|
||||
}
|
||||
(Err(at), true) => self.modules.insert(at, name.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut fresh: Vec<Macro> = macros
|
||||
.iter()
|
||||
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
|
||||
.collect();
|
||||
sort_by_name(&mut fresh, |m| m.name.as_str());
|
||||
let mut held = std::mem::take(&mut self.macros);
|
||||
held.retain(|m| !macros.contains(m.name.as_str()));
|
||||
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
|
||||
}
|
||||
|
||||
/// Every table, rendered for comparison — the equivalence witness the
|
||||
/// incremental tests hold an updated workspace to a rebuilt one with.
|
||||
#[cfg(test)]
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
|
||||
word_files.sort();
|
||||
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
|
||||
per_file.sort();
|
||||
format!(
|
||||
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
|
||||
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
|
||||
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Candidates::update_words`] for a batch of files — the form a scan
|
||||
/// publishing what it has indexed so far uses.
|
||||
///
|
||||
@@ -715,7 +786,15 @@ fn char_mask(text: &str) -> u32 {
|
||||
/// tables want the same records. It is paid once per index build rather than
|
||||
/// once per keystroke, which is the whole point of both.
|
||||
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
|
||||
let symbols = index.workspace_symbols("");
|
||||
unit_tables(index, index.workspace_symbols(""))
|
||||
}
|
||||
|
||||
/// [`index_tables`] over a given part of the symbol listing — all of it, or
|
||||
/// the names one update touched — in the listing's own order.
|
||||
fn unit_tables(
|
||||
index: &WorkspaceIndex,
|
||||
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
|
||||
) -> (Vec<Candidate>, Vec<String>) {
|
||||
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
|
||||
// case-folded one — so same-named declarations are already adjacent and a
|
||||
// plain `dedup` leaves one entry per module name, in `str` order. That is
|
||||
@@ -757,14 +836,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
for id in 0..index.files().len() {
|
||||
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
|
||||
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
|
||||
let args = match &define.params {
|
||||
Some(params) => format!("({})", params.join(", ")),
|
||||
None => String::new(),
|
||||
};
|
||||
out.push(Macro {
|
||||
name: define.name.clone(),
|
||||
detail: format!("`define {}{args}", define.name),
|
||||
});
|
||||
out.push(macro_of(define));
|
||||
}
|
||||
}
|
||||
sort_by_name(&mut out, |m| m.name.as_str());
|
||||
@@ -772,6 +844,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One `` `define``'s completion entry.
|
||||
pub(crate) fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
|
||||
let args = match &define.params {
|
||||
Some(params) => format!("({})", params.join(", ")),
|
||||
None => String::new(),
|
||||
};
|
||||
Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) }
|
||||
}
|
||||
|
||||
/// Two lists sorted by [`word_cmp`] with no name in common, as one.
|
||||
fn merge_by_name<T>(held: Vec<T>, fresh: Vec<T>, name: impl Fn(&T) -> &str) -> Vec<T> {
|
||||
let mut out = Vec::with_capacity(held.len() + fresh.len());
|
||||
let mut fresh = fresh.into_iter().peekable();
|
||||
for item in held {
|
||||
while let Some(next) =
|
||||
fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less)
|
||||
{
|
||||
out.push(next);
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
out.extend(fresh);
|
||||
out
|
||||
}
|
||||
|
||||
/// Every distinct identifier one file's token stream contains.
|
||||
///
|
||||
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
|
||||
@@ -786,6 +883,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
/// one pass at the end: no part of a scan may be longer than one file, or the
|
||||
/// message queue goes unanswered for the length of it
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
words::harvest_text(text)
|
||||
}
|
||||
@@ -1574,3 +1672,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,131 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Which byte a "symbol under the cursor" request is about.
|
||||
//!
|
||||
//! An LSP position is a caret *between* two characters, and a span here is
|
||||
//! end-exclusive, so a caret just past an identifier's last letter names the
|
||||
//! character **after** the name. VS Code calls that caret "on the word" — a
|
||||
//! double-click, a click on the right half of the last letter, or a jump that
|
||||
//! selects the name all leave it there, and its own word highlight and the
|
||||
//! title of a references search both use the word before it. Asking about the
|
||||
//! next character instead answered `[]`, and VS Code said "No references
|
||||
//! found" for a name it was showing as selected
|
||||
//! (`docs/features/scan-ordering/README.md`, A1).
|
||||
//!
|
||||
//! The rule is VS Code's: a caret touching a name on its right edge is on
|
||||
//! that name — unless a name also starts at the caret, which then wins
|
||||
//! (`a|b` cannot happen; `a|.b` is on `a`, `a.|b` is on `b`).
|
||||
|
||||
/// The byte offset a request about the name under the cursor should resolve,
|
||||
/// given the caret's byte offset in `text`.
|
||||
///
|
||||
/// Moves one byte left when the caret is just past a name and not at the
|
||||
/// start of another; every other caret is returned unchanged. A name is an
|
||||
/// identifier, keyword, system task, macro or number written with
|
||||
/// [`is_name_byte`] — or an escaped identifier, `\` up to the whitespace that
|
||||
/// ends it, whose own characters can be anything.
|
||||
pub fn symbol_offset(text: &str, caret: u32) -> u32 {
|
||||
let bytes = text.as_bytes();
|
||||
let at = caret as usize;
|
||||
if at == 0 || at > bytes.len() || bytes.get(at).copied().is_some_and(is_name_byte) {
|
||||
return caret;
|
||||
}
|
||||
let before = bytes[at - 1];
|
||||
if is_name_byte(before) || ends_an_escaped_identifier(bytes, at) {
|
||||
return caret - 1;
|
||||
}
|
||||
caret
|
||||
}
|
||||
|
||||
/// Whether `byte` can be part of a simple identifier (IEEE 1800-2017 §5.6):
|
||||
/// a letter, a digit, `_` or `$`. A system task's leading `$` and a macro
|
||||
/// name after its backtick are covered by the same set.
|
||||
fn is_name_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||||
}
|
||||
|
||||
/// Whether the caret at `at` sits on the whitespace (or the end of the text)
|
||||
/// that terminates an escaped identifier — a `\` followed by at least one
|
||||
/// non-whitespace byte, all of it before the caret.
|
||||
fn ends_an_escaped_identifier(bytes: &[u8], at: usize) -> bool {
|
||||
if bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) {
|
||||
return false;
|
||||
}
|
||||
let start = bytes[..at].iter().rposition(u8::is_ascii_whitespace).map_or(0, |ws| ws + 1);
|
||||
at - start >= 2 && bytes[start] == b'\\'
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::symbol_offset;
|
||||
|
||||
/// The offset `symbol_offset` picks for the caret written as `|` in
|
||||
/// `marked`, as the character it lands on (`None` past the end).
|
||||
fn lands_on(marked: &str) -> Option<char> {
|
||||
let caret = marked.find('|').expect("a caret") as u32;
|
||||
let text = marked.replacen('|', "", 1);
|
||||
let at = symbol_offset(&text, caret) as usize;
|
||||
text[at..].chars().next()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_just_past_a_name_is_on_its_last_letter() {
|
||||
assert_eq!(lands_on("logic tx|,"), Some('x'));
|
||||
assert_eq!(lands_on("assign y = tx|;"), Some('x'));
|
||||
assert_eq!(lands_on("tx|"), Some('x'), "at the end of the text");
|
||||
assert_eq!(lands_on("logic tx|\nwire w;"), Some('x'), "at the end of a line");
|
||||
assert_eq!(lands_on("logic tx|\r\nwire w;"), Some('x'), "before a CRLF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_on_or_inside_a_name_is_left_alone() {
|
||||
assert_eq!(lands_on("logic |tx;"), Some('t'), "at the start");
|
||||
assert_eq!(lands_on("logic t|x;"), Some('x'), "in the middle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_touching_two_names_takes_the_one_that_starts_there() {
|
||||
// VS Code's word at `a|.b` is `a`; at `a.|b` it is `b`.
|
||||
assert_eq!(lands_on("u_a|.sig"), Some('a'), "before the dot: the instance");
|
||||
assert_eq!(lands_on("u_a.|sig"), Some('s'), "after the dot: the member");
|
||||
assert_eq!(lands_on(".clk|(clk_i)"), Some('k'), "a port name before its paren");
|
||||
assert_eq!(lands_on(".clk(|clk_i)"), Some('c'), "the signal after the paren");
|
||||
assert_eq!(lands_on("mem|[3]"), Some('m'), "a name before an index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_after_anything_but_a_name_is_left_alone() {
|
||||
assert_eq!(lands_on("a = b;|"), None, "past a semicolon at the end");
|
||||
assert_eq!(lands_on("a = b; |"), None, "past whitespace");
|
||||
assert_eq!(lands_on("f(x)|;"), Some(';'), "past a paren");
|
||||
assert_eq!(lands_on("|"), None, "an empty text");
|
||||
assert_eq!(lands_on("|tx"), Some('t'), "the very start");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_tasks_macros_and_keywords_are_names_too() {
|
||||
assert_eq!(lands_on("$display|("), Some('y'));
|
||||
assert_eq!(lands_on("`WIDTH|-1"), Some('H'));
|
||||
assert_eq!(lands_on("begin|\n"), Some('n'), "so a keyword pair highlights");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_ends_at_its_whitespace() {
|
||||
// `\a+b ` is one name whose last byte is not an identifier byte.
|
||||
assert_eq!(lands_on(r"assign \a+b+ |= 1;"), Some('='), "past the space: not on it");
|
||||
assert_eq!(lands_on(r"assign \a+b+| = 1;"), Some('+'), "on the space that ends it");
|
||||
assert_eq!(lands_on(r"\bus[0]|"), Some(']'), "at the end of the text");
|
||||
assert_eq!(lands_on(r"x = a \| b;"), Some(' '), "a lone backslash is not a name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_ascii_text_before_the_name_does_not_move_the_byte() {
|
||||
// The caret arrives as a byte offset already converted from UTF-16;
|
||||
// the rule reads bytes, and a multi-byte character is never a name.
|
||||
assert_eq!(lands_on("// é\nlogic tx|;"), Some('x'));
|
||||
assert_eq!(lands_on("é|tx"), Some('t'), "a name starting after a non-ASCII letter");
|
||||
assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one
|
||||
//! `source.fixAll.lucisv` that applies all of them in a single pass.
|
||||
//!
|
||||
@@ -476,3 +478,5 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
|
||||
//! uses (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
@@ -142,3 +144,5 @@ endmodule
|
||||
assert!(sort("al_used") < sort("always_ff"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
|
||||
@@ -100,3 +102,5 @@ mod tests {
|
||||
assert!(!paren_follows(".cl, .b(x)", 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The completion tests' harness: a scratch workspace on disk, and the
|
||||
//! handful of helpers every provider's tests ask through.
|
||||
//!
|
||||
@@ -112,3 +114,5 @@ pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a C
|
||||
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items.iter().map(|item| item.label.as_str()).collect()
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The member answer: after a `.` or a `::`, the members of what stands
|
||||
//! before it and nothing else.
|
||||
//!
|
||||
@@ -1203,3 +1205,5 @@ endmodule
|
||||
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
@@ -79,6 +81,7 @@ use buffer::{buffer_word_tier, declared_tier};
|
||||
use connection::Connection;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use related::{related_macros, related_tier};
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
||||
use word::typed_word;
|
||||
@@ -90,6 +93,7 @@ pub(crate) use module::{nearest_definition, plan_for};
|
||||
pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
pub(crate) use wire::{item_defaults_support, with_item_defaults};
|
||||
|
||||
mod buffer;
|
||||
mod connection;
|
||||
@@ -97,8 +101,10 @@ mod connection;
|
||||
mod harness;
|
||||
mod member;
|
||||
mod module;
|
||||
mod related;
|
||||
mod site;
|
||||
mod tiers;
|
||||
mod wire;
|
||||
mod word;
|
||||
|
||||
/// How many items one response carries, over every tier.
|
||||
@@ -151,10 +157,14 @@ const TIER_SCOPE: char = '1';
|
||||
/// (`completion-ux`, TODO §68.1).
|
||||
const TIER_DECLARED: char = '2';
|
||||
const TIER_BUFFER_WORD: char = '3';
|
||||
const TIER_INDEX: char = '4';
|
||||
const TIER_TEMPLATE: char = '5';
|
||||
const TIER_KEYWORD: char = '6';
|
||||
const TIER_WORD: char = '7';
|
||||
/// What the file is related to — the packages it imports, the classes its
|
||||
/// class extends, the headers it includes — below the file itself and above
|
||||
/// the rest of the workspace (`related.rs`).
|
||||
const TIER_RELATED: char = '4';
|
||||
const TIER_INDEX: char = '5';
|
||||
const TIER_TEMPLATE: char = '6';
|
||||
const TIER_KEYWORD: char = '7';
|
||||
const TIER_WORD: char = '8';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
@@ -205,6 +215,7 @@ pub fn completions(
|
||||
// The backtick itself is replaced, so the item may carry its own.
|
||||
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
|
||||
let mut items = Items::new(doc, replacing);
|
||||
related_macros(&mut items, ws, doc, &word.text);
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
items.simple(
|
||||
&format!("`{}", entry.name),
|
||||
@@ -243,6 +254,7 @@ pub fn completions(
|
||||
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
related_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
|
||||
index_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
|
||||
keyword_tier(&mut items, &word);
|
||||
@@ -273,6 +285,10 @@ struct Items {
|
||||
items: Vec<CompletionItem>,
|
||||
seen: HashSet<String>,
|
||||
incomplete: bool,
|
||||
/// How many of `items` the related tier added — which [`LIMIT`] does not
|
||||
/// count, so every other tier fills exactly as far as it would without
|
||||
/// them (`related.rs`).
|
||||
related: usize,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
@@ -282,6 +298,7 @@ impl Items {
|
||||
items: Vec::new(),
|
||||
seen: HashSet::new(),
|
||||
incomplete: false,
|
||||
related: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +306,7 @@ impl Items {
|
||||
/// only sets [`Items::incomplete`] — which is why the tiers ask first
|
||||
/// rather than building items nobody will see.
|
||||
fn full(&mut self) -> bool {
|
||||
if self.items.len() >= LIMIT {
|
||||
if self.items.len() - self.related >= LIMIT {
|
||||
self.incomplete = true;
|
||||
return true;
|
||||
}
|
||||
@@ -310,6 +327,14 @@ impl Items {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
self.unlimited(name, kind, tier, detail);
|
||||
}
|
||||
|
||||
/// [`Items::simple`] past the cap: the caller has its own.
|
||||
fn unlimited(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
||||
if !self.seen.insert(name.to_string()) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
@@ -322,7 +347,7 @@ impl Items {
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// A port or parameter after a connection list's `.`: the bare name, or
|
||||
@@ -894,3 +919,5 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Tier 0 — module names at module-item position — and the instantiation
|
||||
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
|
||||
//!
|
||||
@@ -921,3 +923,5 @@ endmodule
|
||||
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,345 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The **related** tier: what this file is related to through the workspace
|
||||
//! index, ranked above the rest of the workspace and below the file itself
|
||||
//! (`docs/features/fast-actions/README.md`, completion through the
|
||||
//! relationship map).
|
||||
//!
|
||||
//! The tier-5 table answers "every package member, typedef, class and module
|
||||
//! the workspace declares whose name matches", alphabetically, until the
|
||||
//! response is full — so in a workspace of tens of thousands of files the
|
||||
//! members of the one package this file actually imports were cut off behind
|
||||
//! names from files it has nothing to do with (measured: 46 of 47 matching
|
||||
//! `aes_pkg` names offered at `ae` in 4 000 files, 11 of 47 in 40 000). What a
|
||||
//! file is related to is known without reading anything: the packages its
|
||||
//! scope chain imports, the classes its enclosing class extends, the headers
|
||||
//! its `` `include``s reach. Those names come first.
|
||||
//!
|
||||
//! **No item is taken away.** A related item does not count against
|
||||
//! [`LIMIT`](super::LIMIT): the tiers after it fill exactly as far as they
|
||||
//! did before, and a name the related tier claimed is skipped by them
|
||||
//! without being counted, so every label of the old answer is still offered,
|
||||
//! with the same edit and format (the completion-equivalence test holds the
|
||||
//! server to that). **What does change** for a name the related tier claims
|
||||
//! is its icon and its detail: they now describe the declaration the file is
|
||||
//! related to — the member of the package it imports, the macro of the header
|
||||
//! it includes, the member of the class it extends — where the workspace tier
|
||||
//! described the first declaration of that name in the whole workspace
|
||||
//! (`NumRegs` of whichever register package sorts first; a module of the name
|
||||
//! where the imported package declares a function). The tier has its own
|
||||
//! cap, [`RELATED_LIMIT`], past which it says the answer is incomplete.
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_semantic::{Def, ScopeKind, Semantics, SymbolKind};
|
||||
|
||||
use super::tiers::innermost_scope;
|
||||
use super::word::Word;
|
||||
use super::{completion_kind, Items, TIER_RELATED};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query, Score};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// How many related names one response carries at most.
|
||||
///
|
||||
/// A package of a few hundred members is the large case (`aes_pkg` has 259
|
||||
/// on its connection surface); at an empty prefix the related tier would
|
||||
/// otherwise double a response that is already incomplete.
|
||||
pub(super) const RELATED_LIMIT: usize = 256;
|
||||
|
||||
/// One related name: what to show, and how it ranks.
|
||||
struct Related {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
/// Add a related item, unless a higher tier already offered that name or
|
||||
/// the tier is full. Not counted against [`LIMIT`](super::LIMIT).
|
||||
fn related(&mut self, name: &str, kind: CompletionItemKind, detail: String) {
|
||||
if self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
if self.related >= RELATED_LIMIT {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
self.related += 1;
|
||||
self.unlimited(name, kind, TIER_RELATED, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// The related tier for a name being typed: the members of every package
|
||||
/// the scope chain at the cursor imports, and of the classes the enclosing
|
||||
/// class extends.
|
||||
pub(super) fn related_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
let mut found = imported(ws, &doc.semantics, word.start);
|
||||
found.extend(inherited(ws, &doc.semantics, word.start));
|
||||
let mut matched: Vec<(Related, Option<Score>)> = found
|
||||
.into_iter()
|
||||
.filter_map(|related| match fuzzy {
|
||||
None => starts_with_ignore_case(&related.name, &word.text).then_some((related, None)),
|
||||
Some(query) => query.score(&related.name).map(|score| (related, Some(score))),
|
||||
})
|
||||
.collect();
|
||||
matched.sort_by(|(a, sa), (b, sb)| match (sa, sb) {
|
||||
(Some(sa), Some(sb)) => rank_cmp((&a.name, *sa), (&b.name, *sb)),
|
||||
_ => a.name.cmp(&b.name),
|
||||
});
|
||||
for (related, _) in matched {
|
||||
items.related(&related.name, completion_kind(related.kind), related.detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// The related tier after a backtick: the macros the headers this buffer
|
||||
/// reaches through its `` `include``s define, ahead of every other macro in
|
||||
/// the workspace.
|
||||
pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) {
|
||||
let mut names: Vec<(String, String)> = Vec::new();
|
||||
for path in crate::includes::reachable_from(ws, doc) {
|
||||
let Some(table) = ws.index().file_id(&path).and_then(|file| ws.index().defines(file))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define);
|
||||
for define in defines.filter(|d| starts_with_ignore_case(&d.name, prefix)) {
|
||||
names.push((define.name.clone(), crate::candidates::macro_of(define).detail));
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
names.dedup_by(|a, b| a.0 == b.0);
|
||||
for (name, detail) in names {
|
||||
items.related(&format!("`{name}"), CompletionItemKind::CONSTANT, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every member of every package imported by a scope enclosing `offset`,
|
||||
/// innermost scope first, a wildcard bringing all of a package's members and
|
||||
/// an explicit import the one it names.
|
||||
fn imported(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = innermost_scope(semantics, offset).or(Some(semantics.file_scope()));
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
at = scope.parent;
|
||||
for import in &scope.imports {
|
||||
for (name, defs) in ws.index().members_of(&import.package) {
|
||||
if import.item.as_deref().is_some_and(|item| item != name) {
|
||||
continue;
|
||||
}
|
||||
let Some(def) = defs.first() else { continue };
|
||||
out.push(Related {
|
||||
name: name.to_string(),
|
||||
kind: def.kind,
|
||||
detail: format!("{} — {}::{name}", kind_label(def.kind), import.package),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every member the enclosing class inherits, as the index's member chain for
|
||||
/// that class lists it — its own members included, which the scope tier has
|
||||
/// already claimed — each named after the class that **declares** it, the
|
||||
/// way the workspace tier names a member (`base_c::count`).
|
||||
fn inherited(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
if scope.kind == ScopeKind::Class {
|
||||
let Some(key) = semantics.member_key(id) else { return Vec::new() };
|
||||
let index = ws.index();
|
||||
return index
|
||||
.members_of_chain(&key)
|
||||
.into_iter()
|
||||
.map(|(name, def)| {
|
||||
let owner = declaring_class(ws, &key, name, def).unwrap_or(&key);
|
||||
Related {
|
||||
name: name.to_string(),
|
||||
kind: def.kind,
|
||||
detail: format!("{} — {owner}::{name}", kind_label(def.kind)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
at = scope.parent;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Which class of `class`'s `extends` chain declares `def` as `name`: the
|
||||
/// class itself, then its base, then that base's base — each hop the one
|
||||
/// `vlog_semantic`'s `base_chain` takes, a recorded base or else the class a
|
||||
/// typedef aliases (`typedef mid_c alias_t; class leaf_c extends alias_t;`).
|
||||
/// `None` only for a chain the index cannot follow, and the caller then
|
||||
/// names the class it started from.
|
||||
fn declaring_class<'a>(
|
||||
ws: &'a Workspace,
|
||||
class: &'a str,
|
||||
name: &str,
|
||||
def: &Def,
|
||||
) -> Option<&'a str> {
|
||||
let index = ws.index();
|
||||
let mut hop = Some(class);
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
while let Some(unit) = hop.filter(|unit| !seen.contains(unit)) {
|
||||
if index.members_of(unit).any(|(member, defs)| member == name && defs.first() == Some(def))
|
||||
{
|
||||
return Some(unit);
|
||||
}
|
||||
seen.push(unit);
|
||||
hop = index.base_of(unit).or_else(|| aliased_class(ws, unit)).map(last_segment);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The class a typedef names, when `unit` is a typedef the index holds once —
|
||||
/// the alias hop of `vlog_semantic`'s `base_chain` (`aliased_unit`), read
|
||||
/// through the index's public tables.
|
||||
fn aliased_class<'a>(ws: &'a Workspace, unit: &str) -> Option<&'a str> {
|
||||
match ws.index().units(unit) {
|
||||
[def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly qualified class path — the name the
|
||||
/// member and inheritance tables are keyed by.
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
|
||||
/// A package the buffer imports, and one it does not, both holding names
|
||||
/// that start alike.
|
||||
fn two_packages(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write(
|
||||
"near.sv",
|
||||
"package near_pkg;\n localparam int ZED_NEAR = 1;\n typedef logic zed_t;\nendpackage\n",
|
||||
);
|
||||
tree.write("far.sv", "package far_pkg;\n localparam int ZED_FAR = 2;\nendpackage\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_packages_members_rank_above_the_rest_of_the_workspace() {
|
||||
let top = "module top;\n import near_pkg::*;\n assign x = ze\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(two_packages("rel_import"), top, "= ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let near = find(&items, "ZED_NEAR").expect("the imported member");
|
||||
let far = find(&items, "ZED_FAR").expect("the other package's member is still offered");
|
||||
assert_eq!(tier(near), TIER_RELATED);
|
||||
assert_eq!(tier(far), TIER_INDEX);
|
||||
assert!(near.sort_text < far.sort_text, "related above the workspace");
|
||||
assert_eq!(near.detail.as_deref(), Some("localparam — near_pkg::ZED_NEAR"));
|
||||
assert_eq!(tier(find(&items, "zed_t").expect("the typedef")), TIER_RELATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_import_relates_the_one_name_it_imports() {
|
||||
let top = "module top;\n import near_pkg::zed_t;\n assign x = ze\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(two_packages("rel_explicit"), top, "= ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
// The binder makes an explicitly imported name a declaration of this
|
||||
// scope, so it is offered by the scope tier, above even this one.
|
||||
assert!(tier(find(&items, "zed_t").expect("imported")) <= TIER_RELATED);
|
||||
assert_eq!(tier(find(&items, "ZED_NEAR").expect("still offered")), TIER_INDEX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_items_take_nothing_from_the_tiers_after_them() {
|
||||
// More project names than the cap, and an import whose members all
|
||||
// match too: the workspace tiers still fill the whole cap.
|
||||
let tree = two_packages("rel_cap");
|
||||
let mut many = String::from("package many_pkg;\n");
|
||||
for i in 0..LIMIT + 40 {
|
||||
many.push_str(&format!(" localparam int ZED_{i:04} = {i};\n"));
|
||||
}
|
||||
many.push_str("endpackage\n");
|
||||
tree.write("many.sv", &many);
|
||||
let top = "module top;\n import near_pkg::*;\n assign x = ZE\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= ZE");
|
||||
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
||||
panic!("a list");
|
||||
};
|
||||
let related = list.items.iter().filter(|i| tier(i) == TIER_RELATED).count();
|
||||
assert_eq!(related, 2, "the two near_pkg names");
|
||||
assert_eq!(list.items.len() - related, LIMIT, "the cap counts the others only");
|
||||
assert!(list.is_incomplete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_relates_what_it_inherits() {
|
||||
let tree = Tree::new("rel_class");
|
||||
tree.write(
|
||||
"base.sv",
|
||||
"class base_c;\n int zed_count;\n function void zed_reset();\n endfunction\nendclass\n",
|
||||
);
|
||||
let top = "class derived_c extends base_c;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let count = find(&items, "zed_count").expect("inherited");
|
||||
assert_eq!(tier(count), TIER_RELATED);
|
||||
assert_eq!(tier(find(&items, "zed_reset").expect("inherited")), TIER_RELATED);
|
||||
// Named after the class that declares it, as the workspace tier
|
||||
// names a member — not after the class that inherits it.
|
||||
assert_eq!(count.detail.as_deref(), Some("variable — base_c::zed_count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backtick_ranks_what_the_included_headers_define_first() {
|
||||
let tree = Tree::new("rel_macro");
|
||||
tree.write("near.svh", "`define ZED_NEAR 1\n");
|
||||
tree.write("far.svh", "`define ZED_FAR 2\n");
|
||||
let top = "`include \"near.svh\"\nmodule top;\n assign x = `ZE\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "`ZE");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let near = find(&items, "`ZED_NEAR").expect("the included header's macro");
|
||||
let far = find(&items, "`ZED_FAR").expect("every other macro is still offered");
|
||||
assert_eq!(tier(near), TIER_RELATED);
|
||||
assert!(near.sort_text < far.sort_text);
|
||||
assert_eq!(near.detail.as_deref(), Some("`define ZED_NEAR"), "the detail tier 5 gives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_two_classes_up_names_the_class_that_declares_it() {
|
||||
let tree = Tree::new("rel_grand");
|
||||
tree.write("base.sv", "class root_c;\n int zed_deep;\nendclass\nclass mid_c extends root_c;\n int zed_mid;\nendclass\n");
|
||||
let top =
|
||||
"class leaf_c extends mid_c;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let detail = |label: &str| find(&items, label).and_then(|i| i.detail.clone());
|
||||
assert_eq!(detail("zed_deep").as_deref(), Some("variable — root_c::zed_deep"));
|
||||
assert_eq!(detail("zed_mid").as_deref(), Some("variable — mid_c::zed_mid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_reached_through_a_typedef_alias_names_the_class_that_declares_it() {
|
||||
// QA R2: `leaf_c extends alias_t`, and `alias_t` is a typedef of
|
||||
// `mid_c` — the member is `mid_c`'s.
|
||||
let tree = Tree::new("rel_alias");
|
||||
tree.write("base.sv", "class mid_c;\n int zed_mid;\nendclass\ntypedef mid_c alias_t;\n");
|
||||
let top = "class leaf_c extends alias_t;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let mid = find(&items, "zed_mid").expect("inherited through the alias");
|
||||
assert_eq!(tier(mid), TIER_RELATED);
|
||||
assert_eq!(mid.detail.as_deref(), Some("variable — mid_c::zed_mid"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! What may be written here: the module-item gate and the statement gate,
|
||||
//! judged over the token stream's scope chain.
|
||||
//!
|
||||
@@ -262,3 +264,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
@@ -944,3 +946,5 @@ endmodule
|
||||
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,152 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! What a completion answer costs on the wire, for a client that can take
|
||||
//! less (`docs/features/fast-actions/README.md`, "payload").
|
||||
//!
|
||||
//! Every item of one answer replaces the same range, and almost every item
|
||||
//! inserts its own label as plain text — so the `textEdit` each one carries
|
||||
//! (49 % of a 130 KB answer, measured) and its `insertTextFormat` (8 %) say
|
||||
//! the same thing five hundred times. LSP 3.17's `CompletionList.itemDefaults`
|
||||
//! says it once: an item with no `textEdit` replaces `editRange` with its
|
||||
//! `textEditText`, or with its label when it has none, in
|
||||
//! `insertTextFormat`. `vscode-languageclient` 9 applies exactly that rule
|
||||
//! (`protocolConverter.asCompletionInsertText`), and advertises both defaults.
|
||||
//!
|
||||
//! **The same edits, fewer bytes.** The rewrite is lossless by construction:
|
||||
//! an item keeps its own `textEdit` unless its range *is* the default, keeps
|
||||
//! its own format unless it *is* the default, and moves a `newText` that is
|
||||
//! not its label into `textEditText`. Done on the serialized answer because
|
||||
//! `lsp-types` 0.97 has neither field.
|
||||
|
||||
use lsp_types::InitializeParams;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// `insertTextFormat: PlainText`, the format nearly every item has.
|
||||
const PLAIN_TEXT: u64 = 1;
|
||||
|
||||
/// Whether the client applies `itemDefaults.editRange` and
|
||||
/// `itemDefaults.insertTextFormat` — `textDocument.completion.completionList
|
||||
/// .itemDefaults` listing both. A client that said nothing gets every item
|
||||
/// whole, which is what every client got before this was read.
|
||||
pub(crate) fn item_defaults_support(params: &InitializeParams) -> bool {
|
||||
let listed = params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.completion.as_ref())
|
||||
.and_then(|completion| completion.completion_list.as_ref())
|
||||
.and_then(|list| list.item_defaults.as_ref());
|
||||
listed.is_some_and(|names| {
|
||||
["editRange", "insertTextFormat"].iter().all(|wanted| names.iter().any(|n| n == wanted))
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrite a serialized `CompletionList` so the range and the format every
|
||||
/// item shares are said once, in `itemDefaults`. Anything that is not a list
|
||||
/// with items comes back as it was.
|
||||
pub(crate) fn with_item_defaults(mut answer: Value) -> Value {
|
||||
let Some(list) = answer.as_object_mut() else { return answer };
|
||||
let Some(Value::Array(items)) = list.get_mut("items") else { return answer };
|
||||
let Some(range) = items.first().and_then(edit_range).cloned() else { return answer };
|
||||
for item in items.iter_mut().filter_map(Value::as_object_mut) {
|
||||
lift_edit(item, &range);
|
||||
if item.get("insertTextFormat").and_then(Value::as_u64) == Some(PLAIN_TEXT) {
|
||||
item.remove("insertTextFormat");
|
||||
}
|
||||
}
|
||||
let mut defaults = Map::new();
|
||||
defaults.insert("editRange".to_string(), range);
|
||||
defaults.insert("insertTextFormat".to_string(), Value::from(PLAIN_TEXT));
|
||||
list.insert("itemDefaults".to_string(), Value::Object(defaults));
|
||||
answer
|
||||
}
|
||||
|
||||
/// The range a plain `textEdit` replaces, if the item has one.
|
||||
fn edit_range(item: &Value) -> Option<&Value> {
|
||||
let edit = item.get("textEdit")?;
|
||||
edit.get("newText")?;
|
||||
edit.get("range")
|
||||
}
|
||||
|
||||
/// Drop `item`'s `textEdit` when it replaces `range`, keeping its text in
|
||||
/// `textEditText` unless that text is the label.
|
||||
fn lift_edit(item: &mut Map<String, Value>, range: &Value) {
|
||||
let Some(edit) = item.get("textEdit") else { return };
|
||||
if edit.get("range") != Some(range) {
|
||||
return;
|
||||
}
|
||||
let Some(Value::Object(mut edit)) = item.remove("textEdit") else { return };
|
||||
let new_text = edit.remove("newText").unwrap_or(Value::Null);
|
||||
if item.get("label") != Some(&new_text) {
|
||||
item.insert("textEditText".to_string(), new_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn range(line: u32) -> Value {
|
||||
json!({ "start": { "line": line, "character": 4 }, "end": { "line": line, "character": 6 } })
|
||||
}
|
||||
|
||||
/// The edit an item makes under the LSP 3.17 rule, defaults applied.
|
||||
fn effective(item: &Value, defaults: &Value) -> (Value, Value, Value) {
|
||||
let format = item.get("insertTextFormat").unwrap_or(&defaults["insertTextFormat"]).clone();
|
||||
match item.get("textEdit") {
|
||||
Some(edit) => (edit["range"].clone(), edit["newText"].clone(), format),
|
||||
None => (
|
||||
defaults["editRange"].clone(),
|
||||
item.get("textEditText").unwrap_or(&item["label"]).clone(),
|
||||
format,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_item_makes_the_same_edit_with_the_defaults_applied() {
|
||||
let before = json!({ "isIncomplete": true, "items": [
|
||||
{ "label": "sig", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(2), "newText": "sig" } },
|
||||
{ "label": "if begin/end", "insertTextFormat": 2,
|
||||
"textEdit": { "range": range(2), "newText": "if (${1:cond}) begin\n$0\nend" } },
|
||||
{ "label": "`W", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(2), "newText": "`W" } },
|
||||
{ "label": "odd", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(7), "newText": "odd" } },
|
||||
]});
|
||||
let after = with_item_defaults(before.clone());
|
||||
let defaults = &after["itemDefaults"];
|
||||
assert_eq!(defaults["editRange"], range(2));
|
||||
for (old, new) in
|
||||
before["items"].as_array().unwrap().iter().zip(after["items"].as_array().unwrap())
|
||||
{
|
||||
let old_effect = (
|
||||
old["textEdit"]["range"].clone(),
|
||||
old["textEdit"]["newText"].clone(),
|
||||
old["insertTextFormat"].clone(),
|
||||
);
|
||||
assert_eq!(effective(new, defaults), old_effect, "{new}");
|
||||
}
|
||||
assert!(after["items"][0].get("textEdit").is_none(), "the label is the text");
|
||||
assert!(after["items"][0].get("textEditText").is_none());
|
||||
assert_eq!(after["items"][1]["textEditText"], before["items"][1]["textEdit"]["newText"]);
|
||||
assert!(after["items"][3].get("textEdit").is_some(), "another range keeps its edit");
|
||||
assert!(after.to_string().len() < before.to_string().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_that_is_not_a_list_of_edits_is_left_alone() {
|
||||
for answer in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({ "isIncomplete": false, "items": [] }),
|
||||
json!({ "items": [{ "label": "x", "insertText": "x" }] }),
|
||||
] {
|
||||
assert_eq!(with_item_defaults(answer.clone()), answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! What is typed: the identifier run ending at the cursor and what stands
|
||||
//! around it — a backtick, a `.` or a `::`, and the spine a separator
|
||||
//! follows.
|
||||
@@ -244,3 +246,5 @@ pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Byte offsets ↔ LSP positions.
|
||||
//!
|
||||
//! Everything below the protocol speaks UTF-8 byte offsets; LSP `Position`
|
||||
@@ -518,3 +520,5 @@ mod tests {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! The VS Code instance-oriented design hierarchy.
|
||||
//!
|
||||
//! LSP call hierarchy deliberately groups a module's calls by target module
|
||||
@@ -523,3 +525,5 @@ mod tests {
|
||||
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Diagnostics, published on every buffer change.
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity};
|
||||
@@ -199,3 +201,5 @@ mod tests {
|
||||
assert!(diags[0].range.start < diags[0].range.end, "must be drawable");
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -1,3 +1,5 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Single-step macro expansion, for hover **display** only.
|
||||
//!
|
||||
//! One step means one thing: the definition's body with the call site's
|
||||
@@ -430,3 +432,5 @@ mod tests {
|
||||
assert!(!has_macro_use("plain text"));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
Loaded 100 of 883 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user