Files
lucisv/crates/lucisv_server/src/settings.rs
T
lucioandClaude Fable 5 03a4958294 Inline instantiation round 2: the space is the commitment, and every indexed module answers
Two owner rulings from live use. The ghost now fires only after
'name<space>' — aes alone may still be growing into aes_dft, so the
typed space is what says the name is finished; an Ident ending at the
cursor offers nothing at all. And a module declared in more than one
file no longer declines: completion::nearest_definition picks the copy
sharing the most leading path components with the asking buffer (a
top_earlgrey buffer gets top_earlgrey's ast_dft), then the shallowest,
then the lexicographically smallest — the depth term is QA's catch,
fixed at review, so a direct sibling beats a deeper subdirectory copy
that ties on the prefix. vlog_refactor::module_definition keeps its
ambiguity refusal for its own callers.

The refusal residue is now the enumerable inline::NoGhost, and QA's
sweep proves the ruling: 1131/1131 opentitan module names ghost, zero
declines (199 multiply-declared, tb 61 ways), ast_dft and io_osc
verified from both tops over the wire, 0.05-0.08 ms per non-matching
keystroke.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 17:15:42 -07:00

806 lines
41 KiB
Rust

//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`
//! — or answers when the server pulls them with `workspace/configuration`.
//!
//! These are the editor's copy of what `lucisv.toml` carries — the same keys, so
//! a user with no config file in the tree can still say "indent 4" from their
//! editor's settings UI. The three formatting ones never *beat* a `lucisv.toml`:
//! see the precedence ladder in `format::settings_for` and
//! `docs/features/editor-settings/README.md`. `filelist` is the exception, and
//! deliberately so — it names a *scope* rather than a style, and the person
//! who typed it into their editor is the one saying which project they are
//! working on (`docs/features/filelist/README.md`).
//!
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::ops::RangeInclusive;
use serde_json::Value;
/// Accepted `line-length`, and accepted `indent`.
///
/// Duplicated from `lucisv_core::config`'s parser, which spells the same bounds
/// inline in `parse_entry` and exports no constant for them. A client's value
/// must be exactly as acceptable as the same value written in a `lucisv.toml`,
/// or the two front ends would disagree about what is valid;
/// `the_accepted_ranges_are_the_ones_lucisv_toml_accepts` asserts that against
/// the real parser rather than against a copied number.
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// `lucisv.index.maxFileSize`'s default: 1 MiB. A source file bigger than this
/// is almost always a generated netlist or a dumped trace, which costs minutes
/// to index and answers nothing a user asked. `0` means no cap; see
/// `docs/features/indexing-ux/README.md`.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
/// `lucisv.largeFile.threshold`'s default: 4 MiB. A buffer bigger than this is
/// opened on the fast path — line index only, no lex, no parse, no index — and
/// coloured a viewport at a time. `0` turns the fast path off, so every buffer
/// is analyzed in full however big it is; see
/// `docs/features/large-file-mode/README.md`.
pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024;
/// `lucisv.index.scopeDepth`'s default: 2 levels above the open file's own
/// folder, clamped at the workspace root that contains it.
///
/// **Changed from 0 on 2026-08-28**, and it is a behaviour change, not a
/// tuning one. At 0 the folder scope indexed the opened file's directory and
/// nothing else, and the measurement that forced the change is in
/// `performance.md` §4: opening `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an
/// index of **one file**, so definition, hover, references, `workspace/symbol`
/// and signature help all answered *nothing* until some later jump widened the
/// scope. A user's first experience of the server was silence.
///
/// Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into
/// the IP block it belongs to — `hw/ip/aes`, a few hundred files — which is
/// the unit an engineer actually works in. What keeps the cost bounded is
/// everything the scope ladder already has: the size cap, the persistent
/// cache, the interleaved scan and the incremental widen. See
/// `docs/features/index-scope/README.md`.
pub const DEFAULT_SCOPE_DEPTH: u64 = 2;
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
///
/// The default is deliberately the narrow one. A large project is the case
/// worth optimising for, and in it the files a user is working with are the
/// ones beside the file they opened; walking every workspace folder to answer
/// a question about one folder is minutes of work nobody asked for. See
/// `docs/features/index-scope/README.md` for what the narrow scope costs,
/// which is cross-folder answers until the scope reaches the other folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexScope {
/// The open buffers' own folders, each raised
/// [`ClientSettings::index_scope_depth`] levels, walked.
#[default]
Folder,
/// Every workspace folder, walked whole — what the server did before
/// 2026-08-27, and what a user with a small project or a big machine can
/// ask for back.
Workspace,
}
/// The configuration section these settings live in — the key a push nests
/// them under, and the `section` a pull asks for. One constant, because the
/// two must name the same thing or the pull would answer settings the parser
/// then looks for somewhere else.
pub const SECTION: &str = "lucisv";
/// The `lucisv.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means — except the two whose own default is not silence
/// (`index.maxFileSize`, `index.logFiles`), which resolve to it here so no
/// use site has to remember what "unset" meant. See the hand-written
/// [`Default`] below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings {
/// `lucisv.lineLength`.
pub line_length: Option<usize>,
/// `lucisv.indent`.
pub indent: Option<usize>,
/// `lucisv.exclude`, appended to the config's excludes in the workspace scan.
pub exclude: Vec<String>,
/// `lucisv.filelist`: the `.f` file that defines the index's scope, absolute
/// or relative to the workspace root. Empty means "unset", which is what
/// the VS Code default is — see `docs/features/filelist/README.md`.
pub filelist: Option<String>,
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
/// `lucisv.inlineInstantiation`: whether a module name the workspace
/// declares grows a ghost instantiation once it is spelled exactly and
/// followed by a space. Unset means on, the same way `inline_templates`
/// does — see `docs/features/inline-instantiation/README.md`.
pub inline_instantiation: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
/// own already runs `textDocument/formatting` on save, and a server that
/// also formatted would format twice. See
/// `docs/features/will-save-wait-until/README.md`.
pub format_on_save: bool,
/// `lucisv.index.maxFileSize`: the largest *walked* file, in bytes, that
/// the workspace index will read. `0` is no cap. An open buffer is
/// indexed whatever its size — the user opened it deliberately. Defaults
/// to [`DEFAULT_MAX_FILE_SIZE`] rather than to 0, so a plain
/// `ClientSettings::default()` is the capped behaviour the server ships
/// with.
pub max_file_size: u64,
/// `lucisv.index.logFiles`: whether each file the index reads is named in
/// a `window/logMessage`, and each oversized one in a skip line. On
/// unless a client says otherwise — the Output panel it lands in is
/// hidden until somebody opens it.
pub log_files: bool,
/// `lucisv.index.scope`: whether the walk covers the open files' folders
/// or every workspace folder. Defaults to [`IndexScope::Folder`], which
/// is a narrower index than the server built before 2026-08-27 — see
/// `docs/features/index-scope/README.md`.
pub index_scope: IndexScope,
/// `lucisv.index.scopeDepth`: how many directory levels above an open
/// file's own folder the folder scope starts, clamped so it never climbs
/// out of the workspace folder containing it. `0` is the file's own folder
/// and the default is [`DEFAULT_SCOPE_DEPTH`]. Ignored when `index_scope`
/// is [`IndexScope::Workspace`] or when a filelist defines the scope.
pub index_scope_depth: u64,
/// `lucisv.index.persist`: whether what a scan parsed is written to disk
/// so the next session can skip parsing the files that have not changed.
/// On unless a client says otherwise — a half-finished scan that has to
/// start again from zero is the thing this exists to prevent. Off means
/// off in both directions: nothing is read and nothing is written
/// (`docs/features/index-persistence/README.md`).
pub index_persist: bool,
/// `lucisv.index.cachePath`: where that store lives, absolute or relative
/// to the first workspace root. Empty means "unset", and then the
/// editor's own storage folder — or this platform's cache directory —
/// decides; see `index_cache::cache_dir` for the ladder.
pub index_cache_path: Option<String>,
/// `lucisv.largeFile.threshold`: the size in bytes above which an **open
/// buffer** is served by the fast path instead of being analyzed. `0`
/// disables the fast path. Unlike `index.maxFileSize`, which is about
/// files on disk that nobody asked for, this one is about the file on
/// screen — see `docs/features/large-file-mode/README.md`.
pub large_file_threshold: u64,
}
/// The settings a client that said nothing is treated as having asked for.
///
/// Hand-written because two of them do not default to silence: the size cap
/// is on at 1 MiB and the file log is on. Every other field is its type's own
/// zero, exactly as the derive produced.
impl Default for ClientSettings {
fn default() -> ClientSettings {
ClientSettings {
line_length: None,
indent: None,
exclude: Vec::new(),
filelist: None,
inline_templates: None,
inline_instantiation: None,
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: DEFAULT_SCOPE_DEPTH,
index_persist: true,
index_cache_path: None,
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
}
}
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
/// the settings UI, but the notification is just JSON on a socket, and other
/// editors (the Neovim setup in `editors/nvim/README.md` writes the same
/// section by hand) have no schema at all. A value of the wrong type, out of
/// range, or missing is dropped and leaves that rung of the ladder silent —
/// the same choice `format::config_from` already makes for an absurd
/// `tabSize`, for the same reason: silently honouring half of a nonsensical
/// request is worse than ignoring it.
pub fn from_payload(settings: &Value) -> ClientSettings {
// `{"settings": {"lucisv": {...}}}` — the shape
// `synchronize.configurationSection: 'lucisv'` produces. A payload without
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
// `lucisv.index.maxFileSize` is a dotted id, and both doors nest it: VS
// Code's settings model turns every segment into an object, so the section
// arrives as `{"index": {"maxFileSize": …}}`. An `index` that is missing —
// or is not an object at all — leaves both of its keys at their defaults,
// which is what `Value::get` on a non-object already returns.
let index = lucisv.get("index");
// `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the
// same reason: VS Code turns every dotted segment into an object.
let large_file = lucisv.get("largeFile");
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
inline_templates: flag(lucisv.get("inlineTemplates")),
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
// The safe direction for these two is the shipped default, not zero:
// a wrong-typed cap that read as `0` would index the netlist the
// setting exists to skip.
max_file_size: count(index.and_then(|i| i.get("maxFileSize")))
.unwrap_or(DEFAULT_MAX_FILE_SIZE),
log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true),
// An unreadable scope leaves the narrow default standing, for the
// same reason a junk cap leaves the cap on: the direction that
// silently costs a user minutes of scanning is the wrong one to
// guess in.
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
// A junk depth leaves the shipped default standing, like every
// other setting here: an unreadable value must never be the reason a
// user's index is narrower than the server promised.
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth")))
.unwrap_or(DEFAULT_SCOPE_DEPTH),
// A wrong-typed `persist` leaves the cache on. The direction that
// costs something is turning it *off* by accident — a user who never
// touched the setting would silently pay for every parse again — and
// a cache that is on can only ever cost a file's parse, because every
// hit is verified against the file's own bytes.
index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true),
index_cache_path: path(index.and_then(|i| i.get("cachePath"))),
// The safe direction again: a wrong-typed threshold leaves the fast
// path armed at its default. A junk value that read as `0` would turn
// it off, and the first 100 MB netlist opened after that would hang
// the editor for minutes — which is the whole thing this exists to
// prevent.
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
/// on one client and nothing on another.
fn scope(value: Option<&Value>) -> Option<IndexScope> {
match value?.as_str()? {
"folder" => Some(IndexScope::Folder),
"workspace" => Some(IndexScope::Workspace),
_ => None,
}
}
/// Read one `workspace/configuration` answer — the *contents* of the `lucisv`
/// section, since that is what the server asked for by name.
///
/// Deliberately the same parser as a push, reached by wrapping the section
/// back into the shape a push arrives in. Two entry points, one set of rules:
/// a range, a type or a default that drifted between the pull and the push
/// paths would be a setting that means one thing in VS Code and another in
/// Neovim. `null` — the answer the spec requires when a client cannot provide
/// the section — parses as "no opinion about anything", which is exactly the
/// defaults.
pub fn from_section(section: &Value) -> ClientSettings {
from_payload(&Value::Object([(SECTION.to_string(), section.clone())].into_iter().collect()))
}
/// Whether a `didChangeConfiguration` payload carries nothing at all.
///
/// The 3.17 model: a client that knows the server pulls sends the
/// notification as a bare "something changed, ask me for what you need" —
/// `{"settings": null}` is what `vscode-languageclient` sends once no legacy
/// `synchronize.configurationSection` is configured, and `{}` is the same
/// statement written differently. Both are a *trigger*, not a settings
/// payload, so the server pulls rather than resetting everything to its
/// default. A payload with any key in it is a real push and is applied as it
/// always was, whether or not our section is among those keys.
pub fn says_nothing(settings: &Value) -> bool {
match settings {
Value::Null => true,
Value::Object(map) => map.is_empty(),
_ => false,
}
}
/// A JSON boolean, or nothing. `as_bool` rejects the string `"false"` and the
/// number `0` along with everything else that is not a boolean: a wrong-typed
/// value is dropped here exactly as it is everywhere else in this module, and
/// the setting falls back to its own default rather than to a guess.
fn flag(value: Option<&Value>) -> Option<bool> {
value?.as_bool()
}
/// A non-empty JSON string, or nothing. The empty string is `lucisv.filelist`'s
/// default and means "no filelist", not "the filelist named by the empty
/// path"; anything that is not a string is dropped like every other
/// wrong-typed value here.
fn path(value: Option<&Value>) -> Option<String> {
let text = value?.as_str()?.trim();
(!text.is_empty()).then(|| text.to_string())
}
/// A JSON integer inside `range`, or nothing.
///
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
/// step. A non-integral number cannot reach here from VS Code anyway —
/// JavaScript serializes `4.0` as `4` — so there is no "close enough" case to
/// forgive.
fn bounded(value: Option<&Value>, range: RangeInclusive<u64>) -> Option<usize> {
let number = value?.as_u64()?;
range.contains(&number).then_some(number as usize)
}
/// A JSON count — any unsigned integer, `0` included — or nothing.
///
/// Unbounded on purpose: there is no size a cap may not take, and a cap larger
/// than any file on disk is the same as no cap at all. `as_u64` still rejects
/// the negatives, the fractions, the strings and the booleans, exactly as
/// [`bounded`] does.
fn count(value: Option<&Value>) -> Option<u64> {
value?.as_u64()
}
/// Every string in a JSON array, or an empty list for anything else. Entries
/// that are not strings are dropped rather than stringified: a number in an
/// exclude list is a mistake, and guessing what it meant would hide it.
fn strings(value: Option<&Value>) -> Vec<String> {
let Some(Value::Array(items)) = value else { return Vec::new() };
items.iter().filter_map(Value::as_str).map(str::to_string).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// The settings a `didChangeConfiguration` payload resolves to.
fn settings(payload: Value) -> ClientSettings {
from_payload(&payload)
}
/// The payload shape `vscode-languageclient` actually sends for
/// `synchronize.configurationSection: 'lucisv'` — the whole section, with
/// every key present at its default. Verified against the real library in
/// `node_modules`; see the feature README's Handshakes.
fn vscode_payload(line_length: Value, indent: Value, exclude: Value) -> Value {
json!({
"lucisv": {
"serverPath": "lucisv-server",
"rainbowBeginEnd": true,
"lineLength": line_length,
"indent": indent,
"exclude": exclude,
"filelist": "",
"inlineTemplates": true,
"inlineInstantiation": true,
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
"scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH
}
}
})
}
#[test]
fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() {
assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE);
assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says");
// The whole sub-section missing is the same as the key missing.
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576);
let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } }));
assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all");
let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } }));
assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound");
}
#[test]
fn a_wrong_typed_size_cap_leaves_the_default_standing() {
// The safe direction is the shipped cap: reading junk as `0` would
// turn the cap *off*, which is the failure the setting exists to
// prevent.
for bad in
[json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])]
{
let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored");
}
// An `index` that is not an object at all is the same as no `index`.
for bad in [json!(null), json!(7), json!("index"), json!([])] {
let found = settings(json!({ "lucisv": { "index": bad } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored");
assert!(found.log_files, "and so is its logFiles");
assert_eq!(found.index_scope, IndexScope::Folder, "and its scope");
assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth");
}
}
#[test]
fn the_file_log_is_on_until_a_client_turns_it_off() {
assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on");
assert!(
settings(json!({ "lucisv": { "index": {} } })).log_files,
"and so is an empty section"
);
assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files);
assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } }));
assert!(found.log_files, "logFiles {bad} must be ignored");
}
}
#[test]
fn the_index_settings_come_through_the_pull_door_too() {
// `from_section` is the same parser, and these were the first nested
// keys to go through it — a section that lost the nesting on the way
// would silently un-cap every pulling client.
let section = json!({
"index": {
"maxFileSize": 4096, "logFiles": false,
"scope": "workspace", "scopeDepth": 2,
"persist": false, "cachePath": "/tmp/store"
}
});
let pulled = from_section(&section);
assert_eq!(pulled.max_file_size, 4096);
assert!(!pulled.log_files);
assert_eq!(pulled.index_scope, IndexScope::Workspace);
assert_eq!(pulled.index_scope_depth, 2);
assert!(!pulled.index_persist);
assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store"));
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
}
#[test]
fn the_index_cache_is_on_until_a_client_turns_it_off() {
// Same shape as the file log, and the same direction for junk: the
// setting that costs a user work if it is guessed wrong is "off", so
// anything unreadable leaves it on.
assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on");
assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one");
assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist);
assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "persist": bad } } }));
assert!(found.index_persist, "persist {bad} must be ignored");
}
}
#[test]
fn the_cache_path_is_unset_until_a_client_names_one() {
// The empty string is `lucisv.index.cachePath`'s own default and means
// "you decide", exactly as it does for `lucisv.filelist` — not "the
// directory named by the empty path".
assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path,
None
);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } }))
.index_cache_path
.as_deref(),
Some(".cache/lucisv")
);
for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] {
let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } }));
assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored");
}
}
#[test]
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
// The default is the narrow one, and it is what silence, an empty
// sub-section and a missing `index` all resolve to.
assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder);
assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees");
let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } }));
assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting");
let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } }));
assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing");
// Anything else is junk, and junk leaves the *narrow* default: a
// misparse must never buy a whole-workspace scan silently.
for bad in
[json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])]
{
let found = settings(json!({ "lucisv": { "index": { "scope": bad } } }));
assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored");
}
}
#[test]
fn the_scope_depth_is_two_until_a_client_says_otherwise() {
// Two, not zero, since 2026-08-28: `performance.md` §4 measured the
// file's-own-folder default indexing exactly one file in opentitan's
// `dv/tb` layout, so every cross-file answer was empty until some
// later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`].
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH);
assert_eq!(
settings(json!({ "lucisv": { "index": {} } })).index_scope_depth,
DEFAULT_SCOPE_DEPTH
);
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
assert_eq!(raised.index_scope_depth, 3);
// Zero is still exactly what it always was — the file's own folder and
// nothing above it — and asking for it still gets it.
let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } }));
assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted");
// No upper bound here: the clamp is structural — `state.rs` stops at
// the workspace root — so an absurd number is not wrong, just fully
// clamped.
let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } }));
assert_eq!(absurd.index_scope_depth, 9999);
for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] {
let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } }));
assert_eq!(
found.index_scope_depth, DEFAULT_SCOPE_DEPTH,
"scopeDepth {bad} must be ignored"
);
}
}
#[test]
fn a_filelist_is_taken_when_it_names_something() {
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
assert_eq!(found.filelist.as_deref(), Some("rtl/files.f"));
let found = settings(json!({ "lucisv": { "filelist": " /abs/files.f " } }));
assert_eq!(
found.filelist.as_deref(),
Some("/abs/files.f"),
"surrounding space is not path"
);
}
#[test]
fn an_empty_or_wrong_typed_filelist_is_no_opinion() {
// `""` is the setting's own default: it must mean "no filelist", not
// "a filelist whose path is empty".
for bad in [json!(""), json!(" "), json!(null), json!(3), json!(["a.f"]), json!(true)] {
let found = settings(json!({ "lucisv": { "filelist": bad } }));
assert_eq!(found.filelist, None, "filelist {bad} must be ignored");
}
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
}
/// [`vscode_payload`] above is a hand-written copy of what the extension
/// declares, and a copy that drifts proves nothing. The extension's own
/// `package.json` is the thing a user's settings UI reads, so the two
/// defaults that are not "no opinion" are checked against it directly.
#[test]
fn the_extensions_declared_defaults_are_the_ones_this_module_ships() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = &manifest["contributes"]["configuration"]["properties"];
assert_eq!(
properties["lucisv.index.scopeDepth"]["default"],
json!(DEFAULT_SCOPE_DEPTH),
"the settings UI and the server must ship the same scope depth"
);
assert_eq!(
properties["lucisv.index.maxFileSize"]["default"],
json!(DEFAULT_MAX_FILE_SIZE),
"and the same size cap"
);
// The two ghost-text settings are the ones whose absence resolves to
// `true` here, so a `false` default in the manifest would make the
// settings UI and the server disagree about a feature being on.
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
// list, which must leave today's behaviour exactly unchanged.
// The two ghost-text settings are the defaults that are not "no
// opinion" — both default to `true`, and `None` resolves to the same
// thing.
let found = settings(vscode_payload(json!(null), json!(null), json!([])));
assert_eq!(
found,
ClientSettings {
inline_templates: Some(true),
inline_instantiation: Some(true),
..Default::default()
},
"the only difference from silence must be the settings whose \
default is not null"
);
}
#[test]
fn inline_templates_is_a_boolean_and_nothing_else() {
let found = settings(json!({ "lucisv": { "inlineTemplates": false } }));
assert_eq!(found.inline_templates, Some(false));
let found = settings(json!({ "lucisv": { "inlineTemplates": true } }));
assert_eq!(found.inline_templates, Some(true));
// Absence is not `false`: the feature is on unless a client says no.
assert_eq!(settings(json!({ "lucisv": {} })).inline_templates, None);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "inlineTemplates": bad } }));
assert_eq!(found.inline_templates, None, "inlineTemplates {bad} must be ignored");
}
}
#[test]
fn inline_instantiation_is_a_boolean_and_nothing_else() {
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
assert_eq!(found.inline_instantiation, Some(false));
let found = settings(json!({ "lucisv": { "inlineInstantiation": true } }));
assert_eq!(found.inline_instantiation, Some(true));
// Absence is not `false`: the feature is on unless a client says no.
assert_eq!(settings(json!({ "lucisv": {} })).inline_instantiation, None);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "inlineInstantiation": bad } }));
assert_eq!(found.inline_instantiation, None, "inlineInstantiation {bad} ignored");
}
// The two ghost settings are independent: one off leaves the other on.
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save);
// Absence is off: the hook runs on every save of every buffer, and a
// server that formatted uninvited would fight the editor's own
// format-on-save.
assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence");
for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] {
let found = settings(json!({ "lucisv": { "formatOnSave": bad } }));
assert!(!found.format_on_save, "formatOnSave {bad} must be ignored");
}
}
#[test]
fn a_populated_payload_is_read_whole() {
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
assert_eq!(found.line_length, Some(120));
assert_eq!(found.indent, Some(4));
assert_eq!(found.exclude, vec!["vendor".to_string(), "*_gen.sv".to_string()]);
}
#[test]
fn a_payload_without_our_section_says_nothing() {
assert_eq!(settings(json!({ "someOtherServer": { "indent": 4 } })), Default::default());
assert_eq!(settings(json!(null)), Default::default(), "the `settings: null` form");
assert_eq!(settings(json!({})), Default::default());
}
#[test]
fn a_missing_key_is_not_an_opinion() {
// A hand-written Neovim `settings` table names only what it cares
// about; the keys it leaves out must stay silent, not become 0.
let found = settings(json!({ "lucisv": { "indent": 4 } }));
assert_eq!(found.indent, Some(4));
assert_eq!(found.line_length, None);
assert!(found.exclude.is_empty());
}
#[test]
fn out_of_range_numbers_are_ignored() {
for bad in [json!(0), json!(9), json!(100), json!(-1)] {
let found = settings(json!({ "lucisv": { "indent": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
}
for bad in [json!(0), json!(39), json!(401), json!(-40)] {
let found = settings(json!({ "lucisv": { "lineLength": bad } }));
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
}
#[test]
fn the_range_edges_are_accepted() {
let found = settings(json!({ "lucisv": { "indent": 1, "lineLength": 40 } }));
assert_eq!((found.indent, found.line_length), (Some(1), Some(40)));
let found = settings(json!({ "lucisv": { "indent": 8, "lineLength": 400 } }));
assert_eq!((found.indent, found.line_length), (Some(8), Some(400)));
}
#[test]
fn wrong_types_are_ignored_rather_than_coerced() {
for bad in [json!("4"), json!(true), json!([4]), json!({ "n": 4 }), json!(4.5)] {
let found = settings(json!({ "lucisv": { "indent": bad, "lineLength": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
}
#[test]
fn an_exclude_that_is_not_a_list_of_strings_contributes_nothing() {
assert!(settings(json!({ "lucisv": { "exclude": "vendor" } })).exclude.is_empty());
assert!(settings(json!({ "lucisv": { "exclude": 3 } })).exclude.is_empty());
assert!(settings(json!({ "lucisv": { "exclude": null } })).exclude.is_empty());
// A mixed array keeps the strings and drops the rest.
let found = settings(json!({ "lucisv": { "exclude": ["ok", 3, null, "fine"] } }));
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
}
#[test]
fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() {
// The whole point of `from_section`: the pull answers the section's
// contents, the push nests them one level deeper, and every rule
// about ranges, types and defaults must be the one set of rules.
let section = json!({
"lineLength": 120, "indent": 4, "exclude": ["vendor"],
"filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true
});
assert_eq!(from_section(&section), settings(json!({ "lucisv": section })));
// ...including the rejections.
let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" });
assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk })));
assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections");
}
#[test]
fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() {
// A client that cannot provide the section must answer `null`, per
// spec — and one that answers something absurd instead must cost the
// user no more than one that answered nothing.
for answer in [
json!(null),
json!({}),
json!("lucisv"),
json!(7),
json!([1, 2]),
json!({ "lucisv": { "indent": 4 } }),
] {
assert_eq!(
from_section(&answer),
ClientSettings::default(),
"the answer {answer} must resolve to the defaults"
);
}
}
#[test]
fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() {
// `{"settings": null}` is what a modern `vscode-languageclient`
// sends: "something changed, ask me". Applying it as a payload would
// silently reset every setting the user had pulled.
assert!(says_nothing(&json!(null)));
assert!(says_nothing(&json!({})));
assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } })));
// A legacy push that syncs some *other* server's section is still a
// push: it carries a payload, and this server's answer to it — no
// opinion about anything — is what it has always been.
assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } })));
// Neither an array nor a scalar is the client saying "ask me"; both
// are junk, and junk goes down the push path where `from_payload`
// drops it.
assert!(!says_nothing(&json!([])));
assert!(!says_nothing(&json!("")));
}
#[test]
fn the_section_constant_is_the_key_the_parser_reads() {
// The pull asks for `SECTION` by name and the push nests under it. A
// constant that drifted from the parser would make every pulled
// setting silently invisible.
let found = from_payload(&json!({ SECTION: { "indent": 4 } }));
assert_eq!(found.indent, Some(4));
assert_eq!(SECTION, "lucisv");
}
#[test]
fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() {
// The bounds above are copied from `lucisv_core::config`, which exports
// no constant for them. Rather than trust the copy, ask the real
// parser: every edge this module accepts must parse, and every value
// it rejects must be rejected there too. If `lucisv.toml` ever widens a
// range, this fails and says so.
let ok = |text: &str| lucisv_core::config::parse(text).is_ok();
assert!(ok("indent = 1") && ok("indent = 8"), "the indent edges");
assert!(!ok("indent = 0") && !ok("indent = 9"), "just outside indent");
assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges");
assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length");
}
}