Files
lucisv/crates/lucisv_server/src/lint.rs
T

1230 lines
57 KiB
Rust

//! Lint findings, and the diagnostics they become.
//!
//! `vlog_linter` is the same engine `lucisv check` runs, with the same default
//! rule set — an editor that disagreed with CI about what a violation is would
//! be worse than one that showed none. Since 2026-09-02 that includes the two
//! things a project-wide run has and a single file does not: a **census** the
//! semantic rules ask about names in other files, taken from the workspace
//! index, and a **selection** (`lucisv.lint.select` / `lucisv.lint.ignore`),
//! which is the same `--select`/`--ignore` the CLI has and the same `[lint]`
//! table `lucisv.toml` now carries. See
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
//!
//! Since §42 the two halves of that selection are one contract: the editor's
//! settings play the role the CLI's flags play, and the project's `[lint]`
//! table is what stands when the editor says nothing —
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
//! project's half.
mod project;
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use lucisv_core::config::FileConfig;
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext,
MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::lint_snapshot::{Key, Slot};
use crate::lint_trace::{self, Fences, Reuse, Stage};
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
/// around this one.
///
/// [`LintRun::default`] is a pass with no census and the rules a run without
/// one gets — exactly what this server did before the census existed, and what
/// every caller that has no [`Workspace`] in hand still gets.
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
/// The width a `no-tabs` fix writes where a tab was — the same ladder
/// `format::indent_width` walks, read off the `FileConfig` this pass
/// already discovered.
///
/// On the run rather than passed to [`fixable`] since the review round's
/// §R1a: the diagnostics pass and the quick-fix pass must build the *same*
/// `LintContext` to share one snapshot. Nothing published moves — the
/// width reaches only `no-tabs`' fix *text*, and the diagnostics path
/// never reads a fix.
tab_width: usize,
/// The external waiver files in force for this buffer, from its
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
/// configured, and then costing the pass nothing.
external: ExternalWaivers,
/// Those files' paths and contents, in the order they were read — the
/// snapshot key's row 7. Empty when no waiver file is configured.
///
/// **Written in the same step as `external`**, by `waiver_files` and by
/// `with_waivers` and by nothing else, so a run can never carry a waiver
/// its key cannot see. A run whose key missed a waiver would offer a fix
/// for a finding the waiver had silenced, which is the stale-fix failure
/// this whole key exists to prevent.
waiver_texts: Vec<(PathBuf, String)>,
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
/// (config file, message) — and never fatal here: §42.2.
problems: ConfigProblems,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
tab_width: DEFAULT_TAB_WIDTH,
external: ExternalWaivers::default(),
waiver_texts: Vec::new(),
problems: ConfigProblems::default(),
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
/// The indent width a buffer's fixes are written at when neither its
/// `lucisv.toml` nor the editor says otherwise — `vlog_formatter::Config`'s
/// own default, which is what `format::indent_width` falls back to.
const DEFAULT_TAB_WIDTH: usize = 2;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
/// The census exists when the index holds **some other file**: an index of
/// this buffer alone (or of nothing at all — a rootless session before its
/// first scan) can only repeat what the buffer says about itself, and
/// treating that as a project would switch the semantic rules on with no
/// cross-file evidence behind them, which is the false-positive mode this
/// whole round exists to close.
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
// Two stages, so `--verbose` can say which of them the request spent
// its milliseconds in: everything read from disk, then everything
// decided from what was read (review round §R1b, `crate::lint_trace`).
let found = lint_trace::stage(Stage::Config, || Discovered::read(ws, doc));
lint_trace::saw_config(found.file.source.is_some(), found.texts.len());
lint_trace::stage(Stage::Build, || found.into_run(ws, doc))
}
/// What this buffer's `lucisv.toml` asked for and did not get, for a
/// caller that can tell the user about it.
pub fn config_problems(&self) -> &ConfigProblems {
&self.problems
}
/// A run carrying this waiver file — for the tests that pin what a waiver
/// keeps out of the code actions.
///
/// Takes the file's **text**, not a parsed `ExternalWaivers`, for the same
/// reason `waiver_files` returns both: the waivers a run lints with and
/// the texts its snapshot key holds must be written in one step, or a run
/// could carry waivers its key cannot see. The bad-line messages are
/// dropped here; the caller asserts about them itself where it cares.
#[cfg(test)]
pub(crate) fn with_waivers(mut self, path: &Path, text: &str) -> Self {
self.external.absorb(ExternalWaivers::parse(path, text).0);
self.waiver_texts.push((path.to_path_buf(), text.to_string()));
self
}
/// A run whose fixes are written at this indent width — for the tests
/// that pin what a `no-tabs` fix writes. The server itself reads the
/// width off the buffer's own configuration in [`Discovered::read`].
#[cfg(test)]
pub(crate) fn with_tab_width(mut self, tab_width: usize) -> Self {
self.tab_width = tab_width;
self
}
/// What this run would lint with, as the snapshot compares it.
///
/// Every field is an argument of the `lint_with` call it guards; the
/// buffer itself and the workspace index are settled by identity and by
/// `Document::refresh_overlay` instead. The feature README's table is the
/// whole argument.
fn key(&self) -> Key {
Key {
rules: self.rules.iter().map(|rule| rule.name()).collect(),
options: self.options.clone(),
line_length: self.line_length,
tab_width: self.tab_width,
has_oracle: self.oracle.is_some(),
waivers: self.waiver_texts.clone(),
}
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc)
.with_options(&self.options)
.with_line_length(self.line_length)
.with_tab_width(self.tab_width);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
}
}
}
/// Everything one lint pass reads **from disk**: the `lucisv.toml` governing
/// the buffer, what its `[lint]` table said, and the external waiver files in
/// force.
///
/// Split out of [`LintRun::for_document`] so the I/O has a name and a stage of
/// its own on the `--verbose` channel — "config read plus lint" was as far as
/// take 5 §P1 could attribute the pinmux menu's 23 ms, and that is two
/// answers. Nothing about *what* is read changed: the calls below are
/// `for_document`'s own, in its own order, so the messages a config problem
/// produces arrive in the order §42.2 fixed.
struct Discovered {
options: RuleOptions,
line_length: usize,
tab_width: usize,
file: FileConfig,
project: ProjectLint,
external: ExternalWaivers,
/// Each waiver file's path and the text it was parsed from — the
/// snapshot key's only I/O-derived field.
texts: Vec<(PathBuf, String)>,
messages: Vec<String>,
}
impl Discovered {
/// One discovery for the whole pass: the selection, the options, the
/// width, the indent and the waiver paths all read the same `FileConfig`,
/// so reading the project's rules costs no extra stat and no extra open.
fn read(ws: &Workspace, doc: &Document) -> Discovered {
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
let (project, bad_names) = ProjectLint::read(&file);
messages.extend(bad_names);
let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file));
messages.extend(bad_waivers);
// The editor's own waiver files are read separately and their
// problems dropped: `notification::apply_settings` already said them
// once, where the setting arrived.
let editor = waiver_files(&editor_waivers(ws.client_settings(), ws.roots()));
external.absorb(editor.0);
texts.extend(editor.2);
// `format::indent_width` stays the one authority on the indent ladder
// (`lucisv.toml` > `lucisv.indent` > the formatter's default): reading
// it here rather than spelling the ladder a second time costs a second
// `Discovery` walk, which the R1b trace measures at hundredths of a
// millisecond against a 21 ms pass.
let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings());
Discovered { options, line_length, tab_width, file, project, external, texts, messages }
}
/// What this buffer's index and settings make of it: the census oracle and
/// the rule ladder, neither of which touches the filesystem.
fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let oracle = workspace.then_some(IndexMentions { index, own });
let rules = enabled_rules(ws.client_settings(), &self.project, workspace);
let problems = ConfigProblems::new(&self.file, self.messages);
LintRun {
rules,
oracle,
options: self.options,
line_length: self.line_length,
tab_width: self.tab_width,
external: self.external,
waiver_texts: self.texts,
problems,
}
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(
client: &ClientSettings,
doc: &Document,
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
let mut problems = Vec::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped rather than fatal — an editor
// cannot fail a run — but it is *said*, in the words `lucisv check`
// fails with, once per (config file, entry): §42.2. Silently dropping
// it left a user's option doing nothing with nothing to read about it.
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
let source = file
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width, file, problems)
}
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
/// first, then `lucisv.lint.waivers` from the editor.
///
/// The two **add up**, the way they do on the command line — a waiver file
/// only ever suppresses findings, so there is nothing here for one list to
/// take back from the other. A relative setting path is resolved against the
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
/// paths were already resolved against that file's own directory.
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
let mut paths = project_waivers(file);
paths.extend(editor_waivers(client, roots));
paths
}
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
/// against that file's own directory.
///
/// Read apart from the editor's since §42.2, because a problem in one of
/// *these* is the project's and belongs in the output channel with the
/// `lucisv.toml` that named it, while a problem in the editor's was already
/// said where the setting arrived.
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
file.lint_waivers.iter().flatten().cloned().collect()
}
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
/// the first workspace root exactly as `lucisv.filelist` is.
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
client
.lint_waivers
.iter()
.map(|setting| {
let path = Path::new(setting);
match roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
}
})
.collect()
}
/// Those files, read: the waivers and one message per file or line that could
/// not be used.
///
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
/// must never cost a user every diagnostic in their file — this module's
/// standing rule, and `settings::rule_options`'. The messages are logged once,
/// when the settings arrive (`server::notification::apply_settings`); the lint
/// pass, which runs on every keystroke, drops them silently rather than
/// logging the same line a hundred times.
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
let (waivers, problems, _) = waiver_files(paths);
(waivers, problems)
}
/// [`external_waivers`], keeping each file's **text** as well.
///
/// The text is what the lint snapshot's key holds (review round §R1a): a
/// waiver file is not watched — `watch::SOURCE_GLOB` covers sources and the
/// filelist alone — so comparing its contents is the only thing that ever
/// notices one being rewritten under a running server.
///
/// One read, not two. `ExternalWaivers::read` is `read_to_string` followed by
/// `ExternalWaivers::parse`, and both halves are public, so the bytes are
/// taken once and handed to the parser; the sentence an unreadable file
/// produces is `read`'s own, byte for byte.
fn waiver_files(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>, Vec<(PathBuf, String)>) {
let mut waivers = ExternalWaivers::default();
let mut problems = Vec::new();
let mut texts = Vec::new();
for path in paths {
match std::fs::read_to_string(path) {
Ok(text) => {
let (file, bad) = ExternalWaivers::parse(path, &text);
problems.extend(bad);
waivers.absorb(file);
texts.push((path.clone(), text));
}
Err(problem) => problems.push(format!("{}: {problem}", path.display())),
}
}
(waivers, problems, texts)
}
/// Which rules a buffer is linted with, given what the editor's settings and
/// the buffer's own `lucisv.toml` say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line; when the editor names
/// nothing, the project's `[lint] select` replaces it instead — the flag
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked; when the editor names
/// nothing there either, the project's `[lint] ignore` removes instead.
///
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
/// independently — a project that selects and a user who only ignores keep
/// both halves. Every list accepts a severity word wherever a rule name fits,
/// the project's as much as the editor's.
pub fn enabled_rules(
settings: &ClientSettings,
project: &ProjectLint,
has_oracle: bool,
) -> Vec<&'static dyn Rule> {
let select = pick(&settings.lint_select, &project.select);
let base = if select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
for (severity, class_on) in &settings.lint_severity {
if !class_on {
on.retain(|name| {
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
});
}
}
for (name, wanted) in &settings.lint_rules {
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
if *wanted {
on.insert(rule.name());
} else {
on.remove(rule.name());
}
}
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// The editor's list when it said anything, else the project's — the twin of
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
if editor.is_empty() {
project
} else {
editor
}
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
/// Answered from [`WorkspaceIndex::files_mentioning`] — the *textual* census,
/// which holds the hierarchical uses (`tb.dut.sig`) and `bind` connections the
/// resolved reference tables never see. The buffer's own file is subtracted:
/// a signal's own declaration is not evidence that something else uses it.
///
/// **Staleness is the index's, not this type's.** A file saved but not yet
/// rescanned answers with its last-scanned words, exactly as hover and
/// find-references do; an open buffer's unsaved edits reach the census when
/// its facts are folded in. No new staleness is introduced here.
struct IndexMentions<'a> {
index: &'a WorkspaceIndex,
/// The buffer's own file, when the index holds it. `None` — an untitled
/// buffer, or one outside the indexed scope — means nothing is subtracted,
/// which can only ever make the oracle answer *yes* more often, i.e. make
/// a rule quieter. That is the safe direction.
own: Option<FileId>,
}
impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
/// The ports and overridable parameters of an indexed module or interface,
/// read off the index's member table — the very table a `.port` completion
/// list is offered from, so a connection lucisv would have completed is
/// never one it then calls unknown.
///
/// `None` for a unit the index does not hold, and for one it holds **more
/// than once**: two modules of a name are two different headers, and
/// answering with either would make an Error-class rule guess. A
/// `localparam` is left out, because it is not overridable.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let units = self.index.units(name);
let [unit] = units else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
/// Every name a package exports, read off the index's member table — the
/// same `WorkspaceIndex` answer `vlog_refactor`'s organize-imports engine
/// gets, so the squiggle and the lightbulb cannot disagree about which
/// import is dead.
///
/// `Unknown` for a package the index does not hold and `Ambiguous` for one
/// it holds twice; `vlog_semantic::import_usage` refuses to judge in either
/// case rather than guess.
fn package_exports(&self, package: &str) -> Exports {
vlog_semantic::PackageExports::exports(self.index, package)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
/// tools" (`docs/features/one-parse/README.md`): the buffer was tokenized and
/// tolerantly parsed once, in `Document::new`, and the lint pass reads those
/// products instead of parsing the same text again.
///
/// The symbol table goes the same way (`docs/features/semantic-lints/`): the
/// document is analyzed on every edit for hover, definition and references, so
/// the semantic rules must read *that* analysis rather than run a second one
/// per keystroke.
fn context(doc: &Document) -> LintContext<'_> {
LintContext::from_parse(&doc.text, &doc.tokens, &doc.tree, &doc.line_index, doc.path.clone())
.with_semantics(&doc.semantics)
}
/// Every violation `run`'s rules find in a buffer.
///
/// This is the diagnostics path, which never looks at a fix, so the width a
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
/// The external waivers apply here exactly as the inline ones do, as a union.
/// Which of them *fired* is discarded: only a whole run can tell whether a
/// waiver was dead, and a server never has one — it lints the buffers a user
/// happens to have open. `lucisv check` is what reports an unused external
/// waiver; see `docs/features/waiver-files/README.md`.
pub fn violations_in(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
found(doc, run)
}
/// The one place `vlog_linter::lint_with` is called for an open buffer.
///
/// One place, so there is one snapshot to read (review round §R1a) and one
/// site that says on the `--verbose` channel what a pass ran, what it found,
/// and whether it ran at all. Both doors — the diagnostics publish and
/// quick-fix discovery — arrive here with the *same* context, which is why the
/// tab width lives on the [`LintRun`] rather than being handed to [`fixable`].
fn found(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
let key = run.key();
let (violations, hit) = lint_trace::stage(Stage::Lint, || {
snapshot(doc).read_or(&key, || lint_with(&run.context(doc), &run.rules, &run.external).0)
});
let reuse = if hit { Reuse::Hit } else { Reuse::Miss };
lint_trace::saw_lint(run.rules.len(), violations.len(), reuse);
violations
}
/// The slot this buffer's findings are kept in.
///
/// A field on the `Document`, so it is dropped with the buffer and cannot
/// outlive the text it was computed from: `Workspace::set_document` builds a
/// new `Document` for every flushed change. One per open document and nothing
/// else — no map, no eviction, no second analysis cache.
fn snapshot(doc: &Document) -> &Slot {
&doc.lint
}
/// The findings a code action may offer a fix for.
///
/// The fixes are written at the run's own indent width — the `lucisv.toml`
/// governing the buffer, else `lucisv.indent`, else the formatter's default —
/// so a quick fix that replaces a tab writes exactly what `lucisv` would have
/// written there.
///
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
/// region is dropped here, so the editor keeps the same promise `lucisv check
/// --fix` does: **reported, never auto-fixed**. The diagnostic still reaches
/// the user — [`violations`] is the publishing path and is not filtered — it
/// just has no lightbulb. Which bytes count as fenced is
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
/// `docs/features/shared-fence-filter/README.md`.
pub fn fixable(run: &LintRun, doc: &Document) -> Arc<[Violation]> {
// The buffer's own run: its enabled rules and its external waiver files,
// so a fix is never offered — nor applied by fix-on-save — for a finding
// the diagnostics pass would not have shown. Found by §39's QA: with
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
// line a checked-in waiver file had waived.
let violations = found(doc, run);
// The fence answer is a whole second tolerant parse of the buffer:
// `protected_regions` takes text and parses internally, on purpose — one
// fence answer for every front end, none of which can feed it a stale tree
// (see `docs/features/shared-fence-filter/README.md`). It protects
// *fixes*, so a pass whose findings carry no fix has nothing to protect
// and nothing to ask: the filter below would be the identity. Skipping it
// there is take 5 §P1a. The per-keystroke diagnostics path pays nothing
// either, because it never reads a fix.
if !violations.iter().any(|violation| violation.fix.is_some()) {
lint_trace::saw_fences(Fences::Skipped);
return violations;
}
// Asked once per document revision rather than once per request: the text
// a `Document` holds cannot change without a new `Document` (§P1b,
// `crate::fences`). The question itself is unchanged — still
// `protected_regions` over this buffer's text.
let held = crate::fences::held(doc);
let regions = lint_trace::stage(Stage::Fence, || crate::fences::of(doc));
lint_trace::saw_fences(if held { Fences::Memo } else { Fences::Computed });
// The snapshot's own findings when the fence drops nothing, which is every
// buffer with no `// lucisv: off` region in it: the filter would be the
// identity, and copying the findings to prove it would undo the reuse.
if !violations.iter().any(|violation| fix_touches_fence(violation, regions)) {
return violations;
}
violations.iter().filter(|v| !fix_touches_fence(v, regions)).cloned().collect()
}
/// True when a violation carries a fix any edit of which lands in a fenced
/// region. A fix is all-or-nothing, so one edit inside blocks the whole fix.
fn fix_touches_fence(violation: &Violation, regions: &[Region]) -> bool {
violation.fix.as_ref().is_some_and(|fix| {
fix.edits
.iter()
.any(|(span, _)| fence::is_protected(regions, span.start as usize, span.end as usize))
})
}
/// One LSP diagnostic per lint violation, with no census.
///
/// `#[cfg(test)]` because the server itself always has a workspace to hand and
/// therefore always goes through [`diagnostics_in`]; this is the door the
/// tests that predate the project-aware pass come in by, and keeping it means
/// they go on asserting about the same code with one fewer thing supplied.
#[cfg(test)]
pub fn diagnostics(doc: &Document) -> Vec<Diagnostic> {
diagnostics_in(doc, &LintRun::default())
}
/// [`diagnostics`] for a run that knows what the project says.
pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
let positions = doc.positions();
violations_in(doc, run).iter().map(|v| diagnostic(&positions, v)).collect()
}
/// The diagnostic a violation becomes.
///
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
/// is the rule's stable name, which is what a user needs to write a waiver or
/// an `--ignore`, and what a code action matches on.
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
Diagnostic {
range: positions.diagnostic_range(violation.span),
severity: Some(severity_of(violation.severity)),
code: Some(NumberOrString::String(violation.rule.to_string())),
source: Some(SOURCE.to_string()),
message: violation.message.clone(),
..Default::default()
}
}
/// How an editor is asked to paint one class.
///
/// `error` is the red squiggle a compiler error gets — a rule only claims it
/// when the code would very likely not build, which is why the Error class is
/// held to the silence-when-unsure rule. `style` deliberately stops short of
/// `HINT`: a hint is invisible in most themes and would make the style rules
/// look broken rather than quiet.
fn severity_of(severity: Severity) -> DiagnosticSeverity {
match severity {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
Severity::Style => DiagnosticSeverity::INFORMATION,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::Workspace;
use lsp_types::Uri;
use std::path::PathBuf;
use std::str::FromStr;
fn doc_of(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)
}
#[test]
fn the_index_answers_what_a_package_exports() {
// The handshake `unused-import` reads: the server's oracle hands the
// rule the very member table `vlog_refactor`'s engine reads, so a
// squiggle and a lightbulb cannot disagree about a dead import.
let index = WorkspaceIndex::build([(
PathBuf::from("/rtl/a_pkg.sv"),
"package a_pkg;\n typedef int a_t;\nendpackage\n",
)]);
let oracle = IndexMentions { index: &index, own: None };
match oracle.package_exports("a_pkg") {
Exports::Known(names) => assert!(names.iter().any(|n| n == "a_t"), "{names:?}"),
other => panic!("an indexed package is known: {other:?}"),
}
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
/// Each class paints its own squiggle: a compile-error rule reads as an
/// error, a latch-shaped one as a warning, a naming one as information.
#[test]
fn a_diagnostics_severity_is_its_rules_class() {
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
// `reg` is error-class, the tab is style-class, and the two arrive in
// one publish wearing different colours.
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
let by_code = |name: &str| {
diags
.iter()
.find(|d| d.code == Some(NumberOrString::String(name.into())))
.and_then(|d| d.severity)
};
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
assert!(diagnostics(ws.document(&uri).expect("open")).is_empty());
}
#[test]
fn the_module_filename_rule_sees_the_uris_own_path() {
// The rule is silent without a file name, so this also proves the path
// reached the linter rather than the buffer being linted anonymously.
let (ws, uri) = doc_of("module other;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, Some(NumberOrString::String("module-filename".into())));
assert!(diags[0].message.contains("m.sv"), "{}", diags[0].message);
}
#[test]
fn an_untitled_buffer_is_linted_without_a_name() {
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), "module other;\n\twire a;\nendmodule\n".to_string());
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1, "the tab, and no module-filename: {diags:#?}");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
}
#[test]
fn multi_byte_content_shifts_a_violations_character() {
// The `é` is 2 bytes but 1 UTF-16 unit, and `🎉` is 4 bytes but 2: a
// byte-based server puts this warning four columns to the right.
let (ws, uri) = doc_of("module m;\n // é 🎉\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].range.start.line, 1);
assert_eq!(diags[0].range.start.character, 9, "in UTF-16 units, not bytes");
}
#[test]
fn a_file_that_does_not_parse_is_still_linted() {
// The tolerant parse is what makes a text rule work in a broken file.
let (ws, uri) = doc_of("module m;\n\twire ;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert!(diags.iter().any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))));
}
#[test]
fn a_violation_inside_a_fence_is_reported_but_not_fixable() {
// `off` means hands-off for the editor too: the warning is published,
// the fix is withheld.
let text = "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
let offered = fixable(&LintRun::default(), doc);
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
let free = text.find("\twire b").expect("the unfenced tab") as u32;
assert_eq!(offered[0].span.start, free);
}
#[test]
fn a_fence_holds_even_when_the_file_does_not_parse() {
// Error recovery can swallow the item structure `fence::collect` hangs
// a region on — the buffers the server sees mid-keystroke are exactly
// that population, and the shared filter's scan half covers them.
let text = "module m;\n@@@ junk;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
assert!(
diagnostics(doc)
.iter()
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
"still reported"
);
assert!(fixable(&LintRun::default(), doc).is_empty(), "and still not fixable");
}
#[test]
fn a_semantic_rule_reads_the_documents_own_analysis() {
// The buffer here has no project behind it, so the rule is off by
// default and this goes through `context()` directly — which is the
// point: whichever door a semantic rule comes in by, it must read the
// analysis the server already made, so no keystroke analyzes twice.
let (ws, uri) = doc_of("module m;\n wire spare;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let rule = vlog_linter::rule_by_name("unused-signal").expect("the rule exists");
let found = vlog_linter::lint(&context(doc), &[rule]);
assert_eq!(found.len(), 1, "{found:#?}");
assert!(found[0].message.contains("spare"), "{}", found[0].message);
assert!(std::ptr::eq(context(doc).semantics(), &doc.semantics), "the lent table");
// ... including the project-aware door, which wraps that same context
// in the census rather than building a second one.
let run = LintRun::for_document(&ws, doc);
assert!(std::ptr::eq(run.context(doc).semantics(), &doc.semantics), "still lent");
}
/// A workspace of two files on disk, the second of which reads the
/// first's signal through a hierarchical path — QA's cross-file
/// false-positive repro, made real rather than synthetic.
fn two_file_project(tag: &str) -> (Workspace, PathBuf, Uri) {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(
dir.join("dut.sv"),
"module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n",
)
.expect("write");
std::fs::write(
dir.join("tb.sv"),
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
)
.expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
ws.set_document(uri.clone(), std::fs::read_to_string(dir.join("dut.sv")).expect("read"));
(ws, dir, uri)
}
fn codes(diags: &[Diagnostic]) -> Vec<String> {
diags
.iter()
.filter_map(|d| match &d.code {
Some(NumberOrString::String(name)) => Some(name.clone()),
_ => None,
})
.collect()
}
/// The round's headline, through the server: with a project behind it the
/// semantic rules run, and the file that reads `d.dbg_probe` is what keeps
/// `dbg_probe` quiet while `dead` is still reported.
#[test]
fn a_project_turns_the_semantic_rules_on_and_its_census_keeps_them_honest() {
let (ws, dir, uri) = two_file_project("project");
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let diags = diagnostics_in(doc, &run);
assert_eq!(codes(&diags), vec!["unused-signal"], "{diags:#?}");
assert!(diags[0].message.contains("dead"), "{}", diags[0].message);
assert!(!diags[0].message.contains("dbg_probe"));
// And the same buffer with no project behind it is v0.29.0's answer.
assert!(diagnostics(doc).is_empty(), "no census, no semantic rules");
let _ = std::fs::remove_dir_all(dir);
}
/// The ladder of §33.1, one row per rung, asserted against the rule set
/// `enabled_rules` produces. Each row is (what the settings say, what must
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
// The project's half of the ladder is `lint::project`'s own table
// test; this one holds it empty, which is the editor-only ladder
// §33.1 wrote.
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, &ProjectLint::default(), oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
f(&mut settings);
settings
};
// 1. the base set is the rules' own defaults, and a workspace adds
// exactly the rules that asked for one.
let base = ClientSettings::default();
assert_eq!(
names(&base, false),
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
assert_eq!(
names(&base, true),
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
// 2. a non-empty `select` replaces the base set — including rules that
// ship off, exactly as `--select` does.
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
assert_eq!(names(&selected, false), vec!["module-name-style"]);
// ... and a severity word may stand there.
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
assert!(names(&styled, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
// 3. a class switched off removes every rule of that class.
let no_style = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
});
assert!(!names(&no_style, true).contains(&"no-tabs"));
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
// 4. a per-rule toggle beats the class switch, in both directions.
let style_off_but_tabs = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
s.lint_rules.insert("no-tabs".to_string(), true);
});
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
let one_off = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), false);
});
assert!(!names(&one_off, true).contains(&"no-tabs"));
// A toggle also adds a rule `select` did not name, and one that ships
// off entirely.
let added = with(&|s| {
s.lint_select = vec!["no-tabs".to_string()];
s.lint_rules.insert("module-name-style".to_string(), true);
});
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
// 5. `ignore` is the last word, over a toggle that says `on`.
let ignored = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), true);
s.lint_ignore = vec!["no-tabs".to_string()];
});
assert!(!names(&ignored, true).contains(&"no-tabs"));
// ... and it takes a severity word too.
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
assert!(names(&quiet, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
// The result is always in registry order, whatever order the settings
// named things in — two runs must print findings the same way.
let jumbled = with(&|s| {
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
});
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
}
/// The toggles reach the real published diagnostics, not just the rule
/// list: a class switched off silences its squiggles.
#[test]
fn a_class_switch_changes_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("classes");
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
both.sort();
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
let mut off = ClientSettings::default();
off.lint_severity.insert(Severity::Style, false);
ws.set_client_settings(off);
let doc = ws.document(&uri).expect("open");
assert_eq!(
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
vec!["unused-signal"],
"the style class went quiet"
);
let mut back = ClientSettings::default();
back.lint_severity.insert(Severity::Style, false);
back.lint_rules.insert("no-tabs".to_string(), true);
ws.set_client_settings(back);
let doc = ws.document(&uri).expect("open");
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
with_tabs.sort();
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
let _ = std::fs::remove_dir_all(dir);
}
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
/// rule out of the published set.
#[test]
fn the_lint_settings_select_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("settings");
ws.set_client_settings(ClientSettings {
lint_ignore: vec!["unused-signal".to_string()],
..ClientSettings::default()
});
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert!(diagnostics_in(doc, &run).is_empty(), "the setting silenced the rule");
// `select` replaces the default set, exactly as `--select` does: the
// tab is reported by default and not when something else is selected.
ws.set_client_settings(ClientSettings::default());
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut by_default = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
by_default.sort();
assert_eq!(by_default, vec!["no-tabs", "unused-signal"], "premise");
ws.set_client_settings(ClientSettings {
lint_select: vec!["unused-signal".to_string()],
..ClientSettings::default()
});
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert_eq!(codes(&diagnostics_in(doc, &run)), vec!["unused-signal"], "the tab is dropped");
let _ = std::fs::remove_dir_all(dir);
}
/// An index that holds only this buffer is not a project: there is nothing
/// to ask, so the rules that need one stay off.
#[test]
fn a_workspace_of_one_file_is_not_a_project() {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_alone", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("dut.sv"), "module dut;\n logic dead;\nendmodule\n")
.expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
ws.set_document(uri.clone(), "module dut;\n logic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
assert!(diagnostics_in(doc, &LintRun::for_document(&ws, doc)).is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_unfenced_file_offers_every_fix() {
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open")).len(), 1);
}
#[test]
fn a_fix_expands_a_tab_to_the_width_it_is_given() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
for width in [2usize, 4] {
let found = fixable(&LintRun::default().with_tab_width(width), doc);
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
assert_eq!(fix.edits[0].1, " ".repeat(width));
}
}
/// The two waiver lists add up, and only the setting's relative paths are
/// anchored at the first root — a `lucisv.toml`'s were resolved against
/// that file's own directory before they got here. TODO §39.
#[test]
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
let file = FileConfig {
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
..Default::default()
};
let client = ClientSettings {
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
..Default::default()
};
let roots = vec![PathBuf::from("/work/top")];
assert_eq!(
waiver_paths(&client, &roots, &file),
vec![
PathBuf::from("/proj/rtl/project.waiver"),
PathBuf::from("/work/top/team.waiver"),
PathBuf::from("/etc/global.waiver"),
]
);
// With no root at all a relative path is left as written rather than
// guessed at, exactly as `filelist_path` leaves it.
assert_eq!(
waiver_paths(&client, &[], &FileConfig::default()),
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
);
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
}
/// The run's indent width is the formatter's own ladder, read through
/// `format::indent_width` rather than spelled a second time — pinned at
/// each rung, because the width is a fix's bytes and this lane moved
/// where it is read (review round §R1a).
#[test]
fn the_runs_tab_width_is_the_formatters_own_ladder() {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_indent", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("m.sv"), "module m;\n\twire a;\nendmodule\n").expect("write");
let path = dir.join("m.sv");
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
// Rung by rung: the built-in default, the editor's setting, and a
// `lucisv.toml` that outranks it.
let rungs: Vec<(Option<&str>, Option<usize>, usize)> = vec![
(None, None, 2),
(None, Some(8), 8),
(Some("indent = 4\n"), Some(8), 4),
(Some("indent = 3\n"), None, 3),
];
for (toml, editor, want) in rungs {
match toml {
Some(text) => std::fs::write(dir.join("lucisv.toml"), text).expect("write"),
None => {
let _ = std::fs::remove_file(dir.join("lucisv.toml"));
}
}
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { indent: editor, ..Default::default() });
ws.set_document(uri.clone(), "module m;\n\twire a;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert_eq!(run.tab_width, want, "toml={toml:?} editor={editor:?}");
assert_eq!(
run.tab_width,
crate::format::indent_width(Some(&path), ws.client_settings()),
"the two readings of the ladder agree"
);
assert_eq!(
fixable(&run, doc)[0].fix.as_ref().expect("a fix").edits[0].1,
" ".repeat(want)
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// The snapshot is a memo and not a second implementation: what it hands
/// back is what a pass computed from scratch would have, violation for
/// violation, and both doors get the same object.
#[test]
fn a_reused_snapshot_is_what_a_fresh_pass_would_have_found() {
let (ws, uri) = doc_of("module m;\n\twire a; \nendmodule\n");
let doc = ws.document(&uri).expect("open");
let run = LintRun::default();
let fresh: Vec<Violation> = lint_with(&run.context(doc), &run.rules, &run.external).0;
let first = violations_in(doc, &run);
let second = fixable(&run, doc);
assert!(Arc::ptr_eq(&first, &second), "the diagnostics and the fixes are one pass");
assert_eq!(first.len(), fresh.len(), "{fresh:#?}");
for (held, made) in first.iter().zip(&fresh) {
assert_eq!(
(held.rule, held.span, &held.message),
(made.rule, made.span, &made.message)
);
assert_eq!(
held.fix.as_ref().map(|fix| &fix.edits),
made.fix.as_ref().map(|fix| &fix.edits),
"the fix bytes are the fresh pass's too"
);
}
}
/// A waiver file that is missing, and one with a bad line, are both
/// described rather than fatal — and the good directives of the second
/// still apply. TODO §39.
#[test]
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let good = dir.join("good.waiver");
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
assert_eq!(problems.len(), 2, "{problems:?}");
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
let _ = std::fs::remove_dir_all(&dir);
}
}